@terreno/api 57.19.2 → 57.21.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 (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -0,0 +1,283 @@
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
+
7
+ import {createPrivateKey, createSign, type KeyObject} from "node:crypto";
8
+ // Before the passkey plugin: its @peculiar/x509 dependency loads tsyringe, which needs the
9
+ // Reflect polyfill, and `bun build --compile` can run tsyringe ahead of x509's own import.
10
+ import "reflect-metadata";
11
+ import {expo} from "@better-auth/expo";
12
+ import {passkey} from "@better-auth/passkey";
13
+ import type {BetterAuthPlugin} from "better-auth";
14
+ import {APIError as BetterAuthAPIError, createAuthMiddleware} from "better-auth/api";
15
+ import {lastLoginMethod, multiSession, oAuthProxy, twoFactor} from "better-auth/plugins";
16
+ import {DateTime} from "luxon";
17
+ import type {
18
+ BetterAuthAppleKeyProvider,
19
+ BetterAuthAppleSecretProvider,
20
+ BetterAuthConfig,
21
+ BetterAuthOptionsOverride,
22
+ } from "./betterAuth";
23
+ import {createChallengeHeadersPlugin} from "./betterAuthChallengeHeaders";
24
+ import {APIError} from "./errors";
25
+
26
+ const SECONDS_PER_DAY = 24 * 60 * 60;
27
+
28
+ /** Apple accepts client secrets that expire at most six months after they are issued. */
29
+ const APPLE_CLIENT_SECRET_DAYS = 180;
30
+
31
+ const APPLE_AUDIENCE = "https://appleid.apple.com";
32
+
33
+ const invalidPasskeyConfig = (detail: string): APIError =>
34
+ new APIError({detail, status: 500, title: "passkey config is invalid"});
35
+
36
+ /**
37
+ * Refuses a passkey config whose origins a browser could never use with `rpID`, so the mistake
38
+ * shows at startup rather than as a failed WebAuthn ceremony.
39
+ */
40
+ const assertPasskeyOrigins = (origins: string[], rpID: string): void => {
41
+ if (origins.length === 0) {
42
+ throw invalidPasskeyConfig("passkey.origin must list at least one origin");
43
+ }
44
+ for (const entry of origins) {
45
+ let url: URL;
46
+ try {
47
+ url = new URL(entry);
48
+ } catch {
49
+ throw invalidPasskeyConfig(`passkey.origin "${entry}" is not an absolute URL`);
50
+ }
51
+ if ((url.protocol !== "https:" && url.protocol !== "http:") || url.origin !== entry) {
52
+ throw invalidPasskeyConfig(
53
+ `passkey.origin "${entry}" must be a bare http(s) origin such as "https://app.example.com"`
54
+ );
55
+ }
56
+ if (url.hostname !== rpID && !url.hostname.endsWith(`.${rpID}`)) {
57
+ throw invalidPasskeyConfig(
58
+ `passkey.origin "${entry}" is not on passkey.rpID "${rpID}" or one of its subdomains`
59
+ );
60
+ }
61
+ }
62
+ };
63
+
64
+ // The origin of an absolute URL, or undefined when it does not parse.
65
+ const originOf = (url: string | undefined): string | undefined => {
66
+ if (!url) {
67
+ return undefined;
68
+ }
69
+ try {
70
+ return new URL(url).origin;
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ };
75
+
76
+ /**
77
+ * Better Auth's `oAuthProxy` for `config.oauthProxy`. On the production server itself
78
+ * (`productionURL` on the same origin as `baseURL`), `currentURL` is set to `productionURL`, so
79
+ * every sign-in it starts skips the proxy: a server-side start (such as the OAuth handoff) has no
80
+ * request URL to compare, and clients may reach it on another host (a Cloud Run tag URL). Its
81
+ * own sign-ins then keep Better Auth's state-cookie check, while its callback still forwards
82
+ * previews' returns.
83
+ */
84
+ const buildOAuthProxyPlugin = (
85
+ proxy: NonNullable<BetterAuthConfig["oauthProxy"]>,
86
+ baseURL: string | undefined
87
+ ): BetterAuthPlugin => {
88
+ const isProductionServer =
89
+ originOf(baseURL) !== undefined && originOf(baseURL) === originOf(proxy.productionURL);
90
+ return oAuthProxy({
91
+ productionURL: proxy.productionURL,
92
+ ...(isProductionServer ? {currentURL: proxy.productionURL} : {}),
93
+ }) as unknown as BetterAuthPlugin;
94
+ };
95
+
96
+ /**
97
+ * Builds the Better Auth plugins for every configured auth feature, in a fixed order. Features
98
+ * are opt-in: a config with none of the fields returns an empty list. `baseURL` is the resolved
99
+ * server URL (it defaults to `config.baseURL`), which `oauthProxy` compares with `productionURL`.
100
+ */
101
+ export const buildFeaturePlugins = (
102
+ config: BetterAuthConfig,
103
+ baseURL: string | undefined = config.baseURL
104
+ ): BetterAuthPlugin[] => {
105
+ const plugins: BetterAuthPlugin[] = [];
106
+ if (config.twoFactor) {
107
+ const {backupCodes, issuer, trustDeviceDays} = config.twoFactor;
108
+ plugins.push(
109
+ twoFactor({
110
+ backupCodeOptions: backupCodes,
111
+ issuer,
112
+ trustDeviceMaxAge:
113
+ trustDeviceDays === undefined ? undefined : trustDeviceDays * SECONDS_PER_DAY,
114
+ })
115
+ );
116
+ }
117
+ if (config.passkey) {
118
+ const {origin, rpID, rpName} = config.passkey;
119
+ assertPasskeyOrigins(origin, rpID);
120
+ plugins.push(passkey({origin, rpID, rpName}) as unknown as BetterAuthPlugin);
121
+ }
122
+ if (config.twoFactor || config.passkey) {
123
+ // After both, so its after hook sees the challenge cookies their hooks set.
124
+ plugins.push(createChallengeHeadersPlugin());
125
+ }
126
+ if (config.lastLoginMethod) {
127
+ plugins.push(lastLoginMethod({storeInDatabase: true}) as unknown as BetterAuthPlugin);
128
+ }
129
+ if (config.multiSession) {
130
+ // Better Auth spreads options over its defaults, so an explicit undefined would erase its cap.
131
+ const {maximumSessions} = config.multiSession;
132
+ plugins.push(multiSession(maximumSessions === undefined ? {} : {maximumSessions}));
133
+ }
134
+ if (config.oauthProxy) {
135
+ plugins.push(buildOAuthProxyPlugin(config.oauthProxy, baseURL));
136
+ }
137
+ if (config.nativeApps) {
138
+ plugins.push(expo() as unknown as BetterAuthPlugin);
139
+ }
140
+ return plugins;
141
+ };
142
+
143
+ /**
144
+ * Builds the Better Auth options the feature fields set: the account linking policy and closed
145
+ * email sign-up. `config.options` is merged over the result, so an explicit option still wins.
146
+ */
147
+ export const buildFeatureOptions = (config: BetterAuthConfig): BetterAuthOptionsOverride => {
148
+ const options: BetterAuthOptionsOverride = {};
149
+ if (config.accountLinking) {
150
+ const {mode, trustedProviders} = config.accountLinking;
151
+ options.account = {
152
+ accountLinking: {
153
+ disableImplicitLinking: mode === "explicit",
154
+ enabled: mode !== "never",
155
+ // Linking by email must never trust an unverified local account (takeover by
156
+ // pre-registration), whatever the mode.
157
+ requireLocalEmailVerified: true,
158
+ ...(trustedProviders ? {trustedProviders} : {}),
159
+ },
160
+ };
161
+ }
162
+ if (isSignUpClosed(config)) {
163
+ options.emailAndPassword = {disableSignUp: true};
164
+ }
165
+ return options;
166
+ };
167
+
168
+ /** Whether `signUp.mode` is `closed`. */
169
+ export const isSignUpClosed = (config: BetterAuthConfig): boolean =>
170
+ config.signUp?.mode === "closed";
171
+
172
+ /** The parts of a Better Auth OAuth provider the closed sign-up plugin changes. */
173
+ interface SignUpProviderLike {
174
+ disableImplicitSignUp?: boolean;
175
+ disableSignUp?: boolean;
176
+ options?: Record<string, unknown>;
177
+ }
178
+
179
+ /**
180
+ * The plugin `createBetterAuth` adds after `config.plugins` when `signUp.mode` is `closed`.
181
+ * Its init runs after every other plugin's, so it reaches the social providers Better Auth
182
+ * built from `socialProviders` and the ones `genericOAuth` registered, and marks each one so a
183
+ * sign-in for an unknown email fails with `signup_disabled`. It sets the top-level
184
+ * `disableSignUp` (read by the ID-token sign-in path), `options.disableSignUp` (read by the
185
+ * OAuth callback and the OAuth proxy), and `disableImplicitSignUp`; a client's
186
+ * `requestSignUp: true` cannot undo `disableSignUp`.
187
+ */
188
+ export const createSignUpClosedPlugin = (): BetterAuthPlugin => {
189
+ return {
190
+ id: "terreno-sign-up-closed",
191
+ init: (ctx): void => {
192
+ for (const provider of ctx.socialProviders as unknown as SignUpProviderLike[]) {
193
+ provider.disableImplicitSignUp = true;
194
+ provider.disableSignUp = true;
195
+ provider.options = {...provider.options, disableSignUp: true};
196
+ }
197
+ },
198
+ } satisfies BetterAuthPlugin;
199
+ };
200
+
201
+ /**
202
+ * The plugin `createBetterAuth` adds when linking is off (`accountLinking: {mode: "never"}`, or
203
+ * `options.account.accountLinking.enabled: false`). Better Auth itself only refuses such a link
204
+ * when the provider calls back; this refuses `POST {basePath}/link-social` up front with 403
205
+ * `LINKING_DISABLED`, so a client never sends the user to the provider for nothing.
206
+ */
207
+ export const createLinkingDisabledPlugin = (): BetterAuthPlugin => {
208
+ return {
209
+ hooks: {
210
+ before: [
211
+ {
212
+ handler: createAuthMiddleware(async (): Promise<never> => {
213
+ throw new BetterAuthAPIError("FORBIDDEN", {
214
+ code: "LINKING_DISABLED",
215
+ message: "Account linking is turned off",
216
+ });
217
+ }),
218
+ matcher: (context): boolean => context.path === "/link-social",
219
+ },
220
+ ],
221
+ },
222
+ id: "terreno-linking-disabled",
223
+ } satisfies BetterAuthPlugin;
224
+ };
225
+
226
+ const base64Url = (value: string | Buffer): string => Buffer.from(value).toString("base64url");
227
+
228
+ const loadApplePrivateKey = (privateKey: string): KeyObject => {
229
+ try {
230
+ return createPrivateKey(privateKey.replace(/\\n/g, "\n"));
231
+ } catch (error) {
232
+ throw new APIError({
233
+ cause: error,
234
+ status: 500,
235
+ title: "appleOAuth.privateKey must be a PEM (PKCS#8) Sign in with Apple key",
236
+ });
237
+ }
238
+ };
239
+
240
+ /**
241
+ * Signs the ES256 client-secret JWT Sign in with Apple expects, valid for 180 days from now.
242
+ * Uses `node:crypto` because `createBetterAuth` is synchronous.
243
+ */
244
+ export const createAppleClientSecret = (key: BetterAuthAppleKeyProvider): string => {
245
+ const signingKey = loadApplePrivateKey(key.privateKey);
246
+ const issuedAt = Math.floor(DateTime.now().toSeconds());
247
+ const header = {alg: "ES256", kid: key.keyId};
248
+ const payload = {
249
+ aud: APPLE_AUDIENCE,
250
+ exp: issuedAt + APPLE_CLIENT_SECRET_DAYS * SECONDS_PER_DAY,
251
+ iat: issuedAt,
252
+ iss: key.teamId,
253
+ sub: key.clientId,
254
+ };
255
+ const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
256
+ const signature = createSign("SHA256")
257
+ .update(signingInput)
258
+ .sign({dsaEncoding: "ieee-p1363", key: signingKey});
259
+ return `${signingInput}.${base64Url(signature)}`;
260
+ };
261
+
262
+ /** The Better Auth `socialProviders.apple` entry for either `appleOAuth` form. */
263
+ export interface AppleSocialProviderConfig {
264
+ appBundleIdentifier?: string;
265
+ clientId: string;
266
+ clientSecret: string;
267
+ }
268
+
269
+ /**
270
+ * Resolves `appleOAuth` to a Better Auth provider config, signing the client secret when the
271
+ * key form is used.
272
+ */
273
+ export const resolveAppleProvider = (
274
+ apple: BetterAuthAppleSecretProvider | BetterAuthAppleKeyProvider
275
+ ): AppleSocialProviderConfig => {
276
+ const clientSecret =
277
+ "clientSecret" in apple ? apple.clientSecret : createAppleClientSecret(apple);
278
+ return {
279
+ clientId: apple.clientId,
280
+ clientSecret,
281
+ ...(apple.appBundleIdentifier ? {appBundleIdentifier: apple.appBundleIdentifier} : {}),
282
+ };
283
+ };