@krak-stack/auth 0.2.9 → 0.2.11

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,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.11",
4
4
  "description": "Effect HttpApi clients and schemas for KrakStack Auth.",
5
5
  "license": "MIT",
6
6
  "files": [