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