@krak-stack/auth 0.2.23 → 0.2.24

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.
@@ -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: "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: "Change",
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 instead",
82
- sign_in_use_password: "Use an existing password",
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: "ou continuez avec",
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: "Modifier",
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 existant",
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 sendEmailOtp = authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
347
- payload: { email, type: "sign-in" },
348
- })), Effect.tap(() => Effect.sync(() => {
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(Date.now() + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
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: "sendEmailOtp" });
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: [_jsx(CardTitle, { className: "text-3xl", children: m.auth_sign_in }), _jsx(CardDescription, { children: !emailSubmitted ? (m.sign_in_description) : (_jsxs(_Fragment, { children: [text(m.sign_in_email_as, { email: formValues.email }), " ", _jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: resetEmailStep, children: m.sign_in_change_email })] })) })] }), _jsxs(CardContent, { children: [hasPrimaryAuth ? (_jsx(form.Initialize, { defaultValues: { email: initialEmail, password: "", otp: "" }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
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" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.password, { label: m.field_password, autoFocus: true, autoComplete: "current-password", recovery: {
504
- label: m.sign_in_forgot_password,
505
- disabled: submitResult.waiting,
506
- onClick: () => {
507
- setErrorContext("resetPassword");
508
- submit({ type: "resetPassword" });
509
- },
510
- }, required: true }), _jsx("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(Mail, {}), m.sign_in_use_email_otp] })) : null })] })) : 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 }), _jsxs("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
511
- ? text(m.sign_in_email_otp_resend_countdown, {
512
- seconds: String(emailOtpResendSeconds),
513
- })
514
- : m.sign_in_email_otp_resend })) : null, canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(KeyRound, {}), m.sign_in_use_password] })) : null] })] })) : null, _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
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, options.google && !emailSubmitted ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [hasPrimaryAuth ? (_jsx(Divider, { label: m.auth_or_continue_with })) : null, _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, !hasPrimaryAuth && !options.google ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.oauth_client_no_auth_methods })) : 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
+ });
@@ -110,19 +110,7 @@ const matchesConstraint = (actor, constraint) => {
110
110
  const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.flatMap((actor) => matchesConstraint(actor, constraint)
111
111
  ? Effect.succeed(actor)
112
112
  : Effect.fail(new HttpApiError.Forbidden({}))));
113
- const withCurrentActor = (httpEffect, actor) => {
114
- const userId = actor.actor.type === "user"
115
- ? actor.actor.userId
116
- : actor.actor.owner.type === "user"
117
- ? actor.actor.owner.userId
118
- : undefined;
119
- const attributes = {};
120
- if (actor.organizationId)
121
- attributes["organization.id"] = actor.organizationId;
122
- if (userId)
123
- attributes["user.id"] = userId;
124
- return Effect.annotateCurrentSpan(attributes).pipe(Effect.andThen(httpEffect.pipe(Effect.provideService(CurrentActor, actor), Effect.annotateSpans(attributes), Effect.annotateLogs(attributes))));
125
- };
113
+ const withCurrentActor = (httpEffect, actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor));
126
114
  export function ActorRequired(constraint) {
127
115
  if (!constraint)
128
116
  return AnyActorRequired;
@@ -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>>) => Effect.Effect<A, E, Exclude<Exclude<R, never>, never>>;
@@ -0,0 +1,26 @@
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 === "user.id" ||
5
+ key === "organization.id" ||
6
+ key.startsWith("app.actor.");
7
+ const replaceAttribution = (annotations) => ({
8
+ ...Object.fromEntries(Object.entries(annotations).filter(([key]) => !ownedAttribute(key))),
9
+ ...attributes,
10
+ });
11
+ return Effect.gen(function* () {
12
+ const logs = yield* References.CurrentLogAnnotations;
13
+ const spans = yield* References.TracerSpanAnnotations;
14
+ const current = yield* Effect.currentSpan.pipe(Effect.option);
15
+ if (Option.isSome(current)) {
16
+ for (const key of current.value.attributes.keys()) {
17
+ if (ownedAttribute(key) && attributes[key] === undefined) {
18
+ // Tracer has no removeAttribute API; clear stale current-span values.
19
+ current.value.attribute(key, "");
20
+ }
21
+ }
22
+ }
23
+ yield* Effect.annotateCurrentSpan(attributes);
24
+ return yield* effect.pipe(Effect.provideService(References.TracerSpanAnnotations, replaceAttribution(spans)), Effect.provideService(References.CurrentLogAnnotations, replaceAttribution(logs)));
25
+ });
26
+ };
@@ -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,73 @@ 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.gen(function* () {
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
+ attributes["user.id"] = session.user.id;
73
+ if (session.session.activeOrganizationId) {
74
+ attributes["organization.id"] = session.session.activeOrganizationId;
75
+ }
76
+ if (session.authMethod.type === "cookie" && session.user) {
77
+ attributes["app.actor.type"] = "user";
78
+ attributes["app.actor.id"] = session.user.id;
79
+ }
80
+ else if (session.authMethod.type === "apiKey") {
81
+ const key = session.authMethod.apiKey;
82
+ attributes["app.actor.type"] = "api_key";
83
+ attributes["app.actor.id"] = key.id;
84
+ attributes["app.actor.owner.type"] = key.configId;
85
+ attributes["app.actor.owner.id"] = key.referenceId;
86
+ }
87
+ return attributes;
88
+ };
57
89
  const pathnameFromUrl = (url) => new URL(url, "http://localhost").pathname;
58
90
  const isAllowedRoute = (routes, request) => routes.some(({ method, path }) => method.toUpperCase() === request.method.toUpperCase() &&
59
91
  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.23",
3
+ "version": "0.2.24",
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.48"
79
+ "@krak-stack/registry": "0.1.50"
80
80
  },
81
81
  "peerDependencies": {
82
- "@krak-stack/registry": "^0.1.48",
82
+ "@krak-stack/registry": "^0.1.50",
83
83
  "@tanstack/react-router": "^1.170.15",
84
84
  "effect": "^4.0.0",
85
85
  "input-otp": "^1.5.0",