@effect-auth/core 0.1.0-alpha.1 → 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.
- package/README.md +728 -72
- package/dist/ApiKey.d.ts +207 -0
- package/dist/ApiKey.d.ts.map +1 -0
- package/dist/ApiKey.js +275 -0
- package/dist/ApiKey.js.map +1 -0
- package/dist/AuditLog.d.ts +275 -1
- package/dist/AuditLog.d.ts.map +1 -1
- package/dist/AuditLog.js +213 -1
- package/dist/AuditLog.js.map +1 -1
- package/dist/AuthConfig.d.ts +42 -0
- package/dist/AuthConfig.d.ts.map +1 -0
- package/dist/AuthConfig.js +43 -0
- package/dist/AuthConfig.js.map +1 -0
- package/dist/AuthFlow.d.ts +462 -36
- package/dist/AuthFlow.d.ts.map +1 -1
- package/dist/AuthFlow.js +657 -5
- package/dist/AuthFlow.js.map +1 -1
- package/dist/AuthKernel.d.ts +3 -0
- package/dist/AuthKernel.d.ts.map +1 -0
- package/dist/AuthKernel.js +9 -0
- package/dist/AuthKernel.js.map +1 -0
- package/dist/Challenge.d.ts +24 -4
- package/dist/Challenge.d.ts.map +1 -1
- package/dist/Challenge.js +167 -1
- package/dist/Challenge.js.map +1 -1
- package/dist/Client.d.ts +378 -0
- package/dist/Client.d.ts.map +1 -0
- package/dist/Client.js +768 -0
- package/dist/Client.js.map +1 -0
- package/dist/Crypto.d.ts +6 -1
- package/dist/Crypto.d.ts.map +1 -1
- package/dist/Crypto.js +62 -1
- package/dist/Crypto.js.map +1 -1
- package/dist/EffectQbSqliteStorage.d.ts +600 -0
- package/dist/EffectQbSqliteStorage.d.ts.map +1 -0
- package/dist/EffectQbSqliteStorage.js +1637 -0
- package/dist/EffectQbSqliteStorage.js.map +1 -0
- package/dist/EmailOtp.d.ts +120 -0
- package/dist/EmailOtp.d.ts.map +1 -0
- package/dist/EmailOtp.js +286 -0
- package/dist/EmailOtp.js.map +1 -0
- package/dist/EmailVerification.d.ts +121 -0
- package/dist/EmailVerification.d.ts.map +1 -0
- package/dist/EmailVerification.js +200 -0
- package/dist/EmailVerification.js.map +1 -0
- package/dist/HttpApi/Api.d.ts +1956 -0
- package/dist/HttpApi/Api.d.ts.map +1 -0
- package/dist/HttpApi/Api.js +2325 -0
- package/dist/HttpApi/Api.js.map +1 -0
- package/dist/HttpApi/Endpoints.d.ts +945 -0
- package/dist/HttpApi/Endpoints.d.ts.map +1 -0
- package/dist/HttpApi/Endpoints.js +373 -0
- package/dist/HttpApi/Endpoints.js.map +1 -0
- package/dist/HttpApi/Errors.d.ts +82 -0
- package/dist/HttpApi/Errors.d.ts.map +1 -0
- package/dist/HttpApi/Errors.js +184 -0
- package/dist/HttpApi/Errors.js.map +1 -0
- package/dist/HttpApi/Schemas.d.ts +1113 -0
- package/dist/HttpApi/Schemas.d.ts.map +1 -0
- package/dist/HttpApi/Schemas.js +734 -0
- package/dist/HttpApi/Schemas.js.map +1 -0
- package/dist/HttpApi/Security.d.ts +159 -0
- package/dist/HttpApi/Security.d.ts.map +1 -0
- package/dist/HttpApi/Security.js +530 -0
- package/dist/HttpApi/Security.js.map +1 -0
- package/dist/HttpApi/Transport.d.ts +65 -0
- package/dist/HttpApi/Transport.d.ts.map +1 -0
- package/dist/HttpApi/Transport.js +311 -0
- package/dist/HttpApi/Transport.js.map +1 -0
- package/dist/HttpApi/index.d.ts +8 -0
- package/dist/HttpApi/index.d.ts.map +1 -0
- package/dist/HttpApi/index.js +7 -0
- package/dist/HttpApi/index.js.map +1 -0
- package/dist/HttpApi.d.ts +2 -0
- package/dist/HttpApi.d.ts.map +1 -0
- package/dist/HttpApi.js +2 -0
- package/dist/HttpApi.js.map +1 -0
- package/dist/Identifiers.d.ts.map +1 -1
- package/dist/Identifiers.js.map +1 -1
- package/dist/Internal.d.ts +7 -0
- package/dist/Internal.d.ts.map +1 -0
- package/dist/Internal.js +12 -0
- package/dist/Internal.js.map +1 -0
- package/dist/Jwt.d.ts +271 -0
- package/dist/Jwt.d.ts.map +1 -0
- package/dist/Jwt.js +512 -0
- package/dist/Jwt.js.map +1 -0
- package/dist/LoginApproval.d.ts +314 -0
- package/dist/LoginApproval.d.ts.map +1 -0
- package/dist/LoginApproval.js +551 -0
- package/dist/LoginApproval.js.map +1 -0
- package/dist/LoginNotification.d.ts +183 -0
- package/dist/LoginNotification.d.ts.map +1 -0
- package/dist/LoginNotification.js +329 -0
- package/dist/LoginNotification.js.map +1 -0
- package/dist/LoginRisk.d.ts +73 -0
- package/dist/LoginRisk.d.ts.map +1 -0
- package/dist/LoginRisk.js +57 -0
- package/dist/LoginRisk.js.map +1 -0
- package/dist/MagicLink.d.ts +85 -0
- package/dist/MagicLink.d.ts.map +1 -0
- package/dist/MagicLink.js +206 -0
- package/dist/MagicLink.js.map +1 -0
- package/dist/Mailer.d.ts +147 -0
- package/dist/Mailer.d.ts.map +1 -0
- package/dist/Mailer.js +208 -0
- package/dist/Mailer.js.map +1 -0
- package/dist/OAuth.d.ts +934 -0
- package/dist/OAuth.d.ts.map +1 -0
- package/dist/OAuth.js +1661 -0
- package/dist/OAuth.js.map +1 -0
- package/dist/Passkey.d.ts +334 -0
- package/dist/Passkey.d.ts.map +1 -0
- package/dist/Passkey.js +422 -0
- package/dist/Passkey.js.map +1 -0
- package/dist/PasskeySimpleWebAuthn.d.ts +11 -0
- package/dist/PasskeySimpleWebAuthn.d.ts.map +1 -0
- package/dist/PasskeySimpleWebAuthn.js +181 -0
- package/dist/PasskeySimpleWebAuthn.js.map +1 -0
- package/dist/Password.d.ts +237 -0
- package/dist/Password.d.ts.map +1 -0
- package/dist/Password.js +641 -0
- package/dist/Password.js.map +1 -0
- package/dist/Policy.d.ts +7 -4
- package/dist/Policy.d.ts.map +1 -1
- package/dist/Policy.js +28 -5
- package/dist/Policy.js.map +1 -1
- package/dist/Privacy.d.ts +15 -0
- package/dist/Privacy.d.ts.map +1 -1
- package/dist/Privacy.js +58 -1
- package/dist/Privacy.js.map +1 -1
- package/dist/RateLimiter.d.ts +104 -0
- package/dist/RateLimiter.d.ts.map +1 -0
- package/dist/RateLimiter.js +118 -0
- package/dist/RateLimiter.js.map +1 -0
- package/dist/RecoveryCode.d.ts +169 -0
- package/dist/RecoveryCode.d.ts.map +1 -0
- package/dist/RecoveryCode.js +299 -0
- package/dist/RecoveryCode.js.map +1 -0
- package/dist/RefreshToken.d.ts +222 -0
- package/dist/RefreshToken.d.ts.map +1 -0
- package/dist/RefreshToken.js +342 -0
- package/dist/RefreshToken.js.map +1 -0
- package/dist/SecurityTimeline.d.ts +72 -0
- package/dist/SecurityTimeline.d.ts.map +1 -0
- package/dist/SecurityTimeline.js +386 -0
- package/dist/SecurityTimeline.js.map +1 -0
- package/dist/Sessions.d.ts +123 -11
- package/dist/Sessions.d.ts.map +1 -1
- package/dist/Sessions.js +534 -1
- package/dist/Sessions.js.map +1 -1
- package/dist/StepUp.d.ts +44 -0
- package/dist/StepUp.d.ts.map +1 -0
- package/dist/StepUp.js +82 -0
- package/dist/StepUp.js.map +1 -0
- package/dist/Storage.d.ts +73 -5
- package/dist/Storage.d.ts.map +1 -1
- package/dist/Storage.js +11 -1
- package/dist/Storage.js.map +1 -1
- package/dist/StorageMigrations.d.ts +13 -1
- package/dist/StorageMigrations.d.ts.map +1 -1
- package/dist/StorageMigrations.js +256 -2
- package/dist/StorageMigrations.js.map +1 -1
- package/dist/Testing.d.ts +9 -1
- package/dist/Testing.d.ts.map +1 -1
- package/dist/Testing.js +30 -2
- package/dist/Testing.js.map +1 -1
- package/dist/Totp.d.ts +220 -0
- package/dist/Totp.d.ts.map +1 -0
- package/dist/Totp.js +477 -0
- package/dist/Totp.js.map +1 -0
- package/dist/TrustedDevice.d.ts +127 -0
- package/dist/TrustedDevice.d.ts.map +1 -0
- package/dist/TrustedDevice.js +252 -0
- package/dist/TrustedDevice.js.map +1 -0
- package/dist/WaitUntil.d.ts.map +1 -1
- package/dist/WaitUntil.js +1 -1
- package/dist/WaitUntil.js.map +1 -1
- package/dist/Webhook.d.ts +72 -0
- package/dist/Webhook.d.ts.map +1 -0
- package/dist/Webhook.js +82 -0
- package/dist/Webhook.js.map +1 -0
- package/dist/alchemy/cloudflare/Email.d.ts +25 -0
- package/dist/alchemy/cloudflare/Email.d.ts.map +1 -0
- package/dist/alchemy/cloudflare/Email.js +117 -0
- package/dist/alchemy/cloudflare/Email.js.map +1 -0
- package/dist/alchemy/cloudflare/RateLimitDurableObject.d.ts +34 -0
- package/dist/alchemy/cloudflare/RateLimitDurableObject.d.ts.map +1 -0
- package/dist/alchemy/cloudflare/RateLimitDurableObject.js +30 -0
- package/dist/alchemy/cloudflare/RateLimitDurableObject.js.map +1 -0
- package/dist/cloudflare/Email.d.ts +25 -0
- package/dist/cloudflare/Email.d.ts.map +1 -0
- package/dist/cloudflare/Email.js +153 -0
- package/dist/cloudflare/Email.js.map +1 -0
- package/dist/cloudflare/RateLimitDurableObject.d.ts +50 -0
- package/dist/cloudflare/RateLimitDurableObject.d.ts.map +1 -0
- package/dist/cloudflare/RateLimitDurableObject.js +51 -0
- package/dist/cloudflare/RateLimitDurableObject.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -1
- package/dist/internal/RateLimitDurableObject.d.ts +32 -0
- package/dist/internal/RateLimitDurableObject.d.ts.map +1 -0
- package/dist/internal/RateLimitDurableObject.js +80 -0
- package/dist/internal/RateLimitDurableObject.js.map +1 -0
- package/migrations/0002_auth_password.sql +25 -0
- package/migrations/0003_auth_login_approval_review.sql +22 -0
- package/migrations/0004_auth_trusted_device.sql +12 -0
- package/migrations/0005_auth_passkey.sql +17 -0
- package/migrations/0006_auth_totp_factor.sql +17 -0
- package/migrations/0007_auth_recovery_code.sql +13 -0
- package/migrations/0008_auth_api_key.sql +17 -0
- package/migrations/0009_auth_refresh_token.sql +21 -0
- package/migrations/0010_auth_jwt_revocation.sql +8 -0
- package/migrations/0011_auth_oauth_account.sql +16 -0
- package/migrations/0012_auth_oauth_provider_token_vault.sql +20 -0
- package/migrations/0013_auth_security_timeline.sql +16 -0
- package/package.json +146 -26
- package/dist/D1Kysely.d.ts +0 -40
- package/dist/D1Kysely.d.ts.map +0 -1
- package/dist/D1Kysely.js +0 -75
- package/dist/D1Kysely.js.map +0 -1
- package/dist/KyselyStorage.d.ts +0 -41
- package/dist/KyselyStorage.d.ts.map +0 -1
- package/dist/KyselyStorage.js +0 -176
- package/dist/KyselyStorage.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,22 +4,41 @@ Composable Effect-first authentication primitives.
|
|
|
4
4
|
|
|
5
5
|
The current alpha surface is intentionally small: service contracts and small helpers that can be wired with application-owned layers.
|
|
6
6
|
|
|
7
|
+
## HTTP Client
|
|
8
|
+
|
|
9
|
+
`@effect-auth/core/Client` exposes a browser-friendly client generated from the same `AuthApi` contract used by the server. It accepts plain JSON input types, includes cookies by default, and decodes successful/error responses through Effect Schema.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createAuthClient } from "@effect-auth/core/Client";
|
|
13
|
+
|
|
14
|
+
const authClient = createAuthClient();
|
|
15
|
+
|
|
16
|
+
const result = await authClient.password.signIn({
|
|
17
|
+
email: "reader@example.com",
|
|
18
|
+
password: "correct horse battery staple",
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const session = await authClient.session.currentOrUndefined();
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use `@effect-auth/core/HttpApi` when you are wiring the server or need the raw `HttpApi` contract. Use `@effect-auth/core/Client` in application UI code.
|
|
25
|
+
|
|
7
26
|
## Policy
|
|
8
27
|
|
|
9
28
|
`Policy` is an `Effect` used for authorization. Success means access is allowed. `AuthzError` means access is denied. Other failures stay operational errors.
|
|
10
29
|
|
|
11
30
|
```ts
|
|
12
|
-
import { Effect } from "effect"
|
|
13
|
-
import * as Policy from "@effect-auth/core/Policy"
|
|
31
|
+
import { Effect } from "effect";
|
|
32
|
+
import * as Policy from "@effect-auth/core/Policy";
|
|
14
33
|
|
|
15
|
-
const canEditProject = Policy.deny("missing-permission")
|
|
34
|
+
const canEditProject = Policy.deny("missing-permission");
|
|
16
35
|
|
|
17
36
|
const updateProject = Effect.succeed({ updated: true }).pipe(
|
|
18
37
|
Policy.require(canEditProject)
|
|
19
|
-
)
|
|
38
|
+
);
|
|
20
39
|
|
|
21
|
-
const decision = Policy.check(canEditProject)
|
|
22
|
-
const detailed = Policy.checkDetailed(canEditProject)
|
|
40
|
+
const decision = Policy.check(canEditProject);
|
|
41
|
+
const detailed = Policy.checkDetailed(canEditProject);
|
|
23
42
|
```
|
|
24
43
|
|
|
25
44
|
Use `Policy.check` when callers should branch on allowed/denied and let operational errors fail. Use `Policy.checkDetailed` when callers need a value for allowed, denied, or failed.
|
|
@@ -27,117 +46,706 @@ Use `Policy.check` when callers should branch on allowed/denied and let operatio
|
|
|
27
46
|
Policies compose with `all`, `any`, and `not`:
|
|
28
47
|
|
|
29
48
|
```ts
|
|
30
|
-
declare const isProjectOwner: Policy.Policy
|
|
31
|
-
declare const hasUpdateGrant: Policy.Policy
|
|
32
|
-
declare const isSuspended: Policy.Policy
|
|
49
|
+
declare const isProjectOwner: Policy.Policy;
|
|
50
|
+
declare const hasUpdateGrant: Policy.Policy;
|
|
51
|
+
declare const isSuspended: Policy.Policy;
|
|
33
52
|
|
|
34
|
-
const canEditProject = Policy.any(
|
|
35
|
-
isProjectOwner,
|
|
36
|
-
hasUpdateGrant
|
|
37
|
-
)
|
|
53
|
+
const canEditProject = Policy.any(isProjectOwner, hasUpdateGrant);
|
|
38
54
|
|
|
39
55
|
const canEditAndNotSuspended = Policy.all(
|
|
40
56
|
canEditProject,
|
|
41
57
|
Policy.not(isSuspended, "account-disabled")
|
|
42
|
-
)
|
|
58
|
+
);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Step-up gates live in `@effect-auth/core/StepUp` and can be converted to policies when a product action requires stronger or fresher auth:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { Duration } from "effect";
|
|
65
|
+
import * as Policy from "@effect-auth/core/Policy";
|
|
66
|
+
import * as StepUp from "@effect-auth/core/StepUp";
|
|
67
|
+
|
|
68
|
+
const canGenerateApiKey = StepUp.toPolicy({
|
|
69
|
+
aal: "aal2",
|
|
70
|
+
maxAge: Duration.minutes(15),
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const generateApiKey = createApiKey.pipe(Policy.require(canGenerateApiKey));
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Rate Limiter
|
|
77
|
+
|
|
78
|
+
`RateLimiter` is a small auth-oriented wrapper around Effect's persistent rate limiter. It keeps the public auth API focused on policies and safe keys while delegating fixed-window/token-bucket mechanics to `effect/unstable/persistence`.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { Duration, Effect } from "effect";
|
|
82
|
+
import { EmailHash, type IpHash } from "@effect-auth/core/Identifiers";
|
|
83
|
+
import * as RateLimit from "@effect-auth/core/RateLimiter";
|
|
84
|
+
|
|
85
|
+
const PasswordSignInEmailLimit = RateLimit.RateLimitPolicy.fixedWindow({
|
|
86
|
+
id: "auth.password.sign_in.email",
|
|
87
|
+
key: RateLimit.RateLimitKey.emailHash(EmailHash("hmac-email-hash")),
|
|
88
|
+
limit: 5,
|
|
89
|
+
window: Duration.minutes(10),
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const signIn = Effect.gen(function* () {
|
|
93
|
+
yield* RateLimit.require(PasswordSignInEmailLimit);
|
|
94
|
+
|
|
95
|
+
return yield* Effect.succeed({ ok: true });
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`fixedWindowBy` and `tokenBucketBy` accept any safe `RateLimitKey`, including composite keys built from other safe keys:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
declare const ipHash: IpHash;
|
|
103
|
+
declare const emailHash: EmailHash;
|
|
104
|
+
|
|
105
|
+
const PasswordSignInIpEmailLimit = RateLimit.RateLimitPolicy.fixedWindowBy({
|
|
106
|
+
id: "auth.password.sign_in.ip_email",
|
|
107
|
+
by: RateLimit.RateLimitKey.combine(
|
|
108
|
+
"ip-email",
|
|
109
|
+
RateLimit.RateLimitKey.ipHash(ipHash),
|
|
110
|
+
RateLimit.RateLimitKey.emailHash(emailHash)
|
|
111
|
+
),
|
|
112
|
+
limit: 5,
|
|
113
|
+
window: Duration.minutes(10),
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Use `RateLimitKey.emailHash`, `ipHash`, `userAgentHash`, `customHash`, or `combine` with values produced by `Privacy` or another app-owned hashing layer; raw emails, IPs, tokens, and user agents should not be used as store keys. `PrivacyLive({ secret })` provides a production HMAC implementation with conservative input normalization. Use a dedicated secret such as `AUTH_PRIVACY_SECRET`, separate from session and challenge secrets. `RateLimiterMemoryLive` is process-local for tests/dev, and production deployments can provide a persistent Effect `RateLimiterStore` such as Redis or `@effect-auth/core/CloudflareRateLimitDurableObject`.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { Redacted } from "effect";
|
|
121
|
+
import { PrivacyLive } from "@effect-auth/core/Privacy";
|
|
122
|
+
|
|
123
|
+
const AuthPrivacyLive = PrivacyLive({
|
|
124
|
+
secret: Redacted.make(env.AUTH_PRIVACY_SECRET),
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The built-in HTTP auth API includes default IP and email rate limits. Production deployments still provide their own durable `RateLimiter` store and HMAC `Privacy` secret. `AuthServicesLive` below stands for your app-owned auth service wiring.
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
import { Layer, Redacted } from "effect";
|
|
132
|
+
import { RateLimiter as PersistenceRateLimiter } from "effect/unstable/persistence";
|
|
133
|
+
import { AuthHttpApiLive } from "@effect-auth/core/HttpApi";
|
|
134
|
+
import {
|
|
135
|
+
RateLimitStoreDurableObject,
|
|
136
|
+
type CloudflareRateLimitDurableObjectNamespace,
|
|
137
|
+
} from "@effect-auth/core/CloudflareRateLimitDurableObject";
|
|
138
|
+
import { PrivacyLive } from "@effect-auth/core/Privacy";
|
|
139
|
+
import { RateLimiterLive } from "@effect-auth/core/RateLimiter";
|
|
140
|
+
|
|
141
|
+
export const makeAuthHttpApiLayer = (
|
|
142
|
+
namespace: CloudflareRateLimitDurableObjectNamespace,
|
|
143
|
+
privacySecret: string
|
|
144
|
+
) => {
|
|
145
|
+
const DurableObjectRateLimiterLive = RateLimiterLive.pipe(
|
|
146
|
+
Layer.provide(PersistenceRateLimiter.layer),
|
|
147
|
+
Layer.provide(RateLimitStoreDurableObject.layer({ namespace }))
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
return AuthHttpApiLive.pipe(
|
|
151
|
+
Layer.provide(AuthServicesLive),
|
|
152
|
+
Layer.provide(DurableObjectRateLimiterLive),
|
|
153
|
+
Layer.provide(PrivacyLive({ secret: Redacted.make(privacySecret) }))
|
|
154
|
+
);
|
|
155
|
+
};
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
`AuthHttpApiLive` enforces IP limits in HTTP middleware and email limits after schema decoding in the built-in handlers. A single request may consume both a request-level rule and a payload-level rule. `RateLimitPolicy.all(...)` is still available for custom flows and consumes sequentially; put the most specific limits first, such as `ip + email`, then broader limits such as `email`.
|
|
159
|
+
|
|
160
|
+
Advanced apps can replace the `AuthApiRateLimit` service directly. `AuthApiRateLimitMiddlewareLive` delegates request-level checks to that service, so custom policies can still use the built-in endpoint middleware and handler hooks.
|
|
161
|
+
|
|
162
|
+
Use `AuthHttpApiBareLive` only when you explicitly do not want built-in auth rate limits:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { Layer } from "effect";
|
|
166
|
+
import { AuthHttpApiBareLive } from "@effect-auth/core/HttpApi";
|
|
167
|
+
|
|
168
|
+
export const AuthHttpApiLayer = AuthHttpApiBareLive.pipe(
|
|
169
|
+
Layer.provide(AuthServicesLive)
|
|
170
|
+
);
|
|
43
171
|
```
|
|
44
172
|
|
|
45
173
|
## AuthFlow
|
|
46
174
|
|
|
47
|
-
Login methods should verify a factor, then hand the result to `AuthFlow`. `AuthFlow`
|
|
175
|
+
Login methods should verify a factor, then hand the result to `AuthFlow`. `AuthFlow` returns a flat `AuthResult` tagged enum: authenticated, step-up/verification requirements, or successful auth outcomes such as invalid credentials.
|
|
48
176
|
|
|
49
177
|
```ts
|
|
50
|
-
import { Effect } from "effect"
|
|
51
|
-
import { AuthFlow } from "@effect-auth/core/AuthFlow"
|
|
52
|
-
import type { UserId } from "@effect-auth/core/Identifiers"
|
|
178
|
+
import { Effect } from "effect";
|
|
179
|
+
import { AuthFlow } from "@effect-auth/core/AuthFlow";
|
|
180
|
+
import type { UserId } from "@effect-auth/core/Identifiers";
|
|
53
181
|
|
|
54
182
|
export const completePassword = (userId: UserId) =>
|
|
55
183
|
Effect.gen(function* () {
|
|
56
|
-
const authFlow = yield* AuthFlow
|
|
184
|
+
const authFlow = yield* AuthFlow;
|
|
57
185
|
|
|
58
186
|
return yield* authFlow.completePrimaryFactor({
|
|
59
187
|
userId,
|
|
60
188
|
method: "password",
|
|
61
189
|
amr: ["pwd"],
|
|
62
|
-
aal: "aal1"
|
|
63
|
-
})
|
|
64
|
-
})
|
|
190
|
+
aal: "aal1",
|
|
191
|
+
});
|
|
192
|
+
});
|
|
65
193
|
```
|
|
66
194
|
|
|
67
195
|
Service contracts expose small `make` factories for typed layer wiring:
|
|
68
196
|
|
|
69
197
|
```ts
|
|
70
|
-
import { Effect, Layer } from "effect"
|
|
71
|
-
import { AuthFlow,
|
|
198
|
+
import { Effect, Layer } from "effect";
|
|
199
|
+
import { AuthFlow, AuthResult } from "@effect-auth/core/AuthFlow";
|
|
200
|
+
import type { IssuedSession } from "@effect-auth/core/Sessions";
|
|
201
|
+
|
|
202
|
+
declare const issuedSession: IssuedSession;
|
|
72
203
|
|
|
73
204
|
const AuthFlowLive = Layer.succeed(
|
|
74
205
|
AuthFlow,
|
|
75
206
|
AuthFlow.make({
|
|
76
|
-
startPrimaryFactor: () =>
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
207
|
+
startPrimaryFactor: () =>
|
|
208
|
+
Effect.succeed(AuthResult.PolicyDenied({ reason: "test" })),
|
|
209
|
+
completePrimaryFactor: () =>
|
|
210
|
+
Effect.succeed(AuthResult.PolicyDenied({ reason: "test" })),
|
|
211
|
+
completeMfa: () =>
|
|
212
|
+
Effect.succeed(AuthResult.PolicyDenied({ reason: "test" })),
|
|
213
|
+
complete: () =>
|
|
214
|
+
Effect.succeed(AuthResult.Authenticated({ session: issuedSession })),
|
|
80
215
|
})
|
|
81
|
-
)
|
|
216
|
+
);
|
|
82
217
|
```
|
|
83
218
|
|
|
84
219
|
The same pattern is available on core services such as `AuditLog.make`, `Sessions.make`, `SessionCookie.make`, `Challenge.make`, `Crypto.make`, `Privacy.make`, and `WaitUntil.make`.
|
|
85
220
|
|
|
221
|
+
The first default live implementations are available for the phase-3 web session path:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { Layer, Redacted } from "effect";
|
|
225
|
+
import { AuthFlowLive } from "@effect-auth/core/AuthFlow";
|
|
226
|
+
import { ChallengeLive } from "@effect-auth/core/Challenge";
|
|
227
|
+
import { WebCryptoLive } from "@effect-auth/core/Crypto";
|
|
228
|
+
import {
|
|
229
|
+
PasswordLoginLive,
|
|
230
|
+
PasswordRegistrationLive,
|
|
231
|
+
Pbkdf2PasswordHasherLive,
|
|
232
|
+
} from "@effect-auth/core/Password";
|
|
233
|
+
import { SessionCookieLive, SessionsLive } from "@effect-auth/core/Sessions";
|
|
234
|
+
import { EffectQbSqliteAuthStorageLive } from "@effect-auth/core/EffectQbSqliteStorage";
|
|
235
|
+
|
|
236
|
+
const AuthLive = Layer.mergeAll(
|
|
237
|
+
WebCryptoLive(),
|
|
238
|
+
EffectQbSqliteAuthStorageLive(executor),
|
|
239
|
+
Pbkdf2PasswordHasherLive(),
|
|
240
|
+
SessionsLive({ secret: Redacted.make(env.AUTH_SESSION_SECRET) }),
|
|
241
|
+
SessionCookieLive(),
|
|
242
|
+
ChallengeLive({ secret: Redacted.make(env.AUTH_CHALLENGE_SECRET) }),
|
|
243
|
+
AuthFlowLive,
|
|
244
|
+
PasswordLoginLive,
|
|
245
|
+
PasswordRegistrationLive
|
|
246
|
+
);
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
`SessionsLive` stores only `sessionId` plus HMAC secret hash in the database. The browser cookie contains the opaque bearer token in `sessionId.secret` format.
|
|
250
|
+
|
|
251
|
+
## Password
|
|
252
|
+
|
|
253
|
+
`PasswordLogin` verifies a password factor and hands the result to `AuthFlow`. It does not create sessions directly.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import { Effect, Redacted } from "effect";
|
|
257
|
+
import { Email } from "@effect-auth/core/Identifiers";
|
|
258
|
+
import { PasswordLogin } from "@effect-auth/core/Password";
|
|
259
|
+
|
|
260
|
+
export const signIn = Effect.gen(function* () {
|
|
261
|
+
const password = yield* PasswordLogin;
|
|
262
|
+
|
|
263
|
+
return yield* password.signIn({
|
|
264
|
+
email: Email("user@example.com"),
|
|
265
|
+
password: Redacted.make("correct horse battery staple"),
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`PasswordLoginLive` requires `UserStore`, `CredentialStore`, `PasswordHasher`, and `AuthFlow`. Invalid credentials return `AuthResult.InvalidCredentials()`, while storage/hash/session failures stay as typed errors.
|
|
271
|
+
|
|
272
|
+
`PasswordRegistration` creates a user and password credential, then hands the primary password factor to `AuthFlow`.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import { Effect, Redacted } from "effect";
|
|
276
|
+
import { Email } from "@effect-auth/core/Identifiers";
|
|
277
|
+
import { PasswordRegistration } from "@effect-auth/core/Password";
|
|
278
|
+
|
|
279
|
+
export const signUp = Effect.gen(function* () {
|
|
280
|
+
const registration = yield* PasswordRegistration;
|
|
281
|
+
|
|
282
|
+
return yield* registration.signUp({
|
|
283
|
+
email: Email("user@example.com"),
|
|
284
|
+
password: Redacted.make("correct horse battery staple"),
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Duplicate emails fail with `EmailAlreadyRegisteredError`; callers decide whether to expose that as a conflict, a neutral response, or another boundary-specific behavior.
|
|
290
|
+
|
|
291
|
+
`Pbkdf2PasswordHasherLive` is the first reference hasher. It uses Web Crypto PBKDF2-SHA256 and stores hashes as `pbkdf2-sha256$iterations$salt$hash`.
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { Layer } from "effect";
|
|
295
|
+
import { WebCryptoLive } from "@effect-auth/core/Crypto";
|
|
296
|
+
import { Pbkdf2PasswordHasherLive } from "@effect-auth/core/Password";
|
|
297
|
+
|
|
298
|
+
const PasswordHashingLive = Layer.mergeAll(
|
|
299
|
+
WebCryptoLive(),
|
|
300
|
+
Pbkdf2PasswordHasherLive()
|
|
301
|
+
);
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## HTTP API
|
|
305
|
+
|
|
306
|
+
`@effect-auth/core/HttpApi` contains the first Effect v4 HttpApi contract for the built-in auth surface. It exports `AuthApi`, module-owned endpoint groups, and handler layers for the core services.
|
|
307
|
+
|
|
308
|
+
```ts
|
|
309
|
+
import { Layer } from "effect";
|
|
310
|
+
import { HttpRouter } from "effect/unstable/http";
|
|
311
|
+
import { AuthHttpApiLive } from "@effect-auth/core/HttpApi";
|
|
312
|
+
import { PrivacyLive } from "./auth/privacy";
|
|
313
|
+
import { RateLimiterLive } from "./auth/rate-limiter";
|
|
314
|
+
|
|
315
|
+
export const AuthRoutesLive = HttpRouter.serve(
|
|
316
|
+
AuthHttpApiLive.pipe(
|
|
317
|
+
Layer.provide(AuthServicesLive),
|
|
318
|
+
Layer.provide(RateLimiterLive),
|
|
319
|
+
Layer.provide(PrivacyLive)
|
|
320
|
+
)
|
|
321
|
+
);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
The contract currently includes these endpoint groups:
|
|
325
|
+
|
|
326
|
+
| Group | Endpoints |
|
|
327
|
+
| --- | --- |
|
|
328
|
+
| Password | `POST /auth/password/sign-in`, `POST /auth/password/sign-up`, `POST /auth/password/reset/start`, `POST /auth/password/reset/verify`, `POST /auth/password/set`, `POST /auth/password/change`. |
|
|
329
|
+
| Sessions | `GET /auth/session`, `POST /auth/session/refresh`, `POST /auth/logout`, `GET /auth/sessions`, `POST /auth/sessions/revoke`, `POST /auth/sessions/revoke-others`. |
|
|
330
|
+
| Email verification | `POST /auth/email-verification/start`, `POST /auth/email-verification/verify`. |
|
|
331
|
+
| Email OTP | `POST /auth/email-otp/start`, `POST /auth/email-otp/verify`. |
|
|
332
|
+
| Magic link | `POST /auth/magic-link/start`, `POST /auth/magic-link/verify`. |
|
|
333
|
+
| Login approval | `POST /auth/login-approval/approve`, `POST /auth/login-approval/status`, `POST /auth/login-approval/finalize`. |
|
|
334
|
+
| Security | `POST /auth/security/login/report`. |
|
|
335
|
+
|
|
336
|
+
`AuthHttpApiLive` wires the full built-in surface. Apps can own the final HTTP contract and reuse individual endpoints, handlers, or services when a feature needs app-specific payloads or responses.
|
|
337
|
+
|
|
338
|
+
`Authenticated` results set the configured session cookie and never include the opaque session token in JSON bodies. Invalid credentials and disabled accounts map to the same `401 invalid_credentials` response by default. Duplicate password sign-up emails fail as `EmailAlreadyRegisteredError` in the domain layer and map to a `409 email_already_registered` HTTP API error.
|
|
339
|
+
|
|
340
|
+
`SessionApi` reads the configured session cookie and validates it with `Sessions`, returning a safe current-session JSON body or `401 unauthenticated`. Refresh extends the current session when it is eligible, commits the refreshed session cookie, and returns the safe current-session JSON body. Safe authenticated bodies include session claims when present, but never include the opaque session token. Logout revokes the current session when present and clears the session cookie with a `204` response.
|
|
341
|
+
|
|
342
|
+
`AuthHttpApiLive` includes `AuthOriginCheckMiddlewareLive()` for cookie-based unsafe methods and built-in IP/email rate limits for auth abuse control. Origin checks allow same-origin requests, reject cross-origin browser requests with `403 request_rejected`, and allow missing `Origin`/`Referer` headers by default for non-browser clients. Browser-only apps can compose their own `HttpApiBuilder.layer(AuthApi)` and provide `AuthOriginCheckMiddlewareLive({ allowMissingOrigin: false })`.
|
|
343
|
+
|
|
344
|
+
`AuthCsrfMiddlewareLive()` is available for apps that want double-submit CSRF checks on unsafe cookie endpoints. It compares the `__Host-csrf` cookie to the `x-csrf-token` header by default and rejects mismatches with `403 request_rejected`. App-owned HTTP handlers should map core `AuthzError` policy failures to safe `403 policy_denied` responses without exposing policy reasons or internal details.
|
|
345
|
+
|
|
346
|
+
Apps using `AuthCsrfMiddleware` must issue the CSRF token themselves, usually from an app-owned bootstrap endpoint or page render. The token should be high-entropy, set as the `__Host-csrf` cookie, and echoed by browser code in the `x-csrf-token` header on unsafe cookie requests:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
const csrfToken = crypto.randomUUID();
|
|
350
|
+
|
|
351
|
+
return new Response(JSON.stringify({ csrfToken }), {
|
|
352
|
+
headers: {
|
|
353
|
+
"content-type": "application/json",
|
|
354
|
+
"set-cookie": `__Host-csrf=${encodeURIComponent(csrfToken)}; Path=/; Secure; HttpOnly; SameSite=Lax`,
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
await fetch("/auth/session/refresh", {
|
|
359
|
+
method: "POST",
|
|
360
|
+
credentials: "include",
|
|
361
|
+
headers: { "x-csrf-token": csrfToken },
|
|
362
|
+
});
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
`AuthRequestMetadataMiddlewareLive()` can provide method, URL, origin, user-agent, and trusted proxy IP metadata to app-owned handlers. Built-in auth rate limiting is configured in one place with `AuthHttpApiConfigLive(...)`. It applies IP limits in HTTP middleware, then payload-level email limits after schema decoding:
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
import { Duration, Layer } from "effect";
|
|
369
|
+
import {
|
|
370
|
+
AuthHttpApiConfigLive,
|
|
371
|
+
AuthHttpApiLive,
|
|
372
|
+
} from "@effect-auth/core/HttpApi";
|
|
373
|
+
import { PrivacyLive } from "./auth/privacy";
|
|
374
|
+
import { RateLimiterLive } from "./auth/rate-limiter";
|
|
375
|
+
|
|
376
|
+
export const AuthHttpApiLayer = AuthHttpApiLive.pipe(
|
|
377
|
+
Layer.provide(
|
|
378
|
+
AuthHttpApiConfigLive({
|
|
379
|
+
rateLimit: {
|
|
380
|
+
trustProxyHeaders: true,
|
|
381
|
+
passwordSignIn: {
|
|
382
|
+
byIp: { limit: 20, window: Duration.minutes(10) },
|
|
383
|
+
byEmail: { limit: 5, window: Duration.minutes(10) },
|
|
384
|
+
},
|
|
385
|
+
passwordSignUp: {
|
|
386
|
+
byIp: false,
|
|
387
|
+
byEmail: { limit: 3, window: Duration.hours(1) },
|
|
388
|
+
},
|
|
389
|
+
emailVerificationStart: false,
|
|
390
|
+
},
|
|
391
|
+
})
|
|
392
|
+
),
|
|
393
|
+
Layer.provide(AuthServicesLive),
|
|
394
|
+
Layer.provide(RateLimiterLive),
|
|
395
|
+
Layer.provide(PrivacyLive)
|
|
396
|
+
);
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
Using `AuthHttpApiLive` without `AuthHttpApiConfigLive(...)` uses conservative defaults for `passwordSignIn`, `passwordSignUp`, and `emailVerificationStart`. In `rateLimit` config, `true` means default rules, `false` disables that endpoint or rule, omitted values keep defaults, and an object overrides `limit`, `window`, or `tokens`. Use `AuthHttpApiBareLive` to opt out explicitly. `AuthHttpApiLive` never installs a process-local store by itself; production apps still provide a durable `RateLimiter` and `PrivacyLive`.
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
import { AuthHttpApiBareLive } from "@effect-auth/core/HttpApi";
|
|
403
|
+
|
|
404
|
+
export const AuthHttpApiLayer = AuthHttpApiBareLive.pipe(
|
|
405
|
+
Layer.provide(AuthServicesLive)
|
|
406
|
+
);
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
`EmailVerificationApi` exposes `start` and `verify` endpoints. `start` calls `EmailVerificationFlow` to issue and send a verification challenge through the app-owned `EmailDelivery` adapter. `verify` calls `EmailVerification` and returns `204` on success. When the request includes a valid current session cookie for the same user, `verify` also marks that session's claims as email verified and removes the `email_verification` requirement. Error responses are generic and do not include emails, user ids, challenge secrets, or provider details.
|
|
410
|
+
|
|
411
|
+
Password HTTP handlers can start `EmailVerificationFlow` automatically when a custom auth flow returns `RequiresEmailVerification`. The HTTP response remains `requires_email_verification` and does not include the user id, email, challenge secret, or delivery provider details.
|
|
412
|
+
|
|
413
|
+
You can own the final HTTP contract while reusing core endpoints. For example, replace only password sign-up with an app-specific phone payload and keep the default sign-in endpoint:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import { Effect, Schema } from "effect";
|
|
417
|
+
import {
|
|
418
|
+
HttpApi,
|
|
419
|
+
HttpApiBuilder,
|
|
420
|
+
HttpApiEndpoint,
|
|
421
|
+
HttpApiGroup,
|
|
422
|
+
} from "effect/unstable/httpapi";
|
|
423
|
+
import {
|
|
424
|
+
AuthBadRequestError,
|
|
425
|
+
AuthEmailAlreadyRegisteredError,
|
|
426
|
+
AuthHttp,
|
|
427
|
+
AuthInternalError,
|
|
428
|
+
AuthOriginCheckMiddleware,
|
|
429
|
+
AuthPolicyDeniedError,
|
|
430
|
+
AuthRateLimitedError,
|
|
431
|
+
AuthSchemaErrorMiddleware,
|
|
432
|
+
makePasswordSignInHandler,
|
|
433
|
+
passwordSignInEndpoint,
|
|
434
|
+
PasswordAuthSuccess,
|
|
435
|
+
} from "@effect-auth/core/HttpApi";
|
|
436
|
+
import { EmailSchema } from "@effect-auth/core/Identifiers";
|
|
437
|
+
import { PasswordLogin } from "@effect-auth/core/Password";
|
|
438
|
+
|
|
439
|
+
const PhoneNumber = Schema.String.check(Schema.isPattern(/^\+[1-9]\d{7,14}$/));
|
|
440
|
+
|
|
441
|
+
const PhoneSignUpBody = Schema.Struct({
|
|
442
|
+
email: EmailSchema,
|
|
443
|
+
password: Schema.String,
|
|
444
|
+
phone: PhoneNumber,
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
const phoneSignUpEndpoint = HttpApiEndpoint.post("signUp", "/sign-up", {
|
|
448
|
+
payload: PhoneSignUpBody,
|
|
449
|
+
success: PasswordAuthSuccess,
|
|
450
|
+
error: [
|
|
451
|
+
AuthBadRequestError,
|
|
452
|
+
AuthEmailAlreadyRegisteredError,
|
|
453
|
+
AuthPolicyDeniedError,
|
|
454
|
+
AuthRateLimitedError,
|
|
455
|
+
AuthInternalError,
|
|
456
|
+
],
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
class PasswordApi extends HttpApiGroup.make("password")
|
|
460
|
+
.add(passwordSignInEndpoint, phoneSignUpEndpoint)
|
|
461
|
+
.prefix("/auth/password")
|
|
462
|
+
.middleware(AuthSchemaErrorMiddleware)
|
|
463
|
+
.middleware(AuthOriginCheckMiddleware) {}
|
|
464
|
+
|
|
465
|
+
class AppAuthApi extends HttpApi.make("AppAuthApi").add(PasswordApi) {}
|
|
466
|
+
|
|
467
|
+
export const AppPasswordApiLive = HttpApiBuilder.group(
|
|
468
|
+
AppAuthApi,
|
|
469
|
+
"password",
|
|
470
|
+
Effect.fn("app.auth.password.group")(function* (handlers) {
|
|
471
|
+
const password = yield* PasswordLogin;
|
|
472
|
+
const authHttp = yield* AuthHttp;
|
|
473
|
+
|
|
474
|
+
return handlers
|
|
475
|
+
.handle("signIn", makePasswordSignInHandler({ password, authHttp }))
|
|
476
|
+
.handle(
|
|
477
|
+
"signUp",
|
|
478
|
+
Effect.fn("app.auth.password.sign_up")(function* ({ payload }) {
|
|
479
|
+
return yield* signUpWithPhone(payload, authHttp);
|
|
480
|
+
})
|
|
481
|
+
);
|
|
482
|
+
})
|
|
483
|
+
);
|
|
484
|
+
```
|
|
485
|
+
|
|
86
486
|
## Sessions
|
|
87
487
|
|
|
88
488
|
`Sessions` is the server-side session authority. Transports such as cookies are separate services so browser, API, and custom transports can share the same session strategy.
|
|
89
489
|
|
|
90
490
|
```ts
|
|
91
|
-
import { Effect } from "effect"
|
|
92
|
-
import type { UserId } from "@effect-auth/core/Identifiers"
|
|
93
|
-
import { SessionCookie, Sessions } from "@effect-auth/core/Sessions"
|
|
491
|
+
import { Effect } from "effect";
|
|
492
|
+
import type { UserId } from "@effect-auth/core/Identifiers";
|
|
493
|
+
import { SessionCookie, Sessions } from "@effect-auth/core/Sessions";
|
|
94
494
|
|
|
95
495
|
export const createBrowserSession = (userId: UserId) =>
|
|
96
496
|
Effect.gen(function* () {
|
|
97
|
-
const sessions = yield* Sessions
|
|
98
|
-
const sessionCookie = yield* SessionCookie
|
|
497
|
+
const sessions = yield* Sessions;
|
|
498
|
+
const sessionCookie = yield* SessionCookie;
|
|
99
499
|
|
|
100
500
|
const issued = yield* sessions.create({
|
|
101
501
|
userId,
|
|
102
502
|
method: "password",
|
|
103
503
|
amr: ["pwd"],
|
|
104
|
-
aal: "aal1"
|
|
105
|
-
|
|
504
|
+
aal: "aal1",
|
|
505
|
+
claims: {
|
|
506
|
+
emailVerified: false,
|
|
507
|
+
requirements: ["email_verification"],
|
|
508
|
+
},
|
|
509
|
+
});
|
|
106
510
|
|
|
107
|
-
const cookie = yield* sessionCookie.commit(issued)
|
|
511
|
+
const cookie = yield* sessionCookie.commit(issued);
|
|
108
512
|
|
|
109
|
-
return { issued, cookie }
|
|
110
|
-
})
|
|
513
|
+
return { issued, cookie };
|
|
514
|
+
});
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
`SessionClaims` are a safe, transport-visible session summary. They currently include `emailVerified` and `requirements`, and are returned by password auth success, current-session, and refresh HTTP responses when present. Use `Sessions.updateClaims` to update an active session without rotating the opaque session token. Effect-QB storage persists claims in the existing `auth_session.metadata` column, so no additional storage migration is required.
|
|
518
|
+
|
|
519
|
+
Password auth passes the user's email verification state into `AuthFlow`, where `EmailVerificationSessionPolicy` decides whether unverified users get a normal session or a constrained session. The default mode is `allow-unverified` for compatibility. Use `limited-session` to issue sessions with an `email_verification` requirement. Per-login email approval is a separate `UserSecurityPolicy` / `LoginApprovalPolicy` concern, not an email verification session mode.
|
|
520
|
+
|
|
521
|
+
```ts
|
|
522
|
+
import { AuthFlowLiveWithEmailVerificationPolicy } from "@effect-auth/core/AuthFlow";
|
|
523
|
+
|
|
524
|
+
export const AllowUnverifiedAuthFlowLive =
|
|
525
|
+
AuthFlowLiveWithEmailVerificationPolicy({
|
|
526
|
+
mode: "allow-unverified",
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
export const LimitedSessionAuthFlowLive =
|
|
530
|
+
AuthFlowLiveWithEmailVerificationPolicy({
|
|
531
|
+
mode: "limited-session",
|
|
532
|
+
});
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
For `limited-session`, protect sensitive app routes by requiring the current session to be email verified. This policy expects your route middleware to provide `CurrentSession`.
|
|
536
|
+
|
|
537
|
+
```ts
|
|
538
|
+
import { Effect } from "effect";
|
|
539
|
+
import * as Policy from "@effect-auth/core/Policy";
|
|
540
|
+
|
|
541
|
+
export const updateBillingSettings = Effect.gen(function* () {
|
|
542
|
+
return yield* saveBillingSettings();
|
|
543
|
+
}).pipe(Policy.require(Policy.requireEmailVerified()));
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
`LoginApprovalPolicy` is a separate primary-factor decision for high-security sign-in flows. It decides whether a verified primary factor can continue to session creation or should require app-owned login approval. When `AuthFlow` has a `LoginApprovalFlow` and `AuthFlowState`, it stores the pending primary factor, issues a `login-approval` challenge, and returns `AuthResult.RequiresLoginApproval`. The HTTP response is `requires_login_approval` and includes only `flowId`, `approvalChallengeId`, `channel`, `sessionBinding`, `sameDeviceRequired`, and `reason`.
|
|
547
|
+
|
|
548
|
+
The built-in HTTP API completes approval with `POST /auth/login-approval/approve` using `flowId`, `approvalChallengeId`, and an optional challenge `secret`. It verifies the approval, checks the approval belongs to the pending `flowId`, consumes `AuthFlowState`, marks the user email verified when the approval requested it, and creates the session. `sessionBinding: "originating-device"` protects the pending auth flow state with an HttpOnly `__Host-login-approval` cookie secret; approving from another device fails before session creation. `sessionBinding: "approval-device"` creates the session on the device that completes approval. `sessionBinding: "none"` records an approval review but does not create a user session from the approval response; the originating device finalizes later with `LoginApprovalFinalize`.
|
|
549
|
+
|
|
550
|
+
Custom policy code is the primary extension point. Presets such as `mode: "new-device"` are convenience defaults for simple apps; high-security apps should model product-specific risk logic directly in `LoginApprovalPolicy.custom`.
|
|
551
|
+
|
|
552
|
+
```ts
|
|
553
|
+
import { Effect, Layer } from "effect";
|
|
554
|
+
import { AuthFlowStateLive, AuthFlowLive } from "@effect-auth/core/AuthFlow";
|
|
555
|
+
import {
|
|
556
|
+
LoginApprovalDecision,
|
|
557
|
+
LoginApprovalDeliveryFromAuthMailerLive,
|
|
558
|
+
LoginApprovalFlowLive,
|
|
559
|
+
LoginApprovalLive,
|
|
560
|
+
LoginApprovalPolicy,
|
|
561
|
+
LoginApprovalPolicyLive,
|
|
562
|
+
} from "@effect-auth/core/LoginApproval";
|
|
563
|
+
import {
|
|
564
|
+
LoginRiskContext,
|
|
565
|
+
LoginRiskEngine,
|
|
566
|
+
LoginRiskSignal,
|
|
567
|
+
} from "@effect-auth/core/LoginRisk";
|
|
568
|
+
|
|
569
|
+
export const SimpleEmailApprovalPolicyLive = LoginApprovalPolicyLive({
|
|
570
|
+
mode: "new-device",
|
|
571
|
+
channel: "email",
|
|
572
|
+
sessionBinding: "originating-device",
|
|
573
|
+
requireForUnverifiedEmail: true,
|
|
574
|
+
skipMethods: ["passkey"],
|
|
575
|
+
skipWhenAalAtLeast: "aal2",
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
export const RiskBasedApprovalPolicyLive = Layer.succeed(
|
|
579
|
+
LoginApprovalPolicy,
|
|
580
|
+
LoginApprovalPolicy.custom((input) =>
|
|
581
|
+
Effect.succeed(
|
|
582
|
+
input.risk.hasSignal("impossible-travel")
|
|
583
|
+
? LoginApprovalDecision.emailCode({
|
|
584
|
+
reason: "impossible-travel",
|
|
585
|
+
})
|
|
586
|
+
: LoginApprovalDecision.continue()
|
|
587
|
+
)
|
|
588
|
+
)
|
|
589
|
+
);
|
|
590
|
+
|
|
591
|
+
export const AppLoginRiskEngineLive = Layer.succeed(
|
|
592
|
+
LoginRiskEngine,
|
|
593
|
+
LoginRiskEngine.custom((input) =>
|
|
594
|
+
Effect.succeed(
|
|
595
|
+
input.request?.country === "AU"
|
|
596
|
+
? LoginRiskContext.make({
|
|
597
|
+
level: "critical",
|
|
598
|
+
signals: [
|
|
599
|
+
LoginRiskSignal.make({
|
|
600
|
+
type: "impossible-travel",
|
|
601
|
+
level: "critical",
|
|
602
|
+
}),
|
|
603
|
+
],
|
|
604
|
+
})
|
|
605
|
+
: LoginRiskContext.make({ level: "low", signals: [] })
|
|
606
|
+
)
|
|
607
|
+
)
|
|
608
|
+
);
|
|
609
|
+
|
|
610
|
+
export const AppLoginApprovalLive = Layer.mergeAll(
|
|
611
|
+
AppLoginRiskEngineLive,
|
|
612
|
+
AuthFlowStateLive(),
|
|
613
|
+
LoginApprovalLive(),
|
|
614
|
+
LoginApprovalFlowLive,
|
|
615
|
+
LoginApprovalDeliveryFromAuthMailerLive,
|
|
616
|
+
AuthFlowLive
|
|
617
|
+
);
|
|
111
618
|
```
|
|
112
619
|
|
|
620
|
+
The default preset policy is `mode: "never"`. Passkeys or other high-assurance methods can bypass preset approval with `skipMethods` or `skipWhenAalAtLeast`. Approval `channel` and `reason` are open strings, so apps can model `admin`, `sms`, `push`, `manual-review`, or risk-specific reasons without extending core. `LoginApprovalDecision.emailCode`, `emailLink`, `sms`, `adminReview`, and `custom` set semantic `sessionBinding`; `sameDeviceRequired` remains available as the low-level legacy flag. `adminReview` uses `sessionBinding: "none"`, `LoginApprovalReview.approve` / `deny` record the out-of-band decision, and `LoginApprovalFinalize.complete` creates the session only for the originating device. Email is required only for the built-in email delivery path; non-email channels can omit it and use a custom `LoginApprovalDelivery`. `AuthFlow` always supplies policy with typed `device` and `risk`; the default risk engine returns `LoginRiskContext.make({ level: "unknown", signals: [] })`, and apps can provide `LoginRiskEngine` to calculate impossible travel, IP reputation, tenant policy, or other risk signals. `LoginRiskContext` and `LoginRiskSignal` are `Schema.Class` values, so custom engines should return `LoginRiskContext.make(...)`; policies can use helpers such as `input.risk.hasSignal(...)`, `input.risk.getSignal(...)`, and `input.risk.isAtLeast(...)`. `LoginRiskEngine` receives request context only when the primary-factor integration supplies it; core does not trust proxy or geo headers by default.
|
|
621
|
+
|
|
622
|
+
`LoginApproval.inspect` validates a login approval challenge without consuming it. Use it for GET preview pages or admin panels that need to display pending approval details. For admin, push, or Slack approvals, configure `LoginApprovalReview` with a persistent store, let the out-of-band actor call `approve` or `deny`, then have the user's original browser poll review status and call `LoginApprovalFinalize.complete` with its pending-cookie secret. The built-in HTTP API exposes this originating-browser path as `POST /auth/login-approval/status` and `POST /auth/login-approval/finalize`, also available as `client.loginApproval.status(...)` and `client.loginApproval.finalize(...)`. `EffectQbSqliteAuthStorageLive` provides durable `LoginApprovalReviewStore`; the included `LoginApprovalReviewStoreMemoryLive` is for tests and local composition.
|
|
623
|
+
|
|
624
|
+
`AuthFlowState` stores a short-lived, single-use pending primary-factor result in the existing challenge store. It is the bridge between “password/passkey/OTP verified” and “approval/MFA completed, now create a session”. The stored state contains `userId`, `method`, `amr`, `aal`, optional session claims, and app metadata such as `redirectTo`.
|
|
625
|
+
|
|
626
|
+
```ts
|
|
627
|
+
import { AuthFlowStateLive } from "@effect-auth/core/AuthFlow";
|
|
628
|
+
|
|
629
|
+
export const AppAuthFlowStateLive = AuthFlowStateLive();
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
## Trusted Devices
|
|
633
|
+
|
|
634
|
+
`TrustedDevice` is a small boundary for “remember this device” login policy. It stores only an HMAC hash of an opaque device token and returns `LoginDeviceContext` as `unknown`, `new`, or `known`. `LoginApprovalPolicy({ mode: "new-device" })` can use that context to require approval only for first-time devices.
|
|
635
|
+
|
|
636
|
+
```ts
|
|
637
|
+
import { Layer, Redacted } from "effect";
|
|
638
|
+
import {
|
|
639
|
+
TrustedDeviceCookieLive,
|
|
640
|
+
TrustedDeviceLive,
|
|
641
|
+
TrustedDeviceStoreMemoryLive,
|
|
642
|
+
} from "@effect-auth/core/TrustedDevice";
|
|
643
|
+
|
|
644
|
+
export const AppTrustedDeviceLive = Layer.mergeAll(
|
|
645
|
+
TrustedDeviceStoreMemoryLive,
|
|
646
|
+
TrustedDeviceLive({ secret: Redacted.make("trusted-device-secret") }),
|
|
647
|
+
TrustedDeviceCookieLive()
|
|
648
|
+
);
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
The built-in password sign-in, email OTP verify, and magic-link verify HTTP handlers read the HttpOnly `__Host-auth-device` cookie when `TrustedDeviceCookie` is provided and pass the trusted-device token into `AuthFlow`; `AuthFlow` resolves the device status centrally with `TrustedDevice`. `POST /auth/login-approval/approve` accepts `rememberDevice: true`; when `TrustedDevice` and `TrustedDeviceCookie` are provided it trusts the approved user/device and sets `__Host-auth-device` with the final session response. `EffectQbSqliteAuthStorageLive` provides durable `TrustedDeviceStore`; the in-memory store is intended for tests and local composition.
|
|
652
|
+
|
|
113
653
|
## Challenge
|
|
114
654
|
|
|
115
655
|
`Challenge` is the shared primitive for short-lived proofs: email OTP, magic link, passkey challenges, OAuth state, reset password, and MFA.
|
|
116
656
|
|
|
117
657
|
```ts
|
|
118
|
-
import { Duration, Effect, Redacted } from "effect"
|
|
119
|
-
import { Challenge } from "@effect-auth/core/Challenge"
|
|
658
|
+
import { Duration, Effect, Redacted } from "effect";
|
|
659
|
+
import { Challenge } from "@effect-auth/core/Challenge";
|
|
120
660
|
|
|
121
661
|
export const issueEmailOtp = (email: string, code: string) =>
|
|
122
662
|
Effect.gen(function* () {
|
|
123
|
-
const challenge = yield* Challenge
|
|
663
|
+
const challenge = yield* Challenge;
|
|
124
664
|
|
|
125
665
|
return yield* challenge.issue({
|
|
126
666
|
type: "email-otp",
|
|
127
667
|
subject: email,
|
|
128
668
|
ttl: Duration.minutes(10),
|
|
129
|
-
secret: Redacted.make(code)
|
|
130
|
-
})
|
|
131
|
-
})
|
|
669
|
+
secret: Redacted.make(code),
|
|
670
|
+
});
|
|
671
|
+
});
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
## Email Verification
|
|
675
|
+
|
|
676
|
+
`EmailVerification` composes `Challenge` with `UserStore.markEmailVerified`. It issues an `email-verification` challenge for an unverified user email, then verifies the challenge and marks the user email as verified. `EmailVerificationFlow` adds the app-owned `EmailDelivery` port so issuing and sending happen together without baking a mail provider into core.
|
|
677
|
+
|
|
678
|
+
```ts
|
|
679
|
+
import { Effect, Redacted } from "effect";
|
|
680
|
+
import {
|
|
681
|
+
EmailDelivery,
|
|
682
|
+
EmailVerification,
|
|
683
|
+
EmailVerificationFlow,
|
|
684
|
+
} from "@effect-auth/core/EmailVerification";
|
|
685
|
+
import type { ChallengeId, Email, UserId } from "@effect-auth/core/Identifiers";
|
|
686
|
+
|
|
687
|
+
const emailDelivery = EmailDelivery.make({
|
|
688
|
+
sendEmailVerification: ({ email, secret, challengeId }) =>
|
|
689
|
+
sendMail({
|
|
690
|
+
to: email,
|
|
691
|
+
subject: "Verify your email",
|
|
692
|
+
body:
|
|
693
|
+
secret === undefined
|
|
694
|
+
? `Open /verify-email?challenge=${challengeId}`
|
|
695
|
+
: `Your verification code is ${Redacted.value(secret)}`,
|
|
696
|
+
}),
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
export const startEmailVerification = (
|
|
700
|
+
userId: UserId,
|
|
701
|
+
email: Email,
|
|
702
|
+
code: string
|
|
703
|
+
) =>
|
|
704
|
+
Effect.gen(function* () {
|
|
705
|
+
const flow = yield* EmailVerificationFlow;
|
|
706
|
+
|
|
707
|
+
return yield* flow.start({
|
|
708
|
+
userId,
|
|
709
|
+
email,
|
|
710
|
+
secret: Redacted.make(code),
|
|
711
|
+
});
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
export const verifyEmail = (challengeId: ChallengeId, code: string) =>
|
|
715
|
+
Effect.gen(function* () {
|
|
716
|
+
const emailVerification = yield* EmailVerification;
|
|
717
|
+
|
|
718
|
+
return yield* emailVerification.verify({
|
|
719
|
+
challengeId,
|
|
720
|
+
secret: Redacted.make(code),
|
|
721
|
+
});
|
|
722
|
+
});
|
|
132
723
|
```
|
|
133
724
|
|
|
134
725
|
## Storage
|
|
135
726
|
|
|
136
|
-
Storage is exposed as ORM-free ports. Core flows depend on store services, while
|
|
727
|
+
Storage is exposed as ORM-free ports. Core flows depend on store services, while Effect-QB, future Drizzle, or app-owned adapters provide the implementations.
|
|
137
728
|
|
|
138
729
|
```ts
|
|
139
|
-
import { Effect, Option } from "effect"
|
|
140
|
-
import {
|
|
730
|
+
import { Effect, Option } from "effect";
|
|
731
|
+
import {
|
|
732
|
+
CredentialStore,
|
|
733
|
+
SessionStore,
|
|
734
|
+
UserStore,
|
|
735
|
+
VerificationStore,
|
|
736
|
+
} from "@effect-auth/core/Storage";
|
|
737
|
+
|
|
738
|
+
const UserStoreLive = UserStore.make({
|
|
739
|
+
findById: () => Effect.succeed(Option.none()),
|
|
740
|
+
findByEmail: () => Effect.succeed(Option.none()),
|
|
741
|
+
insert: () => Effect.void,
|
|
742
|
+
markEmailVerified: () => Effect.succeed(Option.none()),
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
const CredentialStoreLive = CredentialStore.make({
|
|
746
|
+
findPasswordByUserId: () => Effect.succeed(Option.none()),
|
|
747
|
+
insertPassword: () => Effect.void,
|
|
748
|
+
});
|
|
141
749
|
|
|
142
750
|
const SessionStoreLive = SessionStore.make({
|
|
143
751
|
findById: () => Effect.succeed(Option.none()),
|
|
@@ -145,51 +753,99 @@ const SessionStoreLive = SessionStore.make({
|
|
|
145
753
|
refresh: () => Effect.succeed(Option.none()),
|
|
146
754
|
rotate: () => Effect.succeed(Option.none()),
|
|
147
755
|
revoke: () => Effect.void,
|
|
148
|
-
revokeAllForUser: () => Effect.void
|
|
149
|
-
})
|
|
756
|
+
revokeAllForUser: () => Effect.void,
|
|
757
|
+
});
|
|
150
758
|
|
|
151
759
|
const VerificationStoreLive = VerificationStore.make({
|
|
152
760
|
findById: () => Effect.succeed(Option.none()),
|
|
153
761
|
insert: () => Effect.void,
|
|
154
762
|
consume: () => Effect.succeed(Option.none()),
|
|
155
|
-
deleteExpired: () => Effect.succeed(0)
|
|
156
|
-
})
|
|
763
|
+
deleteExpired: () => Effect.succeed(0),
|
|
764
|
+
});
|
|
157
765
|
```
|
|
158
766
|
|
|
159
|
-
The
|
|
767
|
+
The default schema is exported as SQL and as package assets:
|
|
160
768
|
|
|
161
769
|
```ts
|
|
162
|
-
import {
|
|
163
|
-
|
|
164
|
-
const { sessionStore, verificationStore } = makeKyselyStorage(db)
|
|
770
|
+
import { authStorageMigrations } from "@effect-auth/core/StorageMigrations";
|
|
165
771
|
```
|
|
166
772
|
|
|
167
|
-
|
|
773
|
+
Effect-QB SQLite/D1 storage is the first-party durable adapter. The default path uses the auth schema and requires no table mapping:
|
|
168
774
|
|
|
169
775
|
```ts
|
|
170
|
-
import {
|
|
171
|
-
import { KyselyAuthStorageLive, type KyselyAuthDatabase } from "@effect-auth/core/KyselyStorage"
|
|
776
|
+
import { EffectQbSqliteAuthStorageLive } from "@effect-auth/core/EffectQbSqliteStorage";
|
|
172
777
|
|
|
173
|
-
|
|
174
|
-
// app tables live here too
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
const db = makeD1Kysely<DB>(env.DB)
|
|
178
|
-
const StorageLive = KyselyAuthStorageLive(db)
|
|
778
|
+
const StorageLive = EffectQbSqliteAuthStorageLive(executor);
|
|
179
779
|
```
|
|
180
780
|
|
|
181
|
-
|
|
781
|
+
`EffectQbSqliteAuthStorageLive` provides all durable auth stores in the default schema, including the OAuth provider-token vault for already-encrypted provider token ciphertexts. Apps still own provider-token encryption and KMS/secrets-service policy before values reach storage.
|
|
782
|
+
|
|
783
|
+
For Cloudflare D1, create an effect-qb SQLite executor from the D1 binding:
|
|
182
784
|
|
|
183
785
|
```ts
|
|
184
|
-
import
|
|
786
|
+
import {
|
|
787
|
+
EffectQbSqliteAuthStorageLive,
|
|
788
|
+
makeD1EffectQbSqliteExecutor,
|
|
789
|
+
} from "@effect-auth/core/EffectQbSqliteStorage";
|
|
185
790
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
}
|
|
791
|
+
const executor = makeD1EffectQbSqliteExecutor(env.DB);
|
|
792
|
+
const StorageLive = EffectQbSqliteAuthStorageLive(executor);
|
|
189
793
|
```
|
|
190
794
|
|
|
191
|
-
|
|
795
|
+
Applications with their own Effect-QB tables can map semantic auth fields to app-owned columns with `defineEffectQbAuthTables`:
|
|
192
796
|
|
|
193
797
|
```ts
|
|
194
|
-
import {
|
|
798
|
+
import { Column, Query, Table } from "effect-qb/sqlite";
|
|
799
|
+
import {
|
|
800
|
+
defineEffectQbAuthTables,
|
|
801
|
+
EffectQbSqliteAuthStorageLive,
|
|
802
|
+
} from "@effect-auth/core/EffectQbSqliteStorage";
|
|
803
|
+
|
|
804
|
+
const users = Table.make("users", {
|
|
805
|
+
user_id: Column.text().pipe(Column.primaryKey),
|
|
806
|
+
email_address: Column.text(),
|
|
807
|
+
verified_at: Column.int().pipe(Column.nullable),
|
|
808
|
+
inserted_at: Column.int(),
|
|
809
|
+
updated_at: Column.int(),
|
|
810
|
+
disabled_at: Column.int().pipe(Column.nullable),
|
|
811
|
+
metadata_json: Column.text().pipe(Column.nullable),
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
const authTables = defineEffectQbAuthTables({
|
|
815
|
+
user: {
|
|
816
|
+
table: users,
|
|
817
|
+
select: {
|
|
818
|
+
id: users.user_id,
|
|
819
|
+
email: users.email_address,
|
|
820
|
+
emailVerified: users.verified_at,
|
|
821
|
+
createdAt: users.inserted_at,
|
|
822
|
+
updatedAt: users.updated_at,
|
|
823
|
+
disabledAt: users.disabled_at,
|
|
824
|
+
metadata: users.metadata_json,
|
|
825
|
+
},
|
|
826
|
+
insert: (row) =>
|
|
827
|
+
({
|
|
828
|
+
user_id: row.id,
|
|
829
|
+
email_address: row.email,
|
|
830
|
+
verified_at: row.emailVerified ? Number(row.updatedAt) : null,
|
|
831
|
+
inserted_at: Number(row.createdAt),
|
|
832
|
+
updated_at: Number(row.updatedAt),
|
|
833
|
+
disabled_at:
|
|
834
|
+
row.disabledAt === undefined ? null : Number(row.disabledAt),
|
|
835
|
+
metadata_json:
|
|
836
|
+
row.metadata === undefined ? null : JSON.stringify(row.metadata),
|
|
837
|
+
}) satisfies Query.MutationInputOf<Table.InsertOf<typeof users>>,
|
|
838
|
+
markEmailVerified: (input) =>
|
|
839
|
+
({
|
|
840
|
+
verified_at: Number(input.updatedAt),
|
|
841
|
+
updated_at: Number(input.updatedAt),
|
|
842
|
+
}) satisfies Query.MutationInputOf<Table.UpdateOf<typeof users>>,
|
|
843
|
+
},
|
|
844
|
+
|
|
845
|
+
// credential/session/verification/review/trusted-device/passkey/TOTP/recovery-code/API-key/refresh-token/OAuth-account/provider-token-vault mappings follow the same pattern.
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
const StorageLive = EffectQbSqliteAuthStorageLive(executor, {
|
|
849
|
+
tables: authTables,
|
|
850
|
+
});
|
|
195
851
|
```
|