@krak-stack/auth 0.1.68 → 0.1.70

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.
@@ -5,6 +5,13 @@ type AuthFormProps = {
5
5
  baseUrl?: string | undefined;
6
6
  locale?: KrakstackAuthLocale | undefined;
7
7
  };
8
+ type AuthMethod = "password" | "emailOtp";
9
+ export declare const resolveInitialAuthMethod: ({ requestedMethod, lastLoginMethod, emailPassword, emailOtp, }: {
10
+ requestedMethod: string | null;
11
+ lastLoginMethod: string | null | undefined;
12
+ emailPassword: boolean;
13
+ emailOtp: boolean;
14
+ }) => AuthMethod;
8
15
  export declare function Signin(props: AuthFormProps): import("react").JSX.Element;
9
16
  export declare function VerifyEmail(props: AuthFormProps): import("react").JSX.Element;
10
17
  export declare function ForgotPassword(props: AuthFormProps): import("react").JSX.Element;
@@ -193,6 +193,17 @@ const authMethodSearch = (searchString, method, email) => {
193
193
  search.delete("email");
194
194
  return Object.fromEntries(search);
195
195
  };
196
+ export const resolveInitialAuthMethod = ({ requestedMethod, lastLoginMethod, emailPassword, emailOtp, }) => {
197
+ if (requestedMethod === "password" && emailPassword)
198
+ return "password";
199
+ if (requestedMethod === "emailOtp" && emailOtp)
200
+ return "emailOtp";
201
+ if (lastLoginMethod === "email" && emailPassword)
202
+ return "password";
203
+ if (lastLoginMethod === "email-otp" && emailOtp)
204
+ return "emailOtp";
205
+ return emailOtp ? "emailOtp" : "password";
206
+ };
196
207
  export function Signin(props) {
197
208
  const { authClient, baseUrl, labels: m, projectConfig: providedProjectConfig, } = useAuthFormOptions(props);
198
209
  const navigate = useNavigate();
@@ -213,13 +224,12 @@ export function Signin(props) {
213
224
  google: authOptions?.google ?? true,
214
225
  };
215
226
  const requestedMethod = getSearchParam(searchString, "method");
216
- const initialAuthMethod = requestedMethod === "password" && options.emailPassword
217
- ? "password"
218
- : requestedMethod === "emailOtp" && options.emailOtp
219
- ? "emailOtp"
220
- : options.emailOtp
221
- ? "emailOtp"
222
- : "password";
227
+ const [initialAuthMethod] = useState(() => resolveInitialAuthMethod({
228
+ requestedMethod,
229
+ lastLoginMethod: authClient.getLastUsedLoginMethod?.(),
230
+ emailPassword: options.emailPassword,
231
+ emailOtp: options.emailOtp,
232
+ }));
223
233
  const initialMethodStep = Boolean(initialEmail) && requestedMethod === initialAuthMethod;
224
234
  const [emailSubmitted, setEmailSubmitted] = useState(initialMethodStep);
225
235
  const [authMethod, setAuthMethod] = useState(initialAuthMethod);
@@ -23,6 +23,7 @@ export type KrakstackAuthContextValue = {
23
23
  authRefreshVersion: number;
24
24
  refreshAuth: () => void;
25
25
  };
26
+ export declare const listenForSessionRevalidation: (target: EventTarget, revalidate: () => void) => () => void;
26
27
  export declare function KrakstackAuthProvider({ children, locale, baseUrl, projectId, authClient, access, accessLabels, }: KrakstackAuthProviderProps): import("react").JSX.Element;
27
28
  export declare const useKrakstackAuth: () => KrakstackAuthContextValue | null;
28
29
  export declare const useAuthClient: () => AuthUiClient;
@@ -1,12 +1,22 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useAtomSuspense } from "@effect/atom-react";
3
3
  import { useRouterState } from "@tanstack/react-router";
4
- import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react";
4
+ import { createContext, useCallback, useContext, useEffect, useEffectEvent, useMemo, useState, } from "react";
5
5
  import { createAuthUiClient } from "./auth-client";
6
6
  import { authClientApi } from "./auth-client-api";
7
7
  import { parseRoleList } from "../roles";
8
8
  const KrakstackAuthContext = createContext(null);
9
9
  const PROJECT_CONTEXT_COOKIE = "krakstack-auth.project_context";
10
+ export const listenForSessionRevalidation = (target, revalidate) => {
11
+ const onPageShow = (event) => {
12
+ if ("persisted" in event && event.persisted === true)
13
+ revalidate();
14
+ };
15
+ target.addEventListener("pageshow", onPageShow);
16
+ return () => {
17
+ target.removeEventListener("pageshow", onPageShow);
18
+ };
19
+ };
10
20
  const setProjectContextCookie = (projectId) => {
11
21
  if (typeof document === "undefined")
12
22
  return;
@@ -79,9 +89,17 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
79
89
  const refreshAuth = useCallback(() => {
80
90
  setAuthRefreshVersion((current) => current + 1);
81
91
  }, []);
92
+ const session = resolvedAuthClient.useSession();
93
+ const revalidateSession = useEffectEvent(async () => {
94
+ await session.refetch();
95
+ refreshAuth();
96
+ });
82
97
  useEffect(() => {
83
98
  setProjectContextCookie(resolvedProjectId);
84
99
  }, [resolvedProjectId]);
100
+ useEffect(() => listenForSessionRevalidation(window, () => {
101
+ void revalidateSession();
102
+ }), []);
85
103
  const value = useMemo(() => ({
86
104
  authClient: resolvedAuthClient,
87
105
  baseUrl,
@@ -887,6 +887,7 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
887
887
  const selectableOrganizations = canSwitchOrganizations
888
888
  ? visibleOrganizations.filter((organization) => organization.id !== active?.id)
889
889
  : [];
890
+ const scrollOrganizationList = selectableOrganizations.length > 5;
890
891
  const hasOrganizationListItems = organizations.isPending ||
891
892
  Boolean(organizations.error) ||
892
893
  canSwitchOrganizations;
@@ -909,20 +910,23 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
909
910
  ? activeDisplay.name
910
911
  : m.organization_switcher_label(), subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "min-w-0 flex-1 !p-0 text-left group-data-[collapsible=icon]:flex-none group-data-[collapsible=icon]:justify-start", ...(activeDisplay.image
911
912
  ? { imageSrc: activeDisplay.image }
912
- : {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.image
913
+ : {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "max-w-[calc(100vw-1rem)] min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.image
913
914
  ? { imageSrc: activeDisplay.image }
914
- : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizations.error ? (_jsx(DropdownMenuItem, { disabled: true, children: organizations.error.message })) : null, canSwitchOrganizations && selectableOrganizations.length ? (selectableOrganizations.map((organization) => {
915
- const display = organizationDisplay(organization, m, baseUrl);
916
- return (_jsx(DropdownMenuItem, { onClick: async () => {
917
- const result = await authClient.organization.setActive({
918
- organizationId: organization.id,
919
- });
920
- if (!result.error) {
921
- await refresh();
922
- onChange?.(organization);
923
- }
924
- }, children: _jsx(AppBrand, { to: null, label: display.name, subtitle: organizationSwitcherSubtitle(organization, display.subtitle, m), icon: Building2, className: "w-full text-left [&>div:first-child]:size-7", ...(display.image ? { imageSrc: display.image } : {}) }) }, organization.id));
925
- })) : canSwitchOrganizations && !organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: active
915
+ : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizations.error ? (_jsx(DropdownMenuItem, { disabled: true, children: organizations.error.message })) : null, canSwitchOrganizations && selectableOrganizations.length ? (_jsx("div", { className: cn(scrollOrganizationList &&
916
+ "max-h-64 overflow-y-auto overscroll-contain"), children: selectableOrganizations.map((organization) => {
917
+ const display = organizationDisplay(organization, m, baseUrl);
918
+ return (_jsx(DropdownMenuItem, { onClick: async () => {
919
+ const result = await authClient.organization.setActive({
920
+ organizationId: organization.id,
921
+ });
922
+ if (!result.error) {
923
+ await refresh();
924
+ onChange?.(organization);
925
+ }
926
+ }, children: _jsx(AppBrand, { to: null, label: display.name, subtitle: organizationSwitcherSubtitle(organization, display.subtitle, m), icon: Building2, className: "w-full text-left [&>div:first-child]:size-7", ...(display.image
927
+ ? { imageSrc: display.image }
928
+ : {}) }) }, organization.id));
929
+ }) })) : canSwitchOrganizations && !organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: active
926
930
  ? m.organization_switcher_no_other_organizations()
927
931
  : m.organization_switcher_empty() })) : null, canCreateOrganization || canViewOrganizationInvitations ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), canCreateOrganization ? (_jsxs(DropdownMenuItem, { onClick: openCreate, children: [_jsx(Plus, {}), m.organization_create_title()] })) : null, canViewOrganizationInvitations ? (_jsxs(DropdownMenuItem, { onClick: () => {
928
932
  setDialog("invitations");
@@ -958,7 +962,7 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
958
962
  auth?.access?.apiKeyPermissions.organization ??
959
963
  {} })) : null }) }), _jsx(Dialog, { open: dialog === "invitations" && canViewOrganizationInvitations, onOpenChange: (open) => {
960
964
  setDialog((current) => open ? "invitations" : current === "invitations" ? null : current);
961
- }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_user_invitations_title() }), _jsx(DialogDescription, { children: m.organization_user_invitations_description() })] }), _jsx(Separator, {}), _jsx(UserInvitationsManager, { authClient: authClient, baseUrl: baseUrl, invitations: userInvitations, loading: loadingUserInvitations, error: userInvitationsError, ...(activeOrganization.data
965
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_user_invitations_title() }), _jsx(DialogDescription, { children: m.organization_user_invitations_description() })] }), _jsx(Separator, {}), _jsx(UserInvitationsManager, { authClient: authClient, baseUrl: baseUrl, invitations: userInvitations, loading: loadingUserInvitations, error: userInvitationsError, ...(activeOrganization.data
962
966
  ? { activeOrganizationId: activeOrganization.data.id }
963
967
  : {}), onActionComplete: refreshAfterInvitationAction })] }) })] }));
964
968
  }
@@ -995,28 +999,28 @@ function UserInvitationsManager({ authClient, baseUrl, invitations, loading, err
995
999
  }
996
1000
  await onActionComplete(activeOrganizationId);
997
1001
  };
998
- return (_jsxs("section", { className: "flex flex-col gap-4", children: [error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, actionError ? (_jsx("p", { className: "text-destructive text-sm", children: actionError })) : null, _jsx(DataTable, { columns: userInvitationColumns({
999
- baseUrl,
1000
- m,
1001
- now: invitationNow,
1002
- }), data: invitations, features: {
1003
- export: { baseName: "organization-invitations" },
1004
- gallery: false,
1005
- rowActions: {
1006
- items: userInvitationRowActions({
1007
- m,
1008
- actingInvitationId,
1009
- now: invitationNow,
1010
- onAccept: acceptInvitation,
1011
- onReject: rejectInvitation,
1012
- }),
1013
- },
1014
- }, searchState: "local", state: {
1015
- empty: loading
1016
- ? m.user_loading()
1017
- : m.organization_user_invitations_empty(),
1018
- loading,
1019
- } })] }));
1002
+ return (_jsxs("section", { className: "flex min-w-0 flex-col gap-4", children: [error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, actionError ? (_jsx("p", { className: "text-destructive text-sm", children: actionError })) : null, _jsx("div", { className: "-m-1 min-w-0 overflow-x-auto p-1", children: _jsx(DataTable, { columns: userInvitationColumns({
1003
+ baseUrl,
1004
+ m,
1005
+ now: invitationNow,
1006
+ }), data: invitations, features: {
1007
+ export: { baseName: "organization-invitations" },
1008
+ gallery: false,
1009
+ rowActions: {
1010
+ items: userInvitationRowActions({
1011
+ m,
1012
+ actingInvitationId,
1013
+ now: invitationNow,
1014
+ onAccept: acceptInvitation,
1015
+ onReject: rejectInvitation,
1016
+ }),
1017
+ },
1018
+ }, searchState: "local", state: {
1019
+ empty: loading
1020
+ ? m.user_loading()
1021
+ : m.organization_user_invitations_empty(),
1022
+ loading,
1023
+ } }) })] }));
1020
1024
  }
1021
1025
  const userInvitationColumns = ({ baseUrl, m, now, }) => [
1022
1026
  {
@@ -90,6 +90,20 @@ const matchesConstraint = (actor, constraint) => {
90
90
  const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.flatMap((actor) => matchesConstraint(actor, constraint)
91
91
  ? Effect.succeed(actor)
92
92
  : Effect.fail(new HttpApiError.Forbidden({}))));
93
+ const withCurrentActor = (httpEffect, actor) => {
94
+ const userId = actor.actor.type === "user"
95
+ ? actor.actor.userId
96
+ : actor.actor.owner.type === "user"
97
+ ? actor.actor.owner.userId
98
+ : undefined;
99
+ const attributes = {
100
+ ...(actor.organizationId
101
+ ? { "organization.id": actor.organizationId }
102
+ : {}),
103
+ ...(userId ? { "user.id": userId } : {}),
104
+ };
105
+ return Effect.annotateCurrentSpan(attributes).pipe(Effect.andThen(httpEffect.pipe(Effect.provideService(CurrentActor, actor), Effect.annotateSpans(attributes), Effect.annotateLogs(attributes))));
106
+ };
93
107
  const actorRequired = (constraint) => {
94
108
  if (!constraint)
95
109
  return AnyActorRequired;
@@ -102,10 +116,10 @@ const actorRequired = (constraint) => {
102
116
  }
103
117
  return ApiKeyActorRequired;
104
118
  };
105
- const actorRequiredLayer = (access) => Layer.mergeAll(Layer.succeed(AnyActorRequired, (httpEffect) => requiredActor(access).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(UserActorRequired, (httpEffect) => requiredActor(access, { type: "user" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(ApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(UserApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey", ownerType: "user" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(OrganizationApiKeyActorRequired, (httpEffect) => requiredActor(access, {
119
+ const actorRequiredLayer = (access) => Layer.mergeAll(Layer.succeed(AnyActorRequired, (httpEffect) => requiredActor(access).pipe(Effect.flatMap((actor) => withCurrentActor(httpEffect, actor)))), Layer.succeed(UserActorRequired, (httpEffect) => requiredActor(access, { type: "user" }).pipe(Effect.flatMap((actor) => withCurrentActor(httpEffect, actor)))), Layer.succeed(ApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey" }).pipe(Effect.flatMap((actor) => withCurrentActor(httpEffect, actor)))), Layer.succeed(UserApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey", ownerType: "user" }).pipe(Effect.flatMap((actor) => withCurrentActor(httpEffect, actor)))), Layer.succeed(OrganizationApiKeyActorRequired, (httpEffect) => requiredActor(access, {
106
120
  type: "apiKey",
107
121
  ownerType: "organization",
108
- }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))));
122
+ }).pipe(Effect.flatMap((actor) => withCurrentActor(httpEffect, actor)))));
109
123
  export const ActorRequired = Object.assign(actorRequired, {
110
124
  layer: actorRequiredLayer,
111
125
  });
@@ -12,9 +12,14 @@ const blockedRequestHeaders = [
12
12
  "transfer-encoding",
13
13
  "upgrade",
14
14
  "cdn-loop",
15
+ "x-krakstack-forwarded-host",
16
+ "x-krakstack-forwarded-proto",
15
17
  ];
16
18
  const hostOnlyCookie = (cookie) => cookie.replace(/;\s*domain=[^;]*/gi, "");
17
- const normalizedCookieDomain = (domain) => domain.trim().toLowerCase().replace(/^\.+|\.+$/g, "");
19
+ const normalizedCookieDomain = (domain) => domain
20
+ .trim()
21
+ .toLowerCase()
22
+ .replace(/^\.+|\.+$/g, "");
18
23
  const sharedCookieDomain = (request, options) => {
19
24
  if (!options?.cookieDomain)
20
25
  return null;
@@ -50,6 +55,8 @@ const proxyResponse = async (request, response, options) => {
50
55
  const forwardedUrl = (request) => {
51
56
  return new URL(request.url);
52
57
  };
58
+ const preservesOAuthOrigin = (pathname) => pathname === "/api/auth/sign-in/social" ||
59
+ pathname.startsWith("/api/auth/callback/");
53
60
  const proxyHeaders = (request) => {
54
61
  const headers = new Headers(request.headers);
55
62
  const url = forwardedUrl(request);
@@ -62,6 +69,10 @@ const proxyHeaders = (request) => {
62
69
  }
63
70
  headers.set("x-forwarded-host", url.host);
64
71
  headers.set("x-forwarded-proto", url.protocol.replace(":", ""));
72
+ if (preservesOAuthOrigin(url.pathname)) {
73
+ headers.set("x-krakstack-forwarded-host", url.host);
74
+ headers.set("x-krakstack-forwarded-proto", url.protocol.replace(":", ""));
75
+ }
65
76
  return headers;
66
77
  };
67
78
  export const proxyAuthRequest = async (request, baseUrl, options) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krak-stack/auth",
3
- "version": "0.1.68",
3
+ "version": "0.1.70",
4
4
  "description": "Effect HttpApi clients and schemas for KrakStack Auth.",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -75,7 +75,7 @@
75
75
  "type:check": "tsc -p tsconfig.json --noEmit"
76
76
  },
77
77
  "dependencies": {
78
- "@krak-stack/registry": "^0.1.1",
78
+ "@krak-stack/registry": "^0.1.6",
79
79
  "react-qr-code": "^2.2.0"
80
80
  },
81
81
  "peerDependencies": {