@terreno/api 57.18.0 → 57.20.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 (169) hide show
  1. package/CHANGELOG.md +2071 -2
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -5,6 +5,8 @@
5
5
  * JWT/Passport authentication system.
6
6
  */
7
7
  import type { BetterAuthOptions, BetterAuthPlugin } from "better-auth";
8
+ import type { SecurityMailTemplateId } from "./accountSecurity/securityNotifications";
9
+ import type { BetterAuthAccountLinkingMode } from "./betterAuthMethods";
8
10
  /**
9
11
  * Makes nested option objects optional too, so `options` can set one nested field (such as
10
12
  * `emailAndPassword.requireEmailVerification`) without restating the fields Terreno sets.
@@ -20,6 +22,121 @@ export interface BetterAuthOAuthProvider {
20
22
  clientId: string;
21
23
  clientSecret: string;
22
24
  }
25
+ /**
26
+ * Sign in with Apple configured with a pre-made client secret (a signed JWT you rotate yourself
27
+ * before it expires).
28
+ */
29
+ export interface BetterAuthAppleSecretProvider extends BetterAuthOAuthProvider {
30
+ /** The iOS bundle id, used as the audience of native ID tokens. */
31
+ appBundleIdentifier?: string;
32
+ }
33
+ /**
34
+ * Sign in with Apple configured with the Sign in with Apple key itself. Terreno signs the
35
+ * ES256 client-secret JWT when Better Auth is created; it is valid for 180 days, so restart
36
+ * (redeploy) the server at least that often.
37
+ */
38
+ export interface BetterAuthAppleKeyProvider {
39
+ /** The iOS bundle id, used as the audience of native ID tokens. */
40
+ appBundleIdentifier?: string;
41
+ /** The Services ID (web) the sign-in uses. */
42
+ clientId: string;
43
+ /** The key id of the Sign in with Apple key. */
44
+ keyId: string;
45
+ /**
46
+ * The `.p8` key contents in PEM (PKCS#8) form. Escaped `\n` sequences, as env vars often carry
47
+ * them, are turned back into newlines.
48
+ */
49
+ privateKey: string;
50
+ /** The Apple developer team id. */
51
+ teamId: string;
52
+ }
53
+ /**
54
+ * How a sign-in with a new method relates to an existing account with the same email.
55
+ * Better Auth's `requireLocalEmailVerified` stays `true` in every mode.
56
+ */
57
+ export interface BetterAuthAccountLinkingConfig {
58
+ /**
59
+ * - `verified-email`: a sign-in whose verified email matches an account whose own email is
60
+ * verified joins that account.
61
+ * - `explicit`: no linking at sign-in; a signed-in user links a method themselves.
62
+ * - `never`: no linking. A same-email sign-in with a new method is refused.
63
+ */
64
+ mode: BetterAuthAccountLinkingMode;
65
+ /**
66
+ * Providers Better Auth trusts to own the email they report: their sign-ins link even without
67
+ * a verified-email claim, and Better Auth also skips the verified-email check for them on an
68
+ * explicit `/link-social` and its callback. List only providers that prove email ownership
69
+ * (such as Google for Gmail addresses); a provider that lets users set any email turns this
70
+ * into an account-takeover path.
71
+ */
72
+ trustedProviders?: string[];
73
+ }
74
+ /**
75
+ * Time-based one-time-password two-factor authentication (Better Auth `twoFactor`).
76
+ */
77
+ export interface BetterAuthTwoFactorConfig {
78
+ /** Issuer shown in authenticator apps, usually the app name. */
79
+ issuer: string;
80
+ /** How many backup codes enrollment makes (default 10) and how long each is (default 10). */
81
+ backupCodes?: {
82
+ amount?: number;
83
+ length?: number;
84
+ };
85
+ /** Days a "trust this device" choice skips the second factor. Defaults to 30. */
86
+ trustDeviceDays?: number;
87
+ }
88
+ /**
89
+ * WebAuthn passkeys (`@better-auth/passkey`).
90
+ */
91
+ export interface BetterAuthPasskeyConfig {
92
+ /** Relying party id: the registrable domain passkeys are bound to, such as `example.com`. */
93
+ rpID: string;
94
+ /** Relying party name shown by the authenticator. */
95
+ rpName: string;
96
+ /** Exact web origins allowed to use passkeys, such as `https://app.example.com`. */
97
+ origin: string[];
98
+ }
99
+ /**
100
+ * Whether new users can create accounts.
101
+ */
102
+ export interface BetterAuthSignUpConfig {
103
+ /**
104
+ * - `open` (default): anyone can sign up.
105
+ * - `closed`: email sign-up is refused, and a social or generic OAuth sign-in for an unknown
106
+ * email fails with `signup_disabled`, even with `requestSignUp: true`.
107
+ *
108
+ * `closed` covers email and password, `socialProviders`, and every OAuth provider in Better
109
+ * Auth's provider list (including `genericOAuth` ones from `plugins`). Other sign-in plugins
110
+ * added through `plugins` (`magicLink`, `emailOTP`, `phoneNumber`, `anonymous`, ...) create
111
+ * users on their own terms and need their own `disableSignUp` (or equivalent) option. With
112
+ * `oauthProxy`, a preview's OAuth sign-in is finished by the production server, so it follows
113
+ * the production server's sign-up mode: give both the same `signUp.mode`.
114
+ */
115
+ mode: "open" | "closed";
116
+ }
117
+ /**
118
+ * Several signed-in accounts on one device (Better Auth `multiSession`).
119
+ */
120
+ export interface BetterAuthMultiSessionConfig {
121
+ /** Most accounts signed in at once on a device. Defaults to 5. */
122
+ maximumSessions?: number;
123
+ }
124
+ /**
125
+ * Lets preview deploys sign in through the stable deploy's registered OAuth callbacks
126
+ * (Better Auth `oAuthProxy`).
127
+ */
128
+ export interface BetterAuthOAuthProxyConfig {
129
+ /** The base URL of the deploy that owns the registered callback URLs. */
130
+ productionURL: string;
131
+ }
132
+ /** Auth mail template ids: recovery links plus security notifications. */
133
+ export type BetterAuthMailTemplateId = "resetPassword" | "verifyEmail" | SecurityMailTemplateId;
134
+ /** A rendered (or overriding) auth mail template. */
135
+ export interface BetterAuthMailTemplate {
136
+ html?: string;
137
+ subject: string;
138
+ text?: string;
139
+ }
23
140
  /**
24
141
  * Configuration options for Better Auth integration.
25
142
  */
@@ -33,9 +150,10 @@ export interface BetterAuthConfig {
33
150
  */
34
151
  googleOAuth?: BetterAuthOAuthProvider;
35
152
  /**
36
- * Apple OAuth provider configuration.
153
+ * Apple OAuth provider configuration: either a pre-made client secret or the Sign in with
154
+ * Apple key, from which Terreno signs the client secret at startup.
37
155
  */
38
- appleOAuth?: BetterAuthOAuthProvider;
156
+ appleOAuth?: BetterAuthAppleSecretProvider | BetterAuthAppleKeyProvider;
39
157
  /**
40
158
  * GitHub OAuth provider configuration.
41
159
  */
@@ -77,7 +195,8 @@ export interface BetterAuthConfig {
77
195
  }) => Promise<void>;
78
196
  /**
79
197
  * Render reset/verify mail. Pass `@terreno/comms` `renderAuthMail` so JWT and
80
- * Better Auth send identical templates.
198
+ * Better Auth send identical templates. Security notifications do not use it; see
199
+ * `AccountSecurityApp` `notifications.render`.
81
200
  */
82
201
  renderAuthMail?: (options: {
83
202
  publicAppUrl: string;
@@ -93,12 +212,11 @@ export interface BetterAuthConfig {
93
212
  subject: string;
94
213
  text?: string;
95
214
  };
96
- /** Optional per-app subject/text/html overrides for auth mail. */
97
- authMailTemplates?: Partial<Record<"resetPassword" | "verifyEmail", {
98
- html?: string;
99
- subject: string;
100
- text?: string;
101
- }>>;
215
+ /**
216
+ * Optional per-app subject/text/html overrides for auth mail, including the `security*`
217
+ * notification templates `AccountSecurityApp` sends.
218
+ */
219
+ authMailTemplates?: Partial<Record<BetterAuthMailTemplateId, BetterAuthMailTemplate>>;
102
220
  /**
103
221
  * Disable Better Auth's built-in IP limiter. Use only on throwaway in-process
104
222
  * seed apps — production `BetterAuthApp` instances keep the default (on in
@@ -115,7 +233,32 @@ export interface BetterAuthConfig {
115
233
  */
116
234
  options?: BetterAuthOptionsOverride;
117
235
  /**
118
- * Better Auth plugins, appended after Terreno's `bearer()` plugin. Their endpoints mount
236
+ * Account linking policy for same-email sign-ins. Maps to Better Auth's
237
+ * `account.accountLinking`. Unset keeps Better Auth's default (`verified-email`).
238
+ */
239
+ accountLinking?: BetterAuthAccountLinkingConfig;
240
+ /** Two-factor authentication. Unset by default. */
241
+ twoFactor?: BetterAuthTwoFactorConfig;
242
+ /** Passkey sign-in and registration. Unset by default. */
243
+ passkey?: BetterAuthPasskeyConfig;
244
+ /** Open or closed sign-up. Defaults to `{mode: "open"}`. */
245
+ signUp?: BetterAuthSignUpConfig;
246
+ /**
247
+ * Remember the method each user last signed in with, in a cookie and on the Better Auth user
248
+ * (`lastLoginMethod`). Off by default.
249
+ */
250
+ lastLoginMethod?: boolean;
251
+ /** Several signed-in accounts per device. Unset by default. */
252
+ multiSession?: BetterAuthMultiSessionConfig;
253
+ /** Proxy OAuth callbacks from the stable deploy to preview deploys. Unset by default. */
254
+ oauthProxy?: BetterAuthOAuthProxyConfig;
255
+ /**
256
+ * Register the `@better-auth/expo` server plugin so native apps can sign in with social
257
+ * providers through the system browser. Off by default.
258
+ */
259
+ nativeApps?: boolean;
260
+ /**
261
+ * Better Auth plugins, appended after Terreno's `bearer()`, methods and feature plugins. Their endpoints mount
119
262
  * under `basePath`. They are not added to the `auth.api` type.
120
263
  */
121
264
  plugins?: BetterAuthPlugin[];
@@ -155,6 +298,32 @@ export interface BetterAuthConfig {
155
298
  * The handoff is for bearer clients only. A handed-off callback redirect carries no session
156
299
  * cookie for the API's origin, and verify drops every Set-Cookie it would send (the session
157
300
  * cookies and any a plugin adds there), so a cookie-mode app gets no session from it.
301
+ *
302
+ * Linking a provider to the signed-in user takes two steps, because the link must also start
303
+ * from a top-level navigation and a bearer cannot ride along on one:
304
+ * - `POST {basePath}/oauth-handoff/link-intent`, authenticated with the bearer (or a cookie
305
+ * session), body `{provider, callbackURL, errorCallbackURL?}`, answers
306
+ * `{token, startURL}`. Both URLs must be absolute and on one of `webOrigins` that
307
+ * `trustedOrigins` allows; `callbackPaths` do not apply, since no token travels on a link's
308
+ * return (400 otherwise; Better Auth's own origin check answers 403 first for an untrusted
309
+ * one). It answers 403
310
+ * `LINKING_DISABLED` when account linking is off. The token is single-use, expires in three
311
+ * minutes, and is stored hashed in the verification table (`terreno-link-intent:<hash>`),
312
+ * bound to the caller's session.
313
+ * - `POST {basePath}/oauth-handoff/link-start`, a form post (`token=<token>`) the web app
314
+ * submits as a page navigation, so the token never appears in a URL. It answers 400 when
315
+ * `Sec-Fetch-Dest` is set and is not `document`, and 403 when `Origin` is missing, `null`, or
316
+ * not one of `webOrigins`; neither uses the token. The web origins must therefore not serve
317
+ * `Referrer-Policy: no-referrer` or `same-origin`, which make the form's `Origin` `null`. It then uses the token up (400 with no redirect
318
+ * when it is unknown, used, or expired), runs Better Auth's link flow as the token's
319
+ * session, sets only the OAuth state cookie, and redirects to the provider.
320
+ * A link that cannot start redirects to `errorCallbackURL` (or `callbackURL`) with
321
+ * `error=session_expired` (the session was revoked after the intent),
322
+ * `error=provider_not_found`, or `error=link_failed`.
323
+ *
324
+ * The provider callback links the account and redirects to `callbackURL` without a token,
325
+ * since no session is created. Better Auth's limiter allows three link intents and three link
326
+ * starts per ten seconds per IP.
158
327
  */
159
328
  oauthHandoff?: BetterAuthOAuthHandoffConfig;
160
329
  }
@@ -17,8 +17,15 @@ import type { TerrenoPlugin } from "./terrenoPlugin";
17
17
  export interface BetterAuthProvider {
18
18
  getAuth: () => BetterAuthInstance | undefined;
19
19
  ensureAuth?: () => BetterAuthInstance;
20
+ /**
21
+ * Hands the provider the host app's user model when it was given none of its own. TerrenoApp
22
+ * calls it before anything creates the Better Auth instance.
23
+ */
24
+ adoptUserModel?: (userModel: UserModel) => void;
20
25
  markSessionMiddlewareMounted?: () => void;
21
26
  getBetterAuthBasePath?: () => string;
27
+ /** The Terreno config the instance was built from (for `publicAppUrl` and similar). */
28
+ getBetterAuthConfig?: () => BetterAuthConfig;
22
29
  }
23
30
  /** Whether a registered plugin provides the app's Better Auth instance. */
24
31
  export declare const isBetterAuthProvider: (plugin: unknown) => plugin is BetterAuthProvider;
@@ -36,8 +43,16 @@ export declare class BetterAuthApp implements TerrenoPlugin {
36
43
  private sessionMiddlewareMounted;
37
44
  constructor(options: BetterAuthAppOptions);
38
45
  ensureAuth(): BetterAuthInstance;
46
+ /**
47
+ * Uses `userModel` (TerrenoApp's) when this plugin was constructed without one. The app User
48
+ * guard and sync (`terreno-app-user-sync`) are installed when the Better Auth instance is
49
+ * created, so a user model that arrives after that would leave sign-ups unguarded while the
50
+ * session middleware still links app Users: that is refused at boot instead.
51
+ */
52
+ adoptUserModel(userModel: UserModel): void;
39
53
  markSessionMiddlewareMounted(): void;
40
54
  register(app: express.Application): void;
55
+ getBetterAuthConfig(): BetterAuthConfig;
41
56
  getBetterAuthBasePath(): string;
42
57
  getAuth(): BetterAuthInstance | undefined;
43
58
  }
@@ -8,6 +8,7 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.BetterAuthApp = exports.getProvidedBetterAuth = exports.findBetterAuthProvider = exports.isBetterAuthProvider = void 0;
10
10
  const betterAuthSetup_1 = require("./betterAuthSetup");
11
+ const errors_1 = require("./errors");
11
12
  const logger_1 = require("./logger");
12
13
  /** Whether a registered plugin provides the app's Better Auth instance. */
13
14
  const isBetterAuthProvider = (plugin) => typeof plugin === "object" &&
@@ -42,6 +43,25 @@ class BetterAuthApp {
42
43
  }
43
44
  return this.auth;
44
45
  }
46
+ /**
47
+ * Uses `userModel` (TerrenoApp's) when this plugin was constructed without one. The app User
48
+ * guard and sync (`terreno-app-user-sync`) are installed when the Better Auth instance is
49
+ * created, so a user model that arrives after that would leave sign-ups unguarded while the
50
+ * session middleware still links app Users: that is refused at boot instead.
51
+ */
52
+ adoptUserModel(userModel) {
53
+ if (this.options.userModel) {
54
+ return;
55
+ }
56
+ if (this.auth) {
57
+ throw new errors_1.APIError({
58
+ detail: "Pass userModel to BetterAuthApp, or let TerrenoApp build it first.",
59
+ status: 500,
60
+ title: "BetterAuthApp created Better Auth before it was given a userModel",
61
+ });
62
+ }
63
+ this.options = { ...this.options, userModel };
64
+ }
45
65
  markSessionMiddlewareMounted() {
46
66
  this.sessionMiddlewareMounted = true;
47
67
  }
@@ -56,6 +76,9 @@ class BetterAuthApp {
56
76
  }
57
77
  logger_1.logger.info("Better Auth initialized via BetterAuthApp plugin");
58
78
  }
79
+ getBetterAuthConfig() {
80
+ return this.options.config;
81
+ }
59
82
  getBetterAuthBasePath() {
60
83
  return this.options.config.basePath ?? "/api/auth";
61
84
  }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Carries Better Auth's challenge cookies (the two-factor challenge, the trust-device token, and
3
+ * the passkey challenge) in a response and request header, so a bearer-mode web client
4
+ * (`credentials: "omit"`) on another site can finish two-factor and passkey sign-in without
5
+ * cookies.
6
+ *
7
+ * Better Auth keeps each of those values in a signed cookie. This plugin copies the signed
8
+ * values from Set-Cookie into `X-Terreno-Auth-Challenge` on the way out, and turns the header
9
+ * back into cookies on the way in. The values stay signed with the auth secret, so a client
10
+ * cannot forge or alter one: Better Auth's `getSignedCookie` rejects a bad signature exactly as
11
+ * it would for a cookie.
12
+ */
13
+ import type { BetterAuthPlugin } from "better-auth";
14
+ /**
15
+ * The header that carries challenge cookies. A client opts in by sending it on a challenge
16
+ * request (`AUTH_CHALLENGE_EMPTY` when it holds none); only then does a response carry it.
17
+ */
18
+ export declare const AUTH_CHALLENGE_HEADER = "X-Terreno-Auth-Challenge";
19
+ /** The value a client sends when it holds no challenge cookies, to opt in to receiving them. */
20
+ export declare const AUTH_CHALLENGE_EMPTY = "-";
21
+ /**
22
+ * The Better Auth plugin behind cookie-free challenges. `buildFeaturePlugins` adds it after the
23
+ * two-factor and passkey plugins whenever either is configured, so its after hook sees the
24
+ * cookies their hooks set.
25
+ *
26
+ * - Requests: on `{basePath}/two-factor/*`, `/passkey/*`, and `/sign-in/*` (where a trusted
27
+ * device is checked), the header's challenge cookies are merged into the Cookie header. This
28
+ * runs in `onRequest`, before endpoint hooks, so `bearer()` still adds the session cookie on
29
+ * top (a passkey registration needs both).
30
+ * - Responses: when the request sent the header, the challenge cookies the response sets are
31
+ * copied into it, and it is added to `Access-Control-Expose-Headers` the way `bearer()`
32
+ * exposes `set-auth-token`. A sign-in that answers with a two-factor challenge loses the
33
+ * `set-auth-token` of the session two-factor deleted. Only values the response sets are
34
+ * copied, and only for requests that send the header, so a cookie-mode page whose own code
35
+ * never sends it keeps its challenge cookies httpOnly.
36
+ */
37
+ export declare const createChallengeHeadersPlugin: () => BetterAuthPlugin;
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ /**
3
+ * Carries Better Auth's challenge cookies (the two-factor challenge, the trust-device token, and
4
+ * the passkey challenge) in a response and request header, so a bearer-mode web client
5
+ * (`credentials: "omit"`) on another site can finish two-factor and passkey sign-in without
6
+ * cookies.
7
+ *
8
+ * Better Auth keeps each of those values in a signed cookie. This plugin copies the signed
9
+ * values from Set-Cookie into `X-Terreno-Auth-Challenge` on the way out, and turns the header
10
+ * back into cookies on the way in. The values stay signed with the auth secret, so a client
11
+ * cannot forge or alter one: Better Auth's `getSignedCookie` rejects a bad signature exactly as
12
+ * it would for a cookie.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createChallengeHeadersPlugin = exports.AUTH_CHALLENGE_EMPTY = exports.AUTH_CHALLENGE_HEADER = void 0;
16
+ const api_1 = require("better-auth/api");
17
+ const cookies_1 = require("better-auth/cookies");
18
+ const luxon_1 = require("luxon");
19
+ /**
20
+ * The header that carries challenge cookies. A client opts in by sending it on a challenge
21
+ * request (`AUTH_CHALLENGE_EMPTY` when it holds none); only then does a response carry it.
22
+ */
23
+ exports.AUTH_CHALLENGE_HEADER = "X-Terreno-Auth-Challenge";
24
+ /** The value a client sends when it holds no challenge cookies, to opt in to receiving them. */
25
+ exports.AUTH_CHALLENGE_EMPTY = "-";
26
+ /** Better Auth paths, relative to its base path, whose requests accept the header. */
27
+ const AUTH_CHALLENGE_PATH_PREFIXES = ["/two-factor/", "/passkey/", "/sign-in/"];
28
+ // Three signed cookies fit comfortably; anything longer is not ours and is ignored.
29
+ const MAX_HEADER_LENGTH = 4096;
30
+ const TWO_FACTOR_COOKIE = "two_factor";
31
+ const TRUST_DEVICE_COOKIE = "trust_device";
32
+ const DONT_REMEMBER_COOKIE = "dont_remember";
33
+ const DEFAULT_PASSKEY_COOKIE = "better-auth-passkey";
34
+ /**
35
+ * The challenge cookies the header may carry. Session cookies are never among them, so the header
36
+ * can never set a session.
37
+ */
38
+ const challengeCookieNames = (context) => {
39
+ const passkey = context.getPlugin("passkey");
40
+ const passkeyCookie = passkey?.options?.advanced?.webAuthnChallengeCookie ?? DEFAULT_PASSKEY_COOKIE;
41
+ return {
42
+ dontRemember: context.createAuthCookie(DONT_REMEMBER_COOKIE).name,
43
+ passkey: context.createAuthCookie(passkeyCookie).name,
44
+ trustDevice: context.createAuthCookie(TRUST_DEVICE_COOKIE).name,
45
+ twoFactor: context.createAuthCookie(TWO_FACTOR_COOKIE).name,
46
+ };
47
+ };
48
+ const isChallengePath = (url, baseURL) => {
49
+ const basePath = new URL(baseURL).pathname.replace(/\/+$/, "");
50
+ const { pathname } = new URL(url);
51
+ if (!pathname.startsWith(`${basePath}/`)) {
52
+ return false;
53
+ }
54
+ const relative = pathname.slice(basePath.length);
55
+ return AUTH_CHALLENGE_PATH_PREFIXES.some((prefix) => relative.startsWith(prefix));
56
+ };
57
+ const readChallengeHeader = (headers) => {
58
+ const value = headers?.get(exports.AUTH_CHALLENGE_HEADER);
59
+ if (!value || value.length > MAX_HEADER_LENGTH) {
60
+ return null;
61
+ }
62
+ return value;
63
+ };
64
+ /**
65
+ * Adds the challenge cookies named in the header to the request's Cookie header. A cookie the
66
+ * request already carries wins, and names outside the challenge list are ignored. Returns null
67
+ * when nothing changes.
68
+ */
69
+ const mergeChallengeCookies = (request, context) => {
70
+ const header = readChallengeHeader(request.headers);
71
+ if (!header) {
72
+ return null;
73
+ }
74
+ const carried = new URLSearchParams(header);
75
+ const existing = (0, cookies_1.parseCookies)(request.headers.get("cookie") ?? "");
76
+ const headers = new Headers(request.headers);
77
+ let isChanged = false;
78
+ for (const name of Object.values(challengeCookieNames(context))) {
79
+ const value = carried.get(name);
80
+ if (!value || existing.has(name)) {
81
+ continue;
82
+ }
83
+ (0, cookies_1.setRequestCookie)(headers, name, value);
84
+ isChanged = true;
85
+ }
86
+ return isChanged ? headers : null;
87
+ };
88
+ const isExpired = (cookie) => {
89
+ if (!cookie.value || cookie["max-age"] === 0) {
90
+ return true;
91
+ }
92
+ return Boolean(cookie.expires && luxon_1.DateTime.fromJSDate(cookie.expires) <= luxon_1.DateTime.now());
93
+ };
94
+ /**
95
+ * The challenge cookies a response sets, as `name=value` pairs (URL search params). An expired
96
+ * cookie is sent with an empty value, which tells the client to forget it. `dont_remember` goes
97
+ * only with the two-factor challenge it belongs to, since every `rememberMe: false` sign-in
98
+ * sets it.
99
+ */
100
+ const collectChallengeCookies = (setCookie, names) => {
101
+ const parsed = (0, cookies_1.parseSetCookieHeader)(setCookie);
102
+ const pairs = new URLSearchParams();
103
+ const carried = [names.twoFactor, names.trustDevice, names.passkey];
104
+ if (parsed.has(names.twoFactor)) {
105
+ carried.push(names.dontRemember);
106
+ }
107
+ for (const name of carried) {
108
+ const cookie = parsed.get(name);
109
+ if (!cookie) {
110
+ continue;
111
+ }
112
+ pairs.set(name, isExpired(cookie) ? "" : cookie.value);
113
+ }
114
+ return pairs;
115
+ };
116
+ /**
117
+ * The Better Auth plugin behind cookie-free challenges. `buildFeaturePlugins` adds it after the
118
+ * two-factor and passkey plugins whenever either is configured, so its after hook sees the
119
+ * cookies their hooks set.
120
+ *
121
+ * - Requests: on `{basePath}/two-factor/*`, `/passkey/*`, and `/sign-in/*` (where a trusted
122
+ * device is checked), the header's challenge cookies are merged into the Cookie header. This
123
+ * runs in `onRequest`, before endpoint hooks, so `bearer()` still adds the session cookie on
124
+ * top (a passkey registration needs both).
125
+ * - Responses: when the request sent the header, the challenge cookies the response sets are
126
+ * copied into it, and it is added to `Access-Control-Expose-Headers` the way `bearer()`
127
+ * exposes `set-auth-token`. A sign-in that answers with a two-factor challenge loses the
128
+ * `set-auth-token` of the session two-factor deleted. Only values the response sets are
129
+ * copied, and only for requests that send the header, so a cookie-mode page whose own code
130
+ * never sends it keeps its challenge cookies httpOnly.
131
+ */
132
+ const createChallengeHeadersPlugin = () => {
133
+ return {
134
+ hooks: {
135
+ after: [
136
+ {
137
+ handler: (0, api_1.createAuthMiddleware)(async (ctx) => {
138
+ const responseHeaders = ctx.context.responseHeaders;
139
+ const setCookie = responseHeaders?.get("set-cookie");
140
+ if (!responseHeaders || !setCookie) {
141
+ return;
142
+ }
143
+ const names = challengeCookieNames(ctx.context);
144
+ const pairs = collectChallengeCookies(setCookie, names);
145
+ if (pairs.size === 0) {
146
+ return;
147
+ }
148
+ // A sign-in that needs a second factor kept no session: two-factor deleted the one
149
+ // bearer() had already turned into `set-auth-token`, so that token is dead.
150
+ if (pairs.get(names.twoFactor) && !ctx.context.newSession) {
151
+ responseHeaders.delete("set-auth-token");
152
+ }
153
+ const encoded = pairs.toString();
154
+ const exposed = new Set((responseHeaders.get("access-control-expose-headers") ?? "")
155
+ .split(",")
156
+ .map((header) => header.trim())
157
+ .filter(Boolean));
158
+ exposed.add(exports.AUTH_CHALLENGE_HEADER);
159
+ ctx.setHeader(exports.AUTH_CHALLENGE_HEADER, encoded);
160
+ ctx.setHeader("Access-Control-Expose-Headers", Array.from(exposed).join(", "));
161
+ }),
162
+ matcher: (context) => Boolean(readChallengeHeader(context.request?.headers) ?? readChallengeHeader(context.headers)),
163
+ },
164
+ ],
165
+ },
166
+ id: "terreno-challenge-headers",
167
+ onRequest: async (request, context) => {
168
+ if (!isChallengePath(request.url, context.baseURL)) {
169
+ return undefined;
170
+ }
171
+ const headers = mergeChallengeCookies(request, context);
172
+ if (!headers) {
173
+ return undefined;
174
+ }
175
+ // `duplex` lets a streamed body move to the new request on Node's fetch implementation.
176
+ return { request: new Request(request, { duplex: "half", headers }) };
177
+ },
178
+ };
179
+ };
180
+ exports.createChallengeHeadersPlugin = createChallengeHeadersPlugin;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Maps the auth feature fields of `BetterAuthConfig` (two-factor, passkeys, sign-up mode,
3
+ * account linking, and the rest) to Better Auth plugins and options, so consumers switch
4
+ * features on in config instead of assembling Better Auth plugins by hand.
5
+ */
6
+ import "reflect-metadata";
7
+ import type { BetterAuthPlugin } from "better-auth";
8
+ import type { BetterAuthAppleKeyProvider, BetterAuthAppleSecretProvider, BetterAuthConfig, BetterAuthOptionsOverride } from "./betterAuth";
9
+ /**
10
+ * Builds the Better Auth plugins for every configured auth feature, in a fixed order. Features
11
+ * are opt-in: a config with none of the fields returns an empty list. `baseURL` is the resolved
12
+ * server URL (it defaults to `config.baseURL`), which `oauthProxy` compares with `productionURL`.
13
+ */
14
+ export declare const buildFeaturePlugins: (config: BetterAuthConfig, baseURL?: string | undefined) => BetterAuthPlugin[];
15
+ /**
16
+ * Builds the Better Auth options the feature fields set: the account linking policy and closed
17
+ * email sign-up. `config.options` is merged over the result, so an explicit option still wins.
18
+ */
19
+ export declare const buildFeatureOptions: (config: BetterAuthConfig) => BetterAuthOptionsOverride;
20
+ /** Whether `signUp.mode` is `closed`. */
21
+ export declare const isSignUpClosed: (config: BetterAuthConfig) => boolean;
22
+ /**
23
+ * The plugin `createBetterAuth` adds after `config.plugins` when `signUp.mode` is `closed`.
24
+ * Its init runs after every other plugin's, so it reaches the social providers Better Auth
25
+ * built from `socialProviders` and the ones `genericOAuth` registered, and marks each one so a
26
+ * sign-in for an unknown email fails with `signup_disabled`. It sets the top-level
27
+ * `disableSignUp` (read by the ID-token sign-in path), `options.disableSignUp` (read by the
28
+ * OAuth callback and the OAuth proxy), and `disableImplicitSignUp`; a client's
29
+ * `requestSignUp: true` cannot undo `disableSignUp`.
30
+ */
31
+ export declare const createSignUpClosedPlugin: () => BetterAuthPlugin;
32
+ /**
33
+ * The plugin `createBetterAuth` adds when linking is off (`accountLinking: {mode: "never"}`, or
34
+ * `options.account.accountLinking.enabled: false`). Better Auth itself only refuses such a link
35
+ * when the provider calls back; this refuses `POST {basePath}/link-social` up front with 403
36
+ * `LINKING_DISABLED`, so a client never sends the user to the provider for nothing.
37
+ */
38
+ export declare const createLinkingDisabledPlugin: () => BetterAuthPlugin;
39
+ /**
40
+ * Signs the ES256 client-secret JWT Sign in with Apple expects, valid for 180 days from now.
41
+ * Uses `node:crypto` because `createBetterAuth` is synchronous.
42
+ */
43
+ export declare const createAppleClientSecret: (key: BetterAuthAppleKeyProvider) => string;
44
+ /** The Better Auth `socialProviders.apple` entry for either `appleOAuth` form. */
45
+ export interface AppleSocialProviderConfig {
46
+ appBundleIdentifier?: string;
47
+ clientId: string;
48
+ clientSecret: string;
49
+ }
50
+ /**
51
+ * Resolves `appleOAuth` to a Better Auth provider config, signing the client secret when the
52
+ * key form is used.
53
+ */
54
+ export declare const resolveAppleProvider: (apple: BetterAuthAppleSecretProvider | BetterAuthAppleKeyProvider) => AppleSocialProviderConfig;