@effect-auth/core 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (222) hide show
  1. package/README.md +774 -36
  2. package/dist/ApiKey.d.ts +207 -0
  3. package/dist/ApiKey.d.ts.map +1 -0
  4. package/dist/ApiKey.js +275 -0
  5. package/dist/ApiKey.js.map +1 -0
  6. package/dist/AuditLog.d.ts +278 -1
  7. package/dist/AuditLog.d.ts.map +1 -1
  8. package/dist/AuditLog.js +217 -2
  9. package/dist/AuditLog.js.map +1 -1
  10. package/dist/AuthConfig.d.ts +42 -0
  11. package/dist/AuthConfig.d.ts.map +1 -0
  12. package/dist/AuthConfig.js +43 -0
  13. package/dist/AuthConfig.js.map +1 -0
  14. package/dist/AuthFlow.d.ts +465 -36
  15. package/dist/AuthFlow.d.ts.map +1 -1
  16. package/dist/AuthFlow.js +660 -5
  17. package/dist/AuthFlow.js.map +1 -1
  18. package/dist/AuthKernel.d.ts +3 -0
  19. package/dist/AuthKernel.d.ts.map +1 -0
  20. package/dist/AuthKernel.js +9 -0
  21. package/dist/AuthKernel.js.map +1 -0
  22. package/dist/Challenge.d.ts +27 -4
  23. package/dist/Challenge.d.ts.map +1 -1
  24. package/dist/Challenge.js +170 -1
  25. package/dist/Challenge.js.map +1 -1
  26. package/dist/Client.d.ts +378 -0
  27. package/dist/Client.d.ts.map +1 -0
  28. package/dist/Client.js +768 -0
  29. package/dist/Client.js.map +1 -0
  30. package/dist/Crypto.d.ts +9 -1
  31. package/dist/Crypto.d.ts.map +1 -1
  32. package/dist/Crypto.js +65 -1
  33. package/dist/Crypto.js.map +1 -1
  34. package/dist/EffectQbSqliteStorage.d.ts +600 -0
  35. package/dist/EffectQbSqliteStorage.d.ts.map +1 -0
  36. package/dist/EffectQbSqliteStorage.js +1637 -0
  37. package/dist/EffectQbSqliteStorage.js.map +1 -0
  38. package/dist/EmailOtp.d.ts +120 -0
  39. package/dist/EmailOtp.d.ts.map +1 -0
  40. package/dist/EmailOtp.js +286 -0
  41. package/dist/EmailOtp.js.map +1 -0
  42. package/dist/EmailVerification.d.ts +121 -0
  43. package/dist/EmailVerification.d.ts.map +1 -0
  44. package/dist/EmailVerification.js +200 -0
  45. package/dist/EmailVerification.js.map +1 -0
  46. package/dist/HttpApi/Api.d.ts +1956 -0
  47. package/dist/HttpApi/Api.d.ts.map +1 -0
  48. package/dist/HttpApi/Api.js +2325 -0
  49. package/dist/HttpApi/Api.js.map +1 -0
  50. package/dist/HttpApi/Endpoints.d.ts +945 -0
  51. package/dist/HttpApi/Endpoints.d.ts.map +1 -0
  52. package/dist/HttpApi/Endpoints.js +373 -0
  53. package/dist/HttpApi/Endpoints.js.map +1 -0
  54. package/dist/HttpApi/Errors.d.ts +82 -0
  55. package/dist/HttpApi/Errors.d.ts.map +1 -0
  56. package/dist/HttpApi/Errors.js +184 -0
  57. package/dist/HttpApi/Errors.js.map +1 -0
  58. package/dist/HttpApi/Schemas.d.ts +1113 -0
  59. package/dist/HttpApi/Schemas.d.ts.map +1 -0
  60. package/dist/HttpApi/Schemas.js +734 -0
  61. package/dist/HttpApi/Schemas.js.map +1 -0
  62. package/dist/HttpApi/Security.d.ts +159 -0
  63. package/dist/HttpApi/Security.d.ts.map +1 -0
  64. package/dist/HttpApi/Security.js +530 -0
  65. package/dist/HttpApi/Security.js.map +1 -0
  66. package/dist/HttpApi/Transport.d.ts +65 -0
  67. package/dist/HttpApi/Transport.d.ts.map +1 -0
  68. package/dist/HttpApi/Transport.js +311 -0
  69. package/dist/HttpApi/Transport.js.map +1 -0
  70. package/dist/HttpApi/index.d.ts +8 -0
  71. package/dist/HttpApi/index.d.ts.map +1 -0
  72. package/dist/HttpApi/index.js +7 -0
  73. package/dist/HttpApi/index.js.map +1 -0
  74. package/dist/HttpApi.d.ts +2 -0
  75. package/dist/HttpApi.d.ts.map +1 -0
  76. package/dist/HttpApi.js +2 -0
  77. package/dist/HttpApi.js.map +1 -0
  78. package/dist/Identifiers.d.ts.map +1 -1
  79. package/dist/Identifiers.js.map +1 -1
  80. package/dist/Internal.d.ts +7 -0
  81. package/dist/Internal.d.ts.map +1 -0
  82. package/dist/Internal.js +12 -0
  83. package/dist/Internal.js.map +1 -0
  84. package/dist/Jwt.d.ts +271 -0
  85. package/dist/Jwt.d.ts.map +1 -0
  86. package/dist/Jwt.js +512 -0
  87. package/dist/Jwt.js.map +1 -0
  88. package/dist/LoginApproval.d.ts +314 -0
  89. package/dist/LoginApproval.d.ts.map +1 -0
  90. package/dist/LoginApproval.js +551 -0
  91. package/dist/LoginApproval.js.map +1 -0
  92. package/dist/LoginNotification.d.ts +183 -0
  93. package/dist/LoginNotification.d.ts.map +1 -0
  94. package/dist/LoginNotification.js +329 -0
  95. package/dist/LoginNotification.js.map +1 -0
  96. package/dist/LoginRisk.d.ts +73 -0
  97. package/dist/LoginRisk.d.ts.map +1 -0
  98. package/dist/LoginRisk.js +57 -0
  99. package/dist/LoginRisk.js.map +1 -0
  100. package/dist/MagicLink.d.ts +85 -0
  101. package/dist/MagicLink.d.ts.map +1 -0
  102. package/dist/MagicLink.js +206 -0
  103. package/dist/MagicLink.js.map +1 -0
  104. package/dist/Mailer.d.ts +147 -0
  105. package/dist/Mailer.d.ts.map +1 -0
  106. package/dist/Mailer.js +208 -0
  107. package/dist/Mailer.js.map +1 -0
  108. package/dist/OAuth.d.ts +934 -0
  109. package/dist/OAuth.d.ts.map +1 -0
  110. package/dist/OAuth.js +1661 -0
  111. package/dist/OAuth.js.map +1 -0
  112. package/dist/Passkey.d.ts +334 -0
  113. package/dist/Passkey.d.ts.map +1 -0
  114. package/dist/Passkey.js +422 -0
  115. package/dist/Passkey.js.map +1 -0
  116. package/dist/PasskeySimpleWebAuthn.d.ts +11 -0
  117. package/dist/PasskeySimpleWebAuthn.d.ts.map +1 -0
  118. package/dist/PasskeySimpleWebAuthn.js +181 -0
  119. package/dist/PasskeySimpleWebAuthn.js.map +1 -0
  120. package/dist/Password.d.ts +237 -0
  121. package/dist/Password.d.ts.map +1 -0
  122. package/dist/Password.js +641 -0
  123. package/dist/Password.js.map +1 -0
  124. package/dist/Policy.d.ts +7 -4
  125. package/dist/Policy.d.ts.map +1 -1
  126. package/dist/Policy.js +28 -5
  127. package/dist/Policy.js.map +1 -1
  128. package/dist/Privacy.d.ts +18 -0
  129. package/dist/Privacy.d.ts.map +1 -1
  130. package/dist/Privacy.js +63 -3
  131. package/dist/Privacy.js.map +1 -1
  132. package/dist/RateLimiter.d.ts +104 -0
  133. package/dist/RateLimiter.d.ts.map +1 -0
  134. package/dist/RateLimiter.js +118 -0
  135. package/dist/RateLimiter.js.map +1 -0
  136. package/dist/RecoveryCode.d.ts +169 -0
  137. package/dist/RecoveryCode.d.ts.map +1 -0
  138. package/dist/RecoveryCode.js +299 -0
  139. package/dist/RecoveryCode.js.map +1 -0
  140. package/dist/RefreshToken.d.ts +222 -0
  141. package/dist/RefreshToken.d.ts.map +1 -0
  142. package/dist/RefreshToken.js +342 -0
  143. package/dist/RefreshToken.js.map +1 -0
  144. package/dist/SecurityTimeline.d.ts +72 -0
  145. package/dist/SecurityTimeline.d.ts.map +1 -0
  146. package/dist/SecurityTimeline.js +386 -0
  147. package/dist/SecurityTimeline.js.map +1 -0
  148. package/dist/Sessions.d.ts +135 -11
  149. package/dist/Sessions.d.ts.map +1 -1
  150. package/dist/Sessions.js +546 -1
  151. package/dist/Sessions.js.map +1 -1
  152. package/dist/StepUp.d.ts +44 -0
  153. package/dist/StepUp.d.ts.map +1 -0
  154. package/dist/StepUp.js +82 -0
  155. package/dist/StepUp.js.map +1 -0
  156. package/dist/Storage.d.ts +175 -0
  157. package/dist/Storage.d.ts.map +1 -0
  158. package/dist/Storage.js +27 -0
  159. package/dist/Storage.js.map +1 -0
  160. package/dist/StorageMigrations.d.ts +19 -0
  161. package/dist/StorageMigrations.d.ts.map +1 -0
  162. package/dist/StorageMigrations.js +291 -0
  163. package/dist/StorageMigrations.js.map +1 -0
  164. package/dist/Testing.d.ts +9 -1
  165. package/dist/Testing.d.ts.map +1 -1
  166. package/dist/Testing.js +30 -2
  167. package/dist/Testing.js.map +1 -1
  168. package/dist/Totp.d.ts +220 -0
  169. package/dist/Totp.d.ts.map +1 -0
  170. package/dist/Totp.js +477 -0
  171. package/dist/Totp.js.map +1 -0
  172. package/dist/TrustedDevice.d.ts +127 -0
  173. package/dist/TrustedDevice.d.ts.map +1 -0
  174. package/dist/TrustedDevice.js +252 -0
  175. package/dist/TrustedDevice.js.map +1 -0
  176. package/dist/WaitUntil.d.ts +3 -0
  177. package/dist/WaitUntil.d.ts.map +1 -1
  178. package/dist/WaitUntil.js +6 -3
  179. package/dist/WaitUntil.js.map +1 -1
  180. package/dist/Webhook.d.ts +72 -0
  181. package/dist/Webhook.d.ts.map +1 -0
  182. package/dist/Webhook.js +82 -0
  183. package/dist/Webhook.js.map +1 -0
  184. package/dist/alchemy/cloudflare/Email.d.ts +25 -0
  185. package/dist/alchemy/cloudflare/Email.d.ts.map +1 -0
  186. package/dist/alchemy/cloudflare/Email.js +117 -0
  187. package/dist/alchemy/cloudflare/Email.js.map +1 -0
  188. package/dist/alchemy/cloudflare/RateLimitDurableObject.d.ts +34 -0
  189. package/dist/alchemy/cloudflare/RateLimitDurableObject.d.ts.map +1 -0
  190. package/dist/alchemy/cloudflare/RateLimitDurableObject.js +30 -0
  191. package/dist/alchemy/cloudflare/RateLimitDurableObject.js.map +1 -0
  192. package/dist/cloudflare/Email.d.ts +25 -0
  193. package/dist/cloudflare/Email.d.ts.map +1 -0
  194. package/dist/cloudflare/Email.js +153 -0
  195. package/dist/cloudflare/Email.js.map +1 -0
  196. package/dist/cloudflare/RateLimitDurableObject.d.ts +50 -0
  197. package/dist/cloudflare/RateLimitDurableObject.d.ts.map +1 -0
  198. package/dist/cloudflare/RateLimitDurableObject.js +51 -0
  199. package/dist/cloudflare/RateLimitDurableObject.js.map +1 -0
  200. package/dist/index.d.ts +22 -0
  201. package/dist/index.d.ts.map +1 -1
  202. package/dist/index.js +22 -0
  203. package/dist/index.js.map +1 -1
  204. package/dist/internal/RateLimitDurableObject.d.ts +32 -0
  205. package/dist/internal/RateLimitDurableObject.d.ts.map +1 -0
  206. package/dist/internal/RateLimitDurableObject.js +80 -0
  207. package/dist/internal/RateLimitDurableObject.js.map +1 -0
  208. package/migrations/0001_auth_storage.sql +32 -0
  209. package/migrations/0002_auth_password.sql +25 -0
  210. package/migrations/0003_auth_login_approval_review.sql +22 -0
  211. package/migrations/0004_auth_trusted_device.sql +12 -0
  212. package/migrations/0005_auth_passkey.sql +17 -0
  213. package/migrations/0006_auth_totp_factor.sql +17 -0
  214. package/migrations/0007_auth_recovery_code.sql +13 -0
  215. package/migrations/0008_auth_api_key.sql +17 -0
  216. package/migrations/0009_auth_refresh_token.sql +21 -0
  217. package/migrations/0010_auth_jwt_revocation.sql +8 -0
  218. package/migrations/0011_auth_oauth_account.sql +16 -0
  219. package/migrations/0012_auth_oauth_provider_token_vault.sql +20 -0
  220. package/migrations/0013_auth_security_timeline.sql +16 -0
  221. package/package.json +161 -16
  222. package/LICENSE +0 -21
@@ -0,0 +1,2325 @@
1
+ import { Effect, Layer, Option, Redacted } from "effect";
2
+ import { HttpServerResponse } from "effect/unstable/http";
3
+ import { HttpApi, HttpApiBuilder, HttpApiGroup } from "effect/unstable/httpapi";
4
+ import { ApiKeyId } from "../ApiKey.js";
5
+ import { AuthFlow, AuthFlowState, AuthResult, LoginApprovalFinalize, } from "../AuthFlow.js";
6
+ import { EmailOtpLogin } from "../EmailOtp.js";
7
+ import { EmailDeliveryError, EmailVerification, EmailVerificationFlow, EmailVerificationIssueError, } from "../EmailVerification.js";
8
+ import { currentUnixMillis } from "../Internal.js";
9
+ import { LoginApproval, LoginApprovalReview } from "../LoginApproval.js";
10
+ import { LoginNotification } from "../LoginNotification.js";
11
+ import { MagicLinkLogin } from "../MagicLink.js";
12
+ import { PasswordLogin, PasswordManagement, PasswordRegistration, PasswordReset, } from "../Password.js";
13
+ import { PasskeyCredentialId } from "../Passkey.js";
14
+ import { CurrentSession, SessionCookie, Sessions, sessionRequestMetadataKey, upgradeCurrentSession, } from "../Sessions.js";
15
+ import { SecurityTimelineStore } from "../SecurityTimeline.js";
16
+ import { UserStore } from "../Storage.js";
17
+ import { TrustedDevice, TrustedDeviceCookie, TrustedDeviceStore, } from "../TrustedDevice.js";
18
+ import { apiKeyCreateEndpoint, apiKeyListEndpoint, apiKeyRevokeEndpoint, currentSessionEndpoint, emailOtpStartEndpoint, emailOtpVerifyEndpoint, emailVerificationStartEndpoint, emailVerificationVerifyEndpoint, loginApprovalApproveEndpoint, loginApprovalFinalizeEndpoint, loginApprovalStatusEndpoint, loginNotificationReportEndpoint, jwtIntrospectEndpoint, jwtRevokeEndpoint, listSessionsEndpoint, logoutEndpoint, magicLinkStartEndpoint, magicLinkVerifyEndpoint, mfaOptionsEndpoint, oauthAccountUnlinkEndpoint, oauthAuthorizationStartEndpoint, oauthLinkConfirmationConfirmEndpoint, oauthLinkConfirmationInspectEndpoint, oauthLinkConfirmationStartEndpoint, passwordChangeEndpoint, passwordResetStartEndpoint, passwordResetVerifyEndpoint, passwordSetEndpoint, passwordSignInEndpoint, passwordSignUpEndpoint, passkeyMfaStartEndpoint, passkeyMfaVerifyEndpoint, recoveryCodeMfaVerifyEndpoint, recoveryCodeMfaVerifyForFlowEndpoint, refreshTokenRefreshEndpoint, refreshSessionEndpoint, revokeOtherSessionsEndpoint, revokeSessionEndpoint, securityTimelineListEndpoint, stepUpOptionsEndpoint, stepUpPasskeyStartEndpoint, stepUpPasskeyVerifyEndpoint, stepUpRecoveryCodeVerifyEndpoint, stepUpTotpVerifyEndpoint, trustedDeviceListEndpoint, trustedDeviceRevokeEndpoint, totpMfaVerifyEndpoint, totpMfaVerifyForFlowEndpoint, } from "./Endpoints.js";
19
+ import { AuthBadRequestError, AuthEmailAlreadyRegisteredError, AuthInternalError, AuthInvalidCredentialsError, AuthPolicyDeniedError, AuthRateLimitedError, AuthSchemaErrorMiddleware, AuthSchemaErrorMiddlewareLive, AuthUnauthenticatedError, } from "./Errors.js";
20
+ import { AuthApiRateLimit, AuthApiRateLimitLive, AuthApiRateLimitNoopLive, AuthHttpApiConfig, AuthOriginCheckMiddleware, AuthOriginCheckMiddlewareConfigLive, AuthRateLimitMiddleware, makeAuthRequestMetadata, } from "./Security.js";
21
+ import { AuthHttp, LoginApprovalPendingCookie, makeLoginApprovalPendingCookie, } from "./Transport.js";
22
+ const canStartRequiredEmailVerification = (result) => result._tag === "RequiresEmailVerification" &&
23
+ result.userId !== undefined &&
24
+ result.email !== undefined;
25
+ const noopAuthApiRateLimit = AuthApiRateLimit.make({
26
+ request: () => Effect.void,
27
+ passwordSignIn: () => Effect.void,
28
+ passwordSignUp: () => Effect.void,
29
+ passwordResetStart: () => Effect.void,
30
+ emailOtpStart: () => Effect.void,
31
+ magicLinkStart: () => Effect.void,
32
+ emailVerificationStart: () => Effect.void,
33
+ });
34
+ export const passwordSignInInput = (payload, trustedDeviceToken, request) => ({
35
+ ...payload,
36
+ password: Redacted.make(payload.password),
37
+ ...(trustedDeviceToken === undefined ? {} : { trustedDeviceToken }),
38
+ ...(request === undefined ? {} : { request }),
39
+ });
40
+ export const passwordSignUpInput = (payload, request) => ({
41
+ ...payload,
42
+ password: Redacted.make(payload.password),
43
+ ...(request === undefined ? {} : { request }),
44
+ });
45
+ export const passwordResetStartInput = (payload) => {
46
+ const { secret, ...input } = payload;
47
+ return {
48
+ ...input,
49
+ ...(secret === undefined ? {} : { secret: Redacted.make(secret) }),
50
+ };
51
+ };
52
+ export const passwordResetVerifyInput = (payload) => ({
53
+ challengeId: payload.challengeId,
54
+ secret: Redacted.make(payload.secret),
55
+ password: Redacted.make(payload.password),
56
+ });
57
+ export const passwordSetInput = (userId, payload) => ({
58
+ userId,
59
+ password: Redacted.make(payload.password),
60
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
61
+ });
62
+ export const passwordChangeInput = (userId, payload) => ({
63
+ userId,
64
+ currentPassword: Redacted.make(payload.currentPassword),
65
+ newPassword: Redacted.make(payload.newPassword),
66
+ });
67
+ export const emailVerificationStartInput = (payload) => {
68
+ const { secret, ...input } = payload;
69
+ return {
70
+ ...input,
71
+ ...(secret === undefined ? {} : { secret: Redacted.make(secret) }),
72
+ };
73
+ };
74
+ export const emailVerificationVerifyInput = (payload) => {
75
+ const { secret, ...input } = payload;
76
+ return {
77
+ ...input,
78
+ ...(secret === undefined ? {} : { secret: Redacted.make(secret) }),
79
+ };
80
+ };
81
+ export const emailOtpStartInput = (payload) => {
82
+ const { secret, ...input } = payload;
83
+ return {
84
+ ...input,
85
+ ...(secret === undefined ? {} : { secret: Redacted.make(secret) }),
86
+ };
87
+ };
88
+ export const emailOtpVerifyInput = (payload, trustedDeviceToken, request) => ({
89
+ challengeId: payload.challengeId,
90
+ secret: Redacted.make(payload.secret),
91
+ ...(trustedDeviceToken === undefined ? {} : { trustedDeviceToken }),
92
+ ...(request === undefined ? {} : { request }),
93
+ });
94
+ export const magicLinkStartInput = (payload) => {
95
+ const { secret, ...input } = payload;
96
+ return {
97
+ ...input,
98
+ ...(secret === undefined ? {} : { secret: Redacted.make(secret) }),
99
+ };
100
+ };
101
+ export const magicLinkVerifyInput = (payload, trustedDeviceToken, request) => ({
102
+ challengeId: payload.challengeId,
103
+ secret: Redacted.make(payload.secret),
104
+ ...(trustedDeviceToken === undefined ? {} : { trustedDeviceToken }),
105
+ ...(request === undefined ? {} : { request }),
106
+ });
107
+ export const oauthAuthorizationStartInput = (payload, provider, options = {}) => ({
108
+ provider,
109
+ ...(options.ttl === undefined ? {} : { ttl: options.ttl }),
110
+ ...(payload.redirectUri === undefined ? {} : { redirectUri: payload.redirectUri }),
111
+ ...(payload.scopes === undefined ? {} : { scopes: payload.scopes }),
112
+ ...(payload.authorizationParams === undefined
113
+ ? {}
114
+ : { authorizationParams: payload.authorizationParams }),
115
+ ...(payload.codeVerifier === undefined
116
+ ? {}
117
+ : { codeVerifier: Redacted.make(payload.codeVerifier) }),
118
+ ...(payload.includeNonce === undefined
119
+ ? {}
120
+ : { includeNonce: payload.includeNonce }),
121
+ ...(payload.nonce === undefined ? {} : { nonce: payload.nonce }),
122
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
123
+ });
124
+ export const oauthAuthorizationStartedHttpBody = (started) => ({
125
+ providerId: started.providerId,
126
+ authorizationUrl: started.authorizationUrl,
127
+ state: started.state,
128
+ challengeId: started.challengeId,
129
+ expiresAt: started.expiresAt,
130
+ codeChallenge: started.codeChallenge,
131
+ codeChallengeMethod: started.codeChallengeMethod,
132
+ ...(started.nonce === undefined ? {} : { nonce: started.nonce }),
133
+ redirectUri: started.redirectUri,
134
+ scopes: started.scopes,
135
+ });
136
+ const oauthVerifiedIdentityInput = (identity) => ({
137
+ providerId: identity.providerId,
138
+ providerAccountId: identity.providerAccountId,
139
+ ...(identity.email === undefined ? {} : { email: identity.email }),
140
+ ...(identity.emailVerified === undefined
141
+ ? {}
142
+ : { emailVerified: identity.emailVerified }),
143
+ ...(identity.metadata === undefined ? {} : { metadata: identity.metadata }),
144
+ });
145
+ export const oauthLinkConfirmationStartInput = (payload, options = {}) => Effect.gen(function* () {
146
+ if (payload.userId === undefined) {
147
+ return yield* oauthBadRequest("OAuth link confirmation is missing userId");
148
+ }
149
+ if (payload.identity === undefined) {
150
+ return yield* oauthBadRequest("OAuth link confirmation is missing identity");
151
+ }
152
+ return {
153
+ userId: payload.userId,
154
+ identity: oauthVerifiedIdentityInput(payload.identity),
155
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
156
+ ...(options.ttl === undefined ? {} : { ttl: options.ttl }),
157
+ ...(payload.secret === undefined
158
+ ? {}
159
+ : { secret: Redacted.make(payload.secret) }),
160
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
161
+ };
162
+ });
163
+ export const oauthLinkConfirmationInspectInput = (payload) => ({
164
+ challengeId: payload.challengeId,
165
+ ...(payload.secret === undefined ? {} : { secret: Redacted.make(payload.secret) }),
166
+ });
167
+ export const oauthLinkConfirmationConfirmInput = (payload, currentUserId) => ({
168
+ challengeId: payload.challengeId,
169
+ ...(payload.secret === undefined ? {} : { secret: Redacted.make(payload.secret) }),
170
+ ...(currentUserId === undefined ? {} : { currentUserId }),
171
+ ...(payload.expectedProviderId === undefined
172
+ ? {}
173
+ : { expectedProviderId: payload.expectedProviderId }),
174
+ ...(payload.expectedProviderAccountId === undefined
175
+ ? {}
176
+ : { expectedProviderAccountId: payload.expectedProviderAccountId }),
177
+ });
178
+ const oauthPublicVerifiedIdentityHttpBody = (identity) => ({
179
+ providerId: identity.providerId,
180
+ providerAccountId: identity.providerAccountId,
181
+ ...(identity.email === undefined ? {} : { email: identity.email }),
182
+ ...(identity.emailVerified === undefined
183
+ ? {}
184
+ : { emailVerified: identity.emailVerified }),
185
+ });
186
+ export const oauthLinkConfirmationStartedHttpBody = (started) => ({
187
+ challengeId: started.challengeId,
188
+ userId: started.userId,
189
+ identity: oauthPublicVerifiedIdentityHttpBody(started.identity),
190
+ reason: started.reason,
191
+ expiresAt: started.expiresAt,
192
+ });
193
+ export const oauthLinkConfirmationPendingHttpBody = (pending) => ({
194
+ challengeId: pending.challengeId,
195
+ userId: pending.userId,
196
+ identity: oauthPublicVerifiedIdentityHttpBody(pending.identity),
197
+ reason: pending.reason,
198
+ expiresAt: pending.expiresAt,
199
+ });
200
+ const oauthAuthorizationCallbackField = (fields, name) => {
201
+ const maybeSearchParams = fields;
202
+ const value = typeof maybeSearchParams.get === "function"
203
+ ? maybeSearchParams.get(name)
204
+ : fields[name];
205
+ const stringValue = Array.isArray(value) ? value[0] : value;
206
+ return typeof stringValue === "string" && stringValue.trim() !== ""
207
+ ? stringValue
208
+ : undefined;
209
+ };
210
+ const oauthAuthorizationCallbackPayload = (input, options) => Effect.gen(function* () {
211
+ const state = oauthAuthorizationCallbackField(input.fields, "state");
212
+ const code = oauthAuthorizationCallbackField(input.fields, "code");
213
+ const error = oauthAuthorizationCallbackField(input.fields, "error");
214
+ const errorDescription = oauthAuthorizationCallbackField(input.fields, "error_description");
215
+ const errorUri = oauthAuthorizationCallbackField(input.fields, "error_uri");
216
+ if (state === undefined) {
217
+ return yield* oauthBadRequest("OAuth callback is missing state");
218
+ }
219
+ const authorizationUser = options.includeAuthorizationUser
220
+ ? oauthAuthorizationCallbackField(input.fields, "user")
221
+ : undefined;
222
+ return {
223
+ providerId: input.providerId,
224
+ state,
225
+ ...(code === undefined ? {} : { code }),
226
+ ...(error === undefined ? {} : { error }),
227
+ ...(errorDescription === undefined ? {} : { errorDescription }),
228
+ ...(errorUri === undefined ? {} : { errorUri }),
229
+ ...(authorizationUser === undefined ? {} : { authorizationUser }),
230
+ };
231
+ });
232
+ export const oauthAuthorizationCallbackQueryPayload = (input) => oauthAuthorizationCallbackPayload(input, { includeAuthorizationUser: false });
233
+ export const oauthAuthorizationCallbackFormPostPayload = (input) => oauthAuthorizationCallbackPayload(input, { includeAuthorizationUser: true });
234
+ export const oauthAuthorizationCallbackInput = (payload, options) => Effect.gen(function* () {
235
+ if (payload.providerId !== options.provider.id) {
236
+ return yield* oauthBadRequest("OAuth callback provider mismatch");
237
+ }
238
+ if (payload.error !== undefined) {
239
+ return yield* oauthBadRequest("OAuth provider returned an error");
240
+ }
241
+ if (payload.code === undefined || payload.code.trim() === "") {
242
+ return yield* oauthBadRequest("OAuth callback is missing code");
243
+ }
244
+ return {
245
+ provider: options.provider,
246
+ state: payload.state,
247
+ code: payload.code,
248
+ codeVerifier: options.codeVerifier,
249
+ ...(options.redirectUri === undefined
250
+ ? {}
251
+ : { redirectUri: options.redirectUri }),
252
+ ...(options.clientAuthentication === undefined
253
+ ? {}
254
+ : { clientAuthentication: options.clientAuthentication }),
255
+ ...(options.tokenParams === undefined
256
+ ? {}
257
+ : { tokenParams: options.tokenParams }),
258
+ };
259
+ });
260
+ const oauthLinkedAccountHttpBody = (account) => ({
261
+ accountId: account.id,
262
+ providerId: account.providerId,
263
+ providerAccountId: account.providerAccountId,
264
+ });
265
+ export const oauthLinkConfirmationConfirmedHttpBody = (confirmed, options = {}) => ({
266
+ challengeId: confirmed.challengeId,
267
+ userId: confirmed.userId,
268
+ identity: oauthPublicVerifiedIdentityHttpBody(confirmed.identity),
269
+ reason: confirmed.reason,
270
+ ...(confirmed.existingAccount === undefined
271
+ ? {}
272
+ : { existingAccount: oauthLinkedAccountHttpBody(confirmed.existingAccount) }),
273
+ linked: options.linked === true || confirmed.existingAccount !== undefined,
274
+ });
275
+ export const oauthAccountUnlinkResolutionHttpBody = (resolution, options = {}) => {
276
+ switch (resolution.type) {
277
+ case "allow": {
278
+ return {
279
+ type: resolution.type,
280
+ reason: resolution.reason,
281
+ account: oauthLinkedAccountHttpBody(resolution.account),
282
+ remainingAccounts: resolution.remainingAccounts.map(oauthLinkedAccountHttpBody),
283
+ unlinked: options.unlinked === true,
284
+ };
285
+ }
286
+ case "requires-step-up": {
287
+ return {
288
+ type: resolution.type,
289
+ reason: resolution.reason,
290
+ account: oauthLinkedAccountHttpBody(resolution.account),
291
+ remainingAccounts: resolution.remainingAccounts.map(oauthLinkedAccountHttpBody),
292
+ };
293
+ }
294
+ case "deny-last-account": {
295
+ return {
296
+ type: resolution.type,
297
+ reason: resolution.reason,
298
+ account: oauthLinkedAccountHttpBody(resolution.account),
299
+ };
300
+ }
301
+ case "deny-not-owner": {
302
+ return {
303
+ type: resolution.type,
304
+ reason: resolution.reason,
305
+ providerId: resolution.account.providerId,
306
+ providerAccountId: resolution.account.providerAccountId,
307
+ };
308
+ }
309
+ case "deny-not-found": {
310
+ return {
311
+ type: resolution.type,
312
+ reason: resolution.reason,
313
+ providerId: resolution.providerId,
314
+ providerAccountId: resolution.providerAccountId,
315
+ };
316
+ }
317
+ }
318
+ };
319
+ export const passkeyRegistrationStartInput = (payload, options) => ({
320
+ relyingParty: options.relyingParty,
321
+ userId: payload.userId,
322
+ userName: payload.userName,
323
+ userDisplayName: payload.userDisplayName,
324
+ ...(options.timeout === undefined ? {} : { timeout: options.timeout }),
325
+ ...(options.pubKeyCredParams === undefined
326
+ ? {}
327
+ : { pubKeyCredParams: options.pubKeyCredParams }),
328
+ ...(options.authenticatorSelection === undefined
329
+ ? {}
330
+ : { authenticatorSelection: options.authenticatorSelection }),
331
+ ...(options.attestation === undefined ? {} : { attestation: options.attestation }),
332
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
333
+ });
334
+ export const passkeyAuthenticationStartInput = (payload, options) => ({
335
+ relyingPartyId: options.relyingPartyId,
336
+ ...(payload.userId === undefined ? {} : { userId: payload.userId }),
337
+ ...(options.timeout === undefined ? {} : { timeout: options.timeout }),
338
+ ...(options.userVerification === undefined
339
+ ? {}
340
+ : { userVerification: options.userVerification }),
341
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
342
+ });
343
+ export const passkeyMfaStartInput = (userId, payload, options) => ({
344
+ relyingPartyId: options.relyingPartyId,
345
+ userId,
346
+ ...(options.timeout === undefined ? {} : { timeout: options.timeout }),
347
+ userVerification: options.userVerification ?? "required",
348
+ metadata: {
349
+ ...payload.metadata,
350
+ flowId: payload.flowId,
351
+ },
352
+ });
353
+ export const passkeyRegistrationFinishInput = (payload, options) => ({
354
+ challengeId: payload.challengeId,
355
+ userId: payload.userId,
356
+ response: payload.credential,
357
+ relyingPartyId: options.relyingPartyId,
358
+ expectedOrigin: options.expectedOrigin,
359
+ ...(options.requireUserVerification === undefined
360
+ ? {}
361
+ : { requireUserVerification: options.requireUserVerification }),
362
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
363
+ });
364
+ export const passkeyAuthenticationFinishInput = (payload, options) => ({
365
+ challengeId: payload.challengeId,
366
+ response: payload.credential,
367
+ ...(payload.userId === undefined ? {} : { userId: payload.userId }),
368
+ relyingPartyId: options.relyingPartyId,
369
+ expectedOrigin: options.expectedOrigin,
370
+ ...(options.requireUserVerification === undefined
371
+ ? {}
372
+ : { requireUserVerification: options.requireUserVerification }),
373
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
374
+ });
375
+ export const passkeyMfaVerifyInput = (payload, options) => ({
376
+ challengeId: payload.challengeId,
377
+ response: payload.credential,
378
+ ...(payload.userId === undefined ? {} : { userId: payload.userId }),
379
+ relyingPartyId: options.relyingPartyId,
380
+ expectedOrigin: options.expectedOrigin,
381
+ ...(options.requireUserVerification === undefined
382
+ ? {}
383
+ : { requireUserVerification: options.requireUserVerification }),
384
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
385
+ });
386
+ export const passkeyCredentialRevokeInput = (userId, payload) => ({
387
+ userId,
388
+ credentialId: PasskeyCredentialId(payload.credentialId),
389
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
390
+ });
391
+ const passkeyCredentialInfoHttpBody = (credential) => ({
392
+ credentialId: credential.credentialId,
393
+ ...(credential.transports === undefined
394
+ ? {}
395
+ : { transports: credential.transports }),
396
+ ...(credential.backedUp === undefined ? {} : { backedUp: credential.backedUp }),
397
+ createdAt: credential.createdAt,
398
+ ...(credential.lastUsedAt === undefined
399
+ ? {}
400
+ : { lastUsedAt: credential.lastUsedAt }),
401
+ ...(credential.revokedAt === undefined
402
+ ? {}
403
+ : { revokedAt: credential.revokedAt }),
404
+ ...(credential.metadata === undefined ? {} : { metadata: credential.metadata }),
405
+ });
406
+ export const totpEnrollmentStartInput = (userId, payload, options) => ({
407
+ userId,
408
+ issuer: options.issuer,
409
+ accountName: payload.accountName,
410
+ ...(options.secretBytes === undefined ? {} : { secretBytes: options.secretBytes }),
411
+ ...(options.algorithm === undefined ? {} : { algorithm: options.algorithm }),
412
+ ...(options.digits === undefined ? {} : { digits: options.digits }),
413
+ ...(options.period === undefined ? {} : { period: options.period }),
414
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
415
+ });
416
+ export const totpEnrollmentConfirmInput = (userId, payload, options = {}) => ({
417
+ userId,
418
+ factorId: payload.factorId,
419
+ code: Redacted.make(payload.code),
420
+ ...(options.window === undefined ? {} : { window: options.window }),
421
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
422
+ });
423
+ export const totpVerifyInput = (userId, payload, options = {}) => ({
424
+ userId,
425
+ code: Redacted.make(payload.code),
426
+ ...(options.window === undefined ? {} : { window: options.window }),
427
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
428
+ });
429
+ export const totpFactorRevokeInput = (userId, payload) => ({
430
+ userId,
431
+ factorId: payload.factorId,
432
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
433
+ });
434
+ const totpFactorInfoHttpBody = (factor) => ({
435
+ factorId: factor.id,
436
+ algorithm: factor.algorithm,
437
+ digits: factor.digits,
438
+ period: factor.period,
439
+ createdAt: factor.createdAt,
440
+ ...(factor.confirmedAt === undefined ? {} : { confirmedAt: factor.confirmedAt }),
441
+ ...(factor.lastUsedAt === undefined ? {} : { lastUsedAt: factor.lastUsedAt }),
442
+ ...(factor.revokedAt === undefined ? {} : { revokedAt: factor.revokedAt }),
443
+ ...(factor.metadata === undefined ? {} : { metadata: factor.metadata }),
444
+ });
445
+ const totpEnrollmentStartedHttpBody = (started) => ({
446
+ factor: totpFactorInfoHttpBody(started.factor),
447
+ secret: Redacted.value(started.secret),
448
+ uri: Redacted.value(started.uri),
449
+ });
450
+ const totpVerifyResultHttpBody = (result) => ({
451
+ valid: result.valid,
452
+ ...(result.factor === undefined
453
+ ? {}
454
+ : { factor: totpFactorInfoHttpBody(result.factor) }),
455
+ ...(result.delta === undefined ? {} : { delta: result.delta }),
456
+ });
457
+ export const recoveryCodeGenerateInput = (userId, payload, options = {}) => ({
458
+ userId,
459
+ ...(options.count === undefined ? {} : { count: options.count }),
460
+ ...(options.length === undefined ? {} : { length: options.length }),
461
+ ...(options.groupSize === undefined ? {} : { groupSize: options.groupSize }),
462
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
463
+ });
464
+ export const recoveryCodeVerifyInput = (userId, payload) => ({
465
+ userId,
466
+ code: Redacted.make(payload.code),
467
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
468
+ });
469
+ export const recoveryCodeRevokeInput = (userId, payload) => ({
470
+ userId,
471
+ codeId: payload.codeId,
472
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
473
+ });
474
+ const recoveryCodeInfoHttpBody = (code) => ({
475
+ codeId: code.id,
476
+ createdAt: code.createdAt,
477
+ ...(code.usedAt === undefined ? {} : { usedAt: code.usedAt }),
478
+ ...(code.revokedAt === undefined ? {} : { revokedAt: code.revokedAt }),
479
+ ...(code.metadata === undefined ? {} : { metadata: code.metadata }),
480
+ });
481
+ const recoveryCodesGeneratedHttpBody = (generated) => ({
482
+ codes: generated.codes.map(Redacted.value),
483
+ records: generated.records.map(recoveryCodeInfoHttpBody),
484
+ });
485
+ const recoveryCodeVerifyResultHttpBody = (result) => ({
486
+ valid: result.valid,
487
+ ...(result.code === undefined
488
+ ? {}
489
+ : { code: recoveryCodeInfoHttpBody(result.code) }),
490
+ });
491
+ export const apiKeyCreateInput = (userId, payload) => ({
492
+ userId,
493
+ ...(payload.scopes === undefined ? {} : { scopes: payload.scopes }),
494
+ ...(payload.expiresAt === undefined ? {} : { expiresAt: payload.expiresAt }),
495
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
496
+ });
497
+ export const apiKeyRevokeInput = (userId, payload) => ({
498
+ userId,
499
+ keyId: ApiKeyId(payload.keyId),
500
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
501
+ });
502
+ const apiKeyInfoHttpBody = (key) => ({
503
+ keyId: key.id,
504
+ prefix: key.prefix,
505
+ scopes: key.scopes,
506
+ createdAt: key.createdAt,
507
+ ...(key.expiresAt === undefined ? {} : { expiresAt: key.expiresAt }),
508
+ ...(key.lastUsedAt === undefined ? {} : { lastUsedAt: key.lastUsedAt }),
509
+ ...(key.revokedAt === undefined ? {} : { revokedAt: key.revokedAt }),
510
+ ...(key.metadata === undefined ? {} : { metadata: key.metadata }),
511
+ });
512
+ const apiKeyCreatedHttpBody = (created) => ({
513
+ secret: Redacted.value(created.secret),
514
+ key: apiKeyInfoHttpBody(created.key),
515
+ });
516
+ export const refreshTokenRefreshInput = (payload, now, expiresAt) => ({
517
+ token: Redacted.make(payload.refreshToken),
518
+ now,
519
+ expiresAt,
520
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
521
+ });
522
+ const refreshTokenInfoHttpBody = (refreshToken) => ({
523
+ tokenId: refreshToken.id,
524
+ familyId: refreshToken.familyId,
525
+ createdAt: refreshToken.createdAt,
526
+ expiresAt: refreshToken.expiresAt,
527
+ ...(refreshToken.lastUsedAt === undefined
528
+ ? {}
529
+ : { lastUsedAt: refreshToken.lastUsedAt }),
530
+ ...(refreshToken.rotatedAt === undefined
531
+ ? {}
532
+ : { rotatedAt: refreshToken.rotatedAt }),
533
+ ...(refreshToken.replacedById === undefined
534
+ ? {}
535
+ : { replacedById: refreshToken.replacedById }),
536
+ ...(refreshToken.revokedAt === undefined
537
+ ? {}
538
+ : { revokedAt: refreshToken.revokedAt }),
539
+ ...(refreshToken.reuseDetectedAt === undefined
540
+ ? {}
541
+ : { reuseDetectedAt: refreshToken.reuseDetectedAt }),
542
+ ...(refreshToken.metadata === undefined ? {} : { metadata: refreshToken.metadata }),
543
+ });
544
+ const issuedJwtExpiresAt = (issued) => typeof issued.claims.exp === "number"
545
+ ? (issued.claims.exp * 1000)
546
+ : undefined;
547
+ const refreshTokenRefreshedHttpBody = (input) => ({
548
+ accessToken: Redacted.value(input.accessToken.token),
549
+ ...(issuedJwtExpiresAt(input.accessToken) === undefined
550
+ ? {}
551
+ : { accessTokenExpiresAt: issuedJwtExpiresAt(input.accessToken) }),
552
+ refreshToken: input.refreshToken,
553
+ refreshTokenRecord: refreshTokenInfoHttpBody(input.refreshTokenRecord),
554
+ });
555
+ export const jwtIntrospectInput = (payload, options = {}) => ({
556
+ token: Redacted.make(payload.token),
557
+ ...(options.issuer === undefined ? {} : { issuer: options.issuer }),
558
+ ...(options.audience === undefined ? {} : { audience: options.audience }),
559
+ ...(options.clockTolerance === undefined
560
+ ? {}
561
+ : { clockTolerance: options.clockTolerance }),
562
+ });
563
+ export const jwtRevokeInput = (payload) => ({
564
+ jwtId: payload.jwtId,
565
+ ...(payload.expiresAt === undefined ? {} : { expiresAt: payload.expiresAt }),
566
+ ...(payload.reason === undefined ? {} : { reason: payload.reason }),
567
+ });
568
+ const jwtKeyInfoHttpBody = (result) => ({
569
+ keyId: result.key.id,
570
+ alg: result.key.alg,
571
+ status: result.key.status,
572
+ ...(result.key.createdAt === undefined ? {} : { createdAt: result.key.createdAt }),
573
+ ...(result.key.expiresAt === undefined ? {} : { expiresAt: result.key.expiresAt }),
574
+ ...(result.key.metadata === undefined ? {} : { metadata: result.key.metadata }),
575
+ });
576
+ const jwtIntrospectionHttpBody = (result) => result.active
577
+ ? {
578
+ active: true,
579
+ header: result.header,
580
+ claims: result.claims,
581
+ key: jwtKeyInfoHttpBody(result),
582
+ ...(result.jwtId === undefined ? {} : { jwtId: result.jwtId }),
583
+ ...(result.expiresAt === undefined ? {} : { expiresAt: result.expiresAt }),
584
+ revoked: false,
585
+ }
586
+ : {
587
+ active: false,
588
+ reason: result.reason,
589
+ ...(result.jwtId === undefined ? {} : { jwtId: result.jwtId }),
590
+ ...(result.expiresAt === undefined ? {} : { expiresAt: result.expiresAt }),
591
+ ...(result.revokedAt === undefined ? {} : { revokedAt: result.revokedAt }),
592
+ ...(result.revokedReason === undefined
593
+ ? {}
594
+ : { revokedReason: result.revokedReason }),
595
+ };
596
+ export const totpMfaVerifyInput = (payload, options = {}) => ({
597
+ userId: payload.userId,
598
+ code: Redacted.make(payload.code),
599
+ ...(options.window === undefined ? {} : { window: options.window }),
600
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
601
+ });
602
+ export const totpMfaVerifyForFlowInput = (userId, payload, options = {}) => ({
603
+ userId,
604
+ code: Redacted.make(payload.code),
605
+ ...(options.window === undefined ? {} : { window: options.window }),
606
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
607
+ });
608
+ export const recoveryCodeMfaVerifyInput = (payload) => ({
609
+ userId: payload.userId,
610
+ code: Redacted.make(payload.code),
611
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
612
+ });
613
+ export const recoveryCodeMfaVerifyForFlowInput = (userId, payload) => ({
614
+ userId,
615
+ code: Redacted.make(payload.code),
616
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
617
+ });
618
+ export const stepUpTotpVerifyInput = (userId, payload, options = {}) => ({
619
+ userId,
620
+ code: Redacted.make(payload.code),
621
+ ...(options.window === undefined ? {} : { window: options.window }),
622
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
623
+ });
624
+ export const stepUpRecoveryCodeVerifyInput = (userId, payload) => ({
625
+ userId,
626
+ code: Redacted.make(payload.code),
627
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
628
+ });
629
+ export const stepUpPasskeyStartInput = (userId, payload, options) => ({
630
+ relyingPartyId: options.relyingPartyId,
631
+ userId,
632
+ ...(options.timeout === undefined ? {} : { timeout: options.timeout }),
633
+ userVerification: options.userVerification ?? "required",
634
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
635
+ });
636
+ export const stepUpPasskeyVerifyInput = (userId, payload, options) => ({
637
+ challengeId: payload.challengeId,
638
+ response: payload.credential,
639
+ userId,
640
+ relyingPartyId: options.relyingPartyId,
641
+ expectedOrigin: options.expectedOrigin,
642
+ ...(options.requireUserVerification === undefined
643
+ ? {}
644
+ : { requireUserVerification: options.requireUserVerification }),
645
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
646
+ });
647
+ export const loginApprovalApproveInput = (payload) => ({
648
+ flowId: payload.flowId,
649
+ approval: {
650
+ challengeId: payload.approvalChallengeId,
651
+ ...(payload.secret === undefined
652
+ ? {}
653
+ : { secret: Redacted.make(payload.secret) }),
654
+ },
655
+ rememberDevice: payload.rememberDevice ?? false,
656
+ });
657
+ export const loginApprovalStatusInput = (payload) => ({
658
+ flowId: payload.flowId,
659
+ approvalChallengeId: payload.approvalChallengeId,
660
+ });
661
+ export const loginApprovalFinalizeInput = (payload) => ({
662
+ flowId: payload.flowId,
663
+ approvalChallengeId: payload.approvalChallengeId,
664
+ rememberDevice: payload.rememberDevice ?? false,
665
+ });
666
+ export const loginNotificationReportInput = (payload) => ({
667
+ challengeId: payload.challengeId,
668
+ secret: Redacted.make(payload.secret),
669
+ });
670
+ const webRequestFromHeaders = (headers) => new Request("http://localhost", { headers });
671
+ const firstHeaderValue = (value) => {
672
+ const first = value?.split(",", 1)[0]?.trim();
673
+ return first === "" ? undefined : first;
674
+ };
675
+ const headerNumber = (value) => {
676
+ const parsed = Number(firstHeaderValue(value));
677
+ return Number.isFinite(parsed) ? parsed : undefined;
678
+ };
679
+ const authRequestMetadataOptions = Effect.gen(function* () {
680
+ const config = yield* Effect.serviceOption(AuthHttpApiConfig);
681
+ return Option.isSome(config) ? (config.value.requestMetadata ?? {}) : {};
682
+ });
683
+ const loginRequestContextFromRequest = (request, options) => {
684
+ if (request === undefined) {
685
+ return undefined;
686
+ }
687
+ const metadata = makeAuthRequestMetadata(request, options);
688
+ const trustProxyHeaders = options.trustProxyHeaders ?? false;
689
+ const { headers } = request;
690
+ const country = trustProxyHeaders
691
+ ? firstHeaderValue(headers["cf-ipcountry"])
692
+ : undefined;
693
+ const region = trustProxyHeaders
694
+ ? firstHeaderValue(headers["cf-region"])
695
+ : undefined;
696
+ const city = trustProxyHeaders
697
+ ? firstHeaderValue(headers["cf-ipcity"])
698
+ : undefined;
699
+ const latitude = trustProxyHeaders
700
+ ? headerNumber(headers["cf-iplatitude"])
701
+ : undefined;
702
+ const longitude = trustProxyHeaders
703
+ ? headerNumber(headers["cf-iplongitude"])
704
+ : undefined;
705
+ const context = {
706
+ ...(metadata.ipAddress === undefined
707
+ ? {}
708
+ : { ip: String(metadata.ipAddress) }),
709
+ ...(metadata.userAgent === undefined
710
+ ? {}
711
+ : { userAgent: metadata.userAgent }),
712
+ ...(country === undefined ? {} : { country }),
713
+ ...(region === undefined ? {} : { region }),
714
+ ...(city === undefined ? {} : { city }),
715
+ ...(latitude === undefined ? {} : { latitude }),
716
+ ...(longitude === undefined ? {} : { longitude }),
717
+ };
718
+ return Object.keys(context).length === 0 ? undefined : context;
719
+ };
720
+ const trustedDeviceTokenFromRequest = (trustedDeviceCookie, request) => trustedDeviceCookie === undefined || request === undefined
721
+ ? Effect.succeed(Option.none())
722
+ : trustedDeviceCookie.read(new Request("http://localhost", { headers: request.headers }));
723
+ const metadataString = (metadata, key) => {
724
+ const value = metadata?.[key];
725
+ return typeof value === "string" && value.length > 0 ? value : undefined;
726
+ };
727
+ const emailVerifiedClaims = (claims) => {
728
+ const requirements = claims?.requirements?.filter((requirement) => requirement !== "email_verification");
729
+ return {
730
+ ...claims,
731
+ emailVerified: true,
732
+ ...(requirements === undefined ? {} : { requirements }),
733
+ };
734
+ };
735
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
736
+ const metadataNumber = (metadata, key) => {
737
+ const value = metadata?.[key];
738
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
739
+ };
740
+ const sessionRequestMetadata = (metadata) => {
741
+ const value = metadata?.[sessionRequestMetadataKey];
742
+ return isRecord(value) ? value : undefined;
743
+ };
744
+ const activeSessionBody = (session, currentSessionId) => {
745
+ const request = sessionRequestMetadata(session.metadata);
746
+ const ip = metadataString(request, "ip");
747
+ const userAgent = metadataString(request, "userAgent");
748
+ const country = metadataString(request, "country");
749
+ const region = metadataString(request, "region");
750
+ const city = metadataString(request, "city");
751
+ const latitude = metadataNumber(request, "latitude");
752
+ const longitude = metadataNumber(request, "longitude");
753
+ return {
754
+ sessionId: session.sessionId,
755
+ userId: session.userId,
756
+ createdAt: session.createdAt,
757
+ authTime: session.authTime,
758
+ ...(session.lastSeenAt === undefined
759
+ ? {}
760
+ : { lastSeenAt: session.lastSeenAt }),
761
+ expiresAt: session.expiresAt,
762
+ aal: session.aal,
763
+ amr: session.amr,
764
+ ...(session.mfaVerifiedAt === undefined
765
+ ? {}
766
+ : { mfaVerifiedAt: session.mfaVerifiedAt }),
767
+ current: session.sessionId === currentSessionId,
768
+ ...(session.claims === undefined ? {} : { claims: session.claims }),
769
+ ...(ip === undefined ? {} : { ip }),
770
+ ...(userAgent === undefined ? {} : { userAgent }),
771
+ ...(country === undefined ? {} : { country }),
772
+ ...(region === undefined ? {} : { region }),
773
+ ...(city === undefined ? {} : { city }),
774
+ ...(latitude === undefined ? {} : { latitude }),
775
+ ...(longitude === undefined ? {} : { longitude }),
776
+ ...(session.metadata === undefined ? {} : { metadata: session.metadata }),
777
+ };
778
+ };
779
+ export const stepUpAuthenticatedHttpBody = (session) => {
780
+ const body = {
781
+ type: "authenticated",
782
+ expiresAt: Number(session.expiresAt),
783
+ aal: session.aal,
784
+ amr: session.amr,
785
+ ...(session.mfaVerifiedAt === undefined
786
+ ? {}
787
+ : { mfaVerifiedAt: session.mfaVerifiedAt }),
788
+ };
789
+ return session.claims === undefined ? body : { ...body, claims: session.claims };
790
+ };
791
+ const readOptionalSession = (dependencies, request) => Effect.gen(function* () {
792
+ const tokenOption = yield* dependencies.sessionCookie
793
+ .read(webRequestFromHeaders(request.headers))
794
+ .pipe(Effect.catchTag("SessionValidateError", (error) => error.cause === undefined
795
+ ? Effect.succeed(Option.none())
796
+ : Effect.fail(new AuthInternalError({
797
+ code: "internal_error",
798
+ message: "Failed to validate session",
799
+ }))));
800
+ if (Option.isNone(tokenOption)) {
801
+ return Option.none();
802
+ }
803
+ return yield* dependencies.sessions.validate(tokenOption.value).pipe(Effect.map(Option.some), Effect.catchTag("SessionValidateError", (error) => error.cause === undefined
804
+ ? Effect.succeed(Option.none())
805
+ : Effect.fail(new AuthInternalError({
806
+ code: "internal_error",
807
+ message: "Failed to validate session",
808
+ }))));
809
+ });
810
+ const readRequiredSession = (dependencies, request) => readOptionalSession(dependencies, request).pipe(Effect.flatMap((sessionOption) => Option.isSome(sessionOption)
811
+ ? Effect.succeed(sessionOption.value)
812
+ : Effect.fail(new AuthUnauthenticatedError({
813
+ code: "unauthenticated",
814
+ message: "Unauthenticated",
815
+ }))));
816
+ const upgradeVerifiedEmailSession = (dependencies, request, verified) => Effect.gen(function* () {
817
+ const sessionOption = yield* readOptionalSession(dependencies, request);
818
+ if (Option.isNone(sessionOption)) {
819
+ return;
820
+ }
821
+ const session = sessionOption.value.currentSession;
822
+ if (session.userId !== verified.user.id) {
823
+ return;
824
+ }
825
+ yield* dependencies.sessions
826
+ .updateClaims({
827
+ sessionId: session.sessionId,
828
+ claims: emailVerifiedClaims(session.claims),
829
+ reason: "email_verification",
830
+ })
831
+ .pipe(Effect.catchTag("SessionUpdateClaimsError", (error) => error.cause === undefined
832
+ ? Effect.void
833
+ : Effect.fail(new AuthInternalError({
834
+ code: "internal_error",
835
+ message: "Failed to update session claims",
836
+ }))));
837
+ });
838
+ const startRequiredEmailVerification = (dependencies, result) => Effect.gen(function* () {
839
+ if (dependencies.emailVerificationFlow === undefined ||
840
+ !canStartRequiredEmailVerification(result)) {
841
+ return result;
842
+ }
843
+ const input = {
844
+ userId: result.userId,
845
+ email: result.email,
846
+ };
847
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
848
+ yield* catchAuthApiRateLimit(authApiRateLimit.emailVerificationStart(input), "Failed to start email verification");
849
+ yield* dependencies.emailVerificationFlow
850
+ .start(input)
851
+ .pipe(Effect.catchTag("EmailVerificationFlowStartError", () => Effect.fail(passwordInternalError("Failed to start email verification"))));
852
+ return result;
853
+ });
854
+ const rateLimited = (retryAfter) => new AuthRateLimitedError({
855
+ code: "rate_limited",
856
+ message: "Too many authentication attempts",
857
+ retryAfter,
858
+ });
859
+ const passwordInternalError = (message) => new AuthInternalError({
860
+ code: "internal_error",
861
+ message,
862
+ });
863
+ const loginApprovalBadRequest = () => new AuthBadRequestError({
864
+ code: "bad_request",
865
+ message: "Invalid login approval request",
866
+ });
867
+ const loginApprovalSameDeviceDenied = () => new AuthPolicyDeniedError({
868
+ code: "policy_denied",
869
+ message: "Login approval must be completed on the same device",
870
+ });
871
+ const loginApprovalNoSessionBindingDenied = () => new AuthPolicyDeniedError({
872
+ code: "policy_denied",
873
+ message: "Login approval does not create a user session",
874
+ });
875
+ const loginApprovalReviewNotConfigured = () => new AuthPolicyDeniedError({
876
+ code: "policy_denied",
877
+ message: "Login approval review is not configured",
878
+ });
879
+ const loginApprovalFinalizeNotConfigured = () => new AuthPolicyDeniedError({
880
+ code: "policy_denied",
881
+ message: "Login approval finalization is not configured",
882
+ });
883
+ const loginApprovalPolicyDenied = (reason) => new AuthPolicyDeniedError({
884
+ code: "policy_denied",
885
+ message: reason ?? "Login approval denied",
886
+ });
887
+ const loginNotificationNotConfigured = () => new AuthPolicyDeniedError({
888
+ code: "policy_denied",
889
+ message: "Login notification reporting is not configured",
890
+ });
891
+ const loginNotificationBadRequest = () => new AuthBadRequestError({
892
+ code: "bad_request",
893
+ message: "Invalid login notification report",
894
+ });
895
+ const oauthBadRequest = (message = "Invalid OAuth request") => new AuthBadRequestError({
896
+ code: "bad_request",
897
+ message,
898
+ });
899
+ const oauthInternalError = (message = "Failed to complete OAuth request") => new AuthInternalError({
900
+ code: "internal_error",
901
+ message,
902
+ });
903
+ const oauthHookHttpError = (error, internalMessage) => error instanceof AuthBadRequestError || error instanceof AuthUnauthenticatedError
904
+ ? error
905
+ : oauthInternalError(internalMessage);
906
+ const oauthLinkConfirmationHttpError = (error, internalMessage) => error.message === "OAuth provider account is already linked to this user" ||
907
+ error.message === "OAuth provider account is linked to a different user" ||
908
+ error.message === "Invalid OAuth link confirmation challenge" ||
909
+ error.message === "OAuth link confirmation does not match current user" ||
910
+ error.message === "OAuth link confirmation provider mismatch" ||
911
+ error.message === "OAuth link confirmation provider account mismatch"
912
+ ? oauthBadRequest(error.message)
913
+ : oauthInternalError(internalMessage);
914
+ const passkeyInternalError = (message = "Failed to complete passkey request") => new AuthInternalError({
915
+ code: "internal_error",
916
+ message,
917
+ });
918
+ const passkeyBadRequest = (message = "Invalid passkey request") => new AuthBadRequestError({
919
+ code: "bad_request",
920
+ message,
921
+ });
922
+ const passkeyVerificationHttpError = (error) => error.message === "Failed to load passkey credential" ||
923
+ error.message === "Failed to store passkey credential" ||
924
+ error.message === "Failed to update passkey credential" ||
925
+ error.message === "Failed to generate passkey credential record id"
926
+ ? passkeyInternalError()
927
+ : passkeyBadRequest();
928
+ const passkeyCredentialManagementHttpError = (error) => error.message === "Passkey credential not found"
929
+ ? passkeyBadRequest("Invalid passkey credential")
930
+ : passkeyInternalError("Failed to update passkey credentials");
931
+ const totpInternalError = (message = "Failed to complete TOTP request") => new AuthInternalError({
932
+ code: "internal_error",
933
+ message,
934
+ });
935
+ const totpBadRequest = (message = "Invalid TOTP request") => new AuthBadRequestError({
936
+ code: "bad_request",
937
+ message,
938
+ });
939
+ const totpFactorManagementHttpError = (error) => {
940
+ switch (error.message) {
941
+ case "Failed to build TOTP enrollment URI":
942
+ case "TOTP factor not found":
943
+ case "TOTP factor already confirmed":
944
+ case "Invalid TOTP code": {
945
+ return totpBadRequest();
946
+ }
947
+ default: {
948
+ return totpInternalError();
949
+ }
950
+ }
951
+ };
952
+ const recoveryCodeInternalError = (message = "Failed to complete recovery code request") => new AuthInternalError({
953
+ code: "internal_error",
954
+ message,
955
+ });
956
+ const recoveryCodeBadRequest = (message = "Invalid recovery code request") => new AuthBadRequestError({
957
+ code: "bad_request",
958
+ message,
959
+ });
960
+ const recoveryCodeManagementHttpError = (error) => {
961
+ switch (error.message) {
962
+ case "Recovery code not found": {
963
+ return recoveryCodeBadRequest();
964
+ }
965
+ default: {
966
+ return recoveryCodeInternalError();
967
+ }
968
+ }
969
+ };
970
+ const apiKeyInternalError = (message = "Failed to complete API key request") => new AuthInternalError({
971
+ code: "internal_error",
972
+ message,
973
+ });
974
+ const apiKeyBadRequest = (message = "Invalid API key request") => new AuthBadRequestError({
975
+ code: "bad_request",
976
+ message,
977
+ });
978
+ const apiKeyManagementHttpError = (error) => {
979
+ switch (error.message) {
980
+ case "API key not found": {
981
+ return apiKeyBadRequest();
982
+ }
983
+ default: {
984
+ return apiKeyInternalError();
985
+ }
986
+ }
987
+ };
988
+ const refreshTokenInternalError = (message = "Failed to complete refresh token request") => new AuthInternalError({
989
+ code: "internal_error",
990
+ message,
991
+ });
992
+ const refreshTokenInvalidCredentials = (message = "Invalid refresh token") => new AuthInvalidCredentialsError({
993
+ code: "invalid_credentials",
994
+ message,
995
+ });
996
+ const jwtInternalError = (message = "Failed to complete JWT request") => new AuthInternalError({
997
+ code: "internal_error",
998
+ message,
999
+ });
1000
+ const jwtBadRequest = (message = "Invalid JWT request") => new AuthBadRequestError({
1001
+ code: "bad_request",
1002
+ message,
1003
+ });
1004
+ const jwtRevocationHttpError = (error) => error.message === "JWT ID must not be empty" ? jwtBadRequest() : jwtInternalError();
1005
+ const mfaInternalError = (message = "Failed to complete MFA request") => new AuthInternalError({
1006
+ code: "internal_error",
1007
+ message,
1008
+ });
1009
+ const mfaBadRequest = (message = "Invalid MFA request") => new AuthBadRequestError({
1010
+ code: "bad_request",
1011
+ message,
1012
+ });
1013
+ const mfaInvalidCredentials = () => new AuthInvalidCredentialsError({
1014
+ code: "invalid_credentials",
1015
+ message: "Invalid MFA code",
1016
+ });
1017
+ const mfaPolicyDenied = (reason) => new AuthPolicyDeniedError({
1018
+ code: "policy_denied",
1019
+ message: reason ?? "MFA policy denied the request",
1020
+ });
1021
+ const authFlowMfaHttpError = (error) => error._tag === "AuthFlowStateError" ? mfaBadRequest() : mfaInternalError();
1022
+ const stepUpInternalError = (message = "Failed to complete step-up request") => new AuthInternalError({
1023
+ code: "internal_error",
1024
+ message,
1025
+ });
1026
+ const stepUpBadRequest = (message = "Invalid step-up request") => new AuthBadRequestError({
1027
+ code: "bad_request",
1028
+ message,
1029
+ });
1030
+ const stepUpInvalidCredentials = () => new AuthInvalidCredentialsError({
1031
+ code: "invalid_credentials",
1032
+ message: "Invalid step-up factor",
1033
+ });
1034
+ const stepUpPolicyDenied = (message = "Step-up policy denied the request") => new AuthPolicyDeniedError({
1035
+ code: "policy_denied",
1036
+ message,
1037
+ });
1038
+ const trustedDeviceSetCookies = (dependencies) => Effect.gen(function* () {
1039
+ if (!dependencies.rememberDevice ||
1040
+ dependencies.trustedDevice === undefined ||
1041
+ dependencies.trustedDeviceCookie === undefined) {
1042
+ return [];
1043
+ }
1044
+ const token = yield* dependencies.trustedDevice
1045
+ .trust({ userId: dependencies.userId })
1046
+ .pipe(Effect.mapError(() => passwordInternalError("Failed to remember trusted device")));
1047
+ const cookie = yield* dependencies.trustedDeviceCookie
1048
+ .commit({ token })
1049
+ .pipe(Effect.mapError(() => passwordInternalError("Failed to remember trusted device")));
1050
+ return [cookie];
1051
+ });
1052
+ const catchAuthApiRateLimit = (effect, internalMessage) => effect.pipe(Effect.catchTag("RateLimitExceededError", (error) => Effect.fail(rateLimited(error.retryAfter))), Effect.catchTag("RateLimitStoreError", () => Effect.fail(passwordInternalError(internalMessage))), Effect.catchTag("PrivacyError", () => Effect.fail(passwordInternalError(internalMessage))));
1053
+ export const makePasswordSignInHandler = (dependencies) => Effect.fn("auth.http.password.sign_in")(function* ({ payload, request, }) {
1054
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.sign_in");
1055
+ const trustedDeviceToken = yield* trustedDeviceTokenFromRequest(dependencies.trustedDeviceCookie, request).pipe(Effect.mapError(() => passwordInternalError("Failed to read trusted device cookie")));
1056
+ const requestMetadataOptions = yield* authRequestMetadataOptions;
1057
+ const requestContext = loginRequestContextFromRequest(request, requestMetadataOptions);
1058
+ const input = passwordSignInInput(payload, Option.isSome(trustedDeviceToken) ? trustedDeviceToken.value : undefined, requestContext);
1059
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1060
+ yield* catchAuthApiRateLimit(authApiRateLimit.passwordSignIn(input), "Failed to sign in with password");
1061
+ const result = yield* dependencies.password.signIn(input).pipe(Effect.catchTag("StorageError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("PasswordHashError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("TrustedDeviceError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("LoginRiskError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("SessionCreateError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("AuthFlowStateError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("LoginApprovalReviewError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))), Effect.catchTag("LoginApprovalFlowStartError", () => Effect.fail(passwordInternalError("Failed to sign in with password"))));
1062
+ yield* startRequiredEmailVerification(dependencies, result);
1063
+ return yield* dependencies.authHttp.commitPasswordSignInResult(result);
1064
+ });
1065
+ export const makePasswordSignUpHandler = (dependencies) => Effect.fn("auth.http.password.sign_up")(function* ({ payload, request, }) {
1066
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.sign_up");
1067
+ const requestMetadataOptions = yield* authRequestMetadataOptions;
1068
+ const input = passwordSignUpInput(payload, loginRequestContextFromRequest(request, requestMetadataOptions));
1069
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1070
+ yield* catchAuthApiRateLimit(authApiRateLimit.passwordSignUp(input), "Failed to sign up with password");
1071
+ const result = yield* dependencies.registration.signUp(input).pipe(Effect.catchTag("EmailAlreadyRegisteredError", () => Effect.fail(new AuthEmailAlreadyRegisteredError({
1072
+ code: "email_already_registered",
1073
+ message: "Email is already registered",
1074
+ }))), Effect.catchTag("StorageError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("PasswordHashError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("CryptoError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("TrustedDeviceError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("LoginRiskError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("SessionCreateError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("AuthFlowStateError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("LoginApprovalReviewError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))), Effect.catchTag("LoginApprovalFlowStartError", () => Effect.fail(passwordInternalError("Failed to sign up with password"))));
1075
+ yield* startRequiredEmailVerification(dependencies, result);
1076
+ return yield* dependencies.authHttp.commitPasswordSignUpResult(result);
1077
+ });
1078
+ export const makePasswordResetStartHandler = (dependencies) => Effect.fn("auth.http.password.reset_start")(function* ({ payload, }) {
1079
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.reset_start");
1080
+ const input = passwordResetStartInput(payload);
1081
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1082
+ yield* catchAuthApiRateLimit(authApiRateLimit.passwordResetStart(input), "Failed to start password reset");
1083
+ yield* dependencies.passwordReset.start(input).pipe(Effect.mapError(() => new AuthInternalError({
1084
+ code: "internal_error",
1085
+ message: "Failed to start password reset",
1086
+ })));
1087
+ return HttpServerResponse.empty({ status: 204 });
1088
+ });
1089
+ export const makePasswordResetVerifyHandler = (dependencies) => Effect.fn("auth.http.password.reset_verify")(function* ({ payload, }) {
1090
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.reset_verify");
1091
+ yield* dependencies.passwordReset
1092
+ .verify(passwordResetVerifyInput(payload))
1093
+ .pipe(Effect.mapError(() => new AuthBadRequestError({
1094
+ code: "bad_request",
1095
+ message: "Invalid password reset request",
1096
+ })));
1097
+ return HttpServerResponse.empty({ status: 204 });
1098
+ });
1099
+ const passwordManagementError = (error) => error.reason === "internal"
1100
+ ? new AuthInternalError({
1101
+ code: "internal_error",
1102
+ message: "Failed to update password",
1103
+ })
1104
+ : new AuthBadRequestError({
1105
+ code: "bad_request",
1106
+ message: "Invalid password update request",
1107
+ });
1108
+ export const makePasswordSetHandler = (dependencies) => Effect.fn("auth.http.password.set")(function* ({ payload, request, }) {
1109
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.set");
1110
+ const current = yield* readRequiredSession(dependencies, request);
1111
+ yield* dependencies.passwordManagement
1112
+ .set(passwordSetInput(current.currentSession.userId, payload))
1113
+ .pipe(Effect.mapError(passwordManagementError));
1114
+ return HttpServerResponse.empty({ status: 204 });
1115
+ });
1116
+ export const makePasswordChangeHandler = (dependencies) => Effect.fn("auth.http.password.change")(function* ({ payload, request, }) {
1117
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "password.change");
1118
+ const current = yield* readRequiredSession(dependencies, request);
1119
+ yield* dependencies.passwordManagement
1120
+ .change(passwordChangeInput(current.currentSession.userId, payload))
1121
+ .pipe(Effect.mapError(passwordManagementError));
1122
+ return HttpServerResponse.empty({ status: 204 });
1123
+ });
1124
+ export const makeCurrentSessionHandler = (dependencies) => Effect.fn("auth.http.session.current")(function* ({ request, }) {
1125
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.current");
1126
+ const tokenOption = yield* dependencies.sessionCookie
1127
+ .read(webRequestFromHeaders(request.headers))
1128
+ .pipe(Effect.mapError((error) => error.cause === undefined
1129
+ ? new AuthUnauthenticatedError({
1130
+ code: "unauthenticated",
1131
+ message: "Unauthenticated",
1132
+ })
1133
+ : new AuthInternalError({
1134
+ code: "internal_error",
1135
+ message: "Failed to validate session",
1136
+ })));
1137
+ if (Option.isNone(tokenOption)) {
1138
+ return yield* new AuthUnauthenticatedError({
1139
+ code: "unauthenticated",
1140
+ message: "Unauthenticated",
1141
+ });
1142
+ }
1143
+ const session = yield* dependencies.sessions
1144
+ .validate(tokenOption.value)
1145
+ .pipe(Effect.mapError((error) => error.cause === undefined
1146
+ ? new AuthUnauthenticatedError({
1147
+ code: "unauthenticated",
1148
+ message: "Unauthenticated",
1149
+ })
1150
+ : new AuthInternalError({
1151
+ code: "internal_error",
1152
+ message: "Failed to validate session",
1153
+ })));
1154
+ return yield* dependencies.authHttp.commitCurrentSession(session);
1155
+ });
1156
+ export const makeRefreshSessionHandler = (dependencies) => Effect.fn("auth.http.session.refresh")(function* ({ request, }) {
1157
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.refresh");
1158
+ const tokenOption = yield* dependencies.sessionCookie
1159
+ .read(webRequestFromHeaders(request.headers))
1160
+ .pipe(Effect.mapError((error) => error.cause === undefined
1161
+ ? new AuthUnauthenticatedError({
1162
+ code: "unauthenticated",
1163
+ message: "Unauthenticated",
1164
+ })
1165
+ : new AuthInternalError({
1166
+ code: "internal_error",
1167
+ message: "Failed to validate session",
1168
+ })));
1169
+ if (Option.isNone(tokenOption)) {
1170
+ return yield* new AuthUnauthenticatedError({
1171
+ code: "unauthenticated",
1172
+ message: "Unauthenticated",
1173
+ });
1174
+ }
1175
+ const session = yield* dependencies.sessions
1176
+ .refresh(tokenOption.value)
1177
+ .pipe(Effect.mapError((error) => error.cause === undefined
1178
+ ? new AuthUnauthenticatedError({
1179
+ code: "unauthenticated",
1180
+ message: "Unauthenticated",
1181
+ })
1182
+ : new AuthInternalError({
1183
+ code: "internal_error",
1184
+ message: "Failed to refresh session",
1185
+ })));
1186
+ return yield* dependencies.authHttp.commitSessionRefreshed(session);
1187
+ });
1188
+ export const makeLogoutHandler = (dependencies) => Effect.fn("auth.http.session.logout")(function* ({ request, }) {
1189
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.logout");
1190
+ const tokenOption = yield* dependencies.sessionCookie
1191
+ .read(webRequestFromHeaders(request.headers))
1192
+ .pipe(Effect.catchTag("SessionValidateError", (error) => error.cause === undefined
1193
+ ? Effect.succeed(Option.none())
1194
+ : Effect.fail(new AuthInternalError({
1195
+ code: "internal_error",
1196
+ message: "Failed to validate session",
1197
+ }))));
1198
+ if (Option.isSome(tokenOption)) {
1199
+ const sessionOption = yield* dependencies.sessions
1200
+ .validate(tokenOption.value)
1201
+ .pipe(Effect.map(Option.some), Effect.catchTag("SessionValidateError", (error) => error.cause === undefined
1202
+ ? Effect.succeed(Option.none())
1203
+ : Effect.fail(new AuthInternalError({
1204
+ code: "internal_error",
1205
+ message: "Failed to validate session",
1206
+ }))));
1207
+ if (Option.isSome(sessionOption)) {
1208
+ yield* dependencies.sessions
1209
+ .revoke({
1210
+ sessionId: sessionOption.value.currentSession.sessionId,
1211
+ reason: "logout",
1212
+ })
1213
+ .pipe(Effect.mapError(() => new AuthInternalError({
1214
+ code: "internal_error",
1215
+ message: "Failed to revoke session",
1216
+ })));
1217
+ }
1218
+ }
1219
+ return yield* dependencies.authHttp.commitSessionCleared();
1220
+ });
1221
+ export const makeListSessionsHandler = (dependencies) => Effect.fn("auth.http.session.list")(function* ({ request, }) {
1222
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.list");
1223
+ const current = yield* readRequiredSession(dependencies, request);
1224
+ const sessions = yield* dependencies.sessions
1225
+ .listForUser({ userId: current.currentSession.userId })
1226
+ .pipe(Effect.mapError(() => new AuthInternalError({
1227
+ code: "internal_error",
1228
+ message: "Failed to list sessions",
1229
+ })));
1230
+ return {
1231
+ sessions: sessions.map((session) => activeSessionBody(session, current.currentSession.sessionId)),
1232
+ };
1233
+ });
1234
+ export const makeRevokeSessionHandler = (dependencies) => Effect.fn("auth.http.session.revoke")(function* ({ payload, request, }) {
1235
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.revoke");
1236
+ const current = yield* readRequiredSession(dependencies, request);
1237
+ yield* dependencies.sessions
1238
+ .revokeForUser({
1239
+ userId: current.currentSession.userId,
1240
+ sessionId: payload.sessionId,
1241
+ reason: "user_revoked_session",
1242
+ })
1243
+ .pipe(Effect.mapError(() => new AuthInternalError({
1244
+ code: "internal_error",
1245
+ message: "Failed to revoke session",
1246
+ })));
1247
+ return payload.sessionId === current.currentSession.sessionId
1248
+ ? yield* dependencies.authHttp.commitSessionCleared()
1249
+ : HttpServerResponse.empty({ status: 204 });
1250
+ });
1251
+ export const makeRevokeOtherSessionsHandler = (dependencies) => Effect.fn("auth.http.session.revoke_others")(function* ({ request, }) {
1252
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "session.revoke_others");
1253
+ const current = yield* readRequiredSession(dependencies, request);
1254
+ yield* dependencies.sessions
1255
+ .revokeAllForUserExcept({
1256
+ userId: current.currentSession.userId,
1257
+ exceptSessionId: current.currentSession.sessionId,
1258
+ reason: "user_revoked_other_sessions",
1259
+ })
1260
+ .pipe(Effect.mapError(() => new AuthInternalError({
1261
+ code: "internal_error",
1262
+ message: "Failed to revoke other sessions",
1263
+ })));
1264
+ return HttpServerResponse.empty({ status: 204 });
1265
+ });
1266
+ export const makeLoginNotificationReportHandler = (dependencies) => Effect.fn("auth.http.security.login_notification.report")(function* ({ payload, }) {
1267
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "security.login_notification.report");
1268
+ if (dependencies.loginNotification === undefined) {
1269
+ return yield* loginNotificationNotConfigured();
1270
+ }
1271
+ yield* dependencies.loginNotification
1272
+ .report(loginNotificationReportInput(payload))
1273
+ .pipe(Effect.mapError((error) => error.reason === "invalid_report"
1274
+ ? loginNotificationBadRequest()
1275
+ : new AuthInternalError({
1276
+ code: "internal_error",
1277
+ message: "Failed to process login notification report",
1278
+ })));
1279
+ return HttpServerResponse.empty({ status: 204 });
1280
+ });
1281
+ const securityTimelineActorHttpBody = (actor) => actor.type === "anonymous"
1282
+ ? { type: "anonymous" }
1283
+ : {
1284
+ type: "user",
1285
+ ...(actor.sessionId === undefined ? {} : { sessionId: actor.sessionId }),
1286
+ };
1287
+ const securityTimelineRequestHttpBody = (request) => ({
1288
+ ...(request.ipHash === undefined ? {} : { ipHash: request.ipHash }),
1289
+ ...(request.userAgentHash === undefined
1290
+ ? {}
1291
+ : { userAgentHash: request.userAgentHash }),
1292
+ });
1293
+ export const securityTimelineEventHttpBody = (event) => ({
1294
+ eventId: event.id,
1295
+ type: event.type,
1296
+ category: event.category,
1297
+ severity: event.severity,
1298
+ occurredAt: event.occurredAt,
1299
+ summary: event.summary,
1300
+ ...(event.actor === undefined
1301
+ ? {}
1302
+ : { actor: securityTimelineActorHttpBody(event.actor) }),
1303
+ ...(event.request === undefined
1304
+ ? {}
1305
+ : { request: securityTimelineRequestHttpBody(event.request) }),
1306
+ ...(event.metadata === undefined ? {} : { metadata: event.metadata }),
1307
+ });
1308
+ const securityTimelineListInput = (query, userId) => ({
1309
+ userId,
1310
+ ...(query.limit === undefined ? {} : { limit: query.limit }),
1311
+ ...(query.beforeOccurredAt === undefined
1312
+ ? {}
1313
+ : { beforeOccurredAt: query.beforeOccurredAt }),
1314
+ ...(query.types === undefined ? {} : { types: query.types }),
1315
+ ...(query.categories === undefined ? {} : { categories: query.categories }),
1316
+ });
1317
+ export const makeSecurityTimelineListHandler = (dependencies) => Effect.fn("auth.http.security_timeline.list")(function* ({ query, request, }) {
1318
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "security_timeline.list");
1319
+ const current = yield* readRequiredSession(dependencies, request);
1320
+ const events = yield* dependencies.securityTimeline
1321
+ .listByUser(securityTimelineListInput(query, current.currentSession.userId))
1322
+ .pipe(Effect.mapError(() => new AuthInternalError({
1323
+ code: "internal_error",
1324
+ message: "Failed to list security timeline",
1325
+ })));
1326
+ return { events: events.map(securityTimelineEventHttpBody) };
1327
+ });
1328
+ export const trustedDeviceHttpBody = (device) => ({
1329
+ deviceId: device.tokenHash,
1330
+ createdAt: device.createdAt,
1331
+ lastSeenAt: device.lastSeenAt,
1332
+ expiresAt: device.expiresAt,
1333
+ ...(device.metadata === undefined ? {} : { metadata: device.metadata }),
1334
+ });
1335
+ export const makeTrustedDeviceListHandler = (dependencies) => Effect.fn("auth.http.trusted_device.list")(function* ({ request, }) {
1336
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "trusted_device.list");
1337
+ const current = yield* readRequiredSession(dependencies, request);
1338
+ const now = yield* currentUnixMillis;
1339
+ const devices = yield* dependencies.trustedDevices
1340
+ .listForUser({ userId: current.currentSession.userId, now })
1341
+ .pipe(Effect.mapError(() => new AuthInternalError({
1342
+ code: "internal_error",
1343
+ message: "Failed to list trusted devices",
1344
+ })));
1345
+ return { devices: devices.map(trustedDeviceHttpBody) };
1346
+ });
1347
+ export const makeTrustedDeviceRevokeHandler = (dependencies) => Effect.fn("auth.http.trusted_device.revoke")(function* ({ payload, request, }) {
1348
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "trusted_device.revoke");
1349
+ const current = yield* readRequiredSession(dependencies, request);
1350
+ yield* dependencies.trustedDevices
1351
+ .revokeForUser({
1352
+ userId: current.currentSession.userId,
1353
+ tokenHash: payload.deviceId,
1354
+ })
1355
+ .pipe(Effect.mapError(() => new AuthInternalError({
1356
+ code: "internal_error",
1357
+ message: "Failed to revoke trusted device",
1358
+ })));
1359
+ return HttpServerResponse.empty({ status: 204 });
1360
+ });
1361
+ export const makeEmailVerificationStartHandler = (dependencies) => Effect.fn("auth.http.email_verification.start")(function* ({ payload, }) {
1362
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "email_verification.start");
1363
+ const input = emailVerificationStartInput(payload);
1364
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1365
+ yield* catchAuthApiRateLimit(authApiRateLimit.emailVerificationStart(input), "Failed to start email verification");
1366
+ yield* dependencies.emailVerificationFlow.start(input).pipe(Effect.catchTag("EmailVerificationFlowStartError", (error) => Effect.fail(error.cause instanceof EmailVerificationIssueError
1367
+ ? new AuthBadRequestError({
1368
+ code: "bad_request",
1369
+ message: "Invalid email verification request",
1370
+ })
1371
+ : error.cause instanceof EmailDeliveryError
1372
+ ? new AuthInternalError({
1373
+ code: "internal_error",
1374
+ message: "Failed to send email verification",
1375
+ })
1376
+ : new AuthInternalError({
1377
+ code: "internal_error",
1378
+ message: "Failed to start email verification",
1379
+ }))));
1380
+ return HttpServerResponse.empty({ status: 204 });
1381
+ });
1382
+ export const makeEmailVerificationVerifyHandler = (dependencies) => Effect.fn("auth.http.email_verification.verify")(function* ({ payload, request, }) {
1383
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "email_verification.verify");
1384
+ const verified = yield* dependencies.emailVerification
1385
+ .verify(emailVerificationVerifyInput(payload))
1386
+ .pipe(Effect.mapError(() => new AuthBadRequestError({
1387
+ code: "bad_request",
1388
+ message: "Invalid email verification request",
1389
+ })));
1390
+ yield* upgradeVerifiedEmailSession(dependencies, request, verified);
1391
+ return HttpServerResponse.empty({ status: 204 });
1392
+ });
1393
+ export const makeEmailOtpStartHandler = (dependencies) => Effect.fn("auth.http.email_otp.start")(function* ({ payload, }) {
1394
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "email_otp.start");
1395
+ const input = emailOtpStartInput(payload);
1396
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1397
+ yield* catchAuthApiRateLimit(authApiRateLimit.emailOtpStart(input), "Failed to start email OTP");
1398
+ return yield* dependencies.emailOtp.start(input).pipe(Effect.mapError(() => new AuthInternalError({
1399
+ code: "internal_error",
1400
+ message: "Failed to start email OTP",
1401
+ })));
1402
+ });
1403
+ export const makeEmailOtpVerifyHandler = (dependencies) => Effect.fn("auth.http.email_otp.verify")(function* ({ payload, request, }) {
1404
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "email_otp.verify");
1405
+ const trustedDeviceToken = yield* trustedDeviceTokenFromRequest(dependencies.trustedDeviceCookie, request).pipe(Effect.mapError(() => passwordInternalError("Failed to read trusted device cookie")));
1406
+ const requestMetadataOptions = yield* authRequestMetadataOptions;
1407
+ const requestContext = loginRequestContextFromRequest(request, requestMetadataOptions);
1408
+ const result = yield* dependencies.emailOtp
1409
+ .verify(emailOtpVerifyInput(payload, Option.isSome(trustedDeviceToken)
1410
+ ? trustedDeviceToken.value
1411
+ : undefined, requestContext))
1412
+ .pipe(Effect.mapError(() => new AuthInternalError({
1413
+ code: "internal_error",
1414
+ message: "Failed to verify email OTP",
1415
+ })));
1416
+ return yield* dependencies.authHttp.commitEmailOtpVerifyResult(result);
1417
+ });
1418
+ export const makeMagicLinkStartHandler = (dependencies) => Effect.fn("auth.http.magic_link.start")(function* ({ payload, }) {
1419
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "magic_link.start");
1420
+ const input = magicLinkStartInput(payload);
1421
+ const authApiRateLimit = dependencies.authApiRateLimit ?? noopAuthApiRateLimit;
1422
+ yield* catchAuthApiRateLimit(authApiRateLimit.magicLinkStart(input), "Failed to start magic link");
1423
+ const started = yield* dependencies.magicLink.start(input).pipe(Effect.mapError(() => new AuthInternalError({
1424
+ code: "internal_error",
1425
+ message: "Failed to start magic link",
1426
+ })));
1427
+ return {
1428
+ email: started.email,
1429
+ expiresAt: started.expiresAt,
1430
+ };
1431
+ });
1432
+ export const makeMagicLinkVerifyHandler = (dependencies) => Effect.fn("auth.http.magic_link.verify")(function* ({ payload, request, }) {
1433
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "magic_link.verify");
1434
+ const trustedDeviceToken = yield* trustedDeviceTokenFromRequest(dependencies.trustedDeviceCookie, request).pipe(Effect.mapError(() => passwordInternalError("Failed to read trusted device cookie")));
1435
+ const requestMetadataOptions = yield* authRequestMetadataOptions;
1436
+ const requestContext = loginRequestContextFromRequest(request, requestMetadataOptions);
1437
+ const result = yield* dependencies.magicLink
1438
+ .verify(magicLinkVerifyInput(payload, Option.isSome(trustedDeviceToken)
1439
+ ? trustedDeviceToken.value
1440
+ : undefined, requestContext))
1441
+ .pipe(Effect.mapError(() => new AuthInternalError({
1442
+ code: "internal_error",
1443
+ message: "Failed to verify magic link",
1444
+ })));
1445
+ return yield* dependencies.authHttp.commitMagicLinkVerifyResult(result);
1446
+ });
1447
+ export const makeOAuthAuthorizationStartHandler = (dependencies) => Effect.fn("auth.http.oauth.authorization_start")(function* ({ payload, }) {
1448
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "oauth.authorization_start");
1449
+ const provider = yield* dependencies.oauthProviders.get(payload.providerId).pipe(Effect.mapError(() => oauthInternalError("Failed to load OAuth provider")));
1450
+ if (Option.isNone(provider)) {
1451
+ return yield* oauthBadRequest("Unknown OAuth provider");
1452
+ }
1453
+ const started = yield* dependencies.oauthState
1454
+ .start(oauthAuthorizationStartInput(payload, provider.value, dependencies))
1455
+ .pipe(Effect.mapError(() => oauthInternalError("Failed to start OAuth authorization")));
1456
+ if (dependencies.storeCodeVerifier !== undefined) {
1457
+ yield* dependencies.storeCodeVerifier({ payload, started }).pipe(Effect.mapError(() => oauthInternalError("Failed to store OAuth verifier")));
1458
+ }
1459
+ return oauthAuthorizationStartedHttpBody(started);
1460
+ });
1461
+ export const makeOAuthAccountUnlinkHandler = (dependencies) => Effect.fn("auth.http.oauth.account_unlink")(function* ({ payload, request, }) {
1462
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "oauth.account_unlink");
1463
+ const session = yield* readRequiredSession(dependencies, request);
1464
+ const stepUpSatisfied = dependencies.stepUpSatisfied === undefined
1465
+ ? undefined
1466
+ : yield* dependencies.stepUpSatisfied({ payload, request, session }).pipe(Effect.mapError(() => oauthInternalError("Failed to evaluate OAuth unlink step-up")));
1467
+ const decision = yield* dependencies.oauthAccountUnlinking
1468
+ .resolve({
1469
+ userId: session.currentSession.userId,
1470
+ providerId: payload.providerId,
1471
+ providerAccountId: payload.providerAccountId,
1472
+ ...(stepUpSatisfied === undefined ? {} : { stepUpSatisfied }),
1473
+ })
1474
+ .pipe(Effect.mapError(() => oauthInternalError("Failed to resolve OAuth account unlinking")));
1475
+ if (decision.type !== "allow") {
1476
+ return oauthAccountUnlinkResolutionHttpBody(decision);
1477
+ }
1478
+ if (dependencies.unlinkAfterAllow !== undefined) {
1479
+ yield* dependencies
1480
+ .unlinkAfterAllow({ payload, request, session, decision })
1481
+ .pipe(Effect.mapError(() => oauthInternalError("Failed to unlink OAuth account")));
1482
+ }
1483
+ return oauthAccountUnlinkResolutionHttpBody(decision, {
1484
+ unlinked: dependencies.unlinkAfterAllow !== undefined,
1485
+ });
1486
+ });
1487
+ export const makeOAuthLinkConfirmationStartHandler = (dependencies) => Effect.fn("auth.http.oauth.link_confirmation_start")(function* ({ payload, request, }) {
1488
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "oauth.link_confirmation_start");
1489
+ const baseInput = dependencies.startInput === undefined
1490
+ ? yield* oauthLinkConfirmationStartInput(payload, dependencies)
1491
+ : yield* dependencies.startInput({ payload, request }).pipe(Effect.mapError((error) => oauthHookHttpError(error, "Failed to resolve OAuth link confirmation input")));
1492
+ const input = {
1493
+ ...baseInput,
1494
+ ...(baseInput.ttl === undefined && dependencies.ttl !== undefined
1495
+ ? { ttl: dependencies.ttl }
1496
+ : {}),
1497
+ };
1498
+ const started = yield* dependencies.oauthLinkConfirmation.start(input).pipe(Effect.mapError((error) => oauthLinkConfirmationHttpError(error, "Failed to start OAuth link confirmation")));
1499
+ if (dependencies.onStarted !== undefined) {
1500
+ yield* dependencies.onStarted({ payload, request, started }).pipe(Effect.mapError(() => oauthInternalError("Failed to deliver OAuth link confirmation")));
1501
+ }
1502
+ return oauthLinkConfirmationStartedHttpBody(started);
1503
+ });
1504
+ export const makeOAuthLinkConfirmationInspectHandler = (dependencies) => Effect.fn("auth.http.oauth.link_confirmation_inspect")(function* ({ payload, }) {
1505
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "oauth.link_confirmation_inspect");
1506
+ const pending = yield* dependencies.oauthLinkConfirmation
1507
+ .inspect(oauthLinkConfirmationInspectInput(payload))
1508
+ .pipe(Effect.mapError((error) => oauthLinkConfirmationHttpError(error, "Failed to inspect OAuth link confirmation")));
1509
+ return oauthLinkConfirmationPendingHttpBody(pending);
1510
+ });
1511
+ export const makeOAuthLinkConfirmationConfirmHandler = (dependencies) => Effect.fn("auth.http.oauth.link_confirmation_confirm")(function* ({ payload, request, }) {
1512
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "oauth.link_confirmation_confirm");
1513
+ const currentUserId = dependencies.currentUserId === undefined
1514
+ ? undefined
1515
+ : yield* dependencies.currentUserId({ payload, request }).pipe(Effect.mapError((error) => oauthHookHttpError(error, "Failed to resolve current OAuth user")));
1516
+ const confirmed = yield* dependencies.oauthLinkConfirmation
1517
+ .confirm(oauthLinkConfirmationConfirmInput(payload, currentUserId))
1518
+ .pipe(Effect.mapError((error) => oauthLinkConfirmationHttpError(error, "Failed to confirm OAuth link confirmation")));
1519
+ if (dependencies.linkAfterConfirm !== undefined) {
1520
+ yield* dependencies.linkAfterConfirm({ payload, request, confirmed }).pipe(Effect.mapError(() => oauthInternalError("Failed to link OAuth account")));
1521
+ }
1522
+ return oauthLinkConfirmationConfirmedHttpBody(confirmed, {
1523
+ linked: dependencies.linkAfterConfirm !== undefined,
1524
+ });
1525
+ });
1526
+ export const makePasskeyRegistrationStartHandler = (dependencies) => Effect.fn("auth.http.passkey.registration_start")(function* ({ payload, }) {
1527
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.registration_start");
1528
+ return yield* dependencies.passkeyOptions
1529
+ .startRegistration(passkeyRegistrationStartInput(payload, dependencies))
1530
+ .pipe(Effect.mapError(() => passkeyInternalError("Failed to start passkey registration")));
1531
+ });
1532
+ export const makePasskeyRegistrationFinishHandler = (dependencies) => Effect.fn("auth.http.passkey.registration_finish")(function* ({ payload, }) {
1533
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.registration_finish");
1534
+ const finished = yield* dependencies.passkeyVerification
1535
+ .finishRegistration(passkeyRegistrationFinishInput(payload, dependencies))
1536
+ .pipe(Effect.mapError(passkeyVerificationHttpError));
1537
+ return { credentialId: finished.credential.credentialId };
1538
+ });
1539
+ export const makePasskeyAuthenticationStartHandler = (dependencies) => Effect.fn("auth.http.passkey.authentication_start")(function* ({ payload, }) {
1540
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.authentication_start");
1541
+ return yield* dependencies.passkeyOptions
1542
+ .startAuthentication(passkeyAuthenticationStartInput(payload, dependencies))
1543
+ .pipe(Effect.mapError(() => passkeyInternalError("Failed to start passkey authentication")));
1544
+ });
1545
+ export const makePasskeyAuthenticationFinishHandler = (dependencies) => Effect.fn("auth.http.passkey.authentication_finish")(function* ({ payload, request, }) {
1546
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.authentication_finish");
1547
+ const finished = yield* dependencies.passkeyVerification
1548
+ .finishAuthentication(passkeyAuthenticationFinishInput(payload, dependencies))
1549
+ .pipe(Effect.mapError(passkeyVerificationHttpError));
1550
+ const session = yield* dependencies.sessions
1551
+ .create(dependencies.makeSessionInput({
1552
+ finished,
1553
+ payload,
1554
+ ...(request === undefined ? {} : { request }),
1555
+ }))
1556
+ .pipe(Effect.mapError(() => passkeyInternalError("Failed to create passkey session")));
1557
+ return yield* dependencies.authHttp.commitAuthenticatedSession(session);
1558
+ });
1559
+ export const makePasskeyCredentialListHandler = (dependencies) => Effect.fn("auth.http.passkey.credential_list")(function* ({ request, }) {
1560
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.credential_list");
1561
+ const current = yield* readRequiredSession(dependencies, request);
1562
+ const credentials = yield* dependencies.passkeyCredentialManagement
1563
+ .listForUser({ userId: current.currentSession.userId })
1564
+ .pipe(Effect.mapError(() => passkeyInternalError("Failed to list passkey credentials")));
1565
+ return {
1566
+ credentials: credentials.map(passkeyCredentialInfoHttpBody),
1567
+ };
1568
+ });
1569
+ export const makePasskeyCredentialRevokeHandler = (dependencies) => Effect.fn("auth.http.passkey.credential_revoke")(function* ({ payload, request, }) {
1570
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "passkey.credential_revoke");
1571
+ const current = yield* readRequiredSession(dependencies, request);
1572
+ yield* dependencies.passkeyCredentialManagement
1573
+ .revokeForUser(passkeyCredentialRevokeInput(current.currentSession.userId, payload))
1574
+ .pipe(Effect.mapError(passkeyCredentialManagementHttpError));
1575
+ return HttpServerResponse.empty({ status: 204 });
1576
+ });
1577
+ export const makeTotpEnrollmentStartHandler = (dependencies) => Effect.fn("auth.http.totp.enrollment_start")(function* ({ payload, request, }) {
1578
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "totp.enrollment_start");
1579
+ const current = yield* readRequiredSession(dependencies, request);
1580
+ const started = yield* dependencies.totpFactorManagement
1581
+ .startEnrollment(totpEnrollmentStartInput(current.currentSession.userId, payload, dependencies))
1582
+ .pipe(Effect.mapError(totpFactorManagementHttpError));
1583
+ return totpEnrollmentStartedHttpBody(started);
1584
+ });
1585
+ export const makeTotpEnrollmentConfirmHandler = (dependencies) => Effect.fn("auth.http.totp.enrollment_confirm")(function* ({ payload, request, }) {
1586
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "totp.enrollment_confirm");
1587
+ const current = yield* readRequiredSession(dependencies, request);
1588
+ const confirmed = yield* dependencies.totpFactorManagement
1589
+ .confirmEnrollment(totpEnrollmentConfirmInput(current.currentSession.userId, payload, dependencies))
1590
+ .pipe(Effect.mapError(totpFactorManagementHttpError));
1591
+ return totpFactorInfoHttpBody(confirmed);
1592
+ });
1593
+ export const makeTotpVerifyHandler = (dependencies) => Effect.fn("auth.http.totp.verify")(function* ({ payload, request, }) {
1594
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "totp.verify");
1595
+ const current = yield* readRequiredSession(dependencies, request);
1596
+ const result = yield* dependencies.totpFactorManagement
1597
+ .verifyForUser(totpVerifyInput(current.currentSession.userId, payload, dependencies))
1598
+ .pipe(Effect.mapError(() => totpInternalError("Failed to verify TOTP factor")));
1599
+ return totpVerifyResultHttpBody(result);
1600
+ });
1601
+ export const makeTotpFactorListHandler = (dependencies) => Effect.fn("auth.http.totp.factor_list")(function* ({ request, }) {
1602
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "totp.factor_list");
1603
+ const current = yield* readRequiredSession(dependencies, request);
1604
+ const factors = yield* dependencies.totpFactorManagement
1605
+ .listForUser({ userId: current.currentSession.userId })
1606
+ .pipe(Effect.mapError(() => totpInternalError("Failed to list TOTP factors")));
1607
+ return { factors: factors.map(totpFactorInfoHttpBody) };
1608
+ });
1609
+ export const makeTotpFactorRevokeHandler = (dependencies) => Effect.fn("auth.http.totp.factor_revoke")(function* ({ payload, request, }) {
1610
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "totp.factor_revoke");
1611
+ const current = yield* readRequiredSession(dependencies, request);
1612
+ yield* dependencies.totpFactorManagement
1613
+ .revokeForUser(totpFactorRevokeInput(current.currentSession.userId, payload))
1614
+ .pipe(Effect.mapError(totpFactorManagementHttpError));
1615
+ return HttpServerResponse.empty({ status: 204 });
1616
+ });
1617
+ export const makeRecoveryCodeGenerateHandler = (dependencies) => Effect.fn("auth.http.recovery_code.generate")(function* ({ payload, request, }) {
1618
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "recovery_code.generate");
1619
+ const current = yield* readRequiredSession(dependencies, request);
1620
+ const generated = yield* dependencies.recoveryCodeManagement
1621
+ .generateForUser(recoveryCodeGenerateInput(current.currentSession.userId, payload, dependencies))
1622
+ .pipe(Effect.mapError(recoveryCodeManagementHttpError));
1623
+ return recoveryCodesGeneratedHttpBody(generated);
1624
+ });
1625
+ export const makeRecoveryCodeVerifyHandler = (dependencies) => Effect.fn("auth.http.recovery_code.verify")(function* ({ payload, request, }) {
1626
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "recovery_code.verify");
1627
+ const current = yield* readRequiredSession(dependencies, request);
1628
+ const result = yield* dependencies.recoveryCodeManagement
1629
+ .verifyForUser(recoveryCodeVerifyInput(current.currentSession.userId, payload))
1630
+ .pipe(Effect.mapError(() => recoveryCodeInternalError("Failed to verify recovery code")));
1631
+ return recoveryCodeVerifyResultHttpBody(result);
1632
+ });
1633
+ export const makeRecoveryCodeListHandler = (dependencies) => Effect.fn("auth.http.recovery_code.list")(function* ({ request, }) {
1634
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "recovery_code.list");
1635
+ const current = yield* readRequiredSession(dependencies, request);
1636
+ const codes = yield* dependencies.recoveryCodeManagement
1637
+ .listForUser({ userId: current.currentSession.userId })
1638
+ .pipe(Effect.mapError(() => recoveryCodeInternalError("Failed to list recovery codes")));
1639
+ return { codes: codes.map(recoveryCodeInfoHttpBody) };
1640
+ });
1641
+ export const makeRecoveryCodeRevokeHandler = (dependencies) => Effect.fn("auth.http.recovery_code.revoke")(function* ({ payload, request, }) {
1642
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "recovery_code.revoke");
1643
+ const current = yield* readRequiredSession(dependencies, request);
1644
+ yield* dependencies.recoveryCodeManagement
1645
+ .revokeForUser(recoveryCodeRevokeInput(current.currentSession.userId, payload))
1646
+ .pipe(Effect.mapError(recoveryCodeManagementHttpError));
1647
+ return HttpServerResponse.empty({ status: 204 });
1648
+ });
1649
+ export const makeApiKeyCreateHandler = (dependencies) => Effect.fn("auth.http.api_key.create")(function* ({ payload, request, }) {
1650
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "api_key.create");
1651
+ const current = yield* readRequiredSession(dependencies, request);
1652
+ const created = yield* dependencies.apiKeyManagement
1653
+ .createForUser(apiKeyCreateInput(current.currentSession.userId, payload))
1654
+ .pipe(Effect.mapError(apiKeyManagementHttpError));
1655
+ return apiKeyCreatedHttpBody(created);
1656
+ });
1657
+ export const makeApiKeyListHandler = (dependencies) => Effect.fn("auth.http.api_key.list")(function* ({ request, }) {
1658
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "api_key.list");
1659
+ const current = yield* readRequiredSession(dependencies, request);
1660
+ const keys = yield* dependencies.apiKeyManagement
1661
+ .listForUser({ userId: current.currentSession.userId })
1662
+ .pipe(Effect.mapError(() => apiKeyInternalError("Failed to list API keys")));
1663
+ return { keys: keys.map(apiKeyInfoHttpBody) };
1664
+ });
1665
+ export const makeApiKeyRevokeHandler = (dependencies) => Effect.fn("auth.http.api_key.revoke")(function* ({ payload, request, }) {
1666
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "api_key.revoke");
1667
+ const current = yield* readRequiredSession(dependencies, request);
1668
+ yield* dependencies.apiKeyManagement
1669
+ .revokeForUser(apiKeyRevokeInput(current.currentSession.userId, payload))
1670
+ .pipe(Effect.mapError(apiKeyManagementHttpError));
1671
+ return HttpServerResponse.empty({ status: 204 });
1672
+ });
1673
+ export const makeRefreshTokenRefreshHandler = (dependencies) => Effect.fn("auth.http.refresh_token.refresh")(function* ({ payload, }) {
1674
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "refresh_token.refresh");
1675
+ const now = yield* currentUnixMillis;
1676
+ const expiresAt = dependencies.refreshTokenExpiresAt({ now });
1677
+ const rotated = yield* dependencies.refreshTokenManagement
1678
+ .rotate(refreshTokenRefreshInput(payload, now, expiresAt))
1679
+ .pipe(Effect.mapError(() => refreshTokenInternalError("Failed to rotate refresh token")));
1680
+ switch (rotated._tag) {
1681
+ case "Invalid": {
1682
+ return yield* refreshTokenInvalidCredentials();
1683
+ }
1684
+ case "ReuseDetected": {
1685
+ return yield* refreshTokenInvalidCredentials("Refresh token reuse detected");
1686
+ }
1687
+ case "Rotated": {
1688
+ const accessToken = yield* dependencies.jwtIssuer
1689
+ .issue(dependencies.accessToken({
1690
+ now,
1691
+ refreshToken: rotated.refreshToken,
1692
+ previousToken: rotated.previousToken,
1693
+ }))
1694
+ .pipe(Effect.mapError(() => refreshTokenInternalError("Failed to issue access token")));
1695
+ return refreshTokenRefreshedHttpBody({
1696
+ accessToken,
1697
+ refreshToken: Redacted.value(rotated.token),
1698
+ refreshTokenRecord: rotated.refreshToken,
1699
+ });
1700
+ }
1701
+ }
1702
+ });
1703
+ export const makeJwtIntrospectHandler = (dependencies) => Effect.fn("auth.http.jwt.introspect")(function* ({ payload, }) {
1704
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "jwt.introspect");
1705
+ const result = yield* dependencies.jwtRevocation
1706
+ .introspect(jwtIntrospectInput(payload, dependencies))
1707
+ .pipe(Effect.mapError(() => jwtInternalError("Failed to introspect JWT access token")));
1708
+ return jwtIntrospectionHttpBody(result);
1709
+ });
1710
+ export const makeJwtRevokeHandler = (dependencies) => Effect.fn("auth.http.jwt.revoke")(function* ({ payload }) {
1711
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "jwt.revoke");
1712
+ yield* dependencies.jwtRevocation
1713
+ .revokeJwtId(jwtRevokeInput(payload))
1714
+ .pipe(Effect.mapError(jwtRevocationHttpError));
1715
+ return HttpServerResponse.empty({ status: 204 });
1716
+ });
1717
+ export const makeMfaOptionsHandler = (dependencies) => Effect.fn("auth.http.mfa.options")(function* ({ payload, }) {
1718
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.options");
1719
+ const pending = yield* dependencies.authFlowState
1720
+ .inspect(payload.flowId)
1721
+ .pipe(Effect.mapError(() => mfaBadRequest()));
1722
+ const factors = [];
1723
+ if (dependencies.totpFactorManagement !== undefined) {
1724
+ const totpFactors = yield* dependencies.totpFactorManagement
1725
+ .listForUser({ userId: pending.userId })
1726
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to list MFA options")));
1727
+ if (totpFactors.length > 0) {
1728
+ factors.push({ type: "totp" });
1729
+ }
1730
+ }
1731
+ if (dependencies.recoveryCodeManagement !== undefined) {
1732
+ const recoveryCodes = yield* dependencies.recoveryCodeManagement
1733
+ .listForUser({ userId: pending.userId })
1734
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to list MFA options")));
1735
+ if (recoveryCodes.length > 0) {
1736
+ factors.push({ type: "backup-code" });
1737
+ }
1738
+ }
1739
+ if (dependencies.passkeyCredentialManagement !== undefined) {
1740
+ const credentials = yield* dependencies.passkeyCredentialManagement
1741
+ .listForUser({ userId: pending.userId })
1742
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to list MFA options")));
1743
+ if (credentials.length > 0) {
1744
+ factors.push({ type: "passkey" });
1745
+ }
1746
+ }
1747
+ return { factors };
1748
+ });
1749
+ export const makeTotpMfaVerifyHandler = (dependencies) => Effect.fn("auth.http.mfa.totp_verify")(function* ({ payload, }) {
1750
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.totp_verify");
1751
+ const verified = yield* dependencies.totpFactorManagement
1752
+ .verifyForUser(totpMfaVerifyInput(payload, dependencies))
1753
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to verify TOTP MFA factor")));
1754
+ if (!verified.valid) {
1755
+ return yield* mfaInvalidCredentials();
1756
+ }
1757
+ const result = yield* dependencies.authFlow
1758
+ .completeMfa({
1759
+ flowId: payload.flowId,
1760
+ userId: payload.userId,
1761
+ method: "totp",
1762
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
1763
+ })
1764
+ .pipe(Effect.mapError(authFlowMfaHttpError));
1765
+ if (result._tag === "PolicyDenied") {
1766
+ return yield* mfaPolicyDenied(result.reason);
1767
+ }
1768
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session);
1769
+ });
1770
+ export const makeTotpMfaVerifyForFlowHandler = (dependencies) => Effect.fn("auth.http.mfa.totp_verify_for_flow")(function* ({ payload, }) {
1771
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.totp_verify_for_flow");
1772
+ const pending = yield* dependencies.authFlowState
1773
+ .inspect(payload.flowId)
1774
+ .pipe(Effect.mapError(() => mfaBadRequest()));
1775
+ const verified = yield* dependencies.totpFactorManagement
1776
+ .verifyForUser(totpMfaVerifyForFlowInput(pending.userId, payload, dependencies))
1777
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to verify TOTP MFA factor")));
1778
+ if (!verified.valid) {
1779
+ return yield* mfaInvalidCredentials();
1780
+ }
1781
+ const result = yield* dependencies.authFlow
1782
+ .completeMfa({
1783
+ flowId: payload.flowId,
1784
+ userId: pending.userId,
1785
+ method: "totp",
1786
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
1787
+ })
1788
+ .pipe(Effect.mapError(authFlowMfaHttpError));
1789
+ if (result._tag === "PolicyDenied") {
1790
+ return yield* mfaPolicyDenied(result.reason);
1791
+ }
1792
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session);
1793
+ });
1794
+ export const makeRecoveryCodeMfaVerifyHandler = (dependencies) => Effect.fn("auth.http.mfa.recovery_code_verify")(function* ({ payload, }) {
1795
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.recovery_code_verify");
1796
+ const verified = yield* dependencies.recoveryCodeManagement
1797
+ .verifyForUser(recoveryCodeMfaVerifyInput(payload))
1798
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to verify recovery code MFA factor")));
1799
+ if (!verified.valid) {
1800
+ return yield* mfaInvalidCredentials();
1801
+ }
1802
+ const result = yield* dependencies.authFlow
1803
+ .completeMfa({
1804
+ flowId: payload.flowId,
1805
+ userId: payload.userId,
1806
+ method: "backup-code",
1807
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
1808
+ })
1809
+ .pipe(Effect.mapError(authFlowMfaHttpError));
1810
+ if (result._tag === "PolicyDenied") {
1811
+ return yield* mfaPolicyDenied(result.reason);
1812
+ }
1813
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session);
1814
+ });
1815
+ export const makeRecoveryCodeMfaVerifyForFlowHandler = (dependencies) => Effect.fn("auth.http.mfa.recovery_code_verify_for_flow")(function* ({ payload, }) {
1816
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.recovery_code_verify_for_flow");
1817
+ const pending = yield* dependencies.authFlowState
1818
+ .inspect(payload.flowId)
1819
+ .pipe(Effect.mapError(() => mfaBadRequest()));
1820
+ const verified = yield* dependencies.recoveryCodeManagement
1821
+ .verifyForUser(recoveryCodeMfaVerifyForFlowInput(pending.userId, payload))
1822
+ .pipe(Effect.mapError(() => mfaInternalError("Failed to verify recovery code MFA factor")));
1823
+ if (!verified.valid) {
1824
+ return yield* mfaInvalidCredentials();
1825
+ }
1826
+ const result = yield* dependencies.authFlow
1827
+ .completeMfa({
1828
+ flowId: payload.flowId,
1829
+ userId: pending.userId,
1830
+ method: "backup-code",
1831
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
1832
+ })
1833
+ .pipe(Effect.mapError(authFlowMfaHttpError));
1834
+ if (result._tag === "PolicyDenied") {
1835
+ return yield* mfaPolicyDenied(result.reason);
1836
+ }
1837
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session);
1838
+ });
1839
+ export const makePasskeyMfaStartHandler = (dependencies) => Effect.fn("auth.http.mfa.passkey_start")(function* ({ payload, }) {
1840
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.passkey_start");
1841
+ const pending = yield* dependencies.authFlowState
1842
+ .inspect(payload.flowId)
1843
+ .pipe(Effect.mapError(() => mfaBadRequest()));
1844
+ return yield* dependencies.passkeyOptions
1845
+ .startAuthentication(passkeyMfaStartInput(pending.userId, payload, dependencies))
1846
+ .pipe(Effect.mapError(() => passkeyInternalError("Failed to start passkey MFA authentication")));
1847
+ });
1848
+ export const makePasskeyMfaVerifyHandler = (dependencies) => Effect.fn("auth.http.mfa.passkey_verify")(function* ({ payload, }) {
1849
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "mfa.passkey_verify");
1850
+ const finished = yield* dependencies.passkeyVerification
1851
+ .finishAuthentication(passkeyMfaVerifyInput(payload, dependencies))
1852
+ .pipe(Effect.mapError(passkeyVerificationHttpError));
1853
+ const result = yield* dependencies.authFlow
1854
+ .completeMfa({
1855
+ flowId: payload.flowId,
1856
+ userId: finished.userId,
1857
+ method: "passkey",
1858
+ ...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),
1859
+ })
1860
+ .pipe(Effect.mapError(authFlowMfaHttpError));
1861
+ if (result._tag === "PolicyDenied") {
1862
+ return yield* mfaPolicyDenied(result.reason);
1863
+ }
1864
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session);
1865
+ });
1866
+ const upgradeStepUpSession = (dependencies, current, method) => upgradeCurrentSession({ method, reason: "step_up" }).pipe(Effect.provideService(CurrentSession, CurrentSession.make(current.currentSession)), Effect.provideService(Sessions, dependencies.sessions), Effect.map(stepUpAuthenticatedHttpBody), Effect.mapError(() => stepUpInternalError("Failed to upgrade current session")));
1867
+ export const makeStepUpOptionsHandler = (dependencies) => Effect.fn("auth.http.step_up.options")(function* ({ request, }) {
1868
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "step_up.options");
1869
+ const current = yield* readRequiredSession(dependencies, request);
1870
+ const { userId } = current.currentSession;
1871
+ const factors = [];
1872
+ if (dependencies.totpFactorManagement !== undefined) {
1873
+ const totpFactors = yield* dependencies.totpFactorManagement
1874
+ .listForUser({ userId })
1875
+ .pipe(Effect.mapError(() => stepUpInternalError("Failed to list step-up options")));
1876
+ if (totpFactors.length > 0) {
1877
+ factors.push({ type: "totp" });
1878
+ }
1879
+ }
1880
+ if (dependencies.recoveryCodeManagement !== undefined) {
1881
+ const recoveryCodes = yield* dependencies.recoveryCodeManagement
1882
+ .listForUser({ userId })
1883
+ .pipe(Effect.mapError(() => stepUpInternalError("Failed to list step-up options")));
1884
+ if (recoveryCodes.length > 0) {
1885
+ factors.push({ type: "backup-code" });
1886
+ }
1887
+ }
1888
+ if (dependencies.passkeyCredentialManagement !== undefined) {
1889
+ const credentials = yield* dependencies.passkeyCredentialManagement
1890
+ .listForUser({ userId })
1891
+ .pipe(Effect.mapError(() => stepUpInternalError("Failed to list step-up options")));
1892
+ if (credentials.length > 0) {
1893
+ factors.push({ type: "passkey" });
1894
+ }
1895
+ }
1896
+ return { factors };
1897
+ });
1898
+ export const makeStepUpTotpVerifyHandler = (dependencies) => Effect.fn("auth.http.step_up.totp_verify")(function* ({ payload, request, }) {
1899
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "step_up.totp_verify");
1900
+ const current = yield* readRequiredSession(dependencies, request);
1901
+ const verified = yield* dependencies.totpFactorManagement
1902
+ .verifyForUser(stepUpTotpVerifyInput(current.currentSession.userId, payload, dependencies))
1903
+ .pipe(Effect.mapError(() => stepUpInternalError("Failed to verify TOTP step-up factor")));
1904
+ if (!verified.valid) {
1905
+ return yield* stepUpInvalidCredentials();
1906
+ }
1907
+ return yield* upgradeStepUpSession(dependencies, current, "totp");
1908
+ });
1909
+ export const makeStepUpRecoveryCodeVerifyHandler = (dependencies) => Effect.fn("auth.http.step_up.recovery_code_verify")(function* ({ payload, request, }) {
1910
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "step_up.recovery_code_verify");
1911
+ const current = yield* readRequiredSession(dependencies, request);
1912
+ const verified = yield* dependencies.recoveryCodeManagement
1913
+ .verifyForUser(stepUpRecoveryCodeVerifyInput(current.currentSession.userId, payload))
1914
+ .pipe(Effect.mapError(() => stepUpInternalError("Failed to verify recovery-code step-up factor")));
1915
+ if (!verified.valid) {
1916
+ return yield* stepUpInvalidCredentials();
1917
+ }
1918
+ return yield* upgradeStepUpSession(dependencies, current, "backup_code");
1919
+ });
1920
+ export const makeStepUpPasskeyStartHandler = (dependencies) => Effect.fn("auth.http.step_up.passkey_start")(function* ({ payload, request, }) {
1921
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "step_up.passkey_start");
1922
+ const current = yield* readRequiredSession(dependencies, request);
1923
+ return yield* dependencies.passkeyOptions
1924
+ .startAuthentication(stepUpPasskeyStartInput(current.currentSession.userId, payload, dependencies))
1925
+ .pipe(Effect.mapError((error) => error.cause === undefined
1926
+ ? stepUpBadRequest()
1927
+ : stepUpInternalError("Failed to start passkey step-up")));
1928
+ });
1929
+ export const makeStepUpPasskeyVerifyHandler = (dependencies) => Effect.fn("auth.http.step_up.passkey_verify")(function* ({ payload, request, }) {
1930
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "step_up.passkey_verify");
1931
+ const current = yield* readRequiredSession(dependencies, request);
1932
+ const finished = yield* dependencies.passkeyVerification
1933
+ .finishAuthentication(stepUpPasskeyVerifyInput(current.currentSession.userId, payload, dependencies))
1934
+ .pipe(Effect.mapError(passkeyVerificationHttpError));
1935
+ if (finished.userId !== current.currentSession.userId) {
1936
+ return yield* stepUpPolicyDenied("Passkey belongs to a different user");
1937
+ }
1938
+ return yield* upgradeStepUpSession(dependencies, current, "passkey");
1939
+ });
1940
+ export const makeLoginApprovalApproveHandler = (dependencies) => Effect.fn("auth.http.login_approval.approve")(function* ({ payload, request, }) {
1941
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "login_approval.approve");
1942
+ const input = loginApprovalApproveInput(payload);
1943
+ const approval = yield* dependencies.loginApproval
1944
+ .verify(input.approval)
1945
+ .pipe(Effect.mapError(() => loginApprovalBadRequest()));
1946
+ const approvedFlowId = metadataString(approval.metadata, "flowId");
1947
+ if (approvedFlowId !== input.flowId) {
1948
+ return yield* loginApprovalBadRequest();
1949
+ }
1950
+ if (approval.sessionBinding === "none") {
1951
+ return yield* loginApprovalNoSessionBindingDenied();
1952
+ }
1953
+ const sameDeviceSecret = approval.sameDeviceRequired
1954
+ ? yield* dependencies.loginApprovalPendingCookie
1955
+ .read(new Request("http://localhost", { headers: request.headers }))
1956
+ .pipe(Effect.flatMap((secret) => Option.isSome(secret)
1957
+ ? Effect.succeed(secret.value)
1958
+ : Effect.fail(loginApprovalSameDeviceDenied())))
1959
+ : undefined;
1960
+ const consumed = yield* dependencies.authFlowState
1961
+ .consume(input.flowId, sameDeviceSecret)
1962
+ .pipe(Effect.mapError(() => approval.sameDeviceRequired
1963
+ ? loginApprovalSameDeviceDenied()
1964
+ : loginApprovalBadRequest()));
1965
+ if (consumed.userId !== approval.userId) {
1966
+ return yield* loginApprovalBadRequest();
1967
+ }
1968
+ if (approval.markEmailVerified === true) {
1969
+ const updated = yield* dependencies.users
1970
+ .markEmailVerified({
1971
+ userId: approval.userId,
1972
+ updatedAt: yield* currentUnixMillis,
1973
+ })
1974
+ .pipe(Effect.mapError(() => passwordInternalError("Failed to mark email verified")));
1975
+ if (Option.isNone(updated)) {
1976
+ return yield* loginApprovalBadRequest();
1977
+ }
1978
+ }
1979
+ const result = yield* dependencies.authFlow
1980
+ .complete(consumed)
1981
+ .pipe(Effect.mapError(() => passwordInternalError("Failed to complete login approval")));
1982
+ const setCookies = yield* trustedDeviceSetCookies({
1983
+ trustedDevice: dependencies.trustedDevice,
1984
+ trustedDeviceCookie: dependencies.trustedDeviceCookie,
1985
+ userId: consumed.userId,
1986
+ rememberDevice: input.rememberDevice,
1987
+ });
1988
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session, { setCookies });
1989
+ });
1990
+ export const makeLoginApprovalStatusHandler = (dependencies) => Effect.fn("auth.http.login_approval.status")(function* ({ payload, }) {
1991
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "login_approval.status");
1992
+ if (dependencies.loginApprovalReview === undefined) {
1993
+ return yield* loginApprovalReviewNotConfigured();
1994
+ }
1995
+ const input = loginApprovalStatusInput(payload);
1996
+ const recordOption = yield* dependencies.loginApprovalReview
1997
+ .status({ approvalChallengeId: input.approvalChallengeId })
1998
+ .pipe(Effect.mapError(() => passwordInternalError("Failed to load login approval review")));
1999
+ if (Option.isNone(recordOption)) {
2000
+ return yield* loginApprovalBadRequest();
2001
+ }
2002
+ const record = recordOption.value;
2003
+ if (record.flowId !== input.flowId) {
2004
+ return yield* loginApprovalBadRequest();
2005
+ }
2006
+ const now = yield* currentUnixMillis;
2007
+ const status = Number(record.expiresAt) <= Number(now)
2008
+ ? "expired"
2009
+ : record.status;
2010
+ return {
2011
+ status,
2012
+ expiresAt: record.expiresAt,
2013
+ };
2014
+ });
2015
+ export const makeLoginApprovalFinalizeHandler = (dependencies) => Effect.fn("auth.http.login_approval.finalize")(function* ({ payload, request, }) {
2016
+ yield* Effect.annotateCurrentSpan("auth.http.endpoint", "login_approval.finalize");
2017
+ if (dependencies.loginApprovalFinalize === undefined) {
2018
+ return yield* loginApprovalFinalizeNotConfigured();
2019
+ }
2020
+ const input = loginApprovalFinalizeInput(payload);
2021
+ const sameDeviceSecret = yield* dependencies.loginApprovalPendingCookie.read(new Request("http://localhost", { headers: request.headers }));
2022
+ const result = yield* dependencies.loginApprovalFinalize
2023
+ .complete({
2024
+ flowId: input.flowId,
2025
+ approvalChallengeId: input.approvalChallengeId,
2026
+ ...(Option.isSome(sameDeviceSecret)
2027
+ ? { sameDeviceSecret: sameDeviceSecret.value }
2028
+ : {}),
2029
+ })
2030
+ .pipe(Effect.mapError((error) => error._tag === "AuthFlowStateError"
2031
+ ? loginApprovalSameDeviceDenied()
2032
+ : passwordInternalError("Failed to finalize login approval")));
2033
+ if (result._tag === "PolicyDenied") {
2034
+ return yield* loginApprovalPolicyDenied(result.reason);
2035
+ }
2036
+ const setCookies = yield* trustedDeviceSetCookies({
2037
+ trustedDevice: dependencies.trustedDevice,
2038
+ trustedDeviceCookie: dependencies.trustedDeviceCookie,
2039
+ userId: result.session.userId,
2040
+ rememberDevice: input.rememberDevice,
2041
+ });
2042
+ return yield* dependencies.authHttp.commitAuthenticatedSession(result.session, { setCookies });
2043
+ });
2044
+ export class PasswordApi extends HttpApiGroup.make("password")
2045
+ .add(passwordSignInEndpoint.middleware(AuthRateLimitMiddleware), passwordSignUpEndpoint.middleware(AuthRateLimitMiddleware), passwordResetStartEndpoint.middleware(AuthRateLimitMiddleware), passwordResetVerifyEndpoint.middleware(AuthRateLimitMiddleware), passwordSetEndpoint.middleware(AuthOriginCheckMiddleware), passwordChangeEndpoint.middleware(AuthOriginCheckMiddleware))
2046
+ .prefix("/auth/password")
2047
+ .middleware(AuthSchemaErrorMiddleware)
2048
+ .middleware(AuthOriginCheckMiddleware) {
2049
+ }
2050
+ export class SessionApi extends HttpApiGroup.make("session")
2051
+ .add(currentSessionEndpoint, refreshSessionEndpoint.middleware(AuthOriginCheckMiddleware), logoutEndpoint.middleware(AuthOriginCheckMiddleware), listSessionsEndpoint, revokeSessionEndpoint.middleware(AuthOriginCheckMiddleware), revokeOtherSessionsEndpoint.middleware(AuthOriginCheckMiddleware))
2052
+ .prefix("/auth") {
2053
+ }
2054
+ export class EmailVerificationApi extends HttpApiGroup.make("emailVerification")
2055
+ .add(emailVerificationStartEndpoint.middleware(AuthRateLimitMiddleware), emailVerificationVerifyEndpoint)
2056
+ .prefix("/auth/email-verification")
2057
+ .middleware(AuthSchemaErrorMiddleware)
2058
+ .middleware(AuthOriginCheckMiddleware) {
2059
+ }
2060
+ export class EmailOtpApi extends HttpApiGroup.make("emailOtp")
2061
+ .add(emailOtpStartEndpoint.middleware(AuthRateLimitMiddleware), emailOtpVerifyEndpoint.middleware(AuthRateLimitMiddleware))
2062
+ .prefix("/auth/email-otp")
2063
+ .middleware(AuthSchemaErrorMiddleware)
2064
+ .middleware(AuthOriginCheckMiddleware) {
2065
+ }
2066
+ export class MagicLinkApi extends HttpApiGroup.make("magicLink")
2067
+ .add(magicLinkStartEndpoint.middleware(AuthRateLimitMiddleware), magicLinkVerifyEndpoint.middleware(AuthRateLimitMiddleware))
2068
+ .prefix("/auth/magic-link")
2069
+ .middleware(AuthSchemaErrorMiddleware)
2070
+ .middleware(AuthOriginCheckMiddleware) {
2071
+ }
2072
+ export class OAuthApi extends HttpApiGroup.make("oauth")
2073
+ .add(oauthAuthorizationStartEndpoint, oauthAccountUnlinkEndpoint, oauthLinkConfirmationStartEndpoint, oauthLinkConfirmationInspectEndpoint, oauthLinkConfirmationConfirmEndpoint)
2074
+ .prefix("/auth/oauth")
2075
+ .middleware(AuthSchemaErrorMiddleware)
2076
+ .middleware(AuthOriginCheckMiddleware) {
2077
+ }
2078
+ export class LoginApprovalApi extends HttpApiGroup.make("loginApproval")
2079
+ .add(loginApprovalApproveEndpoint, loginApprovalStatusEndpoint, loginApprovalFinalizeEndpoint)
2080
+ .prefix("/auth/login-approval")
2081
+ .middleware(AuthSchemaErrorMiddleware)
2082
+ .middleware(AuthOriginCheckMiddleware) {
2083
+ }
2084
+ export class MfaApi extends HttpApiGroup.make("mfa")
2085
+ .add(mfaOptionsEndpoint, totpMfaVerifyEndpoint, totpMfaVerifyForFlowEndpoint, recoveryCodeMfaVerifyEndpoint, recoveryCodeMfaVerifyForFlowEndpoint, passkeyMfaStartEndpoint, passkeyMfaVerifyEndpoint)
2086
+ .prefix("/auth/mfa")
2087
+ .middleware(AuthSchemaErrorMiddleware)
2088
+ .middleware(AuthOriginCheckMiddleware) {
2089
+ }
2090
+ export class StepUpApi extends HttpApiGroup.make("stepUp")
2091
+ .add(stepUpOptionsEndpoint, stepUpTotpVerifyEndpoint, stepUpRecoveryCodeVerifyEndpoint, stepUpPasskeyStartEndpoint, stepUpPasskeyVerifyEndpoint)
2092
+ .prefix("/auth/step-up")
2093
+ .middleware(AuthSchemaErrorMiddleware)
2094
+ .middleware(AuthOriginCheckMiddleware) {
2095
+ }
2096
+ export class ApiKeyApi extends HttpApiGroup.make("apiKey")
2097
+ .add(apiKeyCreateEndpoint, apiKeyListEndpoint, apiKeyRevokeEndpoint)
2098
+ .prefix("/auth/api-keys")
2099
+ .middleware(AuthSchemaErrorMiddleware)
2100
+ .middleware(AuthOriginCheckMiddleware) {
2101
+ }
2102
+ export class RefreshTokenApi extends HttpApiGroup.make("refreshToken")
2103
+ .add(refreshTokenRefreshEndpoint)
2104
+ .prefix("/auth/token")
2105
+ .middleware(AuthSchemaErrorMiddleware) {
2106
+ }
2107
+ export class JwtApi extends HttpApiGroup.make("jwt")
2108
+ .add(jwtIntrospectEndpoint, jwtRevokeEndpoint)
2109
+ .prefix("/auth/jwt")
2110
+ .middleware(AuthSchemaErrorMiddleware) {
2111
+ }
2112
+ export class SecurityApi extends HttpApiGroup.make("security")
2113
+ .add(loginNotificationReportEndpoint)
2114
+ .prefix("/auth/security")
2115
+ .middleware(AuthSchemaErrorMiddleware)
2116
+ .middleware(AuthOriginCheckMiddleware) {
2117
+ }
2118
+ export class SecurityTimelineApi extends HttpApiGroup.make("securityTimeline")
2119
+ .add(securityTimelineListEndpoint)
2120
+ .prefix("/auth/security")
2121
+ .middleware(AuthSchemaErrorMiddleware)
2122
+ .middleware(AuthOriginCheckMiddleware) {
2123
+ }
2124
+ export class SecurityTimelineHttpApi extends HttpApi.make("SecurityTimelineHttpApi")
2125
+ .add(SecurityTimelineApi) {
2126
+ }
2127
+ export class TrustedDeviceApi extends HttpApiGroup.make("trustedDevice")
2128
+ .add(trustedDeviceListEndpoint, trustedDeviceRevokeEndpoint)
2129
+ .prefix("/auth/trusted-devices")
2130
+ .middleware(AuthSchemaErrorMiddleware)
2131
+ .middleware(AuthOriginCheckMiddleware) {
2132
+ }
2133
+ export class TrustedDeviceHttpApi extends HttpApi.make("TrustedDeviceHttpApi")
2134
+ .add(TrustedDeviceApi) {
2135
+ }
2136
+ export class AuthApi extends HttpApi.make("AuthApi")
2137
+ .add(PasswordApi)
2138
+ .add(SessionApi)
2139
+ .add(EmailVerificationApi)
2140
+ .add(EmailOtpApi)
2141
+ .add(MagicLinkApi)
2142
+ .add(LoginApprovalApi)
2143
+ .add(SecurityApi) {
2144
+ }
2145
+ export const PasswordApiLive = HttpApiBuilder.group(AuthApi, "password", Effect.fn("auth.http.password.group")(function* (handlers) {
2146
+ const password = yield* PasswordLogin;
2147
+ const registration = yield* PasswordRegistration;
2148
+ const passwordReset = yield* PasswordReset;
2149
+ const passwordManagement = yield* PasswordManagement;
2150
+ const authHttp = yield* AuthHttp;
2151
+ const emailVerificationFlow = yield* EmailVerificationFlow;
2152
+ const sessions = yield* Sessions;
2153
+ const sessionCookie = yield* SessionCookie;
2154
+ const authApiRateLimit = yield* AuthApiRateLimit;
2155
+ const trustedDeviceCookie = yield* Effect.serviceOption(TrustedDeviceCookie);
2156
+ return handlers
2157
+ .handle("signIn", makePasswordSignInHandler({
2158
+ password,
2159
+ authHttp,
2160
+ emailVerificationFlow,
2161
+ authApiRateLimit,
2162
+ ...(Option.isSome(trustedDeviceCookie)
2163
+ ? { trustedDeviceCookie: trustedDeviceCookie.value }
2164
+ : {}),
2165
+ }))
2166
+ .handle("signUp", makePasswordSignUpHandler({
2167
+ registration,
2168
+ authHttp,
2169
+ emailVerificationFlow,
2170
+ authApiRateLimit,
2171
+ }))
2172
+ .handle("resetStart", makePasswordResetStartHandler({
2173
+ passwordReset,
2174
+ authApiRateLimit,
2175
+ }))
2176
+ .handle("resetVerify", makePasswordResetVerifyHandler({
2177
+ passwordReset,
2178
+ }))
2179
+ .handle("set", makePasswordSetHandler({
2180
+ passwordManagement,
2181
+ sessions,
2182
+ sessionCookie,
2183
+ }))
2184
+ .handle("change", makePasswordChangeHandler({
2185
+ passwordManagement,
2186
+ sessions,
2187
+ sessionCookie,
2188
+ }));
2189
+ }));
2190
+ export const SessionApiLive = HttpApiBuilder.group(AuthApi, "session", Effect.fn("auth.http.session.group")(function* (handlers) {
2191
+ const sessions = yield* Sessions;
2192
+ const sessionCookie = yield* SessionCookie;
2193
+ const authHttp = yield* AuthHttp;
2194
+ return handlers
2195
+ .handle("current", makeCurrentSessionHandler({ sessions, sessionCookie, authHttp }))
2196
+ .handle("refresh", makeRefreshSessionHandler({ sessions, sessionCookie, authHttp }))
2197
+ .handle("logout", makeLogoutHandler({ sessions, sessionCookie, authHttp }))
2198
+ .handle("list", makeListSessionsHandler({ sessions, sessionCookie }))
2199
+ .handle("revoke", makeRevokeSessionHandler({ sessions, sessionCookie, authHttp }))
2200
+ .handle("revokeOthers", makeRevokeOtherSessionsHandler({ sessions, sessionCookie }));
2201
+ }));
2202
+ export const EmailVerificationApiLive = HttpApiBuilder.group(AuthApi, "emailVerification", Effect.fn("auth.http.email_verification.group")(function* (handlers) {
2203
+ const emailVerificationFlow = yield* EmailVerificationFlow;
2204
+ const emailVerification = yield* EmailVerification;
2205
+ const sessions = yield* Sessions;
2206
+ const sessionCookie = yield* SessionCookie;
2207
+ const authApiRateLimit = yield* AuthApiRateLimit;
2208
+ return handlers
2209
+ .handle("start", makeEmailVerificationStartHandler({
2210
+ emailVerificationFlow,
2211
+ authApiRateLimit,
2212
+ }))
2213
+ .handle("verify", makeEmailVerificationVerifyHandler({
2214
+ emailVerification,
2215
+ sessions,
2216
+ sessionCookie,
2217
+ }));
2218
+ }));
2219
+ export const EmailOtpApiLive = HttpApiBuilder.group(AuthApi, "emailOtp", Effect.fn("auth.http.email_otp.group")(function* (handlers) {
2220
+ const emailOtp = yield* EmailOtpLogin;
2221
+ const authHttp = yield* AuthHttp;
2222
+ const authApiRateLimit = yield* AuthApiRateLimit;
2223
+ const trustedDeviceCookie = yield* Effect.serviceOption(TrustedDeviceCookie);
2224
+ return handlers
2225
+ .handle("start", makeEmailOtpStartHandler({ emailOtp, authApiRateLimit }))
2226
+ .handle("verify", makeEmailOtpVerifyHandler({
2227
+ emailOtp,
2228
+ authHttp,
2229
+ ...(Option.isSome(trustedDeviceCookie)
2230
+ ? { trustedDeviceCookie: trustedDeviceCookie.value }
2231
+ : {}),
2232
+ }));
2233
+ }));
2234
+ export const MagicLinkApiLive = HttpApiBuilder.group(AuthApi, "magicLink", Effect.fn("auth.http.magic_link.group")(function* (handlers) {
2235
+ const magicLink = yield* MagicLinkLogin;
2236
+ const authHttp = yield* AuthHttp;
2237
+ const authApiRateLimit = yield* AuthApiRateLimit;
2238
+ const trustedDeviceCookie = yield* Effect.serviceOption(TrustedDeviceCookie);
2239
+ return handlers
2240
+ .handle("start", makeMagicLinkStartHandler({ magicLink, authApiRateLimit }))
2241
+ .handle("verify", makeMagicLinkVerifyHandler({
2242
+ magicLink,
2243
+ authHttp,
2244
+ ...(Option.isSome(trustedDeviceCookie)
2245
+ ? { trustedDeviceCookie: trustedDeviceCookie.value }
2246
+ : {}),
2247
+ }));
2248
+ }));
2249
+ export const LoginApprovalApiLive = HttpApiBuilder.group(AuthApi, "loginApproval", Effect.fn("auth.http.login_approval.group")(function* (handlers) {
2250
+ const loginApproval = yield* LoginApproval;
2251
+ const authFlowState = yield* AuthFlowState;
2252
+ const authFlow = yield* AuthFlow;
2253
+ const users = yield* UserStore;
2254
+ const authHttp = yield* AuthHttp;
2255
+ const loginApprovalReview = yield* Effect.serviceOption(LoginApprovalReview);
2256
+ const loginApprovalFinalize = yield* Effect.serviceOption(LoginApprovalFinalize);
2257
+ const pendingCookieOption = yield* Effect.serviceOption(LoginApprovalPendingCookie);
2258
+ const trustedDevice = yield* Effect.serviceOption(TrustedDevice);
2259
+ const trustedDeviceCookie = yield* Effect.serviceOption(TrustedDeviceCookie);
2260
+ const loginApprovalPendingCookie = Option.isSome(pendingCookieOption)
2261
+ ? pendingCookieOption.value
2262
+ : makeLoginApprovalPendingCookie();
2263
+ return handlers
2264
+ .handle("approve", makeLoginApprovalApproveHandler({
2265
+ loginApproval,
2266
+ authFlowState,
2267
+ authFlow,
2268
+ users,
2269
+ authHttp,
2270
+ loginApprovalPendingCookie,
2271
+ ...(Option.isSome(trustedDevice)
2272
+ ? { trustedDevice: trustedDevice.value }
2273
+ : {}),
2274
+ ...(Option.isSome(trustedDeviceCookie)
2275
+ ? { trustedDeviceCookie: trustedDeviceCookie.value }
2276
+ : {}),
2277
+ }))
2278
+ .handle("status", makeLoginApprovalStatusHandler(Option.isSome(loginApprovalReview)
2279
+ ? { loginApprovalReview: loginApprovalReview.value }
2280
+ : {}))
2281
+ .handle("finalize", makeLoginApprovalFinalizeHandler({
2282
+ authHttp,
2283
+ loginApprovalPendingCookie,
2284
+ ...(Option.isSome(loginApprovalFinalize)
2285
+ ? { loginApprovalFinalize: loginApprovalFinalize.value }
2286
+ : {}),
2287
+ ...(Option.isSome(trustedDevice)
2288
+ ? { trustedDevice: trustedDevice.value }
2289
+ : {}),
2290
+ ...(Option.isSome(trustedDeviceCookie)
2291
+ ? { trustedDeviceCookie: trustedDeviceCookie.value }
2292
+ : {}),
2293
+ }));
2294
+ }));
2295
+ export const SecurityApiLive = HttpApiBuilder.group(AuthApi, "security", Effect.fn("auth.http.security.group")(function* (handlers) {
2296
+ const loginNotification = yield* Effect.serviceOption(LoginNotification);
2297
+ return handlers.handle("reportLogin", makeLoginNotificationReportHandler(Option.isSome(loginNotification)
2298
+ ? { loginNotification: loginNotification.value }
2299
+ : {}));
2300
+ }));
2301
+ export const SecurityTimelineApiLive = HttpApiBuilder.group(SecurityTimelineHttpApi, "securityTimeline", Effect.fn("auth.http.security_timeline.group")(function* (handlers) {
2302
+ const sessions = yield* Sessions;
2303
+ const sessionCookie = yield* SessionCookie;
2304
+ const securityTimeline = yield* SecurityTimelineStore;
2305
+ return handlers.handle("list", makeSecurityTimelineListHandler({
2306
+ sessions,
2307
+ sessionCookie,
2308
+ securityTimeline,
2309
+ }));
2310
+ }));
2311
+ export const SecurityTimelineHttpApiLive = HttpApiBuilder.layer(SecurityTimelineHttpApi).pipe(Layer.provide(SecurityTimelineApiLive), Layer.provide(AuthOriginCheckMiddlewareConfigLive), Layer.provide(AuthSchemaErrorMiddlewareLive));
2312
+ export const TrustedDeviceApiLive = HttpApiBuilder.group(TrustedDeviceHttpApi, "trustedDevice", Effect.fn("auth.http.trusted_device.group")(function* (handlers) {
2313
+ const sessions = yield* Sessions;
2314
+ const sessionCookie = yield* SessionCookie;
2315
+ const trustedDevices = yield* TrustedDeviceStore;
2316
+ return handlers
2317
+ .handle("list", makeTrustedDeviceListHandler({ sessions, sessionCookie, trustedDevices }))
2318
+ .handle("revoke", makeTrustedDeviceRevokeHandler({ sessions, sessionCookie, trustedDevices }));
2319
+ }));
2320
+ export const TrustedDeviceHttpApiLive = HttpApiBuilder.layer(TrustedDeviceHttpApi).pipe(Layer.provide(TrustedDeviceApiLive), Layer.provide(AuthOriginCheckMiddlewareConfigLive), Layer.provide(AuthSchemaErrorMiddlewareLive));
2321
+ const AuthHttpApiBaseLive = HttpApiBuilder.layer(AuthApi).pipe(Layer.provide(PasswordApiLive), Layer.provide(SessionApiLive), Layer.provide(EmailVerificationApiLive), Layer.provide(EmailOtpApiLive), Layer.provide(MagicLinkApiLive), Layer.provide(LoginApprovalApiLive), Layer.provide(SecurityApiLive), Layer.provide(AuthOriginCheckMiddlewareConfigLive), Layer.provide(AuthSchemaErrorMiddlewareLive));
2322
+ export const AuthHttpApiBareLive = AuthHttpApiBaseLive.pipe(Layer.provide(AuthApiRateLimitNoopLive));
2323
+ export const AuthHttpApiLive = AuthHttpApiBaseLive.pipe(Layer.provide(AuthApiRateLimitLive));
2324
+ export { AuthResult };
2325
+ //# sourceMappingURL=Api.js.map