@pithy-sh/auth 0.1.2 → 0.1.4

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 +157 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +207 -0
  4. package/dist/audit/actions.d.ts +68 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +68 -0
  7. package/dist/audit/emit.d.ts +103 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +172 -0
  10. package/dist/capability.d.ts +62 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +171 -0
  13. package/dist/client/api.d.ts +301 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +387 -0
  16. package/dist/client/projection.d.ts +53 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +2 -0
  19. package/dist/data/betterAuth.d.ts +77 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +94 -0
  22. package/dist/data/device.d.ts +38 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +35 -0
  25. package/dist/data/kitFields.d.ts +80 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +79 -0
  28. package/dist/data/rotatedToken.d.ts +22 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +24 -0
  31. package/dist/data/tables.d.ts +106 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +32 -0
  34. package/dist/device/registry.d.ts +56 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +87 -0
  37. package/dist/email/send.d.ts +40 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +50 -0
  40. package/dist/http/adminRoutes.d.ts +11 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +276 -0
  43. package/dist/http/baseUrl.d.ts +43 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +98 -0
  46. package/dist/http/csrf.d.ts +20 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +83 -0
  49. package/dist/http/devLoginRoute.d.ts +44 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +114 -0
  52. package/dist/http/errors.d.ts +26 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +69 -0
  55. package/dist/http/guards.d.ts +105 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +150 -0
  58. package/dist/http/middleware.d.ts +19 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +49 -0
  61. package/dist/http/rateLimit.d.ts +19 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +33 -0
  64. package/dist/http/resolve.d.ts +11 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +94 -0
  67. package/dist/http/responses.d.ts +154 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +123 -0
  70. package/dist/http/routes.d.ts +36 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +270 -0
  73. package/dist/http/schemas.d.ts +68 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +61 -0
  76. package/dist/http/views.d.ts +55 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +88 -0
  79. package/dist/i18n/errorCopy.d.ts +26 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +33 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +35 -0
  84. package/dist/i18n/errorCopy.js +93 -0
  85. package/dist/index.d.ts +16 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +10 -0
  88. package/dist/instance/auth.d.ts +1124 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +178 -0
  91. package/dist/instance/plugins.d.ts +89 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +118 -0
  94. package/dist/instance/providers.d.ts +119 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +113 -0
  97. package/dist/instance/secrets.d.ts +165 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +171 -0
  100. package/dist/migrations/0001_init.d.ts +35 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +79 -0
  103. package/dist/migrations/pluginTables.d.ts +128 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +235 -0
  106. package/dist/seeds/devSession.d.ts +126 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +213 -0
  109. package/dist/seeds/example.d.ts +14 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +32 -0
  112. package/dist/test-utils/liveApp.d.ts +229 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +242 -0
  115. package/dist/token/rotation.d.ts +58 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +70 -0
  118. package/dist/version.generated.d.ts +7 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +9 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sour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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUtD"}
@@ -0,0 +1,178 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit.js";
4
+ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields.js";
5
+ import { parseDeviceMeta, registerDevice } from "../device/registry.js";
6
+ import { kitPlugins } from "./plugins.js";
7
+ import { providerUnavailable, unavailableProviderFor } from "./providers.js";
8
+ import { betterAuth } from "better-auth";
9
+ import { APIError, createAuthMiddleware } from "better-auth/api";
10
+ //#region src/instance/auth.ts
11
+ /**
12
+ * Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
13
+ * per-provider branch matrix is unit-testable without constructing a Better Auth instance — it reads
14
+ * only the resolved credentials on `deps`, never the database.
15
+ *
16
+ * **Only a `ready` provider is registered.** A `disabled` one never was; an `unresolvable` one is the
17
+ * change #381 made, and it is what keeps magic link and OTP working while one credential is unreadable.
18
+ * The narrowing is the type's doing rather than this function's discipline — `deps.google.credentials`
19
+ * does not exist until `state === "ready"` has been established.
20
+ */
21
+ function socialProviders(deps) {
22
+ const providers = {};
23
+ if (deps.google.state === "ready") providers.google = {
24
+ clientId: deps.google.credentials.clientId,
25
+ clientSecret: deps.google.credentials.clientSecret,
26
+ accessType: "offline",
27
+ prompt: "select_account consent"
28
+ };
29
+ if (deps.apple.state === "ready") {
30
+ const apple = deps.apple.credentials;
31
+ providers.apple = {
32
+ clientId: apple.clientId,
33
+ clientSecret: apple.clientSecret,
34
+ ...apple.appBundleIdentifier ? { appBundleIdentifier: apple.appBundleIdentifier } : {}
35
+ };
36
+ }
37
+ if (deps.facebook.state === "ready") providers.facebook = {
38
+ clientId: deps.facebook.credentials.clientId,
39
+ clientSecret: deps.facebook.credentials.clientSecret,
40
+ scope: ["email"],
41
+ mapProfileToUser: () => ({ emailVerified: true })
42
+ };
43
+ if (deps.github.state === "ready") providers.github = {
44
+ clientId: deps.github.credentials.clientId,
45
+ clientSecret: deps.github.credentials.clientSecret,
46
+ scope: ["user:email"]
47
+ };
48
+ return Object.keys(providers).length > 0 ? providers : void 0;
49
+ }
50
+ /**
51
+ * The seeding guard: a new account may be created only for an email a provider has **verified**.
52
+ *
53
+ * Passwordless sign-up (magic link / OTP) always creates `emailVerified: true`; a social sign-up
54
+ * carries the provider's own flag. Refusing an unverified-email create closes the rival-account
55
+ * seeding vector — otherwise an untrusted provider (e.g. a GitHub account holding an *unverified*
56
+ * email at someone else's address) could mint a row that a later magic-link login by the true owner
57
+ * would inherit. Returns `true` when the create must be refused. Account *linking* into an existing
58
+ * user is handled separately by Better Auth's `trustedProviders` gate; this only guards creation.
59
+ */
60
+ function isUnverifiedSignup(user) {
61
+ return user.emailVerified !== true;
62
+ }
63
+ /**
64
+ * Build the Better-Auth instance for one request.
65
+ *
66
+ * Passwordless only — `emailAndPassword` is never enabled. The Kysely adapter wraps our shared
67
+ * `CamelCasePlugin` instance, so Better Auth's camelCase model names + fields map to the snake_case
68
+ * `pithy_auth_*` columns the migration created. Dates are ISO-8601 text on SQLite; ids are WebCrypto
69
+ * UUIDs; rate limiting is durable (D1-backed) since memory limiting is per-isolate on Workers.
70
+ */
71
+ function makeAuth(deps) {
72
+ return betterAuth({
73
+ appName: "Pithy",
74
+ baseURL: deps.baseURL,
75
+ basePath: deps.basePath,
76
+ secret: deps.secret,
77
+ telemetry: { enabled: false },
78
+ trustedOrigins: deps.trustedOrigins,
79
+ database: {
80
+ db: deps.db,
81
+ type: "sqlite",
82
+ transaction: false
83
+ },
84
+ advanced: { database: { generateId: () => crypto.randomUUID() } },
85
+ onAPIError: { throw: true },
86
+ databaseHooks: {
87
+ user: { create: { before: async (user) => {
88
+ if (isUnverifiedSignup(user)) throw new APIError("FORBIDDEN", {
89
+ code: "EMAIL_NOT_VERIFIED",
90
+ message: "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider."
91
+ });
92
+ } } },
93
+ session: { create: { before: async (session, ctx) => {
94
+ const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : void 0;
95
+ if (!meta) return;
96
+ await registerDevice(deps.db, meta, {
97
+ userId: session.userId,
98
+ lastIp: session.ipAddress ?? null,
99
+ now: /* @__PURE__ */ new Date()
100
+ });
101
+ return { data: {
102
+ ...session,
103
+ deviceId: meta.id
104
+ } };
105
+ } } }
106
+ },
107
+ hooks: {
108
+ /**
109
+ * Refuse a provider this deployment enables and could not resolve, before Better Auth answers it
110
+ * with the 404 it gives a provider nobody configured (#381).
111
+ *
112
+ * **This is what makes degrading not the same as degrading quietly.** The instance was built
113
+ * without the provider, so `socialProviders` does not hold it, so `sign-in/social` would throw
114
+ * `PROVIDER_NOT_FOUND` — a 404 that tells somebody who signs in with GitHub every day that
115
+ * GitHub was never set up. It is the same answer for a fault and for a choice, and the two are
116
+ * not the same fact. This hook answers 503 with its own code instead, and records the attempt.
117
+ *
118
+ * **A `before` hook rather than a Hono route, and that is forced rather than preferred.** The
119
+ * provider is in the request *body*, and the body is Better Auth's to read: a Hono handler ahead
120
+ * of the catch-all would have to consume the stream that the catch-all then hands to
121
+ * `instance.handler(c.req.raw)`. Here the body is already parsed against the endpoint's own
122
+ * schema, and this reads one field out of it.
123
+ */
124
+ before: createAuthMiddleware(async (ctx) => {
125
+ const provider = unavailableProviderFor(ctx.path ?? "", ctx.body, deps);
126
+ if (!provider) return;
127
+ await emitProviderUnavailable(deps.emit, {
128
+ provider,
129
+ headers: ctx.headers
130
+ });
131
+ throw providerUnavailable(provider);
132
+ }),
133
+ after: createAuthMiddleware(async (ctx) => {
134
+ const newSession = ctx.context.newSession;
135
+ await emitAfterRequest(deps.emit, {
136
+ path: ctx.path ?? "",
137
+ headers: ctx.headers,
138
+ newSession: newSession ? {
139
+ userId: newSession.user.id,
140
+ sessionId: newSession.session.id,
141
+ deviceId: newSession.session.deviceId ?? null
142
+ } : null,
143
+ currentUserId: ctx.context.session?.user?.id ?? null
144
+ });
145
+ })
146
+ },
147
+ rateLimit: {
148
+ enabled: true,
149
+ storage: "database",
150
+ modelName: "pithyAuthRateLimit"
151
+ },
152
+ user: {
153
+ modelName: "pithyAuthUsers",
154
+ additionalFields: KIT_USER_FIELDS
155
+ },
156
+ session: {
157
+ modelName: "pithyAuthSessions",
158
+ expiresIn: deps.sessionExpiresIn,
159
+ updateAge: deps.sessionUpdateAge,
160
+ additionalFields: KIT_SESSION_FIELDS
161
+ },
162
+ account: {
163
+ modelName: "pithyAuthAccounts",
164
+ accountLinking: {
165
+ enabled: true,
166
+ trustedProviders: ["google", "apple"]
167
+ }
168
+ },
169
+ verification: { modelName: "pithyAuthVerifications" },
170
+ ...(() => {
171
+ const providers = socialProviders(deps);
172
+ return providers ? { socialProviders: providers } : {};
173
+ })(),
174
+ plugins: [...kitPlugins(deps), ...deps.plugins]
175
+ });
176
+ }
177
+ //#endregion
178
+ export { isUnverifiedSignup, makeAuth, socialProviders };
@@ -0,0 +1,89 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { BetterAuthPlugin } from "better-auth";
4
+ import { bearer } from "better-auth/plugins/bearer";
5
+ import { emailOTP } from "better-auth/plugins/email-otp";
6
+ import { jwt } from "better-auth/plugins/jwt";
7
+ import { magicLink } from "better-auth/plugins/magic-link";
8
+ import { z } from "zod";
9
+ import type { SendAuthEmail } from "./auth";
10
+ /**
11
+ * The four Better Auth plugins the kit composes for itself, and the reason they are fixed.
12
+ *
13
+ * `magic-link` and `email-otp` **are** the sign-in this product promises — passwordless, no
14
+ * `emailAndPassword` anywhere. `jwt` mints the JWKS the control-plane seam verifies against and
15
+ * `bearer` is how a mobile client presents its credential. Every one of them is depended on by code
16
+ * outside this package, so an adopter who removed or redefined one would break a contract they cannot
17
+ * see from their config. The adopter's list is therefore **additive**: it extends this set, never
18
+ * replaces a member of it.
19
+ */
20
+ export declare const KIT_PLUGIN_IDS: readonly ["i18n", "bearer", "jwt", "magic-link", "email-otp"];
21
+ /** What the kit's own plugins need to be constructed. The subset of `AuthInstanceDeps` they read. */
22
+ export interface KitPluginDeps {
23
+ /** Magic-link / OTP token lifetime in seconds. */
24
+ verificationExpiresIn: number;
25
+ /** OTP length (digits). */
26
+ otpLength: number;
27
+ /** When true, sign-in never provisions a new user (existing accounts only). */
28
+ disableSignUp: boolean;
29
+ /** Deliver a magic link or OTP. Enqueues an email job; never sends inline. */
30
+ sendEmail: SendAuthEmail;
31
+ /**
32
+ * The catalog locale this request negotiated, or `null`/absent when nothing did.
33
+ *
34
+ * Read from `c.var.locale` where the instance is built, which is per request — so this is the locale
35
+ * the *project* resolved through its own configured chain, never a second negotiation of Better
36
+ * Auth's own. Without that a reader who chose Spanish with `?lang=es` would get Spanish screens and
37
+ * English refusals on the same page, because the two chains ask different signals in different
38
+ * orders (#452).
39
+ *
40
+ * `null` is the ordinary state of a project that never composed `i18n`, and it means English — which
41
+ * is what the plugin answers with anyway, so its absence is not a special case.
42
+ */
43
+ locale?: string | null;
44
+ }
45
+ /**
46
+ * The kit's four, as a **tuple** rather than an array. Better Auth infers a composed instance's whole
47
+ * `$Infer` surface from the element types of its `plugins` list, so widening this to
48
+ * `BetterAuthPlugin[]` here would erase the adopter's plugin types one line later, where `makeAuth`
49
+ * spreads the two lists together.
50
+ */
51
+ export type KitPlugins = [
52
+ BetterAuthPlugin,
53
+ ReturnType<typeof bearer>,
54
+ ReturnType<typeof jwt>,
55
+ ReturnType<typeof magicLink>,
56
+ ReturnType<typeof emailOTP>
57
+ ];
58
+ /**
59
+ * Build the kit's own plugins. **One definition, two readers**: `makeAuth` composes these into the
60
+ * live instance, and the migration builder composes the same four into the baseline schema it diffs an
61
+ * adopter's plugins against. Two copies of this list would be drift that no test could see — the
62
+ * baseline would claim a table the instance never created, or miss one it did.
63
+ */
64
+ export declare function kitPlugins(deps: KitPluginDeps): KitPlugins;
65
+ /**
66
+ * One additional Better Auth plugin, validated at the config boundary.
67
+ *
68
+ * `z.custom` rather than a `z.object`, and deliberately: a plugin is a live object carrying endpoints,
69
+ * hooks and an `init` closure, and an object schema would hand back a **copy** — a different object from
70
+ * the one Better Auth was given, with whatever the schema did not name quietly dropped. What can be
71
+ * checked without rebuilding it is checked: it is an object, and it has the `id` every other rule here
72
+ * (reservation, duplication, migration keys, `pithy doctor`) is written in terms of.
73
+ */
74
+ export declare const AuthPlugin: z.ZodCustom<BetterAuthPlugin, BetterAuthPlugin>;
75
+ /**
76
+ * Refuse a plugin list that is not purely additive, naming the offending plugin.
77
+ *
78
+ * Two ways it can fail, and both name a single id because that is what the adopter has to go delete:
79
+ * a plugin whose id is one of {@link KIT_PLUGIN_IDS} would sit beside the kit's own copy (Better Auth
80
+ * merges endpoints by id — the later registration silently wins, so this is a redefinition even when it
81
+ * reads like an addition), and two plugins sharing an id do the same to each other.
82
+ *
83
+ * **The `message` stays short on purpose.** `auth()` runs while `pithy.config.ts` is being imported, so
84
+ * the CLI catches this through `classifyConfigLoadFailure`, which prints the cause's message and nothing
85
+ * else — and drops it entirely past 160 characters (`safeReason`). A refusal whose whole content is in
86
+ * its `action` reaches the adopter as "the config threw while loading", which names nothing.
87
+ */
88
+ export declare function assertAdditivePlugins(plugins: readonly BetterAuthPlugin[]): void;
89
+ //# sourceMappingURL=plugins.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../../src/instance/plugins.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAC3D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAE5C;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,YAAI,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,CAAU,CAAC;AAE5F,qGAAqG;AACrG,MAAM,WAAW,aAAa;IAC5B,kDAAkD;IAClD,qBAAqB,EAAE,MAAM,CAAC;IAC9B,2BAA2B;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,aAAa,EAAE,OAAO,CAAC;IACvB,8EAA8E;IAC9E,SAAS,EAAE,aAAa,CAAC;IACzB;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED;;;;;GAKG;AACH,MAAM,MAAM,UAAU,GAAG;IAKvB,gBAAgB;IAChB,UAAU,CAAC,OAAO,MAAM,CAAC;IACzB,UAAU,CAAC,OAAO,GAAG,CAAC;IACtB,UAAU,CAAC,OAAO,SAAS,CAAC;IAC5B,UAAU,CAAC,OAAO,QAAQ,CAAC;CAC5B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,aAAa,GAAG,UAAU,CAqC1D;AASD;;;;;;;;GAQG;AACH,eAAO,MAAM,UAAU,iDAMpB,CAAC;AAEJ;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,SAAS,gBAAgB,EAAE,GAAG,IAAI,CAoBhF"}
@@ -0,0 +1,118 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { authErrorTranslations } from "../i18n/errorCopy.js";
4
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { z } from "zod";
6
+ import { i18n } from "@better-auth/i18n";
7
+ import { bearer } from "better-auth/plugins/bearer";
8
+ import { emailOTP } from "better-auth/plugins/email-otp";
9
+ import { jwt } from "better-auth/plugins/jwt";
10
+ import { magicLink } from "better-auth/plugins/magic-link";
11
+ //#region src/instance/plugins.ts
12
+ /**
13
+ * The four Better Auth plugins the kit composes for itself, and the reason they are fixed.
14
+ *
15
+ * `magic-link` and `email-otp` **are** the sign-in this product promises — passwordless, no
16
+ * `emailAndPassword` anywhere. `jwt` mints the JWKS the control-plane seam verifies against and
17
+ * `bearer` is how a mobile client presents its credential. Every one of them is depended on by code
18
+ * outside this package, so an adopter who removed or redefined one would break a contract they cannot
19
+ * see from their config. The adopter's list is therefore **additive**: it extends this set, never
20
+ * replaces a member of it.
21
+ */
22
+ const KIT_PLUGIN_IDS = [
23
+ "i18n",
24
+ "bearer",
25
+ "jwt",
26
+ "magic-link",
27
+ "email-otp"
28
+ ];
29
+ /**
30
+ * Build the kit's own plugins. **One definition, two readers**: `makeAuth` composes these into the
31
+ * live instance, and the migration builder composes the same four into the baseline schema it diffs an
32
+ * adopter's plugins against. Two copies of this list would be drift that no test could see — the
33
+ * baseline would claim a table the instance never created, or miss one it did.
34
+ */
35
+ function kitPlugins(deps) {
36
+ return [
37
+ i18n({
38
+ translations: authErrorTranslations(),
39
+ detection: ["callback"],
40
+ getLocale: () => deps.locale ?? null
41
+ }),
42
+ bearer(),
43
+ jwt({ schema: { jwks: { modelName: "pithyAuthJwks" } } }),
44
+ magicLink({
45
+ expiresIn: deps.verificationExpiresIn,
46
+ disableSignUp: deps.disableSignUp,
47
+ sendMagicLink: async ({ email, url, token }) => {
48
+ await deps.sendEmail({
49
+ to: email,
50
+ template: "magicLink",
51
+ token,
52
+ url
53
+ });
54
+ }
55
+ }),
56
+ emailOTP({
57
+ otpLength: deps.otpLength,
58
+ expiresIn: deps.verificationExpiresIn,
59
+ disableSignUp: deps.disableSignUp,
60
+ sendVerificationOTP: async ({ email, otp, type }) => {
61
+ if (type !== "sign-in") return;
62
+ await deps.sendEmail({
63
+ to: email,
64
+ template: "otp",
65
+ code: otp
66
+ });
67
+ }
68
+ })
69
+ ];
70
+ }
71
+ /** Is this value shaped like a Better Auth plugin — an object carrying a non-empty string `id`? */
72
+ function isBetterAuthPlugin(value) {
73
+ if (typeof value !== "object" || value === null) return false;
74
+ const id = value.id;
75
+ return typeof id === "string" && id.length > 0;
76
+ }
77
+ /**
78
+ * One additional Better Auth plugin, validated at the config boundary.
79
+ *
80
+ * `z.custom` rather than a `z.object`, and deliberately: a plugin is a live object carrying endpoints,
81
+ * hooks and an `init` closure, and an object schema would hand back a **copy** — a different object from
82
+ * the one Better Auth was given, with whatever the schema did not name quietly dropped. What can be
83
+ * checked without rebuilding it is checked: it is an object, and it has the `id` every other rule here
84
+ * (reservation, duplication, migration keys, `pithy doctor`) is written in terms of.
85
+ */
86
+ const AuthPlugin = z.custom(isBetterAuthPlugin, { message: "Expected a Better Auth plugin — an object with a non-empty string `id`." }).describe("An additional Better Auth plugin, e.g. `organization()`, `passkey()`, `twoFactor()`. Added to the set the kit composes, never in place of one.");
87
+ /**
88
+ * Refuse a plugin list that is not purely additive, naming the offending plugin.
89
+ *
90
+ * Two ways it can fail, and both name a single id because that is what the adopter has to go delete:
91
+ * a plugin whose id is one of {@link KIT_PLUGIN_IDS} would sit beside the kit's own copy (Better Auth
92
+ * merges endpoints by id — the later registration silently wins, so this is a redefinition even when it
93
+ * reads like an addition), and two plugins sharing an id do the same to each other.
94
+ *
95
+ * **The `message` stays short on purpose.** `auth()` runs while `pithy.config.ts` is being imported, so
96
+ * the CLI catches this through `classifyConfigLoadFailure`, which prints the cause's message and nothing
97
+ * else — and drops it entirely past 160 characters (`safeReason`). A refusal whose whole content is in
98
+ * its `action` reaches the adopter as "the config threw while loading", which names nothing.
99
+ */
100
+ function assertAdditivePlugins(plugins) {
101
+ const reserved = KIT_PLUGIN_IDS;
102
+ const seen = /* @__PURE__ */ new Set();
103
+ for (const plugin of plugins) {
104
+ if (reserved.includes(plugin.id)) throw new ValidationError({
105
+ message: `The auth capability already composes the Better Auth "${plugin.id}" plugin.`,
106
+ action: `Remove ${plugin.id}() from auth({ plugins: [...] }). The four the kit composes (${KIT_PLUGIN_IDS.join(", ")}) are the sign-in this product promises and what the control-plane seam verifies against; your list adds to them.`,
107
+ detail: `reserved plugin id "${plugin.id}" supplied through AuthConfig.plugins`
108
+ });
109
+ if (seen.has(plugin.id)) throw new ValidationError({
110
+ message: `The Better Auth "${plugin.id}" plugin is listed twice in auth({ plugins: [...] }).`,
111
+ action: `Keep one ${plugin.id}() in auth({ plugins: [...] }) — the second registration would silently win over the first.`,
112
+ detail: `duplicate plugin id "${plugin.id}" supplied through AuthConfig.plugins`
113
+ });
114
+ seen.add(plugin.id);
115
+ }
116
+ }
117
+ //#endregion
118
+ export { AuthPlugin, KIT_PLUGIN_IDS, assertAdditivePlugins, kitPlugins };
@@ -0,0 +1,119 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ import type { AppleOAuthCredentials, FacebookOAuthCredentials, GithubOAuthCredentials, GoogleOAuthCredentials } from "./secrets";
5
+ /**
6
+ * What one social provider *is*, for one instance — three states, carried on the value (#381).
7
+ *
8
+ * ## Why three
9
+ *
10
+ * A provider used to be `Credentials | undefined`, and that shape had room for two facts and needed
11
+ * room for three. `undefined` meant "the adopter did not enable this"; there was no way to say "the
12
+ * adopter enabled it and its credential would not read", so that third fact was expressed by the only
13
+ * means left — the resolution rejecting, inside a `Promise.all` that also carried the session secret.
14
+ * One unreadable `auth-github-credentials` therefore took down magic link and OTP for every user,
15
+ * because a contributor to sign-in was wired as a precondition of it.
16
+ *
17
+ * The session secret and the D1 binding really are preconditions: without either there is no sign-in of
18
+ * any kind, and they keep failing the whole instance. A provider is one method among several.
19
+ *
20
+ * ## Why on the value
21
+ *
22
+ * This is #350's shape, applied to a provider rather than an aggregate. The credentials live *behind*
23
+ * the healthy member, so a call site reaches `clientId` only by narrowing on `state`, and one that
24
+ * forgets the sick case does not silently build a provider out of nothing — it does not compile. A flag
25
+ * beside an optional credential would be the same information and the opposite property.
26
+ *
27
+ * ## Why `unresolvable` carries nothing
28
+ *
29
+ * {@link resolveProvider}'s `catch` takes no binding, so nothing derived from the throw is in reach to
30
+ * put here. That is deliberate rather than incidental: what a secret resolution throws is a
31
+ * `SecretNotFoundError` whose `message` names `auth-github-credentials`, or a schema failure whose
32
+ * issues quote what was stored. Neither may reach a browser. Everything the refusal needs — *which*
33
+ * provider — is known at the call site from the key it was resolved under, so it never has to be
34
+ * recovered from an error.
35
+ */
36
+ export type ResolvedProvider<Credentials> = {
37
+ readonly state: "disabled";
38
+ } | {
39
+ readonly state: "ready";
40
+ readonly credentials: Credentials;
41
+ } | {
42
+ readonly state: "unresolvable";
43
+ };
44
+ /**
45
+ * The one `disabled` value, so the state has one spelling.
46
+ *
47
+ * Typed as the bare member rather than `ResolvedProvider<never>`: it is assignable to every
48
+ * `ResolvedProvider<C>` either way, and this way nothing can read a `credentials` off it by widening.
49
+ */
50
+ export declare const PROVIDER_DISABLED: {
51
+ readonly state: "disabled";
52
+ };
53
+ /** The social providers the kit composes. Ordered as they are declared in config. */
54
+ export declare const SOCIAL_PROVIDER_IDS: readonly ["google", "apple", "facebook", "github"];
55
+ /** One of the kit's social providers. */
56
+ export type SocialProviderId = (typeof SOCIAL_PROVIDER_IDS)[number];
57
+ /**
58
+ * Every provider's state for one instance.
59
+ *
60
+ * A record rather than four loose fields, because two things read it — the `socialProviders` block the
61
+ * instance is built from, and the refusal that answers a caller who asked for one that is not there —
62
+ * and they must be reading the same four values or they will disagree about what is available.
63
+ */
64
+ export interface ResolvedProviders {
65
+ /** Google OAuth: disabled, ready with its credential pair, or declared and unreadable. */
66
+ google: ResolvedProvider<GoogleOAuthCredentials>;
67
+ /** Apple Sign-In: disabled, ready with its credential set, or declared and unreadable. */
68
+ apple: ResolvedProvider<AppleOAuthCredentials>;
69
+ /** Facebook Login: disabled, ready with its credential pair, or declared and unreadable. */
70
+ facebook: ResolvedProvider<FacebookOAuthCredentials>;
71
+ /** GitHub OAuth: disabled, ready with its credential pair, or declared and unreadable. */
72
+ github: ResolvedProvider<GithubOAuthCredentials>;
73
+ }
74
+ /**
75
+ * Every provider disabled — what a composition that enables no social sign-in resolves to, and the
76
+ * base a construction site spreads over rather than spelling four times.
77
+ */
78
+ export declare const NO_SOCIAL_PROVIDERS: Readonly<ResolvedProviders>;
79
+ /**
80
+ * Resolve one provider: `disabled` when the adopter did not enable it, `ready` with its credentials, or
81
+ * `unresolvable` when it is enabled and the read failed.
82
+ *
83
+ * **`try`/`catch`, and `read` is invoked inside it.** A `.catch()` on the returned promise would guard
84
+ * only a rejection, and a seam that throws *before* it returns a promise is not a rejected promise —
85
+ * that is how #371's first plant walked straight through its own guard. Calling `read()` inside the
86
+ * `try` catches both, and `providers.test.ts` plants a synchronous throw to prove it.
87
+ *
88
+ * **The `catch` takes no binding.** See {@link ResolvedProvider} — what a secret resolution throws
89
+ * names the secret, and nothing derived from it may travel toward a browser.
90
+ */
91
+ export declare function resolveProvider<Credentials>(enabled: boolean, read: () => Promise<Credentials>): Promise<ResolvedProvider<Credentials>>;
92
+ /**
93
+ * Which provider this request asks for, when the request is one that names one and that provider is
94
+ * enabled but unreadable. `undefined` for every other request, which is nearly all of them.
95
+ *
96
+ * A provider that is merely *disabled* is not this function's business: Better Auth answers that with
97
+ * its own `PROVIDER_NOT_FOUND` 404, which is the right answer — nobody configured it. This exists so
98
+ * the two stop looking alike from outside the Worker.
99
+ */
100
+ export declare function unavailableProviderFor(path: string, body: unknown, providers: ResolvedProviders): SocialProviderId | undefined;
101
+ /**
102
+ * The refusal a caller gets for a provider this deployment means to serve and cannot.
103
+ *
104
+ * Three audiences, three fields, exactly as the error family prescribes:
105
+ *
106
+ * - `message` is the caller's, and it is the whole of what crosses the wire. It says the method is
107
+ * unavailable *right now* and names one that works, because a 404 saying "provider not found" tells
108
+ * somebody who signs in with GitHub every day that they were wrong about their own account.
109
+ * - `action` is the operator's — the command that fixes it, and the config key that turns it off.
110
+ * - `detail` is the throw site's. It names the provider and says the credential would not resolve. It
111
+ * does **not** carry the resolution's own error: `resolveProvider` dropped that whole, on purpose.
112
+ *
113
+ * `503` rather than `500`, and rather than `404`. This deployment's own dependency — the credential row
114
+ * for one sign-in method — is the thing that could not be served, which is what 503 means and what
115
+ * `payments/provider_unavailable` already uses it for. A 404 would be indistinguishable from a provider
116
+ * nobody enabled, and that indistinguishability is the defect.
117
+ */
118
+ export declare function providerUnavailable(provider: SocialProviderId): PithyError;
119
+ //# sourceMappingURL=providers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.d.ts","sourceRoot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;AACH,wBAAsB,eAAe,CAAC,WAAW,EAC/C,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAOxC;AAyBD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,OAAO,EACb,SAAS,EAAE,iBAAiB,GAC3B,gBAAgB,GAAG,SAAS,CAO9B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,UAAU,CAQ1E"}
@@ -0,0 +1,113 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ import { z } from "zod";
5
+ //#region src/instance/providers.ts
6
+ /**
7
+ * The one `disabled` value, so the state has one spelling.
8
+ *
9
+ * Typed as the bare member rather than `ResolvedProvider<never>`: it is assignable to every
10
+ * `ResolvedProvider<C>` either way, and this way nothing can read a `credentials` off it by widening.
11
+ */
12
+ const PROVIDER_DISABLED = { state: "disabled" };
13
+ /** The social providers the kit composes. Ordered as they are declared in config. */
14
+ const SOCIAL_PROVIDER_IDS = [
15
+ "google",
16
+ "apple",
17
+ "facebook",
18
+ "github"
19
+ ];
20
+ /**
21
+ * Every provider disabled — what a composition that enables no social sign-in resolves to, and the
22
+ * base a construction site spreads over rather than spelling four times.
23
+ */
24
+ const NO_SOCIAL_PROVIDERS = {
25
+ google: PROVIDER_DISABLED,
26
+ apple: PROVIDER_DISABLED,
27
+ facebook: PROVIDER_DISABLED,
28
+ github: PROVIDER_DISABLED
29
+ };
30
+ /**
31
+ * Resolve one provider: `disabled` when the adopter did not enable it, `ready` with its credentials, or
32
+ * `unresolvable` when it is enabled and the read failed.
33
+ *
34
+ * **`try`/`catch`, and `read` is invoked inside it.** A `.catch()` on the returned promise would guard
35
+ * only a rejection, and a seam that throws *before* it returns a promise is not a rejected promise —
36
+ * that is how #371's first plant walked straight through its own guard. Calling `read()` inside the
37
+ * `try` catches both, and `providers.test.ts` plants a synchronous throw to prove it.
38
+ *
39
+ * **The `catch` takes no binding.** See {@link ResolvedProvider} — what a secret resolution throws
40
+ * names the secret, and nothing derived from it may travel toward a browser.
41
+ */
42
+ async function resolveProvider(enabled, read) {
43
+ if (!enabled) return PROVIDER_DISABLED;
44
+ try {
45
+ return {
46
+ state: "ready",
47
+ credentials: await read()
48
+ };
49
+ } catch {
50
+ return { state: "unresolvable" };
51
+ }
52
+ }
53
+ /**
54
+ * The Better Auth endpoints that name a social provider in their body, as their `ctx.path` reads —
55
+ * mounted paths, so no `basePath` appears here.
56
+ *
57
+ * `/callback/:provider` is deliberately absent: a callback can only arrive for a provider that already
58
+ * served an authorize redirect, and an unresolvable one never did.
59
+ */
60
+ const PROVIDER_BODY_PATHS = /* @__PURE__ */ new Set(["/sign-in/social", "/link-social"]);
61
+ /**
62
+ * The provider named in a social sign-in body.
63
+ *
64
+ * Parsed rather than cast. Better Auth has already validated the body against the endpoint's own
65
+ * schema by the time a `before` hook runs, so this is not the trust boundary — but a `catchall` shape
66
+ * read with a cast is how a hook starts reading a field that is not there, and `unknown` narrows for
67
+ * free here.
68
+ */
69
+ const ProviderBody = z.object({ provider: z.string().min(1).describe("The social provider id the caller asked to sign in or link with.") }).describe("The part of a social sign-in body this refusal reads: which provider was asked for.");
70
+ /**
71
+ * Which provider this request asks for, when the request is one that names one and that provider is
72
+ * enabled but unreadable. `undefined` for every other request, which is nearly all of them.
73
+ *
74
+ * A provider that is merely *disabled* is not this function's business: Better Auth answers that with
75
+ * its own `PROVIDER_NOT_FOUND` 404, which is the right answer — nobody configured it. This exists so
76
+ * the two stop looking alike from outside the Worker.
77
+ */
78
+ function unavailableProviderFor(path, body, providers) {
79
+ if (!PROVIDER_BODY_PATHS.has(path)) return void 0;
80
+ const parsed = ProviderBody.safeParse(body);
81
+ if (!parsed.success) return void 0;
82
+ const asked = SOCIAL_PROVIDER_IDS.find((id) => id === parsed.data.provider);
83
+ if (!asked) return void 0;
84
+ return providers[asked].state === "unresolvable" ? asked : void 0;
85
+ }
86
+ /**
87
+ * The refusal a caller gets for a provider this deployment means to serve and cannot.
88
+ *
89
+ * Three audiences, three fields, exactly as the error family prescribes:
90
+ *
91
+ * - `message` is the caller's, and it is the whole of what crosses the wire. It says the method is
92
+ * unavailable *right now* and names one that works, because a 404 saying "provider not found" tells
93
+ * somebody who signs in with GitHub every day that they were wrong about their own account.
94
+ * - `action` is the operator's — the command that fixes it, and the config key that turns it off.
95
+ * - `detail` is the throw site's. It names the provider and says the credential would not resolve. It
96
+ * does **not** carry the resolution's own error: `resolveProvider` dropped that whole, on purpose.
97
+ *
98
+ * `503` rather than `500`, and rather than `404`. This deployment's own dependency — the credential row
99
+ * for one sign-in method — is the thing that could not be served, which is what 503 means and what
100
+ * `payments/provider_unavailable` already uses it for. A 404 would be indistinguishable from a provider
101
+ * nobody enabled, and that indistinguishability is the defect.
102
+ */
103
+ function providerUnavailable(provider) {
104
+ return new PithyError({
105
+ code: "auth/provider_unavailable",
106
+ status: 503,
107
+ message: `Signing in with ${provider} is unavailable right now. Use a magic link instead.`,
108
+ action: `Provision \`auth-${provider}-credentials\` for this environment with \`pithy secrets create\`, or set \`${provider}.enabled\` to false in pithy.config.ts.`,
109
+ detail: `provider ${provider} is enabled and its credential could not be resolved; the instance was built without it`
110
+ });
111
+ }
112
+ //#endregion
113
+ export { NO_SOCIAL_PROVIDERS, PROVIDER_DISABLED, SOCIAL_PROVIDER_IDS, providerUnavailable, resolveProvider, unavailableProviderFor };