@krak-stack/auth 0.2.23 → 0.2.25
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/CHANGELOG.md +24 -0
- package/README.md +58 -0
- package/dist/components/auth-forms.js +58 -31
- package/dist/components/email-otp-state.d.ts +11 -0
- package/dist/components/email-otp-state.js +25 -0
- package/dist/server/actor.js +9 -10
- package/dist/server/attribution.d.ts +3 -0
- package/dist/server/attribution.js +28 -0
- package/dist/server/index.d.ts +1 -1
- package/dist/server/middleware.d.ts +7 -1
- package/dist/server/middleware.js +67 -28
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# @krak-stack/auth
|
|
2
2
|
|
|
3
|
+
## 0.2.25
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Require `@krak-stack/registry` version `^0.1.52` for the coordinated audit attribution and telemetry integration.
|
|
8
|
+
|
|
9
|
+
- Actor authorization adds standard `user.roles` from the current organization membership for historical audit snapshots, without confusing global roles or organization API keys with human members. Auth emits IDs and roles only, not names/photos. Clear inherited profile/role annotations alongside other auth attribution. Audit display names/photos are resolved dynamically from current organization membership.
|
|
10
|
+
|
|
11
|
+
Separate the responsible principal (`app.actor.type/id`, user or organization) from authentication (`app.auth.method`, session or api_key) and API-key record identity (`app.auth.credential.id`). Replace inherited authentication annotations together with actor annotations; never emit credentials or session tokens.
|
|
12
|
+
|
|
13
|
+
Emit `app.auth.impersonator.id` from a verified session's `impersonatedBy`, preserving the effective user's actor ID. Keep organization impersonation route restrictions unchanged and clear stale impersonator annotations for ordinary or anonymous requests.
|
|
14
|
+
|
|
15
|
+
- 32213bb: Add verified actor type/ID and API-key owner type/ID to AuthMiddleware log and span annotations, preserving existing user and organization attribution. Distinguish API-key principals from their owners without emitting credentials or changing the authentication model. This enables audit recording through inherited telemetry context; MCP and AI context remain integration-owned.
|
|
16
|
+
|
|
17
|
+
Replace the complete auth-owned annotation set so organization keys cannot inherit stale user IDs and users cannot inherit API-key owners. Preserve unrelated annotations and restore scoped log/child-span context after the handler. Clear stale fields on the already-created current span using empty strings because the tracer interface does not expose attribute removal.
|
|
18
|
+
|
|
19
|
+
Provide the same optional authentication and attribution for plain HttpRouter routes through AuthMiddleware.routerLayer, with optional exact-path scoping. Anonymous requests clear inherited attribution; auth service failures remain explicit. ActorRequired continues to own project authorization and CurrentActor without reconstructing telemetry attribution.
|
|
20
|
+
|
|
21
|
+
## 0.2.24
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Improve the sign-in flow by moving email-code/password switching into the alternative options below the primary action. Replace the inline email-change link with a Back control so users can return to the initial screen and choose Google. Persist successful code-send timestamps in local storage to preserve the resend cooldown across method switches and reloads, and reuse unexpired codes instead of sending duplicate emails when switching back to email code.
|
|
26
|
+
|
|
3
27
|
## 0.2.23
|
|
4
28
|
|
|
5
29
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -57,6 +57,34 @@ const program = Effect.gen(function* () {
|
|
|
57
57
|
|
|
58
58
|
Use `AuthMiddleware.layer()` to provide request headers and configuration in an Effect HttpApi application. See the [middleware guide](https://auth.krakstack.net/en/docs/middleware).
|
|
59
59
|
|
|
60
|
+
`AuthMiddleware` also annotates request logs and spans with verified user,
|
|
61
|
+
organization, and actor IDs using its existing session lookup. Missing sessions
|
|
62
|
+
are anonymous; auth service failures are not silently treated as anonymous.
|
|
63
|
+
`ActorRequired` remains responsible for project authorization and `CurrentActor`.
|
|
64
|
+
|
|
65
|
+
For plain `HttpRouter` routes, use the same authentication through
|
|
66
|
+
`AuthMiddleware.routerLayer()`. For example, browser Events ingestion can inherit
|
|
67
|
+
verified identity without an `Events.layer({ identity })` callback:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { AuthMiddleware } from "@krak-stack/auth/server";
|
|
71
|
+
import { HttpApiOtlp } from "@krak-stack/registry/opentelemetry/api";
|
|
72
|
+
import { Events } from "@krak-stack/registry/events";
|
|
73
|
+
import { Layer } from "effect";
|
|
74
|
+
|
|
75
|
+
const telemetry = HttpApiOtlp.layer.pipe(
|
|
76
|
+
Layer.provide(AuthMiddleware.routerLayer({ paths: ["/api/otel/v1/logs"] })),
|
|
77
|
+
Layer.provide(Events.ingestionLayer),
|
|
78
|
+
Layer.provide(eventsLayer),
|
|
79
|
+
);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Here `eventsLayer` is the configured Events layer, with SQL provided when
|
|
83
|
+
persistence is needed. `paths` limits auth lookup to the listed URL pathnames;
|
|
84
|
+
without it, the middleware covers every route it is provided to. The router
|
|
85
|
+
adapter uses the same auth configuration and organization-impersonation policy
|
|
86
|
+
as `AuthMiddleware.layer()`. It does not grant permissions or provide `CurrentActor`.
|
|
87
|
+
|
|
60
88
|
## React Components
|
|
61
89
|
|
|
62
90
|
The component bundle uses the optional peer dependencies declared in `package.json` and Krakstack/shadcn UI primitives from `@krak-stack/registry`. Install the component peers used by your application; server-only consumers only need `effect`.
|
|
@@ -92,4 +120,34 @@ See [React components and CSS](https://auth.krakstack.net/en/docs/components) fo
|
|
|
92
120
|
|
|
93
121
|
Define project permissions with `defineProjectAccess`, resolve actors with `ActorRequired`, and enforce backend policies with `withPolicy`. Frontend permission helpers control presentation only.
|
|
94
122
|
|
|
123
|
+
`AuthMiddleware` annotates the current span, child spans and handler logs with verified attribution:
|
|
124
|
+
|
|
125
|
+
| Attribute | User session | User-owned API key | Organization-owned API key |
|
|
126
|
+
| -------------------------- | -------------------------------------- | -------------------------- | -------------------------- |
|
|
127
|
+
| `app.actor.type` | `user` | `user` | `organization` |
|
|
128
|
+
| `app.actor.id` | User ID | Owner user ID | Owner organization ID |
|
|
129
|
+
| `app.auth.method` | `session` | `api_key` | `api_key` |
|
|
130
|
+
| `app.auth.credential.id` | Omitted | API-key record ID | API-key record ID |
|
|
131
|
+
| `app.auth.impersonator.id` | Initiating admin ID when impersonating | Omitted | Omitted |
|
|
132
|
+
| `user.id` | User ID | Owner user ID | Omitted |
|
|
133
|
+
| `user.roles` | Organization roles | Owner's organization roles | Empty array |
|
|
134
|
+
| `organization.id` | Active organization ID | Active organization ID | Owner organization ID |
|
|
135
|
+
|
|
136
|
+
`user.id` and `user.roles` follow OpenTelemetry user semantic conventions. Roles are added by `ActorRequired`, not session-only router middleware. Names, photos, email addresses, API-key values, and session tokens are not emitted. OTel defines `user.name` as login/username and `user.full_name` as full name; neither is needed for attribution here. The `app.actor.*`, `app.auth.*` and existing `organization.id` fields are application conventions. The public authorization model still uses `type: "apiKey"`, but telemetry identifies its owning user or organization as the responsible principal and records the key separately as a credential. This replaces the previous `app.actor.owner.*` fields and API-key actor IDs; telemetry consumers must migrate together with the SDK. Audit consumers resolve current names/photos from organization membership for display, rather than copying them into logs. MCP and AI execution context belongs to the respective integration layers and does not replace the authenticated actor.
|
|
137
|
+
|
|
138
|
+
Auth-owned user, organization and actor annotations replace the inherited set,
|
|
139
|
+
preventing stale user/API-key owner attribution. Unrelated request, MCP and agent
|
|
140
|
+
context is preserved, and scoped log/child-span context is restored afterward.
|
|
141
|
+
Stale fields on an already-created current span are cleared to empty strings
|
|
142
|
+
because the tracer interface has no attribute-removal method; handler logs and
|
|
143
|
+
new child spans omit those fields entirely.
|
|
144
|
+
|
|
145
|
+
`ActorRequired` resolves the project actor, enforces actor constraints, and provides
|
|
146
|
+
`CurrentActor`. It adds `user.roles` to logs and spans from the verified active
|
|
147
|
+
organization membership, not the global user role. Events recorded in the handler
|
|
148
|
+
retain that role snapshot even after membership changes. Session-only router
|
|
149
|
+
middleware does not look up roles. When supplying `AuthService` directly without
|
|
150
|
+
`AuthMiddleware`, only the verified roles are added; session profile/actor
|
|
151
|
+
attribution still requires `AuthMiddleware`.
|
|
152
|
+
|
|
95
153
|
See the [RBAC guide](https://auth.krakstack.net/en/docs/rbac).
|
|
@@ -6,7 +6,7 @@ import { Effect, Option, Schema } from "effect";
|
|
|
6
6
|
import { Atom, AsyncResult } from "effect/reactivity";
|
|
7
7
|
import { HttpClientError } from "effect/http";
|
|
8
8
|
import { REGEXP_ONLY_DIGITS } from "input-otp";
|
|
9
|
-
import { KeyRound, Loader2, Mail } from "lucide-react";
|
|
9
|
+
import { ArrowLeft, KeyRound, Loader2, Mail } from "lucide-react";
|
|
10
10
|
import { useEffect, useRef, useState } from "react";
|
|
11
11
|
import { Button, buttonVariants } from "@/components/ui/button";
|
|
12
12
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card";
|
|
@@ -16,13 +16,13 @@ import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, } from "@/com
|
|
|
16
16
|
import { getLastUsedLoginMethod, notifyAuthChange } from "./auth-atoms.js";
|
|
17
17
|
import { authClientApi, authHttpClient } from "./auth-client-api.js";
|
|
18
18
|
import { PasswordField } from "./password-field.js";
|
|
19
|
+
import { emailOtpSendsAtom, emailOtpSendState, EMAIL_OTP_RESEND_COOLDOWN_SECONDS, } from "./email-otp-state.js";
|
|
19
20
|
import { passwordResetSearch, passwordResetConfirmation, passwordResetConfirmationSearch, passwordResetCallbackUrl, requestPasswordResetEmail, resetPasswordAndSignOut, } from "./password-reset.js";
|
|
20
21
|
import { PasswordResetActions, PasswordResetFeedback, usePasswordResetRequest, } from "./password-reset-flow.js";
|
|
21
22
|
import { useKrakstackAuth } from "./auth-provider.js";
|
|
22
23
|
import { cn } from "./utils.js";
|
|
23
24
|
import { ExtraProjectPublicConfig as ExtraProjectPublicConfigSchema, } from "../extra/schema.js";
|
|
24
25
|
import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, AuthRedirectURLFromString, } from "../auth/schema.js";
|
|
25
|
-
const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
|
|
26
26
|
const signinFormBuilder = FormBuilder.empty
|
|
27
27
|
.addField("email", Schema.String)
|
|
28
28
|
.addField("password", Schema.String)
|
|
@@ -38,7 +38,7 @@ const twoFactorFormBuilder = FormBuilder.empty
|
|
|
38
38
|
const defaultMessages = {
|
|
39
39
|
en: {
|
|
40
40
|
auth_continue_with_google: "Continue with Google",
|
|
41
|
-
auth_or_continue_with: "
|
|
41
|
+
auth_or_continue_with: "Or",
|
|
42
42
|
auth_sign_in: "Sign in",
|
|
43
43
|
field_email: "Email",
|
|
44
44
|
field_password: "Password",
|
|
@@ -63,7 +63,7 @@ const defaultMessages = {
|
|
|
63
63
|
reset_password_missing_token: "The password reset link is missing a token.",
|
|
64
64
|
reset_password_new_password: "New password",
|
|
65
65
|
reset_password_title: "Choose a new password",
|
|
66
|
-
sign_in_change_email: "
|
|
66
|
+
sign_in_change_email: "Back",
|
|
67
67
|
sign_in_continue: "Continue",
|
|
68
68
|
sign_in_description: "Enter your email to continue.",
|
|
69
69
|
sign_in_email_as: "Signing in as {email}",
|
|
@@ -78,8 +78,8 @@ const defaultMessages = {
|
|
|
78
78
|
sign_in_invalid_credentials: "The email or password is incorrect.",
|
|
79
79
|
auth_invalid_code: "The code is invalid or has expired.",
|
|
80
80
|
sign_in_forgot_password: "Forgot your password?",
|
|
81
|
-
sign_in_use_email_otp: "Use email code
|
|
82
|
-
sign_in_use_password: "Use
|
|
81
|
+
sign_in_use_email_otp: "Use email code",
|
|
82
|
+
sign_in_use_password: "Use password",
|
|
83
83
|
two_factor_backup_code: "Backup code",
|
|
84
84
|
two_factor_code: "Authentication code",
|
|
85
85
|
two_factor_email_code: "Email verification code",
|
|
@@ -104,7 +104,7 @@ const defaultMessages = {
|
|
|
104
104
|
},
|
|
105
105
|
fr: {
|
|
106
106
|
auth_continue_with_google: "Continuer avec Google",
|
|
107
|
-
auth_or_continue_with: "
|
|
107
|
+
auth_or_continue_with: "Ou",
|
|
108
108
|
auth_sign_in: "Se connecter",
|
|
109
109
|
field_email: "Courriel",
|
|
110
110
|
field_password: "Mot de passe",
|
|
@@ -129,7 +129,7 @@ const defaultMessages = {
|
|
|
129
129
|
reset_password_missing_token: "Le lien de réinitialisation du mot de passe ne contient pas de jeton.",
|
|
130
130
|
reset_password_new_password: "Nouveau mot de passe",
|
|
131
131
|
reset_password_title: "Choisir un nouveau mot de passe",
|
|
132
|
-
sign_in_change_email: "
|
|
132
|
+
sign_in_change_email: "Retour",
|
|
133
133
|
sign_in_continue: "Continuer",
|
|
134
134
|
sign_in_description: "Saisissez votre courriel pour continuer.",
|
|
135
135
|
sign_in_email_as: "Connexion avec {email}",
|
|
@@ -145,7 +145,7 @@ const defaultMessages = {
|
|
|
145
145
|
auth_invalid_code: "Le code est invalide ou a expiré.",
|
|
146
146
|
sign_in_forgot_password: "Mot de passe oublié?",
|
|
147
147
|
sign_in_use_email_otp: "Utiliser un code courriel",
|
|
148
|
-
sign_in_use_password: "Utiliser un mot de passe
|
|
148
|
+
sign_in_use_password: "Utiliser un mot de passe",
|
|
149
149
|
two_factor_backup_code: "Code de secours",
|
|
150
150
|
two_factor_code: "Code d'authentification",
|
|
151
151
|
two_factor_email_code: "Code de vérification par courriel",
|
|
@@ -301,6 +301,10 @@ export function Signin(props) {
|
|
|
301
301
|
const [otpSentTo, setOtpSentTo] = useState(initialMethodStep && initialAuthMethod === "emailOtp" ? initialEmail : "");
|
|
302
302
|
const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
|
|
303
303
|
const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
|
|
304
|
+
const otpSends = useAtomValue(emailOtpSendsAtom(baseUrl ?? ""));
|
|
305
|
+
const persistOtpSends = useAtomSet(emailOtpSendsAtom(baseUrl ?? ""));
|
|
306
|
+
const otpSendsRef = useRef(otpSends);
|
|
307
|
+
otpSendsRef.current = otpSends;
|
|
304
308
|
const [errorContext, setErrorContext] = useState("signIn");
|
|
305
309
|
const selectedAuthMethod = authMethod === "password" && options.emailPassword
|
|
306
310
|
? "password"
|
|
@@ -343,9 +347,23 @@ export function Signin(props) {
|
|
|
343
347
|
}));
|
|
344
348
|
return;
|
|
345
349
|
}
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
350
|
+
const previousSend = otpSendsRef.current[email];
|
|
351
|
+
const previousSendState = emailOtpSendState(previousSend, Date.now());
|
|
352
|
+
const reuseCode = previousSendState.reusable &&
|
|
353
|
+
(action.type !== "resendEmailOtp" ||
|
|
354
|
+
previousSendState.resendSeconds > 0);
|
|
355
|
+
const sendEmailOtp = (reuseCode
|
|
356
|
+
? Effect.void
|
|
357
|
+
: authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
|
|
358
|
+
payload: { email, type: "sign-in" },
|
|
359
|
+
})), Effect.asVoid, Effect.tap(() => Effect.sync(() => {
|
|
360
|
+
const sends = {
|
|
361
|
+
...otpSendsRef.current,
|
|
362
|
+
[email]: Date.now(),
|
|
363
|
+
};
|
|
364
|
+
otpSendsRef.current = sends;
|
|
365
|
+
persistOtpSends(sends);
|
|
366
|
+
})))).pipe(Effect.tap(() => Effect.sync(() => {
|
|
349
367
|
setAuthMethod("emailOtp");
|
|
350
368
|
setEmailSubmitted(true);
|
|
351
369
|
setOtpSentTo(email);
|
|
@@ -354,9 +372,11 @@ export function Signin(props) {
|
|
|
354
372
|
search: authMethodSearch(searchString, "emailOtp", email),
|
|
355
373
|
replace: true,
|
|
356
374
|
});
|
|
357
|
-
setEmailOtpResendAvailableAt(
|
|
375
|
+
setEmailOtpResendAvailableAt((otpSendsRef.current[email] ?? 0) +
|
|
376
|
+
EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
|
|
358
377
|
})));
|
|
359
|
-
if (action.type === "sendEmailOtp"
|
|
378
|
+
if (action.type === "sendEmailOtp" ||
|
|
379
|
+
action.type === "resendEmailOtp") {
|
|
360
380
|
yield* sendEmailOtp;
|
|
361
381
|
return;
|
|
362
382
|
}
|
|
@@ -438,6 +458,10 @@ export function Signin(props) {
|
|
|
438
458
|
password: "",
|
|
439
459
|
otp: "",
|
|
440
460
|
}));
|
|
461
|
+
const lastOtpSentAt = otpSends[formValues.email.trim()];
|
|
462
|
+
useEffect(() => {
|
|
463
|
+
setEmailOtpResendAvailableAt((lastOtpSentAt ?? 0) + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
|
|
464
|
+
}, [lastOtpSentAt]);
|
|
441
465
|
const resetForm = useAtomSet(form.reset);
|
|
442
466
|
const setEmail = useAtomSet(form.getFieldAtoms(form.fields.email).setValue);
|
|
443
467
|
const setPassword = useAtomSet(form.getFieldAtoms(form.fields.password).setValue);
|
|
@@ -462,8 +486,6 @@ export function Signin(props) {
|
|
|
462
486
|
resetForm();
|
|
463
487
|
setEmail(formValues.email);
|
|
464
488
|
setAuthMethod("password");
|
|
465
|
-
setOtpSentTo("");
|
|
466
|
-
setEmailOtpResendAvailableAt(0);
|
|
467
489
|
navigate({
|
|
468
490
|
to: "/sign-in",
|
|
469
491
|
search: authMethodSearch(searchString, "password", formValues.email),
|
|
@@ -477,10 +499,12 @@ export function Signin(props) {
|
|
|
477
499
|
const resendEmailOtp = () => {
|
|
478
500
|
setOtp("");
|
|
479
501
|
setErrorContext("sendEmailOtp");
|
|
480
|
-
submit({ type: "
|
|
502
|
+
submit({ type: "resendEmailOtp" });
|
|
481
503
|
};
|
|
482
504
|
const signInWithGoogle = () => startSocialSignIn(getSocialSignInDestinations(router, props.defaultRedirectTo, window.location.href));
|
|
483
|
-
return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [
|
|
505
|
+
return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [emailSubmitted ? (_jsxs(Button, { type: "button", variant: "link", className: "w-fit justify-self-start p-0", disabled: submitResult.waiting, onClick: resetEmailStep, children: [_jsx(ArrowLeft, {}), m.sign_in_change_email] })) : null, _jsx(CardTitle, { className: "text-3xl", children: m.auth_sign_in }), _jsx(CardDescription, { children: !emailSubmitted
|
|
506
|
+
? m.sign_in_description
|
|
507
|
+
: text(m.sign_in_email_as, { email: formValues.email }) })] }), _jsxs(CardContent, { children: [hasPrimaryAuth ? (_jsx(form.Initialize, { defaultValues: { email: initialEmail, password: "", otp: "" }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
|
|
484
508
|
event.preventDefault();
|
|
485
509
|
event.stopPropagation();
|
|
486
510
|
setErrorContext(!emailSubmitted ||
|
|
@@ -500,18 +524,18 @@ export function Signin(props) {
|
|
|
500
524
|
return;
|
|
501
525
|
event.preventDefault();
|
|
502
526
|
event.currentTarget.form?.requestSubmit();
|
|
503
|
-
}, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
527
|
+
}, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsx("div", { className: "flex flex-col gap-2", children: _jsx(form.password, { label: m.field_password, autoFocus: true, autoComplete: "current-password", recovery: {
|
|
528
|
+
label: m.sign_in_forgot_password,
|
|
529
|
+
disabled: submitResult.waiting,
|
|
530
|
+
onClick: () => {
|
|
531
|
+
setErrorContext("resetPassword");
|
|
532
|
+
submit({ type: "resetPassword" });
|
|
533
|
+
},
|
|
534
|
+
}, required: true }) })) : null, emailSubmitted && selectedAuthMethod === "emailOtp" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.otp, { label: m.sign_in_email_otp_code }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.sign_in_otp_expiry }), _jsx("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: otpSentTo ? (_jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", disabled: emailOtpResendSeconds > 0, onClick: resendEmailOtp, children: emailOtpResendSeconds > 0
|
|
535
|
+
? text(m.sign_in_email_otp_resend_countdown, {
|
|
536
|
+
seconds: String(emailOtpResendSeconds),
|
|
537
|
+
})
|
|
538
|
+
: m.sign_in_email_otp_resend })) : null })] })) : null, _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
|
|
515
539
|
fallback: errorContext === "resetPassword"
|
|
516
540
|
? m.forgot_password_error
|
|
517
541
|
: errorContext === "sendEmailOtp"
|
|
@@ -535,7 +559,10 @@ export function Signin(props) {
|
|
|
535
559
|
? m.sign_in_continue
|
|
536
560
|
: selectedAuthMethod === "emailOtp"
|
|
537
561
|
? m.sign_in_email_otp_verify
|
|
538
|
-
: m.auth_sign_in] }) })] }) })) : null,
|
|
562
|
+
: m.auth_sign_in] }) })] }) })) : null, (emailSubmitted && canChangeAuthMethod) ||
|
|
563
|
+
(options.google && !emailSubmitted) ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [hasPrimaryAuth ? (_jsx(Divider, { label: m.auth_or_continue_with })) : null, emailSubmitted && canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: submitResult.waiting, onClick: switchAuthMethod, children: [selectedAuthMethod === "password" ? _jsx(Mail, {}) : _jsx(KeyRound, {}), selectedAuthMethod === "password"
|
|
564
|
+
? m.sign_in_use_email_otp
|
|
565
|
+
: m.sign_in_use_password] })) : null, options.google && !emailSubmitted ? (_jsxs(_Fragment, { children: [_jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: submitResult.waiting, onClick: signInWithGoogle, children: [_jsx(GoogleLogo, {}), m.auth_continue_with_google] }), _jsx(AuthSubmitError, { result: socialSignInResult, labels: m, messages: { fallback: m.sign_in_error } })] })) : null] })) : null, !hasPrimaryAuth && !options.google ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.oauth_client_no_auth_methods })) : null] })] }));
|
|
539
566
|
}
|
|
540
567
|
export function VerifyEmail(props) {
|
|
541
568
|
const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Atom } from "effect/reactivity";
|
|
2
|
+
export declare const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
|
|
3
|
+
export declare const emailOtpSendsAtom: (arg: string) => Atom.Writable<{
|
|
4
|
+
readonly [x: string]: number;
|
|
5
|
+
}, {
|
|
6
|
+
readonly [x: string]: number;
|
|
7
|
+
}>;
|
|
8
|
+
export declare const emailOtpSendState: (sentAt: number | undefined, now: number) => {
|
|
9
|
+
reusable: boolean;
|
|
10
|
+
resendSeconds: number;
|
|
11
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { KeyValueStore } from "effect/persistence";
|
|
3
|
+
import { Atom } from "effect/reactivity";
|
|
4
|
+
export const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
|
|
5
|
+
const EMAIL_OTP_LIFETIME_MS = 5 * 60 * 1000;
|
|
6
|
+
const EmailOtpSends = Schema.Record(Schema.String, Schema.Number).annotate({
|
|
7
|
+
identifier: "EmailOtpSends",
|
|
8
|
+
});
|
|
9
|
+
const storageRuntime = Atom.runtime(globalThis.window === undefined
|
|
10
|
+
? KeyValueStore.layerMemory
|
|
11
|
+
: KeyValueStore.layerStorage(() => window.localStorage));
|
|
12
|
+
export const emailOtpSendsAtom = Atom.family((baseUrl) => Atom.kvs({
|
|
13
|
+
runtime: storageRuntime,
|
|
14
|
+
key: `krakstack-auth:email-otp-sends:v1:${baseUrl}`,
|
|
15
|
+
schema: EmailOtpSends,
|
|
16
|
+
defaultValue: () => ({}),
|
|
17
|
+
}));
|
|
18
|
+
export const emailOtpSendState = (sentAt, now) => ({
|
|
19
|
+
reusable: sentAt !== undefined &&
|
|
20
|
+
now >= sentAt &&
|
|
21
|
+
now - sentAt < EMAIL_OTP_LIFETIME_MS,
|
|
22
|
+
resendSeconds: sentAt === undefined
|
|
23
|
+
? 0
|
|
24
|
+
: Math.max(0, Math.ceil((sentAt + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000 - now) / 1000)),
|
|
25
|
+
});
|
package/dist/server/actor.js
CHANGED
|
@@ -111,17 +111,16 @@ const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(E
|
|
|
111
111
|
? Effect.succeed(actor)
|
|
112
112
|
: Effect.fail(new HttpApiError.Forbidden({}))));
|
|
113
113
|
const withCurrentActor = (httpEffect, actor) => {
|
|
114
|
-
const
|
|
115
|
-
? actor.actor.
|
|
114
|
+
const roles = actor.actor.type === "user"
|
|
115
|
+
? actor.actor.roles
|
|
116
116
|
: actor.actor.owner.type === "user"
|
|
117
|
-
? actor.actor.owner.
|
|
118
|
-
:
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return Effect.annotateCurrentSpan(attributes).pipe(Effect.andThen(httpEffect.pipe(Effect.provideService(CurrentActor, actor), Effect.annotateSpans(attributes), Effect.annotateLogs(attributes))));
|
|
117
|
+
? actor.actor.owner.roles
|
|
118
|
+
: [];
|
|
119
|
+
// These are verified active-organization roles, never the global user.role.
|
|
120
|
+
return Effect.gen(function* () {
|
|
121
|
+
yield* Effect.annotateCurrentSpan({ "user.roles": roles });
|
|
122
|
+
return yield* httpEffect.pipe(Effect.provideService(CurrentActor, actor), Effect.annotateLogs({ "user.roles": roles }), Effect.annotateSpans({ "user.roles": roles }));
|
|
123
|
+
});
|
|
125
124
|
};
|
|
126
125
|
export function ActorRequired(constraint) {
|
|
127
126
|
if (!constraint)
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
/** Replace auth-owned attribution rather than merging it with an outer actor. */
|
|
3
|
+
export declare const withAuthAnnotations: <A, E, R>(effect: Effect.Effect<A, E, R>, attributes: Readonly<Record<string, string | ReadonlyArray<string>>>) => Effect.Effect<A, E, Exclude<Exclude<R, never>, never>>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Effect, Option, References } from "effect";
|
|
2
|
+
/** Replace auth-owned attribution rather than merging it with an outer actor. */
|
|
3
|
+
export const withAuthAnnotations = (effect, attributes) => {
|
|
4
|
+
const ownedAttribute = (key) => key.startsWith("user.") ||
|
|
5
|
+
key.startsWith("app.user.") ||
|
|
6
|
+
key === "organization.id" ||
|
|
7
|
+
key.startsWith("app.actor.") ||
|
|
8
|
+
key.startsWith("app.auth.");
|
|
9
|
+
const replaceAttribution = (annotations) => ({
|
|
10
|
+
...Object.fromEntries(Object.entries(annotations).filter(([key]) => !ownedAttribute(key))),
|
|
11
|
+
...attributes,
|
|
12
|
+
});
|
|
13
|
+
return Effect.gen(function* () {
|
|
14
|
+
const logs = yield* References.CurrentLogAnnotations;
|
|
15
|
+
const spans = yield* References.TracerSpanAnnotations;
|
|
16
|
+
const current = yield* Effect.currentSpan.pipe(Effect.option);
|
|
17
|
+
if (Option.isSome(current)) {
|
|
18
|
+
for (const key of current.value.attributes.keys()) {
|
|
19
|
+
if (ownedAttribute(key) && attributes[key] === undefined) {
|
|
20
|
+
// Tracer has no removeAttribute API; clear stale current-span values.
|
|
21
|
+
current.value.attribute(key, "");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
yield* Effect.annotateCurrentSpan(attributes);
|
|
26
|
+
return yield* effect.pipe(Effect.provideService(References.TracerSpanAnnotations, replaceAttribution(spans)), Effect.provideService(References.CurrentLogAnnotations, replaceAttribution(logs)));
|
|
27
|
+
});
|
|
28
|
+
};
|
package/dist/server/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export { AuthProxyError, authProxyKeyHeader, proxyOriginHeaders, readProxyOrigin
|
|
|
8
8
|
export { ActorRequired } from "./actor.js";
|
|
9
9
|
export type { ActorConstraint } from "./actor.js";
|
|
10
10
|
export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware.js";
|
|
11
|
-
export type { AuthenticationLiveOptions } from "./middleware.js";
|
|
11
|
+
export type { AuthenticationLiveOptions, AuthRouterOptions, } from "./middleware.js";
|
|
12
12
|
export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema.js";
|
|
13
13
|
export type { Member, Organization, OrganizationMetadata, User, } from "../schema.js";
|
|
14
14
|
export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
|
-
import { HttpServerRequest } from "effect/http";
|
|
2
|
+
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
3
3
|
import { HttpApiError, HttpApiMiddleware, HttpApiSecurity } from "effect/http-api";
|
|
4
4
|
import { AuthService, type AuthServiceLayerOptions } from "../service.js";
|
|
5
5
|
export declare const ApiKeySecurity: HttpApiSecurity.ApiKey;
|
|
@@ -17,6 +17,8 @@ declare const AuthMiddleware_base: HttpApiMiddleware.ServiceClass<AuthMiddleware
|
|
|
17
17
|
}, AuthService, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden, typeof HttpApiError.ServiceUnavailable], never>>;
|
|
18
18
|
export declare class AuthMiddleware extends AuthMiddleware_base {
|
|
19
19
|
static readonly layer: (options?: AuthenticationLiveOptions | Layer.Layer<AuthService, unknown>) => Layer.Layer<AuthMiddleware, never, never>;
|
|
20
|
+
/** The same optional authentication and attribution for plain HttpRouter routes. */
|
|
21
|
+
static readonly routerLayer: (options?: AuthRouterOptions) => Layer.Layer<never, import("effect/Config").ConfigError, HttpRouter.Request<"Error", HttpApiError.Forbidden> | HttpRouter.Request<"Error", HttpApiError.ServiceUnavailable>>;
|
|
20
22
|
}
|
|
21
23
|
export type AuthenticationLiveOptions = AuthServiceLayerOptions & {
|
|
22
24
|
readonly allowedOrganizationImpersonationRoutes?: readonly {
|
|
@@ -25,5 +27,9 @@ export type AuthenticationLiveOptions = AuthServiceLayerOptions & {
|
|
|
25
27
|
}[];
|
|
26
28
|
readonly authLayer?: Layer.Layer<AuthService, unknown, HttpServerRequest.HttpServerRequest>;
|
|
27
29
|
};
|
|
30
|
+
export type AuthRouterOptions = AuthenticationLiveOptions & {
|
|
31
|
+
/** Resolve auth only for these exact URL pathnames. Defaults to every route in scope. */
|
|
32
|
+
readonly paths?: readonly string[];
|
|
33
|
+
};
|
|
28
34
|
export declare const makeAuthenticationLive: (options?: AuthenticationLiveOptions | Layer.Layer<AuthService, unknown>) => Layer.Layer<AuthMiddleware, never, never>;
|
|
29
35
|
export {};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { Cause, Effect, Layer, Redacted } from "effect";
|
|
2
|
-
import { HttpServerRequest } from "effect/http";
|
|
2
|
+
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
3
3
|
import { HttpApiError, HttpApiMiddleware, HttpApiSecurity, } from "effect/http-api";
|
|
4
|
-
import { AuthService } from "../service.js";
|
|
4
|
+
import { AuthService, } from "../service.js";
|
|
5
|
+
import { AuthClientConfig } from "../config.js";
|
|
6
|
+
import { withAuthAnnotations } from "./attribution.js";
|
|
5
7
|
export const ApiKeySecurity = HttpApiSecurity.apiKey({
|
|
6
8
|
key: "x-api-key",
|
|
7
9
|
in: "header",
|
|
@@ -17,43 +19,80 @@ export class AuthMiddleware extends HttpApiMiddleware.Service()("@krak-stack/aut
|
|
|
17
19
|
},
|
|
18
20
|
}) {
|
|
19
21
|
static layer = (options = {}) => makeAuthenticationLive(options);
|
|
22
|
+
/** The same optional authentication and attribution for plain HttpRouter routes. */
|
|
23
|
+
static routerLayer = (options = {}) => HttpRouter.middleware(Effect.gen(function* () {
|
|
24
|
+
const config = options.authLayer
|
|
25
|
+
? undefined
|
|
26
|
+
: yield* AuthClientConfig.make(options);
|
|
27
|
+
return (httpEffect) => Effect.gen(function* () {
|
|
28
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
29
|
+
if (options.paths &&
|
|
30
|
+
!options.paths.includes(pathnameFromUrl(request.url))) {
|
|
31
|
+
return yield* httpEffect;
|
|
32
|
+
}
|
|
33
|
+
const { auth, session } = yield* authenticateRequest({ ...options, ...config }, options.authLayer);
|
|
34
|
+
return yield* withAuthAnnotations(httpEffect.pipe(Effect.provideService(AuthService, auth)), sessionAnnotations(session));
|
|
35
|
+
});
|
|
36
|
+
})).layer;
|
|
20
37
|
}
|
|
21
38
|
const isAuthServiceLayer = (value) => Layer.isLayer(value);
|
|
22
39
|
export const makeAuthenticationLive = (options = {}) => {
|
|
23
40
|
const legacyLayer = isAuthServiceLayer(options) ? options : undefined;
|
|
24
41
|
const authOptions = isAuthServiceLayer(options) ? {} : options;
|
|
25
42
|
const authLayer = legacyLayer ?? authOptions.authLayer;
|
|
26
|
-
const allowedOrganizationImpersonationRoutes = authOptions.allowedOrganizationImpersonationRoutes ?? [];
|
|
27
43
|
return Layer.effect(AuthMiddleware, Effect.gen(function* () {
|
|
28
44
|
return {
|
|
29
|
-
apiKey: (httpEffect, { credential }) => Effect.
|
|
30
|
-
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
31
|
-
const apiKey = Redacted.value(credential).trim();
|
|
32
|
-
const headers = apiKey
|
|
33
|
-
? { ...request.headers, "x-api-key": apiKey }
|
|
34
|
-
: request.headers;
|
|
35
|
-
const auth = yield* AuthService.pipe(Effect.provide(authLayer ??
|
|
36
|
-
AuthService.layer({
|
|
37
|
-
...authOptions,
|
|
38
|
-
headers,
|
|
39
|
-
})), Effect.tapCause((cause) => Effect.logError("Authentication rejected: auth client initialization failed", Cause.pretty(cause))), Effect.mapError(() => new HttpApiError.ServiceUnavailable({})));
|
|
40
|
-
if (!isAllowedRoute(allowedOrganizationImpersonationRoutes, request)) {
|
|
41
|
-
const session = yield* auth
|
|
42
|
-
.getSession()
|
|
43
|
-
.pipe(Effect.catchTag("Unauthorized", () => Effect.succeed(null)));
|
|
44
|
-
if (session?.session.impersonatedByOrganizationId) {
|
|
45
|
-
return yield* new HttpApiError.Forbidden({});
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
return auth;
|
|
49
|
-
}).pipe(Effect.mapError((error) => error instanceof HttpApiError.Unauthorized ||
|
|
50
|
-
error instanceof HttpApiError.Forbidden ||
|
|
51
|
-
error instanceof HttpApiError.ServiceUnavailable
|
|
52
|
-
? error
|
|
53
|
-
: new HttpApiError.ServiceUnavailable({})), Effect.flatMap((auth) => httpEffect.pipe(Effect.provideService(AuthService, auth)))),
|
|
45
|
+
apiKey: (httpEffect, { credential }) => authenticateRequest(authOptions, authLayer, Redacted.value(credential).trim()).pipe(Effect.flatMap(({ auth, session }) => withAuthAnnotations(httpEffect.pipe(Effect.provideService(AuthService, auth)), sessionAnnotations(session)))),
|
|
54
46
|
};
|
|
55
47
|
}));
|
|
56
48
|
};
|
|
49
|
+
const authenticateRequest = Effect.fnUntraced(function* (options, authLayer, apiKey) {
|
|
50
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
51
|
+
const auth = yield* AuthService.pipe(Effect.provide(authLayer ??
|
|
52
|
+
AuthService.layer({
|
|
53
|
+
...options,
|
|
54
|
+
headers: apiKey
|
|
55
|
+
? { ...request.headers, "x-api-key": apiKey }
|
|
56
|
+
: request.headers,
|
|
57
|
+
})), Effect.tapCause((cause) => Effect.logError("Authentication rejected: auth client initialization failed", Cause.pretty(cause))), Effect.mapError(() => new HttpApiError.ServiceUnavailable({})));
|
|
58
|
+
const session = yield* auth
|
|
59
|
+
.getSession()
|
|
60
|
+
.pipe(Effect.catchTag("Unauthorized", () => Effect.succeed(null)));
|
|
61
|
+
if (session?.session.impersonatedByOrganizationId &&
|
|
62
|
+
!isAllowedRoute(options.allowedOrganizationImpersonationRoutes ?? [], request)) {
|
|
63
|
+
return yield* new HttpApiError.Forbidden({});
|
|
64
|
+
}
|
|
65
|
+
return { auth, session };
|
|
66
|
+
});
|
|
67
|
+
const sessionAnnotations = (session) => {
|
|
68
|
+
const attributes = {};
|
|
69
|
+
if (!session)
|
|
70
|
+
return attributes;
|
|
71
|
+
if (session.user &&
|
|
72
|
+
(session.authMethod.type === "cookie" ||
|
|
73
|
+
session.authMethod.apiKey.configId === "user")) {
|
|
74
|
+
attributes["user.id"] = session.user.id;
|
|
75
|
+
}
|
|
76
|
+
if (session.session.activeOrganizationId) {
|
|
77
|
+
attributes["organization.id"] = session.session.activeOrganizationId;
|
|
78
|
+
}
|
|
79
|
+
if (session.authMethod.type === "cookie" && session.user) {
|
|
80
|
+
attributes["app.actor.type"] = "user";
|
|
81
|
+
attributes["app.actor.id"] = session.user.id;
|
|
82
|
+
attributes["app.auth.method"] = "session";
|
|
83
|
+
if (session.session.impersonatedBy) {
|
|
84
|
+
attributes["app.auth.impersonator.id"] = session.session.impersonatedBy;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
else if (session.authMethod.type === "apiKey") {
|
|
88
|
+
const key = session.authMethod.apiKey;
|
|
89
|
+
attributes["app.actor.type"] = key.configId;
|
|
90
|
+
attributes["app.actor.id"] = key.referenceId;
|
|
91
|
+
attributes["app.auth.method"] = "api_key";
|
|
92
|
+
attributes["app.auth.credential.id"] = key.id;
|
|
93
|
+
}
|
|
94
|
+
return attributes;
|
|
95
|
+
};
|
|
57
96
|
const pathnameFromUrl = (url) => new URL(url, "http://localhost").pathname;
|
|
58
97
|
const isAllowedRoute = (routes, request) => routes.some(({ method, path }) => method.toUpperCase() === request.method.toUpperCase() &&
|
|
59
98
|
routePathMatches(path, pathnameFromUrl(request.url)));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krak-stack/auth",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.25",
|
|
4
4
|
"description": "Effect HttpApi clients and schemas for KrakStack Auth.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"files": [
|
|
@@ -76,10 +76,10 @@
|
|
|
76
76
|
"react-qr-code": "^2.2.0"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
|
-
"@krak-stack/registry": "0.1.
|
|
79
|
+
"@krak-stack/registry": "0.1.52"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
|
-
"@krak-stack/registry": "^0.1.
|
|
82
|
+
"@krak-stack/registry": "^0.1.52",
|
|
83
83
|
"@tanstack/react-router": "^1.170.15",
|
|
84
84
|
"effect": "^4.0.0",
|
|
85
85
|
"input-otp": "^1.5.0",
|