@dads-framework/identity-better-auth 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +280 -2
  3. package/dist/identity-better-auth.tsbuildinfo +1 -0
  4. package/dist/impersonation-store/index.d.ts +3 -0
  5. package/dist/impersonation-store/index.d.ts.map +1 -0
  6. package/dist/impersonation-store/index.js +3 -0
  7. package/dist/impersonation-store/index.js.map +1 -0
  8. package/dist/impersonation-store/postgres-impersonation-store.d.ts +4 -0
  9. package/dist/impersonation-store/postgres-impersonation-store.d.ts.map +1 -0
  10. package/dist/impersonation-store/postgres-impersonation-store.js +75 -0
  11. package/dist/impersonation-store/postgres-impersonation-store.js.map +1 -0
  12. package/dist/index.d.ts +10 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +9 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/lib/account-invitations.d.ts +7 -0
  17. package/dist/lib/account-invitations.d.ts.map +1 -0
  18. package/dist/lib/account-invitations.js +46 -0
  19. package/dist/lib/account-invitations.js.map +1 -0
  20. package/dist/lib/configure-better-auth.d.ts +1509 -0
  21. package/dist/lib/configure-better-auth.d.ts.map +1 -0
  22. package/dist/lib/configure-better-auth.js +85 -0
  23. package/dist/lib/configure-better-auth.js.map +1 -0
  24. package/dist/lib/create-better-auth-identity.d.ts +9 -0
  25. package/dist/lib/create-better-auth-identity.d.ts.map +1 -0
  26. package/dist/lib/create-better-auth-identity.js +37 -0
  27. package/dist/lib/create-better-auth-identity.js.map +1 -0
  28. package/dist/lib/enterprise-callback-context.d.ts +9 -0
  29. package/dist/lib/enterprise-callback-context.d.ts.map +1 -0
  30. package/dist/lib/enterprise-callback-context.js +9 -0
  31. package/dist/lib/enterprise-callback-context.js.map +1 -0
  32. package/dist/lib/enterprise-options.d.ts +31 -0
  33. package/dist/lib/enterprise-options.d.ts.map +1 -0
  34. package/dist/lib/enterprise-options.js +119 -0
  35. package/dist/lib/enterprise-options.js.map +1 -0
  36. package/dist/lib/enterprise-plugin.d.ts +1038 -0
  37. package/dist/lib/enterprise-plugin.d.ts.map +1 -0
  38. package/dist/lib/enterprise-plugin.js +211 -0
  39. package/dist/lib/enterprise-plugin.js.map +1 -0
  40. package/dist/lib/enterprise-routes.d.ts +5 -0
  41. package/dist/lib/enterprise-routes.d.ts.map +1 -0
  42. package/dist/lib/enterprise-routes.js +215 -0
  43. package/dist/lib/enterprise-routes.js.map +1 -0
  44. package/dist/lib/identity-email.d.ts +4 -0
  45. package/dist/lib/identity-email.d.ts.map +1 -0
  46. package/dist/lib/identity-email.js +15 -0
  47. package/dist/lib/identity-email.js.map +1 -0
  48. package/dist/lib/identity-handler.d.ts +9 -0
  49. package/dist/lib/identity-handler.d.ts.map +1 -0
  50. package/dist/lib/identity-handler.js +102 -0
  51. package/dist/lib/identity-handler.js.map +1 -0
  52. package/dist/lib/identity-options.d.ts +15 -0
  53. package/dist/lib/identity-options.d.ts.map +1 -0
  54. package/dist/lib/identity-options.js +17 -0
  55. package/dist/lib/identity-options.js.map +1 -0
  56. package/dist/lib/identity-session-readers.d.ts +23 -0
  57. package/dist/lib/identity-session-readers.d.ts.map +1 -0
  58. package/dist/lib/identity-session-readers.js +81 -0
  59. package/dist/lib/identity-session-readers.js.map +1 -0
  60. package/dist/lib/install-identity-schema-v2.d.ts +4 -0
  61. package/dist/lib/install-identity-schema-v2.d.ts.map +1 -0
  62. package/dist/lib/install-identity-schema-v2.js +8 -0
  63. package/dist/lib/install-identity-schema-v2.js.map +1 -0
  64. package/dist/lib/migrations/20261120070500_identity.migration.d.ts +5 -0
  65. package/dist/lib/migrations/20261120070500_identity.migration.d.ts.map +1 -0
  66. package/dist/lib/migrations/20261120070500_identity.migration.js +81 -0
  67. package/dist/lib/migrations/20261120070500_identity.migration.js.map +1 -0
  68. package/dist/lib/migrations/20261120070530_identity_jwks.migration.d.ts +5 -0
  69. package/dist/lib/migrations/20261120070530_identity_jwks.migration.d.ts.map +1 -0
  70. package/dist/lib/migrations/20261120070530_identity_jwks.migration.js +10 -0
  71. package/dist/lib/migrations/20261120070530_identity_jwks.migration.js.map +1 -0
  72. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.d.ts +5 -0
  73. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.d.ts.map +1 -0
  74. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.js +33 -0
  75. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.js.map +1 -0
  76. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.d.ts +6 -0
  77. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.d.ts.map +1 -0
  78. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.js +37 -0
  79. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.js.map +1 -0
  80. package/package.json +50 -4
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bryton Cooper
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,281 @@
1
- # Temporary Holding Version
1
+ # @dads-framework/identity-better-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Binds the Dads identity contract to Better Auth and PostgreSQL for email, password, and optional tenant SSO sign-in.
4
+
5
+ ## Try it
6
+
7
+ In the generated starter, [`assembly/identity-services.ts`](../../../apps/kit-workbench/assembly/identity-services.ts) constructs
8
+ the adapter with the application database and mail service.
9
+ [`assembly/start-app.ts`](../../../apps/kit-workbench/assembly/start-app.ts) mounts the handler at `/api/auth`. The starter's existing journal installs
10
+ [base identity in its bootstrap migration](../../../apps/kit-workbench/migrations/20261120080000_starter.migration.ts)
11
+ and adds
12
+ [signing-key metadata in a later migration](../../../apps/kit-workbench/migrations/20261120080300_enterprise_identity.migration.ts).
13
+
14
+ Use Node.js 24 and a disposable Postgres database. Apply
15
+ `installIdentitySchemaV2(pgm)` from this package in your migration runner.
16
+ Set `DATABASE_URL` to point at the migrated database. Set `IDENTITY_SECRET`
17
+ to a locally generated secret of at least 32 characters. The example invokes
18
+ the HTTP handler directly, so it needs no listening HTTP server. It captures
19
+ the verification link in memory and keeps it out of the console.
20
+
21
+ ```sh
22
+ npm install @dads-framework/identity-better-auth @dads-framework/postgres
23
+ npm install -D tsx
24
+ ```
25
+
26
+ Save as `identity-boundary.mts` and run `npx tsx identity-boundary.mts`.
27
+
28
+ <!-- dads:check-example -->
29
+
30
+ ```ts
31
+ import { randomUUID } from "node:crypto";
32
+ import {
33
+ createBetterAuthIdentity,
34
+ IDENTITY_PATH,
35
+ } from "@dads-framework/identity-better-auth";
36
+ import { createPostgresConnection } from "@dads-framework/postgres";
37
+
38
+ const connectionString = process.env.DATABASE_URL;
39
+ const secret = process.env.IDENTITY_SECRET;
40
+ if (!connectionString || !secret) {
41
+ throw new Error("Set DATABASE_URL and IDENTITY_SECRET.");
42
+ }
43
+
44
+ const connection = createPostgresConnection(
45
+ { connectionString, schema: {} },
46
+ console,
47
+ );
48
+ const baseUrl = "http://localhost:3000";
49
+ try {
50
+ let verificationUrl: string | undefined;
51
+ const identity = createBetterAuthIdentity({
52
+ database: connection,
53
+ baseUrl,
54
+ secret,
55
+ enqueueEmail: async ({ kind, url }) => {
56
+ if (kind === "verify-email") verificationUrl = url;
57
+ },
58
+ canInvite: async () => false,
59
+ });
60
+
61
+ function post(path: string, body: object) {
62
+ return identity.handle(
63
+ new Request(baseUrl + IDENTITY_PATH + path, {
64
+ method: "POST",
65
+ headers: { origin: baseUrl, "content-type": "application/json" },
66
+ body: JSON.stringify(body),
67
+ }),
68
+ );
69
+ }
70
+
71
+ const email = `example-${randomUUID()}@example.test`;
72
+ const password = randomUUID();
73
+ const registration = await post("/sign-up/email", {
74
+ name: "Example account",
75
+ email,
76
+ password,
77
+ });
78
+ if (registration.status !== 200 || verificationUrl === undefined) {
79
+ throw new Error("Expected a verification email.");
80
+ }
81
+
82
+ console.log((await post("/sign-in/email", { email, password })).status);
83
+ const verification = await identity.handle(new Request(verificationUrl));
84
+ if (verification.status !== 302) throw new Error("Verification failed.");
85
+
86
+ const signIn = await post("/sign-in/email", { email, password });
87
+ console.log(signIn.status);
88
+ const cookie = signIn.headers
89
+ .getSetCookie()
90
+ .find((value) => value.includes("session_token"))
91
+ ?.split(";")[0];
92
+ if (cookie === undefined) throw new Error("Expected a session cookie.");
93
+
94
+ const session = await identity.readSession(new Headers({ cookie }));
95
+ console.log(session?.account.emailVerified);
96
+ } finally {
97
+ await connection.close();
98
+ }
99
+ ```
100
+
101
+ The script prints `403` before email verification, `200` after verification,
102
+ and `true` when the session lookup confirms the verified account.
103
+
104
+ ## Use it
105
+
106
+ For a fresh database, call `installIdentitySchemaV2(pgm)` from an
107
+ application-owned migration. It installs accounts, credentials, sessions,
108
+ verification and invitation records, and the signing-key schema required by
109
+ the default adapter.
110
+
111
+ ```ts
112
+ import { installIdentitySchemaV2 } from "@dads-framework/identity-better-auth";
113
+
114
+ export const up = installIdentitySchemaV2;
115
+ export const down = false;
116
+ ```
117
+
118
+ If you already applied a migration that only called `installIdentitySchemaV1`,
119
+ keep that migration and call `installIdentitySigningKeyMetadataSchema(pgm)`
120
+ once in a new migration. If your journal already applied the signing-key
121
+ migration, the default schema is complete. Dads repository deployments use
122
+ the shipped `20261120070500_identity.migration.ts` and
123
+ `20261120070530_identity_jwks.migration.ts` steps.
124
+
125
+ Mount `identity.handle` under `IDENTITY_PATH` (`/api/auth`)
126
+ and pass through the original browser request and response headers,
127
+ including each `Set-Cookie` header. Replace client-supplied forwarding
128
+ headers at the trusted ingress before invoking the handler. Better Auth
129
+ uses the resulting client address for request limits. An application
130
+ with multiple instances can also enforce shared limits at its ingress.
131
+
132
+ Use `identity.readSession(request.headers)` to authenticate with the session
133
+ cookie. Cookies are host-only, HTTP-only, and secure on HTTPS. The database
134
+ is checked on each lookup. Sessions expire seven days after sign-in and
135
+ sign-out revokes the current session.
136
+
137
+ From the same origin, use the following paths relative to `/api/auth`.
138
+
139
+ | Method | Path | Input and effect |
140
+ | ------ | ------------------------- | -------------------------------------------------------------------------------------- |
141
+ | POST | `/sign-up/email` | `name`, `email`, `password`. Requests email verification with a uniform success body. |
142
+ | GET | `/verify-email` | The verification URL delivered to the account owner. |
143
+ | POST | `/sign-in/email` | `email`, `password`. Sets a session cookie for a verified account. |
144
+ | POST | `/sign-out` | Revokes the cookie's session. |
145
+ | GET | `/get-session` | Returns the safe account and its expiration, or `null`. |
146
+ | POST | `/request-password-reset` | `email`, same-origin `redirectTo`. Returns a generic acknowledgement. |
147
+ | POST | `/reset-password` | `token`, `newPassword`. Consumes the token and revokes existing sessions. |
148
+ | POST | `/invite` | `email`. Requires a verified session and an application policy permitting invitations. |
149
+ | POST | `/accept-invitation` | `token` from the link's fragment. Requires a verified session with the same email. |
150
+ | GET | `/token` | A five-minute JWT for an active cookie session. |
151
+ | GET | `/jwks` | Public verification keys. |
152
+
153
+ An invited recipient signs up and verifies their address first. The
154
+ application's `/accept-invitation` page reads the token fragment and submits
155
+ it to the identity endpoint. An account invitation grants no tenant role.
156
+ Tenant onboarding can instead use its own tenant invitation and map a
157
+ verified identity session to a tenant account.
158
+
159
+ Password reset links expire after 15 minutes, verification links after an
160
+ hour, and account invitations after 24 hours. A password reset is
161
+ single-use. Invite tokens are stored by digest, accepted atomically, and
162
+ cannot be redeemed with another account's email.
163
+
164
+ ## What it refuses to do
165
+
166
+ The handler omits SCIM, and provider token endpoints. Reads return account identity without password or raw
167
+ session records. JWTs carry only the subject, session ID, and standard
168
+ issuer, audience, time and expiry claims. An offline verifier must check
169
+ signature, issuer, audience and expiry. A revoked cookie session cannot
170
+ mint new JWTs, and existing offline JWTs expire within five minutes.
171
+
172
+ ## Contract
173
+
174
+ Use a bare HTTPS origin or a loopback HTTP origin and a secret of at least
175
+ 32 characters from application configuration. The application owns the
176
+ database pool and its shutdown. Use a confidential mail queue. Mail is
177
+ enqueued without delaying reset or registration responses, and enqueue
178
+ failures can call `onEmailError` without exposing any address, secret, or
179
+ link. Keep request bodies and authentication query strings out of logs.
180
+
181
+ Denied invitation issuance returns `401` without a session and `403` for a
182
+ refused origin or account policy. A wrong, expired, or spent invitation
183
+ returns the same `400` response.
184
+
185
+ ## Staff impersonation storage
186
+
187
+ Use the PostgreSQL adapter with the vendor-neutral impersonation service.
188
+ Pass the primary PostgreSQL pool and an application policy that checks the
189
+ actor's permission for the specified action, tenant, and target.
190
+
191
+ ```ts
192
+ import { createImpersonation } from "@dads-framework/identity/impersonation";
193
+ import { createPostgresImpersonationStore } from "@dads-framework/identity-better-auth/impersonation-store";
194
+
195
+ const impersonation = createImpersonation({
196
+ ...createPostgresImpersonationStore(postgres.pool),
197
+ identity,
198
+ authorize: accountPolicy.authorizeImpersonation,
199
+ lifetimeMs: 5 * 60_000,
200
+ });
201
+ ```
202
+
203
+ Apply `20261120070700_staff_impersonation.migration.ts` for this repository.
204
+ In an adopting application, call `installStaffImpersonationSchemaV1` from a
205
+ migration through the same package subpath. The adapter adds a durable audit
206
+ row in the same PostgreSQL statement as each successful grant creation or
207
+ removal. A failure rolls back both writes. Every accepted use also requires a
208
+ durable audit row. Audit entries contain account IDs and grant IDs. The
209
+ server-side session ID is stored only with the grant.
210
+
211
+ Mount application-owned impersonation routes and explicitly allow the
212
+ operations that accept an impersonation grant. The underlying Better Auth
213
+ session remains the authenticated staff session. See the
214
+ [staff impersonation service guide](../identity/src/impersonation/README.md)
215
+ for the start, use, stop, and revoke contracts.
216
+
217
+ ## Enterprise SSO
218
+
219
+ A trusted deployment administrator supplies one or more tenant providers via
220
+ `createEnterpriseBetterAuthIdentity(options, providers)`. Keep the provider
221
+ configuration and OIDC client secrets on the server. Use a different
222
+ `sso-` provider ID for each connection and a unique exact email domain.
223
+ Providers belonging to one tenant must have the same mode.
224
+
225
+ Call `enterpriseSsoDomainChallenge(options.secret, tenantId, domain)` and
226
+ publish its returned TXT name and value in the domain's DNS. The factory
227
+ checks the TXT record during startup. Leave the record published across
228
+ restarts and regenerate it when rotating the identity secret. The
229
+ provider catalog is deployment configuration. The HTTP handler exposes no
230
+ provider registration or mutation routes.
231
+
232
+ Apply `installIdentityEnterpriseSsoSchema(pgm)` in a separate migration
233
+ after installing the default identity schema.
234
+
235
+ ### Connect and test a provider
236
+
237
+ 1. Start with mode `optional`. For OIDC, configure a confidential client,
238
+ registered issuer, authorization, token, and JWKS URLs. Use
239
+ `/api/auth/sso/callback` on the application origin as the redirect URI.
240
+ The provider must support PKCE and supply `email`, boolean
241
+ `email_verified`, and an immutable subject in the signed ID token.
242
+ 2. For SAML, configure the IdP entity ID, Redirect binding sign-in URL,
243
+ signing certificate, and the email attribute when it differs from
244
+ `email`. Register the SP using
245
+ `GET /api/auth/sso/saml2/sp/metadata?providerId=<id>`.
246
+ The metadata describes the application entity ID and ACS at
247
+ `POST /api/auth/sso/saml2/sp/acs/<id>`. Configure signed responses with
248
+ an immutable NameID, recipient, audience, and validity conditions.
249
+ 3. From the application origin, send `POST /api/auth/sign-in/sso` with
250
+ `{ providerId, callbackURL }` and navigate that browser to the returned
251
+ `url`. Use a same-origin application callback. On return, verify
252
+ `readEnterpriseSession(headers, tenantId)` and confirm the account and
253
+ provider. Try a user outside the configured domain before enabling
254
+ required mode.
255
+
256
+ A first SSO sign-in can provision a verified identity. If the email matches
257
+ an already verified local identity in the provider's domain, the transaction
258
+ binds the provider subject to that account. A later sign-in must match the
259
+ subject and verified email. The adapter does not store IdP tokens. Treat
260
+ the issuer, client ID or SAML certificate, tenant, domain, and provider ID
261
+ as the authority boundary. Rebinding an existing identity to changed
262
+ provider authority requires a controlled account migration with reviewed
263
+ credential changes. A deployment changing the authority invalidates
264
+ sessions minted under the previous binding.
265
+
266
+ For tenant routes, call `readTenantSession(headers, tenantId)` before
267
+ authorizing tenant membership. Required mode enforces that tenant's SSO
268
+ session, and password sessions for a required domain cannot authenticate
269
+ or mint identity JWTs. SSO does not assign tenant membership.
270
+
271
+ For reauthentication, initiate a new SSO round trip and call
272
+ `readEnterpriseSession(headers, tenantId, maxAgeMs)`. Compare its account
273
+ ID with the original actor for the sensitive action. Freshness measures
274
+ the completion of an application SSO flow. Configure IdP policy to
275
+ require a new credential prompt or MFA when that assurance is needed.
276
+
277
+ For a tenant invitation, read a verified session with
278
+ `readTenantSessionPolicy(headers)` before opening the membership transaction.
279
+ Apply its `allowsTenant(tenantId)` check to the tenant read from the locked
280
+ invitation. The check reuses the validated session without querying the pool
281
+ again while the transaction holds a connection.