@pithy-sh/auth 0.1.1 → 0.1.3

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 (122) hide show
  1. package/dist/admin/users.d.ts +155 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +205 -0
  4. package/dist/audit/actions.d.ts +66 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +66 -0
  7. package/dist/audit/emit.d.ts +101 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +170 -0
  10. package/dist/capability.d.ts +60 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +169 -0
  13. package/dist/client/api.d.ts +299 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +385 -0
  16. package/dist/client/projection.d.ts +51 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +0 -0
  19. package/dist/data/betterAuth.d.ts +75 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +92 -0
  22. package/dist/data/device.d.ts +36 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +33 -0
  25. package/dist/data/kitFields.d.ts +78 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +77 -0
  28. package/dist/data/rotatedToken.d.ts +20 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +22 -0
  31. package/dist/data/tables.d.ts +104 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +30 -0
  34. package/dist/device/registry.d.ts +54 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +85 -0
  37. package/dist/email/send.d.ts +38 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +48 -0
  40. package/dist/http/adminRoutes.d.ts +9 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +274 -0
  43. package/dist/http/baseUrl.d.ts +41 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +96 -0
  46. package/dist/http/csrf.d.ts +18 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +81 -0
  49. package/dist/http/devLoginRoute.d.ts +42 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +112 -0
  52. package/dist/http/errors.d.ts +24 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +67 -0
  55. package/dist/http/guards.d.ts +103 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +148 -0
  58. package/dist/http/middleware.d.ts +17 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +47 -0
  61. package/dist/http/rateLimit.d.ts +17 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +31 -0
  64. package/dist/http/resolve.d.ts +9 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +92 -0
  67. package/dist/http/responses.d.ts +152 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +121 -0
  70. package/dist/http/routes.d.ts +34 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +268 -0
  73. package/dist/http/schemas.d.ts +66 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +59 -0
  76. package/dist/http/views.d.ts +53 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +86 -0
  79. package/dist/i18n/errorCopy.d.ts +24 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +31 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +33 -0
  84. package/dist/i18n/errorCopy.js +91 -0
  85. package/dist/index.d.ts +14 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +8 -0
  88. package/dist/instance/auth.d.ts +1122 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +176 -0
  91. package/dist/instance/plugins.d.ts +87 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +116 -0
  94. package/dist/instance/providers.d.ts +117 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +111 -0
  97. package/dist/instance/secrets.d.ts +163 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +169 -0
  100. package/dist/migrations/0001_init.d.ts +33 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +77 -0
  103. package/dist/migrations/pluginTables.d.ts +126 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +233 -0
  106. package/dist/seeds/devSession.d.ts +124 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +211 -0
  109. package/dist/seeds/example.d.ts +12 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +30 -0
  112. package/dist/test-utils/liveApp.d.ts +227 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +240 -0
  115. package/dist/token/rotation.d.ts +56 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +68 -0
  118. package/dist/version.generated.d.ts +5 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +7 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1,112 @@
1
+ import { authDatabase } from "../data/tables.js";
2
+ import { resolveSessionSecret } from "../instance/secrets.js";
3
+ import { DEV_SESSION_COOKIE_NAME, DEV_SESSION_TOKEN_PREFIX, secretFingerprint, signCookieValue } from "../seeds/devSession.js";
4
+ import { resolveDb } from "./resolve.js";
5
+ import { NotFoundError, fromZodError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { z } from "zod";
7
+ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
8
+ import { ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
9
+ import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
10
+ import { DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
11
+ //#region src/http/devLoginRoute.ts
12
+ /**
13
+ * `GET /__pithy/dev-login` — the seeded session, as a redirect that signs the browser in.
14
+ *
15
+ * The seed already mints a real session row and a real signed cookie. What was missing was a way to
16
+ * *hand it to a browser*: the artifact is a file, and the only route to a browser from a file was the
17
+ * terminal — `document.cookie = "…"`, printed on the ready banner, pasted into a console. That line put
18
+ * a live session token in the one place a credential must never be, which is a place people read, copy,
19
+ * screenshot, and tee into a log. A URL carries the same credential to the same browser without it ever
20
+ * being rendered as text.
21
+ *
22
+ * ## The two gates, and why they are two statements
23
+ *
24
+ * This route mints an authenticated session with **no credential presented**. That is the entire risk of
25
+ * the feature, so it is refused twice, independently:
26
+ *
27
+ * 1. The composition's environment is not `dev`.
28
+ * 2. `CI` is set to any non-blank value — even in a `dev` composition.
29
+ *
30
+ * Neither implies the other. CI runs `dev` compositions constantly (integration suites, packaging
31
+ * checks, `pithy dev` itself), and a developer's laptop is not CI, so "not `dev`" does not cover CI and
32
+ * "not CI" does not cover production. Written as one `||` the pair reads like a single condition, and a
33
+ * single condition is one edit from an `&&` — with a session-minting endpoint answering as the failure
34
+ * mode, silently. Two `if`s, two comments, two tests.
35
+ *
36
+ * ## And the gates are at registration
37
+ *
38
+ * Not inside the handler. A route that exists and refuses is one refactor away from a route that exists
39
+ * and does not, and it is visible in the route table of a production Worker, where its presence alone is
40
+ * a finding. The assertion the tests make is therefore about what a composition *mounts*.
41
+ *
42
+ * **What the CI gate can and cannot see.** In a Worker, `process.env` is the script's bindings and
43
+ * nothing else — the shell's `CI` does not cross into workerd. `pithy dev` forwards it as a var for
44
+ * exactly this reason, so the read is truthful for every Worker Pithy starts; a Worker started some
45
+ * other way in CI is covered only by the environment gate. That is why there are two, and why the
46
+ * second is the one that needs no cooperation.
47
+ */
48
+ function registerDevLoginRoute(wiring, env = ambientEnv()) {
49
+ return (app) => {
50
+ if (compositionEnvironment(env) !== "dev") return;
51
+ if (isContinuousIntegration(env)) return;
52
+ app.get(DEV_LOGIN_ROUTE, (c) => serveDevLogin(c, wiring));
53
+ };
54
+ }
55
+ /**
56
+ * The seeded session row, narrowed to what handing it to a browser needs — and validated, because a D1
57
+ * row is a boundary like any other. `z.input` is the stored row (ISO-8601 text); `z.output` the app shape.
58
+ */
59
+ const DevSessionRow = z.object({
60
+ token: z.string().min(1).describe("The seeded session's opaque token — signed with this environment's secret to make the cookie."),
61
+ expiresAt: JsonDate.describe("When the seeded session expires. ISO-8601 text in SQLite; a `Date` here.")
62
+ }).describe("A seeded dev session, narrowed to the two columns the dev-login redirect needs.");
63
+ /** How long the browser is told to keep the cookie: whatever is left of the seeded session, never longer. */
64
+ function maxAgeSeconds(expiresAt, now) {
65
+ return Math.floor((expiresAt.getTime() - now.getTime()) / 1e3);
66
+ }
67
+ /**
68
+ * The refusal when there is nothing to sign in as. A 404, because the honest answer is that this
69
+ * composition has no seeded session — not that the caller got something wrong.
70
+ *
71
+ * It names `pithy seed` because that is the command that mints one, and it carries no detail about what
72
+ * was searched for: the search key is derived from the signing secret.
73
+ *
74
+ * **In `message`, not in `action` (#344).** `action` is the operator's field and the HTTP codec strips it,
75
+ * because on every other route the caller is somebody who must not be handed a `pithy` command. This route
76
+ * is the exception the gates above already make: it registers only in a `dev` composition outside CI, so
77
+ * the browser at the other end is the developer's own. That is a decision one route makes in the open,
78
+ * which is the opposite of a field nobody classified carrying it everywhere.
79
+ */
80
+ function noSeededSession() {
81
+ return new NotFoundError({ message: "No dev login has been seeded for this environment. Run pithy seed, then open this URL again." });
82
+ }
83
+ /**
84
+ * Serve the seeded session as a `Set-Cookie` and a redirect to `/`.
85
+ *
86
+ * The row is found by the prefix every seeded session carries and **verified against the current
87
+ * signing secret's fingerprint**, which the seed puts in the token for this exact purpose. A session
88
+ * minted before a rotation is a cookie Better Auth will reject, so handing it over would sign nobody in
89
+ * and send the developer hunting through auth for a bug that is a stale seed. Unfound is unfound.
90
+ *
91
+ * Nothing about the cookie is logged, and nothing is written to a response body: the value exists in
92
+ * this handler and in the browser, and in no third place.
93
+ */
94
+ async function serveDevLogin(c, wiring) {
95
+ const secret = await resolveSessionSecret(c.env);
96
+ const fingerprint = await secretFingerprint(secret);
97
+ const found = await authDatabase(resolveDb(c.env, wiring.config.database)).selectFrom("pithyAuthSessions").select(["token", "expiresAt"]).where("token", "like", `${DEV_SESSION_TOKEN_PREFIX}%-${fingerprint}`).orderBy("createdAt", "desc").limit(1).executeTakeFirst();
98
+ if (!found) throw noSeededSession();
99
+ const parsed = DevSessionRow.safeParse(found);
100
+ if (!parsed.success) throw fromZodError(parsed.error, { message: "The seeded dev session is not readable. Run pithy seed to mint a fresh one." });
101
+ const row = parsed.data;
102
+ const maxAge = maxAgeSeconds(row.expiresAt, /* @__PURE__ */ new Date());
103
+ if (maxAge <= 0) throw noSeededSession();
104
+ const value = await signCookieValue(row.token, secret);
105
+ const cookie = `${DEV_SESSION_COOKIE_NAME}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
106
+ return c.body(null, 302, {
107
+ "Set-Cookie": cookie,
108
+ Location: "/"
109
+ });
110
+ }
111
+ //#endregion
112
+ export { registerDevLoginRoute };
@@ -0,0 +1,24 @@
1
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
2
+ /**
3
+ * Translate a thrown Better-Auth `APIError` into the matching `PithyError` subclass, by HTTP status.
4
+ *
5
+ * **What reaches here is a much smaller set than `onAPIError: { throw: true }` suggests.** That option
6
+ * reads as though every endpoint's `APIError` bubbles to the Hono boundary, and none of them do:
7
+ * better-auth's `onError` re-raises (`better-auth/dist/api/index.mjs:193`) straight into better-call's
8
+ * own catch (`better-call@1.4.0`, `dist/router.mjs:83-89`), which renders an `APIError` as a Response
9
+ * and returns it. An endpoint refusal is therefore an ordinary non-2xx answer, and `handleBetterAuth`
10
+ * hands it back untouched (#449).
11
+ *
12
+ * What still arrives is what better-call declined to handle: a non-`APIError` throw from an endpoint
13
+ * (`throw error` at `router.mjs:88` — a database failure, a genuine bug), and a throw from a plugin's
14
+ * `onRequest` hook, which runs outside the router's try. The `isAPIError` branch is kept for those,
15
+ * which can carry one, and because a caller other than the delegating route may hand this anything.
16
+ *
17
+ * The shape, when it is one: `{ statusCode, status, message, body: { message, code } }`. We re-home it
18
+ * in the one `PithyError` family so the HTTP codec owns the response shape and strips `detail`. For 4xx the
19
+ * Better-Auth message is user-actionable and safe to surface (it never reveals account existence —
20
+ * sign-up is silently no-op'd for unknown users); 5xx gets a generic public message. The Better-Auth
21
+ * status + error code stay in `detail` (logs/audit only, never the client).
22
+ */
23
+ export declare function apiErrorToPithy(error: unknown): PithyError;
24
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/http/errors.ts"],"names":[],"mappings":"AAGA,OAAO,EAKL,UAAU,EAIX,MAAM,qCAAqC,CAAC;AAG7C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,CAiC1D"}
@@ -0,0 +1,67 @@
1
+ import { ConflictError, ForbiddenError, InternalError, NotFoundError, PithyError, RateLimitError, UnauthorizedError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
2
+ import { isAPIError } from "better-auth/api";
3
+ //#region src/http/errors.ts
4
+ /**
5
+ * Translate a thrown Better-Auth `APIError` into the matching `PithyError` subclass, by HTTP status.
6
+ *
7
+ * **What reaches here is a much smaller set than `onAPIError: { throw: true }` suggests.** That option
8
+ * reads as though every endpoint's `APIError` bubbles to the Hono boundary, and none of them do:
9
+ * better-auth's `onError` re-raises (`better-auth/dist/api/index.mjs:193`) straight into better-call's
10
+ * own catch (`better-call@1.4.0`, `dist/router.mjs:83-89`), which renders an `APIError` as a Response
11
+ * and returns it. An endpoint refusal is therefore an ordinary non-2xx answer, and `handleBetterAuth`
12
+ * hands it back untouched (#449).
13
+ *
14
+ * What still arrives is what better-call declined to handle: a non-`APIError` throw from an endpoint
15
+ * (`throw error` at `router.mjs:88` — a database failure, a genuine bug), and a throw from a plugin's
16
+ * `onRequest` hook, which runs outside the router's try. The `isAPIError` branch is kept for those,
17
+ * which can carry one, and because a caller other than the delegating route may hand this anything.
18
+ *
19
+ * The shape, when it is one: `{ statusCode, status, message, body: { message, code } }`. We re-home it
20
+ * in the one `PithyError` family so the HTTP codec owns the response shape and strips `detail`. For 4xx the
21
+ * Better-Auth message is user-actionable and safe to surface (it never reveals account existence —
22
+ * sign-up is silently no-op'd for unknown users); 5xx gets a generic public message. The Better-Auth
23
+ * status + error code stay in `detail` (logs/audit only, never the client).
24
+ */
25
+ function apiErrorToPithy(error) {
26
+ if (error instanceof PithyError) return error;
27
+ if (!isAPIError(error)) return new InternalError({
28
+ message: "Authentication failed.",
29
+ detail: error instanceof Error ? error.message : String(error)
30
+ });
31
+ const e = error;
32
+ const status = typeof e.statusCode === "number" ? e.statusCode : 500;
33
+ const publicMessage = e.body?.message ?? e.message ?? "Authentication failed.";
34
+ const detail = `better-auth ${String(e.status)}${e.body?.code ? ` ${e.body.code}` : ""}: ${e.message ?? ""}`.trim();
35
+ switch (status) {
36
+ case 400: return new ValidationError({
37
+ message: publicMessage,
38
+ detail
39
+ });
40
+ case 401: return new UnauthorizedError({
41
+ message: publicMessage,
42
+ detail
43
+ });
44
+ case 403: return new ForbiddenError({
45
+ message: publicMessage,
46
+ detail
47
+ });
48
+ case 404: return new NotFoundError({
49
+ message: publicMessage,
50
+ detail
51
+ });
52
+ case 409: return new ConflictError({
53
+ message: publicMessage,
54
+ detail
55
+ });
56
+ case 429: return new RateLimitError({
57
+ message: publicMessage,
58
+ detail
59
+ });
60
+ default: return new InternalError({
61
+ message: "Authentication failed.",
62
+ detail
63
+ });
64
+ }
65
+ }
66
+ //#endregion
67
+ export { apiErrorToPithy };
@@ -0,0 +1,103 @@
1
+ import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
2
+ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
3
+ /**
4
+ * Auth's control-plane scopes, and the admin surface a manifest advertises.
5
+ *
6
+ * ## The gate is core's; auth contributes only the scope names
7
+ *
8
+ * `requireControlPlane` lives in `@pithy-sh/core/src/controlPlane/http/guard` and every admin route
9
+ * wears it directly. Auth verifies nothing itself: a management call arrives as an EdDSA-signed compact
10
+ * JWS on the `pithy-control-plane` header, and the seam checks the signature against a public key the
11
+ * **adopter** registered, the connection it addresses, that connection's environment, the token's
12
+ * lifetime, a digest of the body, and the token's single use.
13
+ *
14
+ * Importing that gate is not the opposite of `requireAuth` being copied into every other capability; it
15
+ * is the same rule. The rule is never to import authorization from a package that might be absent.
16
+ * `@pithy-sh/core` is a hard dependency of every capability there is, and with the seam *uncomposed*
17
+ * the imported gate raises `controlplane/not_connected` rather than passing. Both halves fail closed.
18
+ *
19
+ * ## `requireAuth()` must never appear on one of these routes
20
+ *
21
+ * This is the sharpest edge in this package, because auth is the capability that *implements*
22
+ * `requireAuth`. A management client is not a user of the adopter's app: it holds no session, owns no
23
+ * user row, and the seam deliberately leaves `c.var.auth` null so a control-plane credential cannot
24
+ * satisfy an ordinary `requireAuth()` anywhere in the tree. An auth gate on an admin route would deny
25
+ * every legitimate management call, permanently, and **no credential could fix it** — there is no user
26
+ * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
27
+ *
28
+ * ## Five scopes, because these are five different blast radii
29
+ *
30
+ * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
31
+ * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
32
+ * one.** A support tool that looks people up should never be able to sign the whole customer base out,
33
+ * and an incident-response tool that kills a stolen session has no business reading every address in
34
+ * the user table. `scopeCovers` matches exactly, with no prefix or wildcard rule, so holding one of
35
+ * these confers nothing whatever about the others — `auth:users` grants none of them.
36
+ *
37
+ * The split within *reads* is between one user and the fleet: `auth:users:read` answers "who is this
38
+ * person", while `auth:devices:read` walks every device of every user, which is a different question
39
+ * with a much larger answer. The split within *writes* is by blast radius: one session, one device, or
40
+ * every session a person has.
41
+ *
42
+ * The names are constants rather than config. A configurable scope name is a way to misconfigure a
43
+ * default-denied gate into a differently-named one, and tooling that read the docs would then hold a
44
+ * scope nothing checks. They are also the join key with what `pithy dashboard connect` offers an
45
+ * adopter to grant, so they must be the same strings in both places.
46
+ *
47
+ * ## There is no impersonation scope, and its absence is deliberate
48
+ *
49
+ * "Sign in as this user" is the most dangerous administrative capability there is: it produces a
50
+ * credential indistinguishable from the user's own, so every action taken with it reads in the trail as
51
+ * theirs. It is excluded from this surface on purpose and is not reachable by composing what is here —
52
+ * nothing below mints a session, and the read routes never project a session token. If it is ever
53
+ * built it gets its own design and its own security review, not a scope added to this list.
54
+ */
55
+ /**
56
+ * Look a user up and read their account: the listing, the search, and one user with their sessions and
57
+ * devices. The privacy-bearing read — it returns email addresses, IPs, and user agents — and by far the
58
+ * most commonly granted, because nearly every dashboard pane resolves to a user.
59
+ */
60
+ export declare const AUTH_USERS_READ_SCOPE: ControlPlaneScope;
61
+ /**
62
+ * Walk the device registry across every user. Separate from reading one user because the question is
63
+ * different in kind: this is fleet-wide, and answers "what is signing in to this product" rather than
64
+ * "what does this person use".
65
+ */
66
+ export declare const AUTH_DEVICES_READ_SCOPE: ControlPlaneScope;
67
+ /**
68
+ * Revoke one named session. The targeted write — what an incident-response tool needs to kill a stolen
69
+ * token, and nothing more. Granting it confers no ability to read who the session belongs to.
70
+ */
71
+ export declare const AUTH_SESSIONS_REVOKE_SCOPE: ControlPlaneScope;
72
+ /**
73
+ * Sign one user out everywhere: every session on every device, at once. The most disruptive thing on
74
+ * this surface — the person is signed out of the product mid-use with no warning — which is exactly why
75
+ * it is granted separately from revoking a single session.
76
+ */
77
+ export declare const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope;
78
+ /**
79
+ * Sign one of a user's devices out and drop its registration, so it must register again at next
80
+ * sign-in. The admin counterpart of the user's own `POST /devices/revoke`, for a phone somebody
81
+ * reported lost — and destructive in a way the session revokes are not, because the device row and its
82
+ * push token go with it.
83
+ */
84
+ export declare const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope;
85
+ /**
86
+ * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
87
+ * and the list a manifest or a doc quotes rather than re-typing.
88
+ */
89
+ export declare const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[];
90
+ /**
91
+ * Auth's management surface, as `GET /control-plane/manifest` reports it.
92
+ *
93
+ * Declared beside the scopes rather than in `adminRoutes.ts`, so the scope a route demands and the
94
+ * scope a manifest advertises are the same constant read from one place. `basePath` is a parameter and
95
+ * never a default: an adopter who mounted auth at `/identity` must get a manifest naming
96
+ * `/identity/admin/users`, or a management client composing its calls from the manifest would 404
97
+ * against exactly the adopters who customized anything.
98
+ *
99
+ * The summaries say what the operation is *for*. A client renders these next to a button somebody is
100
+ * about to press on a real person's account.
101
+ */
102
+ export declare function authAdminRoutes(basePath: string): AdminRoute[];
103
+ //# sourceMappingURL=guards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAA0C,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,EAAE,iBAAyC,CAAC;AAElF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,EAAE,SAAS,iBAAiB,EAMjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAuC9D"}
@@ -0,0 +1,148 @@
1
+ //#region src/http/guards.ts
2
+ /**
3
+ * Auth's control-plane scopes, and the admin surface a manifest advertises.
4
+ *
5
+ * ## The gate is core's; auth contributes only the scope names
6
+ *
7
+ * `requireControlPlane` lives in `@pithy-sh/core/src/controlPlane/http/guard` and every admin route
8
+ * wears it directly. Auth verifies nothing itself: a management call arrives as an EdDSA-signed compact
9
+ * JWS on the `pithy-control-plane` header, and the seam checks the signature against a public key the
10
+ * **adopter** registered, the connection it addresses, that connection's environment, the token's
11
+ * lifetime, a digest of the body, and the token's single use.
12
+ *
13
+ * Importing that gate is not the opposite of `requireAuth` being copied into every other capability; it
14
+ * is the same rule. The rule is never to import authorization from a package that might be absent.
15
+ * `@pithy-sh/core` is a hard dependency of every capability there is, and with the seam *uncomposed*
16
+ * the imported gate raises `controlplane/not_connected` rather than passing. Both halves fail closed.
17
+ *
18
+ * ## `requireAuth()` must never appear on one of these routes
19
+ *
20
+ * This is the sharpest edge in this package, because auth is the capability that *implements*
21
+ * `requireAuth`. A management client is not a user of the adopter's app: it holds no session, owns no
22
+ * user row, and the seam deliberately leaves `c.var.auth` null so a control-plane credential cannot
23
+ * satisfy an ordinary `requireAuth()` anywhere in the tree. An auth gate on an admin route would deny
24
+ * every legitimate management call, permanently, and **no credential could fix it** — there is no user
25
+ * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
26
+ *
27
+ * ## Five scopes, because these are five different blast radii
28
+ *
29
+ * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
30
+ * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
31
+ * one.** A support tool that looks people up should never be able to sign the whole customer base out,
32
+ * and an incident-response tool that kills a stolen session has no business reading every address in
33
+ * the user table. `scopeCovers` matches exactly, with no prefix or wildcard rule, so holding one of
34
+ * these confers nothing whatever about the others — `auth:users` grants none of them.
35
+ *
36
+ * The split within *reads* is between one user and the fleet: `auth:users:read` answers "who is this
37
+ * person", while `auth:devices:read` walks every device of every user, which is a different question
38
+ * with a much larger answer. The split within *writes* is by blast radius: one session, one device, or
39
+ * every session a person has.
40
+ *
41
+ * The names are constants rather than config. A configurable scope name is a way to misconfigure a
42
+ * default-denied gate into a differently-named one, and tooling that read the docs would then hold a
43
+ * scope nothing checks. They are also the join key with what `pithy dashboard connect` offers an
44
+ * adopter to grant, so they must be the same strings in both places.
45
+ *
46
+ * ## There is no impersonation scope, and its absence is deliberate
47
+ *
48
+ * "Sign in as this user" is the most dangerous administrative capability there is: it produces a
49
+ * credential indistinguishable from the user's own, so every action taken with it reads in the trail as
50
+ * theirs. It is excluded from this surface on purpose and is not reachable by composing what is here —
51
+ * nothing below mints a session, and the read routes never project a session token. If it is ever
52
+ * built it gets its own design and its own security review, not a scope added to this list.
53
+ */
54
+ /**
55
+ * Look a user up and read their account: the listing, the search, and one user with their sessions and
56
+ * devices. The privacy-bearing read — it returns email addresses, IPs, and user agents — and by far the
57
+ * most commonly granted, because nearly every dashboard pane resolves to a user.
58
+ */
59
+ const AUTH_USERS_READ_SCOPE = "auth:users:read";
60
+ /**
61
+ * Walk the device registry across every user. Separate from reading one user because the question is
62
+ * different in kind: this is fleet-wide, and answers "what is signing in to this product" rather than
63
+ * "what does this person use".
64
+ */
65
+ const AUTH_DEVICES_READ_SCOPE = "auth:devices:read";
66
+ /**
67
+ * Revoke one named session. The targeted write — what an incident-response tool needs to kill a stolen
68
+ * token, and nothing more. Granting it confers no ability to read who the session belongs to.
69
+ */
70
+ const AUTH_SESSIONS_REVOKE_SCOPE = "auth:sessions:revoke";
71
+ /**
72
+ * Sign one user out everywhere: every session on every device, at once. The most disruptive thing on
73
+ * this surface — the person is signed out of the product mid-use with no warning — which is exactly why
74
+ * it is granted separately from revoking a single session.
75
+ */
76
+ const AUTH_USERS_LOGOUT_SCOPE = "auth:users:logout";
77
+ /**
78
+ * Sign one of a user's devices out and drop its registration, so it must register again at next
79
+ * sign-in. The admin counterpart of the user's own `POST /devices/revoke`, for a phone somebody
80
+ * reported lost — and destructive in a way the session revokes are not, because the device row and its
81
+ * push token go with it.
82
+ */
83
+ const AUTH_DEVICES_REVOKE_SCOPE = "auth:devices:revoke";
84
+ /**
85
+ * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
86
+ * and the list a manifest or a doc quotes rather than re-typing.
87
+ */
88
+ const AUTH_CONTROL_PLANE_SCOPES = [
89
+ AUTH_USERS_READ_SCOPE,
90
+ AUTH_DEVICES_READ_SCOPE,
91
+ AUTH_SESSIONS_REVOKE_SCOPE,
92
+ AUTH_USERS_LOGOUT_SCOPE,
93
+ AUTH_DEVICES_REVOKE_SCOPE
94
+ ];
95
+ /**
96
+ * Auth's management surface, as `GET /control-plane/manifest` reports it.
97
+ *
98
+ * Declared beside the scopes rather than in `adminRoutes.ts`, so the scope a route demands and the
99
+ * scope a manifest advertises are the same constant read from one place. `basePath` is a parameter and
100
+ * never a default: an adopter who mounted auth at `/identity` must get a manifest naming
101
+ * `/identity/admin/users`, or a management client composing its calls from the manifest would 404
102
+ * against exactly the adopters who customized anything.
103
+ *
104
+ * The summaries say what the operation is *for*. A client renders these next to a button somebody is
105
+ * about to press on a real person's account.
106
+ */
107
+ function authAdminRoutes(basePath) {
108
+ return [
109
+ {
110
+ method: "GET",
111
+ path: `${basePath}/admin/users`,
112
+ scope: AUTH_USERS_READ_SCOPE,
113
+ summary: "Find a user. Lists everyone newest first, or searches email and display name."
114
+ },
115
+ {
116
+ method: "GET",
117
+ path: `${basePath}/admin/users/:userId`,
118
+ scope: AUTH_USERS_READ_SCOPE,
119
+ summary: "One user, with where they are signed in and what they sign in with."
120
+ },
121
+ {
122
+ method: "GET",
123
+ path: `${basePath}/admin/devices`,
124
+ scope: AUTH_DEVICES_READ_SCOPE,
125
+ summary: "The device registry across users, most-recently-seen first."
126
+ },
127
+ {
128
+ method: "POST",
129
+ path: `${basePath}/admin/sessions/revoke`,
130
+ scope: AUTH_SESSIONS_REVOKE_SCOPE,
131
+ summary: "Kill one session. The rest of that person's sign-ins keep working."
132
+ },
133
+ {
134
+ method: "POST",
135
+ path: `${basePath}/admin/users/:userId/sessions/revoke`,
136
+ scope: AUTH_USERS_LOGOUT_SCOPE,
137
+ summary: "Sign a user out everywhere, on every device, immediately."
138
+ },
139
+ {
140
+ method: "POST",
141
+ path: `${basePath}/admin/users/:userId/devices/revoke`,
142
+ scope: AUTH_DEVICES_REVOKE_SCOPE,
143
+ summary: "Sign one device out and forget it — for a phone reported lost."
144
+ }
145
+ ];
146
+ }
147
+ //#endregion
148
+ export { AUTH_CONTROL_PLANE_SCOPES, AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE, authAdminRoutes };
@@ -0,0 +1,17 @@
1
+ import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
2
+ import type { MiddlewareHandler } from "hono";
3
+ import type { AuthWiring } from "../capability";
4
+ /**
5
+ * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
6
+ * request that carries a credential — a bearer token or a session cookie. Better Auth resolves both
7
+ * transparently (the bearer plugin rewrites the header into the session cookie), so one `getSession`
8
+ * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
9
+ * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
10
+ */
11
+ export declare function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware;
12
+ /**
13
+ * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
14
+ * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
15
+ */
16
+ export declare function requireAuth(): MiddlewareHandler<PithyHonoEnv>;
17
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAgC3E;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
@@ -0,0 +1,47 @@
1
+ import { getAuthInstance } from "./resolve.js";
2
+ import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
3
+ import { isLocale } from "@pithy-sh/core/src/i18n/locale";
4
+ import { AuthContext } from "@pithy-sh/core/src/http/authContext";
5
+ //#region src/http/middleware.ts
6
+ /**
7
+ * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
8
+ * request that carries a credential — a bearer token or a session cookie. Better Auth resolves both
9
+ * transparently (the bearer plugin rewrites the header into the session cookie), so one `getSession`
10
+ * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
11
+ * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
12
+ */
13
+ function createSessionMiddleware(wiring) {
14
+ return (app) => {
15
+ app.use("*", async (c, next) => {
16
+ const headers = c.req.raw.headers;
17
+ if (headers.has("authorization") || headers.has("cookie")) try {
18
+ const session = await (await getAuthInstance(c, wiring)).api.getSession({ headers });
19
+ if (session) {
20
+ const stored = session.user.locale;
21
+ c.set("auth", AuthContext.parse({
22
+ userId: session.user.id,
23
+ sessionId: session.session.id,
24
+ scopes: [],
25
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null
26
+ }));
27
+ }
28
+ } catch {}
29
+ await next();
30
+ });
31
+ };
32
+ }
33
+ /**
34
+ * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
35
+ * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
36
+ */
37
+ function requireAuth() {
38
+ return async (c, next) => {
39
+ if (!c.var.auth) throw new UnauthorizedError({
40
+ message: "Authentication required.",
41
+ action: "Sign in and retry with a valid session or bearer token."
42
+ });
43
+ await next();
44
+ };
45
+ }
46
+ //#endregion
47
+ export { createSessionMiddleware, requireAuth };
@@ -0,0 +1,17 @@
1
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
2
+ import type { MiddlewareHandler } from "hono";
3
+ /**
4
+ * Tier 1 of two: the coarse edge rate limiter.
5
+ *
6
+ * Cloudflare's native Workers Rate Limiting binding caps requests per client IP at the edge with no
7
+ * storage round-trip — blunting floods and credential-stuffing before they reach Better Auth's
8
+ * per-action D1 limiter (tier 2: the 5/min magic-link and 3/min OTP caps, keyed per identity). Two
9
+ * limiters, two jobs: this one is a cheap per-IP flood guard across every auth route; tier 2 is the
10
+ * fine-grained per-action cap.
11
+ *
12
+ * Keys on `cf-connecting-ip`. The limit and window are set on the binding in `wrangler.jsonc`, not
13
+ * here. Skips only when the binding is absent (local dev / tests) — in a real deployment the binding is
14
+ * a required binding, enforced at compose.
15
+ */
16
+ export declare function createRateLimitMiddleware(bindingName: string): MiddlewareHandler<PithyHonoEnv>;
17
+ //# sourceMappingURL=rateLimit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rateLimit.d.ts","sourceRoot":"","sources":["../../src/http/rateLimit.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,MAAM,GAAG,iBAAiB,CAAC,YAAY,CAAC,CAe9F"}
@@ -0,0 +1,31 @@
1
+ import { RateLimitError } from "@pithy-sh/core/src/error/pithyError";
2
+ //#region src/http/rateLimit.ts
3
+ /**
4
+ * Tier 1 of two: the coarse edge rate limiter.
5
+ *
6
+ * Cloudflare's native Workers Rate Limiting binding caps requests per client IP at the edge with no
7
+ * storage round-trip — blunting floods and credential-stuffing before they reach Better Auth's
8
+ * per-action D1 limiter (tier 2: the 5/min magic-link and 3/min OTP caps, keyed per identity). Two
9
+ * limiters, two jobs: this one is a cheap per-IP flood guard across every auth route; tier 2 is the
10
+ * fine-grained per-action cap.
11
+ *
12
+ * Keys on `cf-connecting-ip`. The limit and window are set on the binding in `wrangler.jsonc`, not
13
+ * here. Skips only when the binding is absent (local dev / tests) — in a real deployment the binding is
14
+ * a required binding, enforced at compose.
15
+ */
16
+ function createRateLimitMiddleware(bindingName) {
17
+ return async (c, next) => {
18
+ const limiter = c.env[bindingName];
19
+ if (limiter && typeof limiter.limit === "function") {
20
+ const key = c.req.raw.headers.get("cf-connecting-ip") ?? "anonymous";
21
+ const { success } = await limiter.limit({ key });
22
+ if (!success) throw new RateLimitError({
23
+ message: "Too many requests.",
24
+ action: "Slow down and retry in a moment."
25
+ });
26
+ }
27
+ await next();
28
+ };
29
+ }
30
+ //#endregion
31
+ export { createRateLimitMiddleware };
@@ -0,0 +1,9 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
3
+ import type { Context } from "hono";
4
+ import type { AuthWiring } from "../capability";
5
+ import { type AuthInstance } from "../instance/auth";
6
+ /** Read the configured D1 binding by name from the worker env, or fail loudly (not a silent undefined). */
7
+ export declare function resolveDb(env: Record<string, unknown>, bindingName: string): D1Database;
8
+ export declare function getAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring): Promise<AuthInstance>;
9
+ //# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAqB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}