@krak-stack/auth 0.2.9 → 0.2.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.
@@ -1,5 +1,5 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
2
+ import { useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { useNavigate, useRouter } from "@tanstack/react-router";
4
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
5
  import { Effect, Option, Schema } from "effect";
@@ -138,7 +138,6 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
138
138
  const baseUrl = auth?.baseUrl;
139
139
  const sessionAtom = authSessionAtom(baseUrl);
140
140
  const sessionResult = useAtomValue(sessionAtom);
141
- const refetchSession = useAtomRefresh(sessionAtom);
142
141
  const session = AsyncResult.match(sessionResult, {
143
142
  onInitial: () => null,
144
143
  onFailure: () => null,
@@ -159,8 +158,6 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
159
158
  const client = yield* authHttpClient(baseUrl);
160
159
  yield* client.auth.adminImpersonateUser({ payload: { userId } });
161
160
  notifyAuthChange();
162
- auth?.refreshAuth();
163
- refetchSession();
164
161
  yield* Effect.tryPromise({
165
162
  try: async () => {
166
163
  await navigate({ to: "/" });
@@ -179,8 +176,6 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
179
176
  payload: { organizationId, actorUserId, targetUserId },
180
177
  });
181
178
  notifyAuthChange();
182
- auth?.refreshAuth();
183
- refetchSession();
184
179
  yield* Effect.tryPromise({
185
180
  try: async () => {
186
181
  await navigate({ to: "/" });
@@ -1,6 +1,7 @@
1
- import { Atom } from "effect/unstable/reactivity";
1
+ import { AsyncResult, Atom } from "effect/unstable/reactivity";
2
2
  export declare const AUTH_CLIENT_CHANGE_EVENT = "krakstack-auth:change";
3
- export declare const authSessionAtom: (arg: string | undefined) => Atom.Writable<import("effect/unstable/reactivity/AsyncResult").AsyncResult<{
3
+ export declare const refreshOnAuthChange: <A>(atom: Atom.Atom<A>) => Atom.Atom<A>;
4
+ export declare const authSessionAtom: (arg: string | undefined) => Atom.Atom<AsyncResult.AsyncResult<{
4
5
  readonly session: {
5
6
  readonly id: string;
6
7
  readonly expiresAt: Date;
@@ -61,69 +62,8 @@ export declare const authSessionAtom: (arg: string | undefined) => Atom.Writable
61
62
  readonly createdAt: Date;
62
63
  readonly updatedAt: Date;
63
64
  };
64
- } | null, import("../auth/schema.js").AuthBadRequest>, Atom.Atom<import("effect/unstable/reactivity/AsyncResult").AsyncResult<import("effect/unstable/reactivity/AsyncResult").AsyncResult<{
65
- readonly session: {
66
- readonly id: string;
67
- readonly expiresAt: Date;
68
- readonly token: string;
69
- readonly createdAt: Date;
70
- readonly updatedAt: Date;
71
- readonly ipAddress?: string | null | undefined;
72
- readonly userAgent?: string | null | undefined;
73
- readonly userId: string;
74
- readonly impersonatedBy?: string | null | undefined;
75
- readonly impersonatedByOrganizationId?: string | null | undefined;
76
- readonly activeOrganizationId?: string | null | undefined;
77
- };
78
- readonly user: {
79
- readonly id: string;
80
- readonly name: string;
81
- readonly email: string;
82
- readonly emailVerified: boolean;
83
- readonly image: string | null;
84
- readonly metadata?: {
85
- readonly emails?: readonly {
86
- readonly email: string;
87
- readonly translations: readonly {
88
- readonly locale: "en" | "fr";
89
- readonly label: string;
90
- }[];
91
- }[] | undefined;
92
- readonly phones?: readonly {
93
- readonly number: string;
94
- readonly extension?: string | undefined;
95
- readonly translations: readonly {
96
- readonly locale: "en" | "fr";
97
- readonly label: string;
98
- }[];
99
- }[] | undefined;
100
- readonly websites?: readonly {
101
- readonly url: string;
102
- readonly translations: readonly {
103
- readonly locale: "en" | "fr";
104
- readonly label: string;
105
- }[];
106
- }[] | undefined;
107
- readonly socials?: readonly {
108
- readonly platform: "facebook" | "github" | "instagram" | "linkedin" | "tiktok" | "x" | "youtube";
109
- readonly url: string;
110
- readonly translations: readonly {
111
- readonly locale: "en" | "fr";
112
- readonly label: string;
113
- }[];
114
- }[] | undefined;
115
- } | null | undefined;
116
- readonly role: string | null;
117
- readonly banned: boolean | null;
118
- readonly banReason?: string | null | undefined;
119
- readonly banExpires?: Date | null | undefined;
120
- readonly twoFactorEnabled?: boolean | undefined;
121
- readonly lastLoginMethod?: string | null | undefined;
122
- readonly createdAt: Date;
123
- readonly updatedAt: Date;
124
- };
125
- } | null, import("../auth/schema.js").AuthBadRequest>, unknown>>>;
126
- export declare const authOrganizationsAtom: (arg: string | undefined) => Atom.Writable<import("effect/unstable/reactivity/AsyncResult").AsyncResult<readonly {
65
+ } | null, import("../auth/schema.js").AuthBadRequest>>;
66
+ export declare const authOrganizationsAtom: (arg: string | undefined) => Atom.Atom<AsyncResult.AsyncResult<readonly {
127
67
  readonly id: string;
128
68
  readonly name: string;
129
69
  readonly slug: string;
@@ -134,87 +74,8 @@ export declare const authOrganizationsAtom: (arg: string | undefined) => Atom.Wr
134
74
  readonly userId?: string | null | undefined;
135
75
  readonly parentId?: string | null | undefined;
136
76
  readonly createdAt: Date;
137
- }[], import("../auth/schema.js").AuthBadRequest>, Atom.Atom<import("effect/unstable/reactivity/AsyncResult").AsyncResult<import("effect/unstable/reactivity/AsyncResult").AsyncResult<readonly {
138
- readonly id: string;
139
- readonly name: string;
140
- readonly slug: string;
141
- readonly logo?: string | null | undefined;
142
- readonly metadata?: string | {
143
- readonly [x: string]: import("effect/Schema").Json;
144
- } | null | undefined;
145
- readonly userId?: string | null | undefined;
146
- readonly parentId?: string | null | undefined;
147
- readonly createdAt: Date;
148
- }[], import("../auth/schema.js").AuthBadRequest>, unknown>>>;
149
- export declare const activeAuthOrganizationAtom: (arg: string | undefined) => (arg: string | null) => Atom.Writable<import("effect/unstable/reactivity/AsyncResult").AsyncResult<{
150
- readonly id: string;
151
- readonly name: string;
152
- readonly slug: string;
153
- readonly logo?: string | null | undefined;
154
- readonly metadata?: string | {
155
- readonly [x: string]: import("effect/Schema").Json;
156
- } | null | undefined;
157
- readonly userId?: string | null | undefined;
158
- readonly parentId?: string | null | undefined;
159
- readonly createdAt: Date;
160
- readonly members: readonly {
161
- readonly id: string;
162
- readonly organizationId: string;
163
- readonly userId: string;
164
- readonly role: string;
165
- readonly createdAt: Date;
166
- readonly user: {
167
- readonly id: string;
168
- readonly name: string;
169
- readonly email: string;
170
- readonly image?: string | null | undefined;
171
- readonly metadata?: {
172
- readonly emails?: readonly {
173
- readonly email: string;
174
- readonly translations: readonly {
175
- readonly locale: "en" | "fr";
176
- readonly label: string;
177
- }[];
178
- }[] | undefined;
179
- readonly phones?: readonly {
180
- readonly number: string;
181
- readonly extension?: string | undefined;
182
- readonly translations: readonly {
183
- readonly locale: "en" | "fr";
184
- readonly label: string;
185
- }[];
186
- }[] | undefined;
187
- readonly websites?: readonly {
188
- readonly url: string;
189
- readonly translations: readonly {
190
- readonly locale: "en" | "fr";
191
- readonly label: string;
192
- }[];
193
- }[] | undefined;
194
- readonly socials?: readonly {
195
- readonly platform: "facebook" | "github" | "instagram" | "linkedin" | "tiktok" | "x" | "youtube";
196
- readonly url: string;
197
- readonly translations: readonly {
198
- readonly locale: "en" | "fr";
199
- readonly label: string;
200
- }[];
201
- }[] | undefined;
202
- } | null | undefined;
203
- };
204
- }[];
205
- readonly invitations: readonly {
206
- readonly id: string;
207
- readonly email: string;
208
- readonly role: string;
209
- readonly organizationId: string;
210
- readonly organizationName?: string | null | undefined;
211
- readonly inviterId: string;
212
- readonly teamId?: string | null | undefined;
213
- readonly status: string;
214
- readonly expiresAt: Date;
215
- readonly createdAt?: Date | undefined;
216
- }[];
217
- } | null, import("../auth/schema.js").AuthBadRequest>, Atom.Atom<import("effect/unstable/reactivity/AsyncResult").AsyncResult<import("effect/unstable/reactivity/AsyncResult").AsyncResult<{
77
+ }[], import("../auth/schema.js").AuthBadRequest>>;
78
+ export declare const activeAuthOrganizationAtom: (arg: string | undefined) => (arg: string | null) => Atom.Atom<AsyncResult.AsyncResult<{
218
79
  readonly id: string;
219
80
  readonly name: string;
220
81
  readonly slug: string;
@@ -282,7 +143,6 @@ export declare const activeAuthOrganizationAtom: (arg: string | undefined) => (a
282
143
  readonly expiresAt: Date;
283
144
  readonly createdAt?: Date | undefined;
284
145
  }[];
285
- } | null, import("../auth/schema.js").AuthBadRequest>, unknown>>>;
146
+ } | null, import("../auth/schema.js").AuthBadRequest>>;
286
147
  export declare const getLastUsedLoginMethod: () => string | null;
287
148
  export declare const notifyAuthChange: () => void;
288
- export declare const isAuthClientStorageEvent: (event: StorageEvent) => boolean;
@@ -1,22 +1,44 @@
1
- import { Atom } from "effect/unstable/reactivity";
1
+ import { Option } from "effect";
2
+ import { AsyncResult, Atom } from "effect/unstable/reactivity";
2
3
  import { authClientApi } from "./auth-client-api.js";
3
4
  const LAST_LOGIN_METHOD_COOKIE = "krakstack-auth.last_used_login_method";
4
5
  export const AUTH_CLIENT_CHANGE_EVENT = "krakstack-auth:change";
5
- const AUTH_CLIENT_CHANGE_STORAGE_KEY = "krakstack-auth.change";
6
- export const authSessionAtom = Atom.family((baseUrl) => Atom.optimistic(authClientApi(baseUrl).query("auth", "getSession", {
6
+ const authRevalidationSignal = Atom.make((get) => {
7
+ if (globalThis.window) {
8
+ const onChange = (event) => get.setSelf(event);
9
+ window.addEventListener(AUTH_CLIENT_CHANGE_EVENT, onChange);
10
+ get.addFinalizer(() => window.removeEventListener(AUTH_CLIENT_CHANGE_EVENT, onChange));
11
+ }
12
+ return null;
13
+ });
14
+ // Each registry subscribes once; query refreshes stay inside the atom graph.
15
+ const refreshOnAuthSignal = Atom.makeRefreshOnSignal(authRevalidationSignal);
16
+ export const refreshOnAuthChange = (atom) => {
17
+ const reactive = refreshOnAuthSignal(atom);
18
+ // The built-in visibility helper is browser-only.
19
+ return globalThis.window ? Atom.refreshOnWindowFocus(reactive) : reactive;
20
+ };
21
+ export const authSessionAtom = Atom.family((baseUrl) => Atom.optimistic(authClientApi(baseUrl)
22
+ .query("auth", "getSession", {
7
23
  query: {},
8
24
  timeToLive: "1 minute",
9
25
  reactivityKeys: ["auth-session"],
10
- })));
26
+ })
27
+ .pipe(Atom.map((result) => {
28
+ const unauthorized = AsyncResult.error(result).pipe(Option.exists((error) => error._tag === "AuthUnauthorized"));
29
+ return unauthorized && !result.waiting
30
+ ? AsyncResult.success(null)
31
+ : result;
32
+ }))).pipe(refreshOnAuthChange));
11
33
  export const authOrganizationsAtom = Atom.family((baseUrl) => Atom.optimistic(authClientApi(baseUrl).query("auth", "organizationList", {
12
34
  timeToLive: "1 minute",
13
35
  reactivityKeys: ["auth-organizations"],
14
- })));
36
+ })).pipe(refreshOnAuthChange));
15
37
  export const activeAuthOrganizationAtom = Atom.family((baseUrl) => Atom.family((organizationId) => Atom.optimistic(authClientApi(baseUrl).query("auth", "organizationGetFull", {
16
38
  query: organizationId ? { organizationId } : {},
17
39
  timeToLive: "1 minute",
18
40
  reactivityKeys: ["auth-active-organization", organizationId ?? "none"],
19
- }))));
41
+ })).pipe(refreshOnAuthChange)));
20
42
  export const getLastUsedLoginMethod = () => {
21
43
  const cookies = globalThis.document?.cookie;
22
44
  if (!cookies)
@@ -36,11 +58,4 @@ export const getLastUsedLoginMethod = () => {
36
58
  };
37
59
  export const notifyAuthChange = () => {
38
60
  globalThis.window?.dispatchEvent(new Event(AUTH_CLIENT_CHANGE_EVENT));
39
- try {
40
- globalThis.localStorage?.setItem(AUTH_CLIENT_CHANGE_STORAGE_KEY, String(Date.now()));
41
- }
42
- catch {
43
- // Storage may be unavailable in privacy-restricted browser contexts.
44
- }
45
61
  };
46
- export const isAuthClientStorageEvent = (event) => event.key === AUTH_CLIENT_CHANGE_STORAGE_KEY;
@@ -1,3 +1,4 @@
1
+ import { useNavigate } from "@tanstack/react-router";
1
2
  import { type KrakstackAuthLocale } from "./auth-provider.js";
2
3
  type AuthFormProps = {
3
4
  baseUrl?: string | undefined;
@@ -10,11 +11,10 @@ export declare const resolveInitialAuthMethod: ({ requestedMethod, lastLoginMeth
10
11
  emailPassword: boolean;
11
12
  emailOtp: boolean;
12
13
  }) => AuthMethod;
13
- export declare function Signin(props: AuthFormProps & {
14
- otpExpiryDescription?: string | undefined;
15
- }): import("react").JSX.Element;
14
+ export declare function Signin(props: AuthFormProps): import("react").JSX.Element;
16
15
  export declare function VerifyEmail(props: AuthFormProps): import("react").JSX.Element;
17
16
  export declare function ForgotPassword(props: AuthFormProps): import("react").JSX.Element;
18
17
  export declare function ResetPassword(props: AuthFormProps): import("react").JSX.Element;
19
18
  export declare function TwoFactor(props: AuthFormProps): import("react").JSX.Element;
19
+ export declare const navigateTarget: (target: string, navigate: ReturnType<typeof useNavigate>) => Promise<void>;
20
20
  export {};
@@ -55,6 +55,7 @@ const defaultMessages = {
55
55
  sign_in_email_as: "Signing in as {email}",
56
56
  sign_in_email_otp_code: "Email code",
57
57
  sign_in_email_otp_error: "Unable to verify the sign-in code.",
58
+ sign_in_otp_expiry: "Your code expires 5 minutes after it's sent.",
58
59
  sign_in_email_otp_resend: "Resend code",
59
60
  sign_in_email_otp_resend_countdown: "Resend in {seconds}s",
60
61
  sign_in_email_otp_send_error: "Unable to send the sign-in code.",
@@ -109,6 +110,7 @@ const defaultMessages = {
109
110
  sign_in_email_as: "Connexion avec {email}",
110
111
  sign_in_email_otp_code: "Code courriel",
111
112
  sign_in_email_otp_error: "Impossible de vérifier le code de connexion.",
113
+ sign_in_otp_expiry: "Votre code expire 5 minutes après son envoi.",
112
114
  sign_in_email_otp_resend: "Renvoyer le code",
113
115
  sign_in_email_otp_resend_countdown: "Renvoyer dans {seconds} s",
114
116
  sign_in_email_otp_send_error: "Impossible d'envoyer le code de connexion.",
@@ -421,7 +423,7 @@ export function Signin(props) {
421
423
  return;
422
424
  event.preventDefault();
423
425
  event.currentTarget.form?.requestSubmit();
424
- }, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.password, { label: m.field_password, type: "password", autoComplete: "current-password", required: true }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx(Link, { className: authLinkClassName, to: "/reset-password", search: authMethodSearch(searchString, "password", formValues.email.trim()), children: m.sign_in_forgot_password }), 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 }), props.otpExpiryDescription ? (_jsx("p", { className: "text-muted-foreground text-sm", children: props.otpExpiryDescription })) : null, _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
426
+ }, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.password, { label: m.field_password, type: "password", autoComplete: "current-password", required: true }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx(Link, { className: authLinkClassName, to: "/reset-password", search: authMethodSearch(searchString, "password", formValues.email.trim()), children: m.sign_in_forgot_password }), 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
425
427
  ? text(m.sign_in_email_otp_resend_countdown, {
426
428
  seconds: String(emailOtpResendSeconds),
427
429
  })
@@ -697,22 +699,10 @@ const getDefaultAuthRedirectTarget = (_projectAuthDomain, _projectRootDomain) =>
697
699
  };
698
700
  const getSearchParam = (searchString, key) => new URLSearchParams(searchString).get(key);
699
701
  const getBrowserAuthHost = () => globalThis.window?.location.host ?? null;
700
- const navigateTarget = (target, navigate) => {
701
- if (shouldUseDocumentRedirect(target)) {
702
- navigate({ href: target });
703
- }
704
- else {
705
- navigate({ to: target });
706
- }
707
- };
708
- const shouldUseDocumentRedirect = (target) => {
709
- if (target.startsWith("/api/"))
710
- return true;
711
- if (target.startsWith("/"))
712
- return false;
713
- if (target.startsWith(window.location.origin))
714
- return true;
715
- return target.startsWith("http://") || target.startsWith("https://");
702
+ export const navigateTarget = (target, navigate) => {
703
+ // Return destinations are complete URLs, including any search and hash.
704
+ // API callbacks must reach the server rather than the client route tree.
705
+ return navigate({ href: target, reloadDocument: target.startsWith("/api/") });
716
706
  };
717
707
  const nameFromEmail = (email) => {
718
708
  const trimmed = email.trim();
@@ -17,10 +17,7 @@ export type KrakstackAuthContextValue = {
17
17
  projectConfig: ExtraProjectPublicConfig | null;
18
18
  access: ProjectAccessCatalog | null;
19
19
  accessLabels: ProjectAccessLabelCatalog | null;
20
- authRefreshVersion: number;
21
- refreshAuth: () => void;
22
20
  };
23
- export declare const listenForSessionRevalidation: (target: EventTarget, revalidate: () => void) => () => void;
24
21
  export declare function KrakstackAuthProvider({ children, locale, baseUrl, projectId, access, accessLabels, }: KrakstackAuthProviderProps): import("react").JSX.Element;
25
22
  export declare const useKrakstackAuth: () => KrakstackAuthContextValue | null;
26
23
  export declare const useKrakstackAuthProjectConfig: () => {
@@ -1,43 +1,13 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useAtomRefresh, useAtomSuspense, useAtomValue, } from "@effect/atom-react";
2
+ import { useAtomSuspense, useAtomValue } from "@effect/atom-react";
3
3
  import { useRouterState } from "@tanstack/react-router";
4
4
  import { AsyncResult } from "effect/unstable/reactivity";
5
- import { createContext, useCallback, useContext, useEffect, useEffectEvent, useMemo, useState, } from "react";
6
- import { activeAuthOrganizationAtom, AUTH_CLIENT_CHANGE_EVENT, authSessionAtom, isAuthClientStorageEvent, } from "./auth-atoms.js";
5
+ import { createContext, useContext, useEffect, useMemo, useRef, } from "react";
6
+ import { activeAuthOrganizationAtom, authSessionAtom } from "./auth-atoms.js";
7
7
  import { authClientApi } from "./auth-client-api.js";
8
8
  import { parseRoleList } from "../roles.js";
9
9
  const KrakstackAuthContext = createContext(null);
10
10
  const PROJECT_CONTEXT_COOKIE = "krakstack-auth.project_context";
11
- export const listenForSessionRevalidation = (target, revalidate) => {
12
- const onPageShow = (event) => {
13
- if ("persisted" in event && event.persisted === true)
14
- revalidate();
15
- };
16
- target.addEventListener("pageshow", onPageShow);
17
- return () => {
18
- target.removeEventListener("pageshow", onPageShow);
19
- };
20
- };
21
- const listenForAuthChanges = (revalidate) => {
22
- const onStorage = (event) => {
23
- if (isAuthClientStorageEvent(event))
24
- revalidate();
25
- };
26
- const onVisible = () => {
27
- if (document.visibilityState === "visible")
28
- revalidate();
29
- };
30
- window.addEventListener(AUTH_CLIENT_CHANGE_EVENT, revalidate);
31
- window.addEventListener("storage", onStorage);
32
- window.addEventListener("online", revalidate);
33
- document.addEventListener("visibilitychange", onVisible);
34
- return () => {
35
- window.removeEventListener(AUTH_CLIENT_CHANGE_EVENT, revalidate);
36
- window.removeEventListener("storage", onStorage);
37
- window.removeEventListener("online", revalidate);
38
- document.removeEventListener("visibilitychange", onVisible);
39
- };
40
- };
41
11
  const setProjectContextCookie = (projectId) => {
42
12
  if (!globalThis.document)
43
13
  return;
@@ -109,26 +79,24 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
109
79
  });
110
80
  const resolvedProjectId = projectId ?? getSearchParam(searchString, "projectId");
111
81
  const projectConfig = useProjectConfig(baseUrl, projectId);
112
- const [authRefreshVersion, setAuthRefreshVersion] = useState(0);
113
- const refreshAuth = useCallback(() => {
114
- setAuthRefreshVersion((current) => current + 1);
115
- }, []);
116
82
  const sessionAtom = authSessionAtom(baseUrl);
117
- useAtomValue(sessionAtom);
118
- const refreshSession = useAtomRefresh(sessionAtom);
119
- const revalidateSession = useEffectEvent(async () => {
120
- await refreshSession();
121
- refreshAuth();
122
- });
83
+ const sessionResult = useAtomValue(sessionAtom);
84
+ const wasAuthenticated = useRef(false);
85
+ useEffect(() => {
86
+ if (!AsyncResult.isSuccess(sessionResult) || sessionResult.waiting)
87
+ return;
88
+ if (sessionResult.value) {
89
+ wasAuthenticated.current = true;
90
+ }
91
+ else if (wasAuthenticated.current) {
92
+ // Reset route guards and all nested registries after cross-project logout.
93
+ wasAuthenticated.current = false;
94
+ window.location.reload();
95
+ }
96
+ }, [sessionResult]);
123
97
  useEffect(() => {
124
98
  setProjectContextCookie(resolvedProjectId);
125
99
  }, [resolvedProjectId]);
126
- useEffect(() => listenForSessionRevalidation(window, () => {
127
- void revalidateSession();
128
- }), []);
129
- useEffect(() => listenForAuthChanges(() => {
130
- void revalidateSession();
131
- }), []);
132
100
  const value = useMemo(() => ({
133
101
  baseUrl,
134
102
  locale,
@@ -136,18 +104,7 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
136
104
  projectConfig,
137
105
  access: access ?? null,
138
106
  accessLabels: accessLabels ?? null,
139
- authRefreshVersion,
140
- refreshAuth,
141
- }), [
142
- baseUrl,
143
- locale,
144
- resolvedProjectId,
145
- projectConfig,
146
- access,
147
- accessLabels,
148
- authRefreshVersion,
149
- refreshAuth,
150
- ]);
107
+ }), [baseUrl, locale, resolvedProjectId, projectConfig, access, accessLabels]);
151
108
  return (_jsx(KrakstackAuthContext.Provider, { value: value, children: children }));
152
109
  }
153
110
  export const useKrakstackAuth = () => useContext(KrakstackAuthContext);
@@ -1,13 +1,13 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomRefresh, useAtomSet, useAtomSuspense, } from "@effect/atom-react";
2
+ import { useAtomSet, useAtomSuspense } from "@effect/atom-react";
3
3
  import { Effect, Schema } from "effect";
4
4
  import { Atom } from "effect/unstable/reactivity";
5
5
  import { Check, Loader2, Mail, ShieldAlert } from "lucide-react";
6
- import { useEffect, useRef, useState } from "react";
6
+ import { useState } from "react";
7
7
  import { Button } from "@/components/ui/button";
8
8
  import { CopyButton } from "@krak-stack/registry/copy-button";
9
9
  import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card";
10
- import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
10
+ import { authSessionAtom, notifyAuthChange, refreshOnAuthChange, } from "./auth-atoms.js";
11
11
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
12
12
  import { useKrakstackAuth } from "./auth-provider.js";
13
13
  import { AuthForbidden } from "../auth/schema.js";
@@ -90,10 +90,12 @@ const organizationProfileAtom = Atom.family((baseUrl) => Atom.family((key) => {
90
90
  serializationKey: `member-organization-profile:${key}`,
91
91
  });
92
92
  }));
93
- const invitationsAtom = Atom.family((baseUrl) => Atom.family((accessKey) => authClientApi(baseUrl).query("auth", "organizationListUserInvitations", {
93
+ const invitationsAtom = Atom.family((baseUrl) => Atom.family((accessKey) => authClientApi(baseUrl)
94
+ .query("auth", "organizationListUserInvitations", {
94
95
  query: {},
95
96
  serializationKey: `member-invitations:${accessKey}`,
96
- })));
97
+ })
98
+ .pipe(refreshOnAuthChange)));
97
99
  const accessAtom = Atom.family((baseUrl) => Atom.family((key) => {
98
100
  const AccessKey = Schema.fromJsonString(Schema.Struct({
99
101
  baseUrl: Schema.optional(Schema.String),
@@ -132,7 +134,7 @@ const accessAtom = Atom.family((baseUrl) => Atom.family((key) => {
132
134
  organization,
133
135
  invitation: invitations.find((item) => invitationMatches(item, organizationId)) ?? null,
134
136
  };
135
- }))));
137
+ })))).pipe(refreshOnAuthChange);
136
138
  }));
137
139
  const accessAtomKey = ({ baseUrl, locale, organizationId, userId, }) => JSON.stringify({
138
140
  baseUrl,
@@ -143,9 +145,7 @@ const accessAtomKey = ({ baseUrl, locale, organizationId, userId, }) => JSON.str
143
145
  export function MemberRequired({ organizationId, contactEmail, children, messages, }) {
144
146
  const auth = useKrakstackAuth();
145
147
  const baseUrl = auth?.baseUrl;
146
- const authRefreshVersion = auth?.authRefreshVersion ?? 0;
147
148
  const locale = auth?.locale;
148
- const refreshAuth = auth?.refreshAuth;
149
149
  const session = useAtomSuspense(authSessionAtom(baseUrl), {
150
150
  suspendOnWaiting: false,
151
151
  }).value;
@@ -156,13 +156,11 @@ export function MemberRequired({ organizationId, contactEmail, children, message
156
156
  organizationId,
157
157
  userId,
158
158
  });
159
- return (_jsx(MemberRequiredGate, { accessKey: currentAccessKey, authRefreshVersion: authRefreshVersion, baseUrl: baseUrl, contactEmail: contactEmail, locale: locale, messages: messages, organizationId: organizationId, refreshAuth: refreshAuth, children: children }));
159
+ return (_jsx(MemberRequiredGate, { accessKey: currentAccessKey, baseUrl: baseUrl, contactEmail: contactEmail, locale: locale, messages: messages, organizationId: organizationId, children: children }));
160
160
  }
161
- function MemberRequiredGate({ accessKey, authRefreshVersion, baseUrl, contactEmail, children, locale, messages, organizationId, refreshAuth, }) {
161
+ function MemberRequiredGate({ accessKey, baseUrl, contactEmail, children, locale, messages, organizationId, }) {
162
162
  const m = labels(locale, messages);
163
163
  const queryAtom = accessAtom(baseUrl)(accessKey);
164
- const refreshAccess = useAtomRefresh(queryAtom);
165
- const lastAuthRefreshVersion = useRef(authRefreshVersion);
166
164
  const accessResult = useAtomSuspense(queryAtom, {
167
165
  suspendOnWaiting: false,
168
166
  });
@@ -171,12 +169,6 @@ function MemberRequiredGate({ accessKey, authRefreshVersion, baseUrl, contactEma
171
169
  const [error, setError] = useState(null);
172
170
  const access = accessResult.value;
173
171
  const invitationNow = useInvitationExpirationClock(access.allowed || !access.invitation ? [] : [access.invitation]);
174
- useEffect(() => {
175
- if (lastAuthRefreshVersion.current === authRefreshVersion)
176
- return;
177
- lastAuthRefreshVersion.current = authRefreshVersion;
178
- refreshAccess();
179
- }, [authRefreshVersion, refreshAccess]);
180
172
  if (access.allowed)
181
173
  return _jsx(_Fragment, { children: children });
182
174
  const { invitation, organization } = access;
@@ -200,10 +192,6 @@ function MemberRequiredGate({ accessKey, authRefreshVersion, baseUrl, contactEma
200
192
  : m.member_required_accept_error);
201
193
  },
202
194
  onSuccess: () => {
203
- if (refreshAuth)
204
- refreshAuth();
205
- else
206
- refreshAccess();
207
195
  setAccepting(false);
208
196
  },
209
197
  });
@@ -4,7 +4,7 @@ import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
4
  import { Effect, Option, Predicate, Schema } from "effect";
5
5
  import { AsyncResult, Atom } from "effect/unstable/reactivity";
6
6
  import { ArrowLeft, Building2, Check, ChevronsUpDown, Copy, KeyRound, LogOut, Mail, PencilIcon, Plus, Trash2, UserIcon, UserPlus, Users, X, } from "lucide-react";
7
- import { createContext, useContext, useEffect, useEffectEvent, useRef, useState, } from "react";
7
+ import { createContext, useContext, useEffect, useRef, useState, } from "react";
8
8
  import { DataTable, DataTableListSummary, DataTableRelationshipCell, } from "@krak-stack/registry/data-table";
9
9
  import { CheckboxField, ImageField, SelectField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
10
10
  import { EditingLocaleSwitcher } from "@krak-stack/registry/editing-locale-switcher";
@@ -19,7 +19,7 @@ import { Separator } from "@/components/ui/separator";
19
19
  import { OrganizationEmail, OrganizationAddress, OrganizationMetadata, OrganizationPhone, OrganizationSocial, OrganizationTranslation, OrganizationWebsite, decodeOrganizationMetadata, } from "@krak-stack/auth/schema";
20
20
  import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles.js";
21
21
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
22
- import { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, notifyAuthChange, } from "./auth-atoms.js";
22
+ import { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, notifyAuthChange, refreshOnAuthChange, } from "./auth-atoms.js";
23
23
  import { useKrakstackAuth } from "./auth-provider.js";
24
24
  import { parseApiKeyReferrers } from "./api-key.js";
25
25
  import { ApiKeyPermissions } from "./api-key-permissions.js";
@@ -359,11 +359,13 @@ const normalizeInvitationRole = (role) => {
359
359
  const normalized = normalizeOrganizationRole(role);
360
360
  return normalized === "support" ? "member" : normalized;
361
361
  };
362
- const userInvitationsAtom = Atom.family((baseUrl) => authClientApi(baseUrl).query("auth", "organizationListUserInvitations", {
362
+ const userInvitationsAtom = Atom.family((baseUrl) => authClientApi(baseUrl)
363
+ .query("auth", "organizationListUserInvitations", {
363
364
  query: {},
364
365
  timeToLive: "1 minute",
365
366
  reactivityKeys: ["auth-user-invitations"],
366
- }));
367
+ })
368
+ .pipe(refreshOnAuthChange));
367
369
  const invitationOrganizationProfileAtom = Atom.family((baseUrl) => Atom.family((organizationId) => Atom.family((locale) => authClientApi(baseUrl).query("authExtra", "getOrganizationPublicProfile", {
368
370
  query: { locale, organizationId },
369
371
  timeToLive: "5 minutes",
@@ -737,19 +739,14 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
737
739
  onFailure: () => m.organization_switcher_empty(),
738
740
  onSuccess: () => null,
739
741
  });
740
- const refreshSession = useAtomRefresh(sessionAtom);
741
- const refreshOrganizations = useAtomRefresh(organizationsAtom);
742
- const refreshActiveOrganization = useAtomRefresh(activeOrganizationAtom);
743
742
  const setActiveOrganization = (organizationId) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationSetActive({
744
743
  payload: { organizationId },
745
744
  })));
746
- const lastAuthRefreshVersion = useRef(auth?.authRefreshVersion ?? 0);
747
745
  const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
748
746
  const [editingOrganizationLocale, setEditingOrganizationLocale] = useState(currentOrganizationLocale);
749
747
  const dialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
750
748
  const invitationsAtom = userInvitationsAtom(baseUrl);
751
749
  const invitationsResult = useAtomValue(invitationsAtom);
752
- const refreshUserInvitations = useAtomRefresh(invitationsAtom);
753
750
  const userInvitations = AsyncResult.match(invitationsResult, {
754
751
  onInitial: () => [],
755
752
  onFailure: () => [],
@@ -776,21 +773,6 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
776
773
  onDialogChange?.(nextDialog);
777
774
  };
778
775
  const openCreate = () => setDialog("create");
779
- const refresh = async () => {
780
- refreshOrganizations();
781
- refreshActiveOrganization();
782
- refreshSession();
783
- };
784
- const refreshOnSessionChanged = useEffectEvent(() => {
785
- void refresh();
786
- });
787
- useEffect(() => {
788
- const version = auth?.authRefreshVersion ?? 0;
789
- if (version === lastAuthRefreshVersion.current)
790
- return;
791
- lastAuthRefreshVersion.current = version;
792
- refreshOnSessionChanged();
793
- }, [auth?.authRefreshVersion]);
794
776
  if (!session) {
795
777
  return _jsx(_Fragment, { children: renderUnauthenticated?.() });
796
778
  }
@@ -808,13 +790,11 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
808
790
  Boolean(organizationsError) ||
809
791
  canSwitchOrganizations;
810
792
  const refreshAfterInvitationAction = async (previousActiveId) => {
811
- refreshUserInvitations();
812
- await refresh();
793
+ notifyAuthChange();
813
794
  if (!canSwitchOrganizations && previousActiveId) {
814
795
  try {
815
796
  await Effect.runPromise(setActiveOrganization(previousActiveId));
816
797
  notifyAuthChange();
817
- await refresh();
818
798
  onChange?.(organizations.find((organization) => organization.id === previousActiveId) ?? null);
819
799
  }
820
800
  catch {
@@ -841,7 +821,6 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
841
821
  if (!result)
842
822
  return;
843
823
  notifyAuthChange();
844
- await refresh();
845
824
  onChange?.(organization);
846
825
  }
847
826
  catch {
@@ -868,23 +847,21 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
868
847
  try {
869
848
  await Effect.runPromise(setActiveOrganization(organization.id));
870
849
  activated = true;
871
- notifyAuthChange();
872
850
  }
873
851
  catch {
874
852
  // Creation succeeded even if activating the organization did not.
875
853
  }
876
- await refresh();
854
+ notifyAuthChange();
877
855
  if (activated) {
878
856
  onCreate?.(organization);
879
857
  onChange?.(organization);
880
858
  }
881
859
  } }) }), _jsx(Dialog, { open: dialog === "manage" && canUpdateOrganization, onOpenChange: (open) => {
882
860
  setDialog((current) => open ? "manage" : current === "manage" ? null : current);
883
- }, children: activeOrganization && canUpdateOrganization ? (_jsx(EditOrganizationSection, { header: _jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_switcher_manage() }), _jsx(DialogDescription, { children: m.organization_edit_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), baseUrl: baseUrl, editingLocale: editingOrganizationLocale, organization: activeOrganization, onUpdated: refresh })) : null }), _jsx(Dialog, { open: dialog === "members", onOpenChange: (open) => {
861
+ }, children: activeOrganization && canUpdateOrganization ? (_jsx(EditOrganizationSection, { header: _jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_switcher_manage() }), _jsx(DialogDescription, { children: m.organization_edit_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), baseUrl: baseUrl, editingLocale: editingOrganizationLocale, organization: activeOrganization })) : null }), _jsx(Dialog, { open: dialog === "members", onOpenChange: (open) => {
884
862
  setDialog((current) => open ? "members" : current === "members" ? null : current);
885
- }, children: _jsx(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: activeOrganization ? (_jsx(OrganizationMembersManager, { baseUrl: baseUrl, canManageMembers: canManageApiKeys, organization: activeOrganization, currentUserId: session.user.id, active: dialog === "members", onLeft: async () => {
863
+ }, children: _jsx(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: activeOrganization ? (_jsx(OrganizationMembersManager, { baseUrl: baseUrl, canManageMembers: canManageApiKeys, organization: activeOrganization, currentUserId: session.user.id, active: dialog === "members", onLeft: () => {
886
864
  setDialog(null);
887
- await refresh();
888
865
  onChange?.(null);
889
866
  } })) : null }) }), _jsx(Dialog, { open: dialog === "apiKeys" && canManageApiKeys, onOpenChange: (open) => {
890
867
  setDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
@@ -910,7 +887,6 @@ function UserInvitationsManager({ baseUrl, invitations, loading, error, activeOr
910
887
  await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationAcceptInvitation({
911
888
  payload: { invitationId: invitation.id },
912
889
  }))));
913
- notifyAuthChange();
914
890
  await onActionComplete(activeOrganizationId);
915
891
  }
916
892
  catch (cause) {
@@ -1010,7 +986,7 @@ const userInvitationRowActions = ({ m, actingInvitationId, now, onAccept, onReje
1010
986
  onClick: onReject,
1011
987
  },
1012
988
  ];
1013
- function EditOrganizationSection({ header, baseUrl, editingLocale, organization, onUpdated, }) {
989
+ function EditOrganizationSection({ header, baseUrl, editingLocale, organization, }) {
1014
990
  const m = useOrganizationMessages();
1015
991
  const [defaultLocale] = useState(currentOrganizationLocale);
1016
992
  const defaultValues = organizationFormDefaults(organization, baseUrl);
@@ -1036,10 +1012,6 @@ function EditOrganizationSection({ header, baseUrl, editingLocale, organization,
1036
1012
  },
1037
1013
  });
1038
1014
  yield* Effect.sync(notifyAuthChange);
1039
- yield* Effect.tryPromise({
1040
- try: onUpdated,
1041
- catch: (cause) => cause,
1042
- });
1043
1015
  return updated;
1044
1016
  }).pipe(Effect.mapError((cause) => cause instanceof Error
1045
1017
  ? cause
@@ -1302,7 +1274,7 @@ function OrganizationMembersManager({ baseUrl, canManageMembers, organization, c
1302
1274
  payload: { organizationId: organization.id },
1303
1275
  }))));
1304
1276
  notifyAuthChange();
1305
- await onLeft();
1277
+ onLeft();
1306
1278
  }
1307
1279
  catch (cause) {
1308
1280
  setError(organizationFailureMessage(cause, m.organization_member_leave_error()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krak-stack/auth",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "description": "Effect HttpApi clients and schemas for KrakStack Auth.",
5
5
  "license": "MIT",
6
6
  "files": [