@dads-framework/identity-better-auth 0.1.0 → 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 (63) hide show
  1. package/README.md +214 -16
  2. package/dist/identity-better-auth.tsbuildinfo +1 -1
  3. package/dist/impersonation-store/index.d.ts +3 -0
  4. package/dist/impersonation-store/index.d.ts.map +1 -0
  5. package/dist/impersonation-store/index.js +3 -0
  6. package/dist/impersonation-store/index.js.map +1 -0
  7. package/dist/impersonation-store/postgres-impersonation-store.d.ts +4 -0
  8. package/dist/impersonation-store/postgres-impersonation-store.d.ts.map +1 -0
  9. package/dist/impersonation-store/postgres-impersonation-store.js +75 -0
  10. package/dist/impersonation-store/postgres-impersonation-store.js.map +1 -0
  11. package/dist/index.d.ts +6 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +5 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/lib/configure-better-auth.d.ts +1226 -5
  16. package/dist/lib/configure-better-auth.d.ts.map +1 -1
  17. package/dist/lib/configure-better-auth.js +21 -3
  18. package/dist/lib/configure-better-auth.js.map +1 -1
  19. package/dist/lib/create-better-auth-identity.d.ts +4 -0
  20. package/dist/lib/create-better-auth-identity.d.ts.map +1 -1
  21. package/dist/lib/create-better-auth-identity.js +22 -16
  22. package/dist/lib/create-better-auth-identity.js.map +1 -1
  23. package/dist/lib/enterprise-callback-context.d.ts +9 -0
  24. package/dist/lib/enterprise-callback-context.d.ts.map +1 -0
  25. package/dist/lib/enterprise-callback-context.js +9 -0
  26. package/dist/lib/enterprise-callback-context.js.map +1 -0
  27. package/dist/lib/enterprise-options.d.ts +31 -0
  28. package/dist/lib/enterprise-options.d.ts.map +1 -0
  29. package/dist/lib/enterprise-options.js +119 -0
  30. package/dist/lib/enterprise-options.js.map +1 -0
  31. package/dist/lib/enterprise-plugin.d.ts +1038 -0
  32. package/dist/lib/enterprise-plugin.d.ts.map +1 -0
  33. package/dist/lib/enterprise-plugin.js +211 -0
  34. package/dist/lib/enterprise-plugin.js.map +1 -0
  35. package/dist/lib/enterprise-routes.d.ts +5 -0
  36. package/dist/lib/enterprise-routes.d.ts.map +1 -0
  37. package/dist/lib/enterprise-routes.js +215 -0
  38. package/dist/lib/enterprise-routes.js.map +1 -0
  39. package/dist/lib/identity-handler.d.ts +2 -1
  40. package/dist/lib/identity-handler.d.ts.map +1 -1
  41. package/dist/lib/identity-handler.js +25 -5
  42. package/dist/lib/identity-handler.js.map +1 -1
  43. package/dist/lib/identity-session-readers.d.ts +23 -0
  44. package/dist/lib/identity-session-readers.d.ts.map +1 -0
  45. package/dist/lib/identity-session-readers.js +81 -0
  46. package/dist/lib/identity-session-readers.js.map +1 -0
  47. package/dist/lib/install-identity-schema-v2.d.ts +4 -0
  48. package/dist/lib/install-identity-schema-v2.d.ts.map +1 -0
  49. package/dist/lib/install-identity-schema-v2.js +8 -0
  50. package/dist/lib/install-identity-schema-v2.js.map +1 -0
  51. package/dist/lib/migrations/20261120070530_identity_jwks.migration.d.ts +5 -0
  52. package/dist/lib/migrations/20261120070530_identity_jwks.migration.d.ts.map +1 -0
  53. package/dist/lib/migrations/20261120070530_identity_jwks.migration.js +10 -0
  54. package/dist/lib/migrations/20261120070530_identity_jwks.migration.js.map +1 -0
  55. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.d.ts +5 -0
  56. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.d.ts.map +1 -0
  57. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.js +33 -0
  58. package/dist/lib/migrations/20261120070600_enterprise_sso.migration.js.map +1 -0
  59. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.d.ts +6 -0
  60. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.d.ts.map +1 -0
  61. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.js +37 -0
  62. package/dist/lib/migrations/20261120070700_staff_impersonation.migration.js.map +1 -0
  63. package/package.json +12 -5
package/README.md CHANGED
@@ -1,27 +1,128 @@
1
1
  # @dads-framework/identity-better-auth
2
2
 
3
- Binds the Dads identity contract to Better Auth and PostgreSQL for email and password sign-in.
3
+ Binds the Dads identity contract to Better Auth and PostgreSQL for email, password, and optional tenant SSO sign-in.
4
4
 
5
5
  ## Try it
6
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
+
7
30
  ```ts
8
- import { createBetterAuthIdentity } from "@dads-framework/identity-better-auth";
9
-
10
- const identity = createBetterAuthIdentity({
11
- database: postgres,
12
- baseUrl: environment.appOrigin,
13
- secret: environment.identitySecret,
14
- enqueueEmail: mailQueue.enqueueIdentityEmail,
15
- canInvite: accountPolicy.canInvite,
16
- });
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
+ }
17
99
  ```
18
100
 
101
+ The script prints `403` before email verification, `200` after verification,
102
+ and `true` when the session lookup confirms the verified account.
103
+
19
104
  ## Use it
20
105
 
21
- Apply the migration with the Dads migration runner. It discovers
22
- `20261120070500_identity.migration.ts` for this repository. An adopter can
23
- call `installIdentitySchemaV1` from its own migration via the package's
24
- public export. Mount `identity.handle` under `IDENTITY_PATH` (`/api/auth`)
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`)
25
126
  and pass through the original browser request and response headers,
26
127
  including each `Set-Cookie` header. Replace client-supplied forwarding
27
128
  headers at the trusted ingress before invoking the handler. Better Auth
@@ -62,8 +163,7 @@ cannot be redeemed with another account's email.
62
163
 
63
164
  ## What it refuses to do
64
165
 
65
- The handler omits SSO, SCIM, administrative impersonation and provider
66
- token endpoints. Reads return account identity without password or raw
166
+ The handler omits SCIM, and provider token endpoints. Reads return account identity without password or raw
67
167
  session records. JWTs carry only the subject, session ID, and standard
68
168
  issuer, audience, time and expiry claims. An offline verifier must check
69
169
  signature, issuer, audience and expiry. A revoked cookie session cannot
@@ -81,3 +181,101 @@ link. Keep request bodies and authentication query strings out of logs.
81
181
  Denied invitation issuance returns `401` without a session and `403` for a
82
182
  refused origin or account policy. A wrong, expired, or spent invitation
83
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.