@pithy-sh/auth 0.7.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 (108) 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/adminRoutes.d.ts.map +1 -1
  19. package/dist/http/adminRoutes.js +39 -8
  20. package/dist/http/credentialResign.d.ts +46 -0
  21. package/dist/http/credentialResign.d.ts.map +1 -0
  22. package/dist/http/credentialResign.js +203 -0
  23. package/dist/http/devLoginRoute.d.ts.map +1 -1
  24. package/dist/http/devLoginRoute.js +12 -5
  25. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  26. package/dist/http/errorCallbackUrl.js +15 -9
  27. package/dist/http/middleware.d.ts.map +1 -1
  28. package/dist/http/middleware.js +66 -15
  29. package/dist/http/providerRefusal.d.ts +8 -7
  30. package/dist/http/providerRefusal.d.ts.map +1 -1
  31. package/dist/http/providerRefusal.js +29 -32
  32. package/dist/http/resolve.d.ts.map +1 -1
  33. package/dist/http/resolve.js +18 -3
  34. package/dist/http/responses.d.ts +52 -0
  35. package/dist/http/responses.d.ts.map +1 -1
  36. package/dist/http/responses.js +25 -1
  37. package/dist/http/routes.d.ts.map +1 -1
  38. package/dist/http/routes.js +60 -9
  39. package/dist/http/schemas.d.ts +1 -1
  40. package/dist/http/schemas.js +1 -1
  41. package/dist/instance/auth.d.ts +1225 -2
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +6 -2
  44. package/dist/instance/jwksReencryption.d.ts +75 -0
  45. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  46. package/dist/instance/jwksReencryption.js +160 -0
  47. package/dist/instance/providerSignInGate.d.ts +7 -6
  48. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  49. package/dist/instance/providerSignInGate.js +16 -14
  50. package/dist/instance/providers.d.ts.map +1 -1
  51. package/dist/instance/providers.js +2 -1
  52. package/dist/instance/secrets.d.ts +168 -1
  53. package/dist/instance/secrets.d.ts.map +1 -1
  54. package/dist/instance/secrets.js +86 -3
  55. package/dist/instance/sessionSecrets.d.ts +45 -0
  56. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  57. package/dist/instance/sessionSecrets.js +29 -0
  58. package/dist/migrations/0001_init.d.ts.map +1 -1
  59. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  60. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  61. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  62. package/dist/migrations/set.d.ts +2 -1
  63. package/dist/migrations/set.d.ts.map +1 -1
  64. package/dist/migrations/set.js +4 -2
  65. package/dist/seeds/devSession.d.ts.map +1 -1
  66. package/dist/seeds/devSession.js +2 -1
  67. package/dist/test-utils/liveApp.d.ts +5 -0
  68. package/dist/test-utils/liveApp.d.ts.map +1 -1
  69. package/dist/test-utils/liveApp.js +3 -3
  70. package/dist/test-utils/schemaDrift.d.ts +49 -0
  71. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  72. package/dist/test-utils/schemaDrift.js +35 -0
  73. package/dist/test-utils/scopedBackend.d.ts +183 -0
  74. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  75. package/dist/test-utils/scopedBackend.js +160 -0
  76. package/dist/version.generated.d.ts +1 -1
  77. package/dist/version.generated.js +1 -1
  78. package/docs/server-authoritative.md +182 -0
  79. package/package.json +14 -11
  80. package/src/caller/certificate.ts +133 -0
  81. package/src/caller/request.ts +84 -0
  82. package/src/caller/token.ts +276 -0
  83. package/src/capability.ts +65 -4
  84. package/src/data/betterAuth.ts +2 -1
  85. package/src/http/adminRoutes.ts +46 -10
  86. package/src/http/credentialResign.ts +268 -0
  87. package/src/http/devLoginRoute.ts +19 -6
  88. package/src/http/errorCallbackUrl.ts +21 -13
  89. package/src/http/middleware.ts +100 -35
  90. package/src/http/providerRefusal.ts +30 -32
  91. package/src/http/resolve.ts +27 -3
  92. package/src/http/responses.ts +54 -0
  93. package/src/http/routes.ts +97 -11
  94. package/src/http/schemas.ts +1 -1
  95. package/src/instance/auth.ts +22 -4
  96. package/src/instance/jwksReencryption.ts +206 -0
  97. package/src/instance/providerSignInGate.ts +23 -21
  98. package/src/instance/providers.ts +2 -1
  99. package/src/instance/secrets.ts +94 -1
  100. package/src/instance/sessionSecrets.ts +64 -0
  101. package/src/migrations/0001_init.ts +8 -10
  102. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  103. package/src/migrations/set.ts +3 -1
  104. package/src/seeds/devSession.ts +2 -1
  105. package/src/test-utils/liveApp.ts +8 -6
  106. package/src/test-utils/schemaDrift.ts +82 -0
  107. package/src/test-utils/scopedBackend.ts +136 -0
  108. package/src/version.generated.ts +1 -1
package/README.md CHANGED
@@ -56,6 +56,10 @@ Pressing a provider button while signed out is not a claim on an address. It is
56
56
 
57
57
  So: **do not "improve" this by matching more addresses, and do not make the refusal more helpful.** An address is not a credential — a provider hands over whatever primary happens to be set, chosen years ago for unrelated reasons — and every sentence that separates "you have no account here" from "you have one and this provider is not attached to it" is the oracle back. The remedy for a refused sign-in is the same either way: sign in with a magic link, then connect the provider from the account. Linking from inside the account is a different flow with both sides already proven, and it is deliberately unconstrained by the address.
58
58
 
59
+ ## Server-authoritative writes
60
+
61
+ The leaderboard, rating and ledger gates open only for a caller your `resolveScopes` vouches for. A scope is an attestation about the caller, not a permission granted to the user. [`docs/server-authoritative.md`](docs/server-authoritative.md) ranks the three ways to prove it: a service binding, mTLS, and a short-lived token bound to this origin.
62
+
59
63
  ## License
60
64
 
61
65
  MIT — adopter-side app value. The root `LICENSE` covers it.
@@ -0,0 +1,83 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * **The client certificate a request arrived with, read off `request.cf.tlsClientAuth` (#560).**
6
+ *
7
+ * mTLS is the option that is sender-constrained at the edge: the zone refuses a caller without a
8
+ * certificate **before the Worker runs**, through a WAF custom rule scoped to the hostname that blocks on
9
+ * `not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked`. Both halves, because a revoked
10
+ * certificate whose chain verifies still reports `cert_verified`. That rule is the gate. **This helper is not.** It is a defense-in-depth check
11
+ * inside the Worker, for the one question the zone rule cannot answer — which of the certificates your CA
12
+ * issued is this — and on its own it blocks nothing: a Worker with no zone rule in front of it still
13
+ * receives every request, certificate or not, and a resolver that forgot to call this would trust them all.
14
+ *
15
+ * Cloudflare-managed client certificates are available on every plan. They need a proxied zone and a
16
+ * hostname that matches exactly — no wildcards, so not `workers.dev`. `docs/server-authoritative.md` has
17
+ * the rule and the setup.
18
+ *
19
+ * **Anything other than `certVerified === "SUCCESS"` is untrusted**, and so is a revoked certificate whose
20
+ * chain did verify. "No certificate" and "a certificate that did not verify" are different states, because
21
+ * the first is an ordinary device and the second is somebody presenting a certificate your CA did not issue,
22
+ * and an adopter's log should be able to tell them apart.
23
+ */
24
+ /** The fields of `request.cf.tlsClientAuth` this reads. Cloudflare sends more; nothing here needs them. */
25
+ export declare const TlsClientAuth: z.ZodObject<{
26
+ certPresented: z.ZodString;
27
+ certVerified: z.ZodString;
28
+ certRevoked: z.ZodString;
29
+ certIssuerDN: z.ZodString;
30
+ certSubjectDN: z.ZodString;
31
+ certSerial: z.ZodString;
32
+ certFingerprintSHA1: z.ZodString;
33
+ certFingerprintSHA256: z.ZodString;
34
+ certNotBefore: z.ZodString;
35
+ certNotAfter: z.ZodString;
36
+ }, z.core.$strip>;
37
+ export type TlsClientAuth = z.infer<typeof TlsClientAuth>;
38
+ /** A certificate that verified against the zone's CA and has not been revoked, and who it names. */
39
+ export interface VerifiedCertificate {
40
+ state: "verified";
41
+ issuerDN: string;
42
+ subjectDN: string;
43
+ serial: string;
44
+ fingerprintSHA1: string;
45
+ fingerprintSHA256: string;
46
+ notBefore: string;
47
+ notAfter: string;
48
+ }
49
+ /** What a request's client certificate turned out to be. Only `verified` is ever trusted. */
50
+ export type ClientCertificate = VerifiedCertificate | {
51
+ state: "absent";
52
+ } | {
53
+ state: "unverified";
54
+ verification: string;
55
+ } | {
56
+ state: "revoked";
57
+ };
58
+ /** Read the client certificate off a request. Never throws: anything it cannot read is not `verified`. */
59
+ export declare function readClientCertificate(request: Request): ClientCertificate;
60
+ /** Which certificates a resolver trusts. A fingerprint pin is required; the issuer is an extra check. */
61
+ export interface CertificatePins {
62
+ /**
63
+ * The issuer the certificate must also name, exactly — your CA's distinguished name. **Never enough on
64
+ * its own**: on the Cloudflare-managed CA every certificate the zone verifies names the same issuer.
65
+ */
66
+ issuerDN?: string;
67
+ /**
68
+ * The SHA-256 fingerprints of the certificates you issued to your backend. Case and colons are ignored.
69
+ * Required, and an empty list trusts nothing.
70
+ */
71
+ fingerprintsSHA256: readonly string[];
72
+ }
73
+ /**
74
+ * Whether a certificate is one this Worker trusts: verified, not revoked, one of the pinned fingerprints,
75
+ * and from the pinned issuer when one is given.
76
+ *
77
+ * **No fingerprint is no trust.** Every certificate the zone's CA issued verifies, so with nothing pinned
78
+ * this would trust a certificate minted for any other purpose under the same account. An issuer pin does
79
+ * not close that: on a shared CA, every certificate behind the zone rule already names that issuer. Pin
80
+ * the fingerprints of the certificates your backend holds, and add the issuer if you like.
81
+ */
82
+ export declare function isTrustedCertificate(certificate: ClientCertificate, pins: CertificatePins): boolean;
83
+ //# sourceMappingURL=certificate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"certificate.d.ts","sourceRoot":"","sources":["../../src/caller/certificate.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,2GAA2G;AAC3G,eAAO,MAAM,aAAa;;;;;;;;;;;iBAiBiE,CAAC;AAC5F,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAE1D,oGAAoG;AACpG,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,UAAU,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,6FAA6F;AAC7F,MAAM,MAAM,iBAAiB,GACzB,mBAAmB,GACnB;IAAE,KAAK,EAAE,QAAQ,CAAA;CAAE,GACnB;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC7C;IAAE,KAAK,EAAE,SAAS,CAAA;CAAE,CAAC;AAEzB,0GAA0G;AAC1G,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,iBAAiB,CA2BzE;AAED,yGAAyG;AACzG,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,kBAAkB,EAAE,SAAS,MAAM,EAAE,CAAC;CACvC;AAOD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,iBAAiB,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAQnG"}
@@ -0,0 +1,92 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ //#region src/caller/certificate.ts
5
+ /**
6
+ * **The client certificate a request arrived with, read off `request.cf.tlsClientAuth` (#560).**
7
+ *
8
+ * mTLS is the option that is sender-constrained at the edge: the zone refuses a caller without a
9
+ * certificate **before the Worker runs**, through a WAF custom rule scoped to the hostname that blocks on
10
+ * `not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked`. Both halves, because a revoked
11
+ * certificate whose chain verifies still reports `cert_verified`. That rule is the gate. **This helper is not.** It is a defense-in-depth check
12
+ * inside the Worker, for the one question the zone rule cannot answer — which of the certificates your CA
13
+ * issued is this — and on its own it blocks nothing: a Worker with no zone rule in front of it still
14
+ * receives every request, certificate or not, and a resolver that forgot to call this would trust them all.
15
+ *
16
+ * Cloudflare-managed client certificates are available on every plan. They need a proxied zone and a
17
+ * hostname that matches exactly — no wildcards, so not `workers.dev`. `docs/server-authoritative.md` has
18
+ * the rule and the setup.
19
+ *
20
+ * **Anything other than `certVerified === "SUCCESS"` is untrusted**, and so is a revoked certificate whose
21
+ * chain did verify. "No certificate" and "a certificate that did not verify" are different states, because
22
+ * the first is an ordinary device and the second is somebody presenting a certificate your CA did not issue,
23
+ * and an adopter's log should be able to tell them apart.
24
+ */
25
+ /** The fields of `request.cf.tlsClientAuth` this reads. Cloudflare sends more; nothing here needs them. */
26
+ const TlsClientAuth = z.object({
27
+ certPresented: z.string().describe("\"1\" when the client presented a certificate, \"0\" when it did not."),
28
+ certVerified: z.string().describe("\"SUCCESS\" when the certificate verified against the zone's CA; \"NONE\" or \"FAILED:<reason>\" otherwise."),
29
+ certRevoked: z.string().describe("\"1\" when the certificate has been revoked, \"0\" when it has not."),
30
+ certIssuerDN: z.string().describe("The issuer's distinguished name."),
31
+ certSubjectDN: z.string().describe("The subject's distinguished name."),
32
+ certSerial: z.string().describe("The certificate's serial number."),
33
+ certFingerprintSHA1: z.string().describe("The certificate's SHA-1 fingerprint, hex."),
34
+ certFingerprintSHA256: z.string().describe("The certificate's SHA-256 fingerprint, hex."),
35
+ certNotBefore: z.string().describe("When the certificate becomes valid."),
36
+ certNotAfter: z.string().describe("When the certificate stops being valid.")
37
+ }).describe("The client-certificate fields Cloudflare puts on `request.cf.tlsClientAuth`.");
38
+ /** Read the client certificate off a request. Never throws: anything it cannot read is not `verified`. */
39
+ function readClientCertificate(request) {
40
+ const cf = request.cf;
41
+ const raw = typeof cf === "object" && cf !== null ? cf.tlsClientAuth : void 0;
42
+ if (typeof raw !== "object" || raw === null) return { state: "absent" };
43
+ const parsed = TlsClientAuth.safeParse(raw);
44
+ if (!parsed.success) {
45
+ if (raw.certPresented === "0") return { state: "absent" };
46
+ const verification = raw.certVerified;
47
+ return {
48
+ state: "unverified",
49
+ verification: typeof verification === "string" ? verification : "unreadable"
50
+ };
51
+ }
52
+ const auth = parsed.data;
53
+ if (auth.certPresented !== "1") return { state: "absent" };
54
+ if (auth.certVerified !== "SUCCESS") return {
55
+ state: "unverified",
56
+ verification: auth.certVerified
57
+ };
58
+ if (auth.certRevoked !== "0") return { state: "revoked" };
59
+ return {
60
+ state: "verified",
61
+ issuerDN: auth.certIssuerDN,
62
+ subjectDN: auth.certSubjectDN,
63
+ serial: auth.certSerial,
64
+ fingerprintSHA1: auth.certFingerprintSHA1,
65
+ fingerprintSHA256: auth.certFingerprintSHA256,
66
+ notBefore: auth.certNotBefore,
67
+ notAfter: auth.certNotAfter
68
+ };
69
+ }
70
+ /** A fingerprint in one spelling: uppercase hex, no separators. */
71
+ function normalizeFingerprint(value) {
72
+ return value.replace(/[^0-9a-fA-F]/g, "").toUpperCase();
73
+ }
74
+ /**
75
+ * Whether a certificate is one this Worker trusts: verified, not revoked, one of the pinned fingerprints,
76
+ * and from the pinned issuer when one is given.
77
+ *
78
+ * **No fingerprint is no trust.** Every certificate the zone's CA issued verifies, so with nothing pinned
79
+ * this would trust a certificate minted for any other purpose under the same account. An issuer pin does
80
+ * not close that: on a shared CA, every certificate behind the zone rule already names that issuer. Pin
81
+ * the fingerprints of the certificates your backend holds, and add the issuer if you like.
82
+ */
83
+ function isTrustedCertificate(certificate, pins) {
84
+ if (certificate.state !== "verified") return false;
85
+ const fingerprints = Array.isArray(pins.fingerprintsSHA256) ? pins.fingerprintsSHA256 : [];
86
+ if (fingerprints.length === 0) return false;
87
+ if (pins.issuerDN !== void 0 && certificate.issuerDN !== pins.issuerDN) return false;
88
+ const presented = normalizeFingerprint(certificate.fingerprintSHA256);
89
+ return presented !== "" && fingerprints.some((pin) => normalizeFingerprint(pin) === presented);
90
+ }
91
+ //#endregion
92
+ export { TlsClientAuth, isTrustedCertificate, readClientCertificate };
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Context } from "hono";
5
+ import { type CallerTokenVerdict } from "./token";
6
+ /**
7
+ * **The caller token, verified off a request, with its key read the one way a secret is read (#560).**
8
+ *
9
+ * This is what a `resolveScopes` calls. It reads the token from {@link CALLER_TOKEN_HEADER} and the key
10
+ * from `@pithy-sh/secrets` — `secretsStore(env, registry)`, never `env.X` — and hands both to
11
+ * `verifyCallerToken`.
12
+ *
13
+ * ```ts
14
+ * auth({
15
+ * baseURL: PUBLIC_ORIGIN,
16
+ * resolveScopes: async (c) =>
17
+ * (await verifyCallerRequest(c, { audience: PUBLIC_ORIGIN })).trusted ? ["leaderboard:submit"] : [],
18
+ * })
19
+ * ```
20
+ *
21
+ * **The key is declared here and supplied by the operator.** Spread {@link callerTokenRegistry} into the
22
+ * `secrets({ registry })` call so `pithy secrets` knows it. The kit does not mint it: the backend that signs
23
+ * with it is the one that needs this option, a backend outside Cloudflare, and nothing in the kit hands a
24
+ * minted value back out. So the operator generates one value, stores it with the backend, and writes the
25
+ * same value here with `pithy secrets create`. A Worker that could read this store would be a Worker of
26
+ * this project, and that one calls over a service binding instead.
27
+ *
28
+ * **Read per call, not through the shared cache.** A token arrives rarely next to a session, and a key
29
+ * read fresh is a rotation that takes effect on the next request. A request with no token reads nothing.
30
+ */
31
+ /** The secret a caller token is signed with. One per environment, supplied by the operator. */
32
+ export declare const CALLER_TOKEN_SECRET = "auth-caller-token-key";
33
+ /** Where an operator is told how to make the caller-token key, hand it to the backend, and replace it. */
34
+ export declare const CALLER_TOKEN_KEY_PAGE = "https://github.com/pithy-sh/pithy/blob/main/packages/auth/docs/server-authoritative.md#the-signing-key";
35
+ /** The registry entry for {@link CALLER_TOKEN_SECRET}. Spread it into the project's `secrets({ registry })`. */
36
+ export declare const callerTokenRegistry: {
37
+ readonly "auth-caller-token-key": {
38
+ readonly backend: "d1";
39
+ readonly scope: "environment";
40
+ readonly rotatable: true;
41
+ readonly valueType: "text";
42
+ readonly origin: {
43
+ readonly kind: "obtained";
44
+ readonly issuer: "other";
45
+ readonly documentation: "https://github.com/pithy-sh/pithy/blob/main/packages/auth/docs/server-authoritative.md#the-signing-key";
46
+ };
47
+ readonly rotation: {
48
+ readonly kind: "manual";
49
+ readonly issuer: "other";
50
+ readonly documentation: "https://github.com/pithy-sh/pithy/blob/main/packages/auth/docs/server-authoritative.md#the-signing-key";
51
+ };
52
+ };
53
+ };
54
+ /** What {@link verifyCallerRequest} takes. */
55
+ export interface VerifyCallerRequestOptions {
56
+ /** This Worker's own public origin — the `baseURL` handed to `auth()`. Never read off the request. */
57
+ audience: string;
58
+ /** A tighter lifetime ceiling than the kit's fifteen minutes. */
59
+ maxLifetimeSeconds?: number;
60
+ }
61
+ /**
62
+ * Verify the caller token on this request. `absent` when there is none — read only from
63
+ * {@link CALLER_TOKEN_HEADER}, never from `Authorization`, which carries the player's forwarded session.
64
+ */
65
+ export declare function verifyCallerRequest(c: Context<PithyHonoEnv>, options: VerifyCallerRequestOptions): Promise<CallerTokenVerdict>;
66
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/caller/request.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAuB,KAAK,kBAAkB,EAAqB,MAAM,SAAS,CAAC;AAE1F;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,+FAA+F;AAC/F,eAAO,MAAM,mBAAmB,0BAA0B,CAAC;AAE3D,0GAA0G;AAC1G,eAAO,MAAM,qBAAqB,2GACwE,CAAC;AAE3G,gHAAgH;AAChH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;CAa9B,CAAC;AAEH,8CAA8C;AAC9C,MAAM,WAAW,0BAA0B;IACzC,sGAAsG;IACtG,QAAQ,EAAE,MAAM,CAAC;IACjB,iEAAiE;IACjE,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;;GAGG;AACH,wBAAsB,mBAAmB,CACvC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EACxB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,kBAAkB,CAAC,CAS7B"}
@@ -0,0 +1,71 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { CALLER_TOKEN_HEADER, verifyCallerToken } from "./token.js";
4
+ import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
5
+ import { secretsStore } from "@pithy-sh/secrets/src/secretsStore";
6
+ //#region src/caller/request.ts
7
+ /**
8
+ * **The caller token, verified off a request, with its key read the one way a secret is read (#560).**
9
+ *
10
+ * This is what a `resolveScopes` calls. It reads the token from {@link CALLER_TOKEN_HEADER} and the key
11
+ * from `@pithy-sh/secrets` — `secretsStore(env, registry)`, never `env.X` — and hands both to
12
+ * `verifyCallerToken`.
13
+ *
14
+ * ```ts
15
+ * auth({
16
+ * baseURL: PUBLIC_ORIGIN,
17
+ * resolveScopes: async (c) =>
18
+ * (await verifyCallerRequest(c, { audience: PUBLIC_ORIGIN })).trusted ? ["leaderboard:submit"] : [],
19
+ * })
20
+ * ```
21
+ *
22
+ * **The key is declared here and supplied by the operator.** Spread {@link callerTokenRegistry} into the
23
+ * `secrets({ registry })` call so `pithy secrets` knows it. The kit does not mint it: the backend that signs
24
+ * with it is the one that needs this option, a backend outside Cloudflare, and nothing in the kit hands a
25
+ * minted value back out. So the operator generates one value, stores it with the backend, and writes the
26
+ * same value here with `pithy secrets create`. A Worker that could read this store would be a Worker of
27
+ * this project, and that one calls over a service binding instead.
28
+ *
29
+ * **Read per call, not through the shared cache.** A token arrives rarely next to a session, and a key
30
+ * read fresh is a rotation that takes effect on the next request. A request with no token reads nothing.
31
+ */
32
+ /** The secret a caller token is signed with. One per environment, supplied by the operator. */
33
+ const CALLER_TOKEN_SECRET = "auth-caller-token-key";
34
+ /** Where an operator is told how to make the caller-token key, hand it to the backend, and replace it. */
35
+ const CALLER_TOKEN_KEY_PAGE = "https://github.com/pithy-sh/pithy/blob/main/packages/auth/docs/server-authoritative.md#the-signing-key";
36
+ /** The registry entry for {@link CALLER_TOKEN_SECRET}. Spread it into the project's `secrets({ registry })`. */
37
+ const callerTokenRegistry = defineSecretRegistry({ [CALLER_TOKEN_SECRET]: {
38
+ backend: "d1",
39
+ scope: "environment",
40
+ rotatable: true,
41
+ valueType: "text",
42
+ origin: {
43
+ kind: "obtained",
44
+ issuer: "other",
45
+ documentation: CALLER_TOKEN_KEY_PAGE
46
+ },
47
+ rotation: {
48
+ kind: "manual",
49
+ issuer: "other",
50
+ documentation: CALLER_TOKEN_KEY_PAGE
51
+ }
52
+ } });
53
+ /**
54
+ * Verify the caller token on this request. `absent` when there is none — read only from
55
+ * {@link CALLER_TOKEN_HEADER}, never from `Authorization`, which carries the player's forwarded session.
56
+ */
57
+ async function verifyCallerRequest(c, options) {
58
+ const token = c.req.header(CALLER_TOKEN_HEADER);
59
+ if (token === void 0 || token === "") return {
60
+ trusted: false,
61
+ reason: "absent"
62
+ };
63
+ const secrets = await secretsStore(c.env, callerTokenRegistry);
64
+ return verifyCallerToken(token, {
65
+ keys: secrets.getVersions(CALLER_TOKEN_SECRET),
66
+ audience: options.audience,
67
+ ...options.maxLifetimeSeconds === void 0 ? {} : { maxLifetimeSeconds: options.maxLifetimeSeconds }
68
+ });
69
+ }
70
+ //#endregion
71
+ export { CALLER_TOKEN_KEY_PAGE, CALLER_TOKEN_SECRET, callerTokenRegistry, verifyCallerRequest };
@@ -0,0 +1,130 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * **A short-lived, audience-restricted caller token — the portable way to prove a request came from the
6
+ * adopter's own backend (#560).**
7
+ *
8
+ * `resolveScopes` asks one question: is this request's caller the adopter's trusted backend, or a device?
9
+ * Where that backend is a Worker, a service binding answers it with no credential at all, and where the
10
+ * zone can run mTLS a client certificate answers it at the edge. Neither works everywhere — a service
11
+ * binding needs both ends on Cloudflare, mTLS needs a proxied zone and an exact hostname, so not
12
+ * `workers.dev`. This is what works on day one anywhere, and it is shipped because the alternative every
13
+ * adopter otherwise reaches for is a long-lived shared secret compared in a header, which fails every
14
+ * control RFC 9700 names at once.
15
+ *
16
+ * So it holds to those controls, each on its own line below:
17
+ *
18
+ * - **Audience-restricted.** `aud` is the origin the token was minted for, and it verifies there and nowhere
19
+ * else — a staging token presented to production is refused, and so is one Worker's token replayed at
20
+ * another that happens to share the key.
21
+ * - **Short-lived.** Five minutes by default, and a ceiling of fifteen that no token and no configuration
22
+ * gets past. A token whose `exp` is a day after its `iat` is refused even when it is otherwise perfect,
23
+ * because honoring it would make it a shared secret with extra steps.
24
+ * - **Signed with a key the Worker reads from `@pithy-sh/secrets`.** The operator supplies it and the
25
+ * backend holds the same value. The `kid` names the stored version the token was signed with, and a kid
26
+ * the store does not hold is refused.
27
+ *
28
+ * What it is not is **sender-constrained**: a token lifted off the wire is usable by whoever lifted it, for
29
+ * the minutes it has left. RFC 9700 says a token SHOULD be bound to its sender, and the two answers are
30
+ * mTLS (`readClientCertificate`) and DPoP, which the kit does not ship yet. Short lifetime is what limits
31
+ * the damage here, which is why the ceiling is not negotiable.
32
+ *
33
+ * **HS256 and nothing else.** One algorithm, one key type, one token shape — the header is validated
34
+ * against a literal, so `alg: none` and an asymmetric algorithm are malformed rather than negotiated. No
35
+ * JWT library: the algorithm agility one brings is where the JWT vulnerabilities live.
36
+ */
37
+ /** The header a caller token travels on. Not `Authorization`, which carries the player's forwarded session. */
38
+ export declare const CALLER_TOKEN_HEADER = "pithy-caller";
39
+ /** How long a minted token lives unless the minter asks for less: five minutes. */
40
+ export declare const DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS: number;
41
+ /**
42
+ * The longest a caller token may live, from its `iat` to its `exp` — fifteen minutes, minted or verified.
43
+ *
44
+ * A ceiling rather than a default, and it refuses above rather than clamping: a verifier configured past it
45
+ * is a configuration error, and a token claiming more is refused. Minutes because the token is a bearer
46
+ * credential with no sender binding, and its lifetime is the whole of what bounds a stolen one.
47
+ */
48
+ export declare const MAX_CALLER_TOKEN_LIFETIME_SECONDS: number;
49
+ /** How far in the future an `iat` may sit before the token is refused — clocks disagree by seconds, not minutes. */
50
+ export declare const CALLER_TOKEN_CLOCK_SKEW_SECONDS = 30;
51
+ /** The protected header of a caller token. */
52
+ export declare const CallerTokenHeader: z.ZodObject<{
53
+ alg: z.ZodLiteral<"HS256">;
54
+ typ: z.ZodOptional<z.ZodLiteral<"JWT">>;
55
+ kid: z.ZodString;
56
+ }, z.core.$strip>;
57
+ export type CallerTokenHeader = z.infer<typeof CallerTokenHeader>;
58
+ /** The claims a caller token carries. */
59
+ export declare const CallerTokenClaims: z.ZodObject<{
60
+ aud: z.ZodString;
61
+ iat: z.ZodNumber;
62
+ exp: z.ZodNumber;
63
+ sub: z.ZodOptional<z.ZodString>;
64
+ }, z.core.$strip>;
65
+ export type CallerTokenClaims = z.infer<typeof CallerTokenClaims>;
66
+ /**
67
+ * Why a caller token was not trusted. Distinct values so the adopter's own log can say which, never so a
68
+ * response can — a resolver answers `[]` for every one of them, and the gate's 403 is the same either way.
69
+ */
70
+ export type CallerTokenRefusal = "absent" | "malformed" | "unknown_key" | "signature" | "audience" | "expired" | "lifetime";
71
+ /** What {@link verifyCallerToken} decided. */
72
+ export type CallerTokenVerdict = {
73
+ trusted: true;
74
+ claims: CallerTokenClaims;
75
+ } | {
76
+ trusted: false;
77
+ reason: CallerTokenRefusal;
78
+ };
79
+ /** A key set in the shape `secretsStore(...).getVersions(name)` answers: version → key. */
80
+ export interface CallerTokenKeys {
81
+ versions: Record<string, string>;
82
+ }
83
+ /** What {@link mintCallerToken} takes. */
84
+ export interface MintCallerTokenOptions {
85
+ /** The caller-token key, the same value the Worker's store holds under `auth-caller-token-key`. */
86
+ key: string;
87
+ /** The version the Worker's store holds it as. `"1"` for any value `pithy secrets create` or `update` wrote. */
88
+ kid: string;
89
+ /** Any URL on the Worker the token will be presented to. Reduced to its origin. */
90
+ audience: string;
91
+ /** Which backend is minting, for the receiving Worker's logs. Optional; it grants nothing. */
92
+ subject?: string;
93
+ /** How long it lives. Defaults to {@link DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS}; never more than the ceiling. */
94
+ lifetimeSeconds?: number;
95
+ /** The clock. Defaults to now. */
96
+ now?: Date;
97
+ }
98
+ /**
99
+ * Mint a caller token — on the **trusted backend**, never on a device.
100
+ *
101
+ * Mint one per call, or per few minutes, and present it on {@link CALLER_TOKEN_HEADER}. A backend that is
102
+ * another Worker in this project reads the key the way the verifier does, through `@pithy-sh/secrets`.
103
+ */
104
+ export declare function mintCallerToken(options: MintCallerTokenOptions): Promise<string>;
105
+ /** What {@link verifyCallerToken} takes. */
106
+ export interface VerifyCallerTokenOptions {
107
+ /** Every still-valid key version, as `getVersions` answers them. */
108
+ keys: CallerTokenKeys;
109
+ /**
110
+ * This Worker's own public origin — the `baseURL` handed to `auth()`. **Never** a value read off the
111
+ * request or the token: a verifier handed the caller's idea of the audience accepts every audience.
112
+ */
113
+ audience: string;
114
+ /** The clock. Defaults to now. */
115
+ now?: Date;
116
+ /** A tighter ceiling than {@link MAX_CALLER_TOKEN_LIFETIME_SECONDS}, for a verifier that wants one. */
117
+ maxLifetimeSeconds?: number;
118
+ }
119
+ /**
120
+ * Decide whether a caller token is one to trust, and why not when it is not.
121
+ *
122
+ * **In this order, and the order is the security model:** structure, then the key, then the signature,
123
+ * then the audience, then the lifetime, then expiry. Nothing about the claims is read as a fact until the
124
+ * signature has verified, so a forgery learns nothing from the answer about how far it got.
125
+ *
126
+ * Returns a verdict rather than throwing, so a resolver can answer `[]` and log the reason. It throws only
127
+ * for its own misconfiguration — a ceiling past the maximum — which `resolveScopes` turns into no scopes.
128
+ */
129
+ export declare function verifyCallerToken(token: string, options: VerifyCallerTokenOptions): Promise<CallerTokenVerdict>;
130
+ //# sourceMappingURL=token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/caller/token.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,+GAA+G;AAC/G,eAAO,MAAM,mBAAmB,iBAAiB,CAAC;AAElD,mFAAmF;AACnF,eAAO,MAAM,qCAAqC,QAAS,CAAC;AAE5D;;;;;;GAMG;AACH,eAAO,MAAM,iCAAiC,QAAU,CAAC;AAEzD,oHAAoH;AACpH,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAElD,8CAA8C;AAC9C,eAAO,MAAM,iBAAiB;;;;iBAMgE,CAAC;AAC/F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE,yCAAyC;AACzC,eAAO,MAAM,iBAAiB;;;;;iBAUmD,CAAC;AAClF,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAC1B,QAAQ,GACR,WAAW,GACX,aAAa,GACb,WAAW,GACX,UAAU,GACV,SAAS,GACT,UAAU,CAAC;AAEf,8CAA8C;AAC9C,MAAM,MAAM,kBAAkB,GAC1B;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,iBAAiB,CAAA;CAAE,GAC5C;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAA;CAAE,CAAC;AAEnD,2FAA2F;AAC3F,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAiED,0CAA0C;AAC1C,MAAM,WAAW,sBAAsB;IACrC,mGAAmG;IACnG,GAAG,EAAE,MAAM,CAAC;IACZ,gHAAgH;IAChH,GAAG,EAAE,MAAM,CAAC;IACZ,mFAAmF;IACnF,QAAQ,EAAE,MAAM,CAAC;IACjB,8FAA8F;IAC9F,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iHAAiH;IACjH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kCAAkC;IAClC,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBtF;AAED,4CAA4C;AAC5C,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,IAAI,EAAE,eAAe,CAAC;IACtB;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,GAAG,CAAC,EAAE,IAAI,CAAC;IACX,uGAAuG;IACvG,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;;;;;;;;GASG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA0CrH"}