@krak-stack/auth 0.2.15 → 0.2.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth/schema.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
+
export declare const AuthRedirectURLFromString: (origin?: string) => Schema.decodeTo<Schema.URL, Schema.String, never, never>;
|
|
2
3
|
export declare const AuthUser: Schema.Struct<{
|
|
3
4
|
readonly id: Schema.String;
|
|
4
5
|
readonly name: Schema.String;
|
package/dist/auth/schema.js
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
1
|
+
import { Effect, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
|
2
2
|
import { User, UserMetadata } from "../schema.js";
|
|
3
3
|
const JsonRecord = Schema.Record(Schema.String, Schema.Json);
|
|
4
4
|
const StringArrayRecord = Schema.Record(Schema.String, Schema.Array(Schema.String));
|
|
5
|
+
export const AuthRedirectURLFromString = (origin = "http://localhost") => Schema.String.pipe(Schema.decodeTo(Schema.URL.check(Schema.makeFilter((url) => (url.protocol === "http:" || url.protocol === "https:") &&
|
|
6
|
+
!url.username &&
|
|
7
|
+
!url.password
|
|
8
|
+
? undefined
|
|
9
|
+
: "Expected an HTTP or HTTPS redirect URL without credentials")), SchemaTransformation.transformOrFail({
|
|
10
|
+
decode: (value) => Effect.try({
|
|
11
|
+
try: () => new URL(value, origin),
|
|
12
|
+
catch: () => new SchemaIssue.InvalidValue({ message: "Invalid authentication redirect URL" }, value),
|
|
13
|
+
}),
|
|
14
|
+
encode: (url) => Effect.succeed(url.href),
|
|
15
|
+
}))).annotate({ identifier: "AuthRedirectURLFromString" });
|
|
5
16
|
export const AuthUser = Schema.Struct({
|
|
6
17
|
id: Schema.String,
|
|
7
18
|
name: Schema.String,
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { useNavigate } from "@tanstack/react-router";
|
|
1
|
+
import { useNavigate, useRouter } from "@tanstack/react-router";
|
|
2
2
|
import { type KrakstackAuthLocale } from "./auth-provider.js";
|
|
3
3
|
type AuthFormProps = {
|
|
4
4
|
baseUrl?: string | undefined;
|
|
5
5
|
locale?: KrakstackAuthLocale | undefined;
|
|
6
|
+
defaultRedirectTo?: string | undefined;
|
|
6
7
|
};
|
|
7
8
|
type AuthMethod = "password" | "emailOtp";
|
|
8
9
|
export declare const resolveInitialAuthMethod: ({ requestedMethod, lastLoginMethod, emailPassword, emailOtp, }: {
|
|
@@ -16,5 +17,12 @@ export declare function VerifyEmail(props: AuthFormProps): import("react").JSX.E
|
|
|
16
17
|
export declare function ForgotPassword(props: AuthFormProps): import("react").JSX.Element;
|
|
17
18
|
export declare function ResetPassword(props: AuthFormProps): import("react").JSX.Element;
|
|
18
19
|
export declare function TwoFactor(props: AuthFormProps): import("react").JSX.Element;
|
|
20
|
+
export declare const getRedirectTarget: (searchString: string, defaultRedirectTo?: string) => string;
|
|
21
|
+
export declare const getSocialRedirectTarget: (searchString: string, defaultRedirectTo?: string, origin?: string) => string;
|
|
22
|
+
export declare const getSocialSignInDestinations: (router: ReturnType<typeof useRouter>, defaultRedirectTo: string | undefined, browserHref: string) => {
|
|
23
|
+
callbackURL: string;
|
|
24
|
+
errorCallbackURL: string;
|
|
25
|
+
oauthQuery: string | null;
|
|
26
|
+
};
|
|
19
27
|
export declare const navigateTarget: (target: string, navigate: ReturnType<typeof useNavigate>) => Promise<void> | undefined;
|
|
20
28
|
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { useAtomSet, useAtomSuspense, useAtomValue } from "@effect/atom-react";
|
|
3
3
|
import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
|
|
4
|
-
import { Link, useNavigate, useRouterState } from "@tanstack/react-router";
|
|
4
|
+
import { Link, useNavigate, useRouter, useRouterState, } from "@tanstack/react-router";
|
|
5
5
|
import { Effect, Option, Schema } from "effect";
|
|
6
6
|
import { Atom, AsyncResult } from "effect/unstable/reactivity";
|
|
7
7
|
import { HttpClientError } from "effect/unstable/http";
|
|
@@ -18,7 +18,7 @@ import { authClientApi, authHttpClient } from "./auth-client-api.js";
|
|
|
18
18
|
import { useKrakstackAuth } from "./auth-provider.js";
|
|
19
19
|
import { cn } from "./utils.js";
|
|
20
20
|
import { ExtraProjectPublicConfig as ExtraProjectPublicConfigSchema, } from "../extra/schema.js";
|
|
21
|
-
import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, } from "../auth/schema.js";
|
|
21
|
+
import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, AuthRedirectURLFromString, } from "../auth/schema.js";
|
|
22
22
|
const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
|
|
23
23
|
const signinFormBuilder = FormBuilder.empty
|
|
24
24
|
.addField("email", Schema.String)
|
|
@@ -257,13 +257,13 @@ export const resolveInitialAuthMethod = ({ requestedMethod, lastLoginMethod, ema
|
|
|
257
257
|
};
|
|
258
258
|
export function Signin(props) {
|
|
259
259
|
const { baseUrl, locale, labels: m, projectConfig: providedProjectConfig, } = useAuthFormOptions(props);
|
|
260
|
+
const router = useRouter();
|
|
260
261
|
const navigate = useNavigate();
|
|
261
262
|
const searchString = useRouterState({
|
|
262
263
|
select: (state) => state.location.searchStr,
|
|
263
264
|
});
|
|
264
265
|
const projectConfig = useAuthProjectConfig(baseUrl, searchString, providedProjectConfig);
|
|
265
|
-
const redirectTarget = getRedirectTarget(searchString,
|
|
266
|
-
const socialRedirectTarget = getSocialRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
|
|
266
|
+
const redirectTarget = getRedirectTarget(searchString, props.defaultRedirectTo);
|
|
267
267
|
const initialEmail = getSearchParam(searchString, "email")?.trim() ?? "";
|
|
268
268
|
const oauthQuery = getOAuthQuery(searchString);
|
|
269
269
|
const authOptions = projectConfig?.authOptions;
|
|
@@ -385,19 +385,19 @@ export function Signin(props) {
|
|
|
385
385
|
}));
|
|
386
386
|
const submit = useAtomSet(form.submit);
|
|
387
387
|
const submitResult = useAtomValue(form.submit);
|
|
388
|
-
const [socialSignIn] = useState(() => authClientApi(baseUrl).runtime.fn((
|
|
389
|
-
const payload = oauthQuery
|
|
388
|
+
const [socialSignIn] = useState(() => authClientApi(baseUrl).runtime.fn((input) => Effect.gen(function* () {
|
|
389
|
+
const payload = input.oauthQuery
|
|
390
390
|
? {
|
|
391
|
-
provider,
|
|
392
|
-
callbackURL:
|
|
393
|
-
errorCallbackURL:
|
|
394
|
-
additionalData: { query: oauthQuery },
|
|
395
|
-
oauth_query: oauthQuery,
|
|
391
|
+
provider: "google",
|
|
392
|
+
callbackURL: input.callbackURL,
|
|
393
|
+
errorCallbackURL: input.errorCallbackURL,
|
|
394
|
+
additionalData: { query: input.oauthQuery },
|
|
395
|
+
oauth_query: input.oauthQuery,
|
|
396
396
|
}
|
|
397
397
|
: {
|
|
398
|
-
provider,
|
|
399
|
-
callbackURL:
|
|
400
|
-
errorCallbackURL:
|
|
398
|
+
provider: "google",
|
|
399
|
+
callbackURL: input.callbackURL,
|
|
400
|
+
errorCallbackURL: input.errorCallbackURL,
|
|
401
401
|
};
|
|
402
402
|
const result = yield* authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.signInSocial({ payload })));
|
|
403
403
|
notifyAuthChange();
|
|
@@ -452,7 +452,7 @@ export function Signin(props) {
|
|
|
452
452
|
setErrorContext("sendEmailOtp");
|
|
453
453
|
submit({ type: "sendEmailOtp" });
|
|
454
454
|
};
|
|
455
|
-
const signInWithGoogle = () => startSocialSignIn(
|
|
455
|
+
const signInWithGoogle = () => startSocialSignIn(getSocialSignInDestinations(router, props.defaultRedirectTo, window.location.href));
|
|
456
456
|
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) => {
|
|
457
457
|
event.preventDefault();
|
|
458
458
|
event.stopPropagation();
|
|
@@ -498,13 +498,12 @@ export function Signin(props) {
|
|
|
498
498
|
: 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] })] }));
|
|
499
499
|
}
|
|
500
500
|
export function VerifyEmail(props) {
|
|
501
|
-
const { baseUrl, locale, labels: m
|
|
501
|
+
const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
|
|
502
502
|
const navigate = useNavigate();
|
|
503
503
|
const searchString = useRouterState({
|
|
504
504
|
select: (state) => state.location.searchStr,
|
|
505
505
|
});
|
|
506
|
-
const
|
|
507
|
-
const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
|
|
506
|
+
const redirectTarget = getRedirectTarget(searchString, props.defaultRedirectTo);
|
|
508
507
|
const onNavigate = (target) => navigateTarget(target, navigate);
|
|
509
508
|
const [resent, setResent] = useState(false);
|
|
510
509
|
const [lastAction, setLastAction] = useState("verify");
|
|
@@ -620,13 +619,12 @@ function ResetPasswordForm({ token, ...props }) {
|
|
|
620
619
|
}, children: [_jsx(form.password, { label: m.reset_password_new_password, type: "password", autoComplete: "new-password", minLength: 8, required: true }), _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: { fallback: m.reset_password_error } }), _jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, effectFormMessages().submit] })] }) }) })] }));
|
|
621
620
|
}
|
|
622
621
|
export function TwoFactor(props) {
|
|
623
|
-
const { baseUrl, locale, labels: m
|
|
622
|
+
const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
|
|
624
623
|
const navigate = useNavigate();
|
|
625
624
|
const searchString = useRouterState({
|
|
626
625
|
select: (state) => state.location.searchStr,
|
|
627
626
|
});
|
|
628
|
-
const
|
|
629
|
-
const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
|
|
627
|
+
const redirectTarget = getRedirectTarget(searchString, props.defaultRedirectTo);
|
|
630
628
|
const oauthQuery = getOAuthQuery(searchString);
|
|
631
629
|
const onNavigate = (target) => navigateTarget(target, navigate);
|
|
632
630
|
const [mode, setMode] = useState("totp");
|
|
@@ -713,18 +711,46 @@ const TwoFactorRedirect = Schema.Struct({ twoFactorRedirect: Schema.Boolean });
|
|
|
713
711
|
const RedirectResult = Schema.Struct({ url: Schema.String });
|
|
714
712
|
const hasTwoFactorRedirect = (data) => Option.exists(Schema.decodeUnknownOption(TwoFactorRedirect)(data), (result) => result.twoFactorRedirect);
|
|
715
713
|
const getResultRedirectUrl = (data) => Option.map(Schema.decodeUnknownOption(RedirectResult)(data), (result) => result.url).pipe(Option.getOrNull);
|
|
716
|
-
const getRedirectTarget = (searchString,
|
|
714
|
+
export const getRedirectTarget = (searchString, defaultRedirectTo = "/") => {
|
|
717
715
|
const oauthTarget = getOAuthAuthorizeTarget(searchString);
|
|
718
716
|
if (oauthTarget)
|
|
719
717
|
return oauthTarget;
|
|
720
|
-
|
|
721
|
-
|
|
718
|
+
const decode = Schema.decodeUnknownOption(AuthRedirectURLFromString());
|
|
719
|
+
const target = getAuthRedirectParam(searchString);
|
|
720
|
+
if (target && Option.isSome(decode(target)))
|
|
721
|
+
return target;
|
|
722
|
+
return Option.isSome(decode(defaultRedirectTo)) ? defaultRedirectTo : "/";
|
|
722
723
|
};
|
|
723
|
-
const getSocialRedirectTarget = (searchString,
|
|
724
|
+
export const getSocialRedirectTarget = (searchString, defaultRedirectTo = "/", origin = globalThis.window?.location.origin) => {
|
|
724
725
|
const oauthTarget = getOAuthAuthorizeTargetWithoutPromptLogin(searchString);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
726
|
+
const target = oauthTarget ?? getRedirectTarget(searchString, defaultRedirectTo);
|
|
727
|
+
// A relative callback is otherwise resolved against the auth backend, which
|
|
728
|
+
// may be a different origin from the site displaying the sign-in form.
|
|
729
|
+
if (!origin)
|
|
730
|
+
return target;
|
|
731
|
+
return Schema.decodeUnknownOption(AuthRedirectURLFromString(origin))(target).pipe(Option.map((url) => url.href), Option.getOrElse(() => origin));
|
|
732
|
+
};
|
|
733
|
+
export const getSocialSignInDestinations = (router, defaultRedirectTo = "/", browserHref) => {
|
|
734
|
+
const browserURL = Schema.decodeUnknownSync(AuthRedirectURLFromString())(browserHref);
|
|
735
|
+
const searchString = router.state.location.searchStr;
|
|
736
|
+
const defaultTarget = getRedirectTarget("", defaultRedirectTo);
|
|
737
|
+
const defaultURL = Schema.decodeUnknownSync(AuthRedirectURLFromString(browserURL.origin))(defaultTarget);
|
|
738
|
+
const defaultHref = Option.isSome(Schema.decodeUnknownOption(Schema.URLFromString)(defaultTarget))
|
|
739
|
+
? defaultTarget
|
|
740
|
+
: router.buildLocation({
|
|
741
|
+
to: defaultURL.pathname,
|
|
742
|
+
search: Object.fromEntries(defaultURL.searchParams),
|
|
743
|
+
hash: defaultURL.hash.slice(1),
|
|
744
|
+
}).publicHref;
|
|
745
|
+
// Resolve at click time so router rewrites use the current locale. Error
|
|
746
|
+
// callbacks return to the actual browser-facing sign-in route, not a guessed
|
|
747
|
+
// locale-prefixed path.
|
|
748
|
+
browserURL.searchParams.delete("error");
|
|
749
|
+
return {
|
|
750
|
+
callbackURL: getSocialRedirectTarget(searchString, defaultHref, browserURL.origin),
|
|
751
|
+
errorCallbackURL: browserURL.href,
|
|
752
|
+
oauthQuery: getOAuthQuery(searchString),
|
|
753
|
+
};
|
|
728
754
|
};
|
|
729
755
|
const getOAuthAuthorizeTarget = (searchString) => {
|
|
730
756
|
if (!searchString)
|
|
@@ -774,9 +800,6 @@ const getAuthRedirectParam = (searchString) => {
|
|
|
774
800
|
search.get("redirectTo") ??
|
|
775
801
|
search.get("returnTo"));
|
|
776
802
|
};
|
|
777
|
-
const getDefaultAuthRedirectTarget = (_projectAuthDomain, _projectRootDomain) => {
|
|
778
|
-
return "/admin";
|
|
779
|
-
};
|
|
780
803
|
const getSearchParam = (searchString, key) => new URLSearchParams(searchString).get(key);
|
|
781
804
|
const getBrowserAuthHost = () => globalThis.window?.location.host ?? null;
|
|
782
805
|
export const navigateTarget = (target, navigate) => {
|
|
@@ -13,7 +13,6 @@ export declare class KrakstackAuthUnavailableError extends KrakstackAuthUnavaila
|
|
|
13
13
|
}
|
|
14
14
|
export type KrakstackAuthProviderProps = {
|
|
15
15
|
children: ReactNode;
|
|
16
|
-
locale?: KrakstackAuthLocale | undefined;
|
|
17
16
|
baseUrl?: string | undefined;
|
|
18
17
|
projectId?: string | null | undefined;
|
|
19
18
|
access?: ProjectAccessCatalog | undefined;
|
|
@@ -35,7 +34,8 @@ type ProjectConfigState = {
|
|
|
35
34
|
projectConfig: ExtraProjectPublicConfig | null;
|
|
36
35
|
};
|
|
37
36
|
export declare const resolveProjectConfigState: (result: AsyncResult.AsyncResult<ExtraProjectPublicConfig | null, unknown>) => ProjectConfigState;
|
|
38
|
-
export declare
|
|
37
|
+
export declare const resolveKrakstackAuthLocale: (locale: string) => KrakstackAuthLocale;
|
|
38
|
+
export declare function KrakstackAuthProvider({ children, baseUrl, projectId, access, accessLabels, }: KrakstackAuthProviderProps): import("react").JSX.Element;
|
|
39
39
|
export declare const useKrakstackAuth: () => KrakstackAuthContextValue | null;
|
|
40
40
|
export declare const useKrakstackAuthProjectConfig: () => {
|
|
41
41
|
readonly projectKey: string;
|
|
@@ -4,6 +4,7 @@ import { useRouterState } from "@tanstack/react-router";
|
|
|
4
4
|
import { Cause, Option, Schema } from "effect";
|
|
5
5
|
import { HttpApiError } from "effect/unstable/httpapi";
|
|
6
6
|
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
|
7
|
+
import { useKrakstackLocale } from "@krak-stack/registry/krakstack-provider";
|
|
7
8
|
import { createContext, useContext, useEffect, useMemo, useRef, } from "react";
|
|
8
9
|
import { activeAuthOrganizationAtom, authSessionAtom } from "./auth-atoms.js";
|
|
9
10
|
import { authClientApi } from "./auth-client-api.js";
|
|
@@ -70,6 +71,7 @@ export const resolveProjectConfigState = (result) => {
|
|
|
70
71
|
}
|
|
71
72
|
return { status: "loading", error: null, projectConfig: null };
|
|
72
73
|
};
|
|
74
|
+
export const resolveKrakstackAuthLocale = (locale) => (locale.startsWith("fr") ? "fr" : "en");
|
|
73
75
|
const useProjectConfigState = (baseUrl, providedProjectId) => {
|
|
74
76
|
const searchString = useRouterState({
|
|
75
77
|
select: (state) => state.location.searchStr,
|
|
@@ -104,7 +106,8 @@ const useProjectConfigState = (baseUrl, providedProjectId) => {
|
|
|
104
106
|
const result = useAtomValue(projectConfigAtom);
|
|
105
107
|
return useMemo(() => resolveProjectConfigState(result), [result]);
|
|
106
108
|
};
|
|
107
|
-
export function KrakstackAuthProvider({ children,
|
|
109
|
+
export function KrakstackAuthProvider({ children, baseUrl, projectId, access, accessLabels, }) {
|
|
110
|
+
const locale = resolveKrakstackAuthLocale(useKrakstackLocale());
|
|
108
111
|
const searchString = useRouterState({
|
|
109
112
|
select: (state) => state.location.searchStr,
|
|
110
113
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krak-stack/auth",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.17",
|
|
4
4
|
"description": "Effect HttpApi clients and schemas for KrakStack Auth.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"files": [
|
|
@@ -76,11 +76,14 @@
|
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
78
|
"@effect/atom-react": "4.0.0-rc.112",
|
|
79
|
-
"@krak-stack/registry": "^0.1.33",
|
|
80
79
|
"@lucas-barake/effect-form-react": "0.26.0-beta.5",
|
|
81
80
|
"react-qr-code": "^2.2.0"
|
|
82
81
|
},
|
|
82
|
+
"devDependencies": {
|
|
83
|
+
"@krak-stack/registry": "0.1.35"
|
|
84
|
+
},
|
|
83
85
|
"peerDependencies": {
|
|
86
|
+
"@krak-stack/registry": "^0.1.35",
|
|
84
87
|
"@tanstack/react-router": "^1.170.15",
|
|
85
88
|
"effect": "4.0.0-rc.112",
|
|
86
89
|
"input-otp": "^1.5.0",
|