@krak-stack/auth 0.2.31 → 0.3.0

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +175 -1
  3. package/dist/access.d.ts +3 -1
  4. package/dist/admin/api.group.d.ts +41 -41
  5. package/dist/admin/schema.d.ts +23 -23
  6. package/dist/admin/schema.js +21 -19
  7. package/dist/api.d.ts +141 -81
  8. package/dist/auth/api.group.d.ts +37 -19
  9. package/dist/auth/api.group.js +17 -1
  10. package/dist/auth/schema.d.ts +61 -33
  11. package/dist/auth/schema.js +30 -18
  12. package/dist/components/account-deletion-request.d.ts +5 -0
  13. package/dist/components/account-deletion-request.js +7 -0
  14. package/dist/components/account-deletion.d.ts +8 -0
  15. package/dist/components/account-deletion.js +59 -0
  16. package/dist/components/admin-organization-form.js +2 -2
  17. package/dist/components/admin-organizations.js +9 -7
  18. package/dist/components/admin-users.js +6 -6
  19. package/dist/components/api-key-edit-form.js +19 -11
  20. package/dist/components/associated-projects-notice.d.ts +2 -1
  21. package/dist/components/associated-projects-notice.js +7 -3
  22. package/dist/components/auth-atoms.js +1 -2
  23. package/dist/components/auth-client-api.d.ts +94 -61
  24. package/dist/components/auth-forms.d.ts +1 -0
  25. package/dist/components/auth-forms.js +41 -56
  26. package/dist/components/auth-provider.d.ts +3 -1
  27. package/dist/components/deletion-visibility.d.ts +1 -0
  28. package/dist/components/deletion-visibility.js +3 -0
  29. package/dist/components/hooks.d.ts +2 -0
  30. package/dist/components/hooks.js +13 -6
  31. package/dist/components/index.d.ts +3 -0
  32. package/dist/components/index.js +2 -0
  33. package/dist/components/member-required.js +3 -5
  34. package/dist/components/oauth-consent.d.ts +22 -0
  35. package/dist/components/oauth-consent.js +79 -0
  36. package/dist/components/organization-deletion-request.d.ts +17 -0
  37. package/dist/components/organization-deletion-request.js +9 -0
  38. package/dist/components/organization-switcher.d.ts +1 -1
  39. package/dist/components/organization-switcher.js +113 -55
  40. package/dist/components/project-card-list.d.ts +6 -0
  41. package/dist/components/project-card-list.js +4 -0
  42. package/dist/components/user-button.d.ts +29 -1
  43. package/dist/components/user-button.js +145 -47
  44. package/dist/extra/api.group.d.ts +13 -1
  45. package/dist/extra/api.group.js +5 -1
  46. package/dist/extra/schema.d.ts +16 -1
  47. package/dist/extra/schema.js +13 -0
  48. package/dist/oauth/authorization.d.ts +3 -0
  49. package/dist/oauth/authorization.js +39 -0
  50. package/dist/oauth/schema.d.ts +24 -0
  51. package/dist/oauth/schema.js +12 -0
  52. package/dist/oauth/verify.d.ts +13 -0
  53. package/dist/oauth/verify.js +67 -0
  54. package/dist/schema.d.ts +35 -0
  55. package/dist/schema.js +26 -1
  56. package/dist/server/actor.js +2 -4
  57. package/dist/server/index.d.ts +4 -1
  58. package/dist/server/index.js +2 -0
  59. package/dist/server/mcp.d.ts +20 -0
  60. package/dist/server/mcp.js +66 -0
  61. package/dist/server/middleware.d.ts +15 -7
  62. package/dist/server/middleware.js +19 -6
  63. package/dist/server/webhook-layer.d.ts +6 -0
  64. package/dist/server/webhook-layer.js +41 -0
  65. package/dist/server/webhooks.d.ts +44 -0
  66. package/dist/server/webhooks.js +39 -0
  67. package/dist/service.d.ts +118 -46
  68. package/dist/service.js +56 -9
  69. package/package.json +8 -3
@@ -1,7 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { RegistryContext, useAtomSet, useAtomSuspense, useAtomValue, } from "@effect/atom-react";
3
3
  import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
- import { Link, useNavigate, useRouter, useRouterState, } from "@tanstack/react-router";
4
+ import { defaultParseSearch, Link, useNavigate, useRouter, useRouterState, } from "@tanstack/react-router";
5
5
  import { Effect, Option, Schema } from "effect";
6
6
  import { Atom, AsyncResult } from "effect/reactivity";
7
7
  import { HttpClientError } from "effect/http";
@@ -21,6 +21,7 @@ import { passwordResetSearch, passwordResetConfirmation, passwordResetConfirmati
21
21
  import { PasswordResetActions, PasswordResetFeedback, usePasswordResetRequest, } from "./password-reset-flow.js";
22
22
  import { useKrakstackAuth } from "./auth-provider.js";
23
23
  import { cn } from "./utils.js";
24
+ import { getOAuthAuthorizationQuery } from "../oauth/authorization.js";
24
25
  import { ExtraProjectPublicConfig as ExtraProjectPublicConfigSchema, } from "../extra/schema.js";
25
26
  import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, AuthRedirectURLFromString, } from "../auth/schema.js";
26
27
  const signinFormBuilder = FormBuilder.empty
@@ -245,18 +246,18 @@ const useAuthProjectConfig = (baseUrl, searchString, projectConfig) => {
245
246
  const result = useAtomSuspense(atom, { suspendOnWaiting: true });
246
247
  return result.value === null
247
248
  ? null
248
- : Schema.decodeUnknownSync(ExtraProjectPublicConfigSchema)(result.value);
249
+ : Schema.decodeSync(ExtraProjectPublicConfigSchema)(result.value);
249
250
  };
250
251
  const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
251
252
  const authLinkClassName = cn(buttonVariants({ variant: "link", size: null }), "h-auto align-baseline");
252
- const authMethodSearch = (searchString, method, email) => {
253
+ export const authMethodSearch = (searchString, method, email) => {
253
254
  const search = new URLSearchParams(searchString);
254
255
  search.set("method", method);
255
256
  if (email?.trim())
256
257
  search.set("email", email.trim());
257
258
  else if (email !== undefined)
258
259
  search.delete("email");
259
- return Object.fromEntries(search);
260
+ return defaultParseSearch(search.toString());
260
261
  };
261
262
  export const resolveInitialAuthMethod = ({ requestedMethod, lastLoginMethod, emailPassword, emailOtp, }) => {
262
263
  if (requestedMethod === "password" && emailPassword)
@@ -303,8 +304,10 @@ export function Signin(props) {
303
304
  const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(() => initialMethodStep && initialAuthMethod === "emailOtp"
304
305
  ? Date.now() + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000
305
306
  : 0);
306
- const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
307
- const otpSendsRef = useRef(new Map(initialMethodStep && initialAuthMethod === "emailOtp"
307
+ const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(initialMethodStep && initialAuthMethod === "emailOtp"
308
+ ? EMAIL_OTP_RESEND_COOLDOWN_SECONDS
309
+ : 0);
310
+ const [otpSendsAtom] = useState(() => Atom.make(new Map(initialMethodStep && initialAuthMethod === "emailOtp"
308
311
  ? [
309
312
  [
310
313
  initialEmail,
@@ -312,7 +315,7 @@ export function Signin(props) {
312
315
  EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000,
313
316
  ],
314
317
  ]
315
- : []));
318
+ : [])));
316
319
  const [errorContext, setErrorContext] = useState("signIn");
317
320
  const selectedAuthMethod = authMethod === "password" && options.emailPassword
318
321
  ? "password"
@@ -322,17 +325,14 @@ export function Signin(props) {
322
325
  const hasPrimaryAuth = options.emailPassword || options.emailOtp;
323
326
  const canChangeAuthMethod = options.emailPassword && options.emailOtp;
324
327
  useEffect(() => {
325
- if (!emailOtpResendAvailableAt) {
326
- setEmailOtpResendSeconds(0);
328
+ if (!emailOtpResendAvailableAt)
327
329
  return;
328
- }
329
330
  const updateResendSeconds = () => {
330
331
  const seconds = getEmailOtpResendSeconds(emailOtpResendAvailableAt, Date.now());
331
332
  setEmailOtpResendSeconds(seconds);
332
333
  if (seconds === 0)
333
334
  setEmailOtpResendAvailableAt(0);
334
335
  };
335
- updateResendSeconds();
336
336
  const interval = window.setInterval(updateResendSeconds, 1000);
337
337
  return () => window.clearInterval(interval);
338
338
  }, [emailOtpResendAvailableAt]);
@@ -340,7 +340,7 @@ export function Signin(props) {
340
340
  runtime: authClientApi(baseUrl).runtime,
341
341
  fields: { email: TextField, password: PasswordField, otp: OtpField },
342
342
  mode: { validation: "onSubmit" },
343
- onSubmit: (action, { decoded: value }) => Effect.gen(function* () {
343
+ onSubmit: (action, { decoded: value, get }) => Effect.gen(function* () {
344
344
  const email = value.email.trim();
345
345
  if (action.type === "resetPassword") {
346
346
  yield* requestPasswordResetEmail({
@@ -358,10 +358,10 @@ export function Signin(props) {
358
358
  const sendEmailOtpRequest = authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
359
359
  payload: { email, type: "sign-in" },
360
360
  })), Effect.asVoid, Effect.tap(() => Effect.sync(() => {
361
- otpSendsRef.current.set(email, Date.now());
361
+ get.set(otpSendsAtom, new Map(get(otpSendsAtom)).set(email, Date.now()));
362
362
  })));
363
363
  const sendEmailOtp = (shouldSendEmailOtp({
364
- sentAt: otpSendsRef.current.get(email),
364
+ sentAt: get(otpSendsAtom).get(email),
365
365
  now: Date.now(),
366
366
  resend: action.type === "resendEmailOtp",
367
367
  })
@@ -370,13 +370,15 @@ export function Signin(props) {
370
370
  setAuthMethod("emailOtp");
371
371
  setEmailSubmitted(true);
372
372
  setOtpSentTo(email);
373
- navigate({
373
+ void navigate({
374
374
  to: "/sign-in",
375
375
  search: authMethodSearch(searchString, "emailOtp", email),
376
376
  replace: true,
377
377
  });
378
- setEmailOtpResendAvailableAt((otpSendsRef.current.get(email) ?? 0) +
379
- EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
378
+ const availableAt = (get(otpSendsAtom).get(email) ?? 0) +
379
+ EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000;
380
+ setEmailOtpResendAvailableAt(availableAt);
381
+ setEmailOtpResendSeconds(getEmailOtpResendSeconds(availableAt, Date.now()));
380
382
  })));
381
383
  if (action.type === "sendEmailOtp" ||
382
384
  action.type === "resendEmailOtp") {
@@ -388,7 +390,7 @@ export function Signin(props) {
388
390
  yield* sendEmailOtp;
389
391
  else {
390
392
  setEmailSubmitted(true);
391
- navigate({
393
+ void navigate({
392
394
  to: "/sign-in",
393
395
  search: authMethodSearch(searchString, "password", email),
394
396
  replace: true,
@@ -409,7 +411,7 @@ export function Signin(props) {
409
411
  },
410
412
  })));
411
413
  yield* refreshAuthSession(registry, baseUrl);
412
- onNavigate(redirectTarget);
414
+ yield* Effect.promise(() => Promise.resolve(onNavigate(redirectTarget)));
413
415
  return;
414
416
  }
415
417
  const payload = oauthQuery
@@ -426,11 +428,11 @@ export function Signin(props) {
426
428
  };
427
429
  const result = yield* authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.signInEmail({ payload })));
428
430
  if (hasTwoFactorRedirect(result)) {
429
- onTwoFactorRedirect(`/2fa${oauthQuery ? `?${oauthQuery}` : `?callbackURL=${encodeURIComponent(redirectTarget)}`}`);
431
+ yield* Effect.promise(() => Promise.resolve(onTwoFactorRedirect(`/2fa${oauthQuery ? `?${oauthQuery}` : `?callbackURL=${encodeURIComponent(redirectTarget)}`}`)));
430
432
  return;
431
433
  }
432
434
  yield* refreshAuthSession(registry, baseUrl);
433
- onNavigate(result.url ?? redirectTarget);
435
+ yield* Effect.promise(() => Promise.resolve(onNavigate(result.url ?? redirectTarget)));
434
436
  }),
435
437
  }));
436
438
  const submit = useAtomSet(form.submit);
@@ -451,8 +453,9 @@ export function Signin(props) {
451
453
  };
452
454
  const result = yield* authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.signInSocial({ payload })));
453
455
  notifyAuthChange();
454
- if (result.url)
455
- onNavigate(result.url);
456
+ const redirectUrl = result.url;
457
+ if (redirectUrl)
458
+ yield* Effect.promise(() => Promise.resolve(onNavigate(redirectUrl)));
456
459
  })));
457
460
  const startSocialSignIn = useAtomSet(socialSignIn);
458
461
  const socialSignInResult = useAtomValue(socialSignIn);
@@ -472,7 +475,7 @@ export function Signin(props) {
472
475
  setEmailSubmitted(false);
473
476
  setOtpSentTo("");
474
477
  setEmailOtpResendAvailableAt(0);
475
- navigate({
478
+ void navigate({
476
479
  to: "/sign-in",
477
480
  search: authMethodSearch(searchString, selectedAuthMethod, ""),
478
481
  replace: true,
@@ -485,7 +488,7 @@ export function Signin(props) {
485
488
  resetForm();
486
489
  setEmail(formValues.email);
487
490
  setAuthMethod("password");
488
- navigate({
491
+ void navigate({
489
492
  to: "/sign-in",
490
493
  search: authMethodSearch(searchString, "password", formValues.email),
491
494
  replace: true,
@@ -596,7 +599,7 @@ export function VerifyEmail(props) {
596
599
  },
597
600
  })));
598
601
  yield* refreshAuthSession(registry, baseUrl);
599
- onNavigate(redirectTarget);
602
+ yield* Effect.promise(() => Promise.resolve(onNavigate(redirectTarget)));
600
603
  }),
601
604
  }));
602
605
  const submit = useAtomSet(form.submit);
@@ -690,7 +693,7 @@ function ResetPasswordForm({ token, ...props }) {
690
693
  token,
691
694
  });
692
695
  notifyAuthChange();
693
- onSuccess();
696
+ yield* Effect.promise(() => Promise.resolve(onSuccess()));
694
697
  }),
695
698
  }));
696
699
  const submit = useAtomSet(form.submit);
@@ -745,7 +748,7 @@ export function TwoFactor(props) {
745
748
  payload: verification,
746
749
  })));
747
750
  yield* refreshAuthSession(registry, baseUrl);
748
- onNavigate(getResultRedirectUrl(result) ?? redirectTarget);
751
+ yield* Effect.promise(() => Promise.resolve(onNavigate(getResultRedirectUrl(result) ?? redirectTarget)));
749
752
  }),
750
753
  }));
751
754
  const submit = useAtomSet(form.submit);
@@ -812,14 +815,14 @@ export const getSocialRedirectTarget = (searchString, defaultRedirectTo = "/", o
812
815
  // may be a different origin from the site displaying the sign-in form.
813
816
  if (!origin)
814
817
  return target;
815
- return Schema.decodeUnknownOption(AuthRedirectURLFromString(origin))(target).pipe(Option.map((url) => url.href), Option.getOrElse(() => origin));
818
+ return Schema.decodeOption(AuthRedirectURLFromString(origin))(target).pipe(Option.map((url) => url.href), Option.getOrElse(() => origin));
816
819
  };
817
820
  export const getSocialSignInDestinations = (router, defaultRedirectTo = "/", browserHref) => {
818
- const browserURL = Schema.decodeUnknownSync(AuthRedirectURLFromString())(browserHref);
821
+ const browserURL = Schema.decodeSync(AuthRedirectURLFromString())(browserHref);
819
822
  const searchString = router.state.location.searchStr;
820
823
  const defaultTarget = getRedirectTarget("", defaultRedirectTo);
821
- const defaultURL = Schema.decodeUnknownSync(AuthRedirectURLFromString(browserURL.origin))(defaultTarget);
822
- const defaultHref = Option.isSome(Schema.decodeUnknownOption(Schema.URLFromString)(defaultTarget))
824
+ const defaultURL = Schema.decodeSync(AuthRedirectURLFromString(browserURL.origin))(defaultTarget);
825
+ const defaultHref = Option.isSome(Schema.decodeOption(Schema.URLFromString)(defaultTarget))
823
826
  ? defaultTarget
824
827
  : router.buildLocation({
825
828
  to: defaultURL.pathname,
@@ -837,19 +840,14 @@ export const getSocialSignInDestinations = (router, defaultRedirectTo = "/", bro
837
840
  };
838
841
  };
839
842
  const getOAuthAuthorizeTarget = (searchString) => {
840
- if (!searchString)
841
- return null;
842
- const search = new URLSearchParams(searchString);
843
- if (!search.has("sig"))
844
- return null;
845
- return `/api/auth/oauth2/authorize${searchString}`;
843
+ const query = getOAuthAuthorizationQuery(searchString);
844
+ return query ? `/api/auth/oauth2/authorize?${query}` : null;
846
845
  };
847
846
  const getOAuthAuthorizeTargetWithoutPromptLogin = (searchString) => {
848
- if (!searchString)
849
- return null;
850
- const search = new URLSearchParams(searchString);
851
- if (!search.has("sig"))
847
+ const query = getOAuthAuthorizationQuery(searchString);
848
+ if (!query)
852
849
  return null;
850
+ const search = new URLSearchParams(query);
853
851
  const prompts = search
854
852
  .get("prompt")
855
853
  ?.split(" ")
@@ -863,20 +861,7 @@ const getOAuthAuthorizeTargetWithoutPromptLogin = (searchString) => {
863
861
  const nextSearchString = search.toString();
864
862
  return `/api/auth/oauth2/authorize${nextSearchString ? `?${nextSearchString}` : ""}`;
865
863
  };
866
- const getOAuthQuery = (searchString) => {
867
- if (!searchString)
868
- return null;
869
- const search = new URLSearchParams(searchString);
870
- if (!search.has("sig"))
871
- return null;
872
- const signedSearch = new URLSearchParams();
873
- for (const [key, value] of search.entries()) {
874
- signedSearch.append(key, value);
875
- if (key === "sig")
876
- break;
877
- }
878
- return signedSearch.toString();
879
- };
864
+ const getOAuthQuery = getOAuthAuthorizationQuery;
880
865
  const getAuthRedirectParam = (searchString) => {
881
866
  const search = new URLSearchParams(searchString);
882
867
  return (search.get("callbackURL") ??
@@ -7,7 +7,9 @@ export type KrakstackAuthLocale = "en" | "fr";
7
7
  export type KrakstackAuthStatus = "loading" | "ready" | "degraded" | "error";
8
8
  declare const KrakstackAuthUnavailableError_base: Schema.Class<KrakstackAuthUnavailableError, Schema.TaggedStruct<"KrakstackAuthUnavailableError", {
9
9
  readonly cause: Schema.Defect;
10
- }>, Cause.YieldableError>;
10
+ }>, Cause.YieldableError & {
11
+ readonly brand: unique symbol;
12
+ }>;
11
13
  export declare class KrakstackAuthUnavailableError extends KrakstackAuthUnavailableError_base {
12
14
  readonly status = 503;
13
15
  }
@@ -0,0 +1 @@
1
+ export declare const deletionControlsEnabled: boolean;
@@ -0,0 +1,3 @@
1
+ // Temporary rollout gate: the consuming app's production build hides deletion UI.
2
+ // This is not authorization; deletion endpoints retain their server-side checks.
3
+ export const deletionControlsEnabled = import.meta.env.DEV;
@@ -1 +1,3 @@
1
+ import { Atom } from "effect/reactivity";
2
+ export declare const useLatestAtom: <A>(value: A) => Atom.Writable<A, A>;
1
3
  export declare const useOpenedOnce: (open: boolean) => boolean;
@@ -1,9 +1,16 @@
1
- import { useEffect, useState } from "react";
1
+ import { useLayoutEffect, useState } from "react";
2
+ import { useAtomSet } from "@effect/atom-react";
3
+ import { Atom } from "effect/reactivity";
4
+ // Stable submission-time input for form instances retained across renders.
5
+ export const useLatestAtom = (value) => {
6
+ const [atom] = useState(() => Atom.make(value));
7
+ const set = useAtomSet(atom);
8
+ useLayoutEffect(() => set(value), [set, value]);
9
+ return atom;
10
+ };
2
11
  export const useOpenedOnce = (open) => {
3
12
  const [opened, setOpened] = useState(open);
4
- useEffect(() => {
5
- if (open)
6
- setOpened(true);
7
- }, [open]);
8
- return opened;
13
+ if (open && !opened)
14
+ setOpened(true);
15
+ return opened || open;
9
16
  };
@@ -1,6 +1,9 @@
1
1
  export { KrakstackAuthProvider, KrakstackAuthRequired, KrakstackAuthUnavailableError, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
2
2
  export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
3
3
  export { OrganizationSwitcher } from "./organization-switcher.js";
4
+ export { OAuthConsent } from "./oauth-consent.js";
5
+ export { getOAuthAuthorizationQuery } from "../oauth/authorization.js";
6
+ export type { OAuthConsentMessages } from "./oauth-consent.js";
4
7
  export { MemberRequired } from "./member-required.js";
5
8
  export { HasPermission, useHasPermission } from "./has-permission.js";
6
9
  export { ProjectAccessMatrix } from "./project-access-matrix.js";
@@ -1,6 +1,8 @@
1
1
  export { KrakstackAuthProvider, KrakstackAuthRequired, KrakstackAuthUnavailableError, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
2
2
  export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
3
3
  export { OrganizationSwitcher } from "./organization-switcher.js";
4
+ export { OAuthConsent } from "./oauth-consent.js";
5
+ export { getOAuthAuthorizationQuery } from "../oauth/authorization.js";
4
6
  export { MemberRequired } from "./member-required.js";
5
7
  export { HasPermission, useHasPermission } from "./has-permission.js";
6
8
  export { ProjectAccessMatrix } from "./project-access-matrix.js";
@@ -82,7 +82,7 @@ const organizationProfileAtom = Atom.family((baseUrl) => Atom.family((key) => {
82
82
  locale: Schema.optional(Schema.Literals(["en", "fr"])),
83
83
  organizationId: Schema.String,
84
84
  }));
85
- const { locale, organizationId } = Schema.decodeUnknownSync(ProfileKey)(key);
85
+ const { locale, organizationId } = Schema.decodeSync(ProfileKey)(key);
86
86
  const query = locale ? { organizationId, locale } : { organizationId };
87
87
  return authClientApi(baseUrl).query("authExtra", "getOrganizationPublicProfile", {
88
88
  query,
@@ -103,14 +103,12 @@ const accessAtom = Atom.family((baseUrl) => Atom.family((key) => {
103
103
  organizationId: Schema.String,
104
104
  userId: Schema.optional(Schema.String),
105
105
  }));
106
- const { locale, organizationId } = Schema.decodeUnknownSync(AccessKey)(key);
106
+ const { locale, organizationId } = Schema.decodeSync(AccessKey)(key);
107
107
  return Atom.optimistic(Atom.keepAlive(authClientApi(baseUrl).runtime.atom((get) => Effect.gen(function* () {
108
108
  const client = yield* authHttpClient(baseUrl);
109
109
  const allowed = yield* client.auth
110
110
  .organizationSetActive({ payload: { organizationId } })
111
- .pipe(Effect.as(true), Effect.catch((error) => error instanceof AuthForbidden
112
- ? Effect.succeed(false)
113
- : Effect.fail(error)));
111
+ .pipe(Effect.as(true), Effect.catchIf((error) => error instanceof AuthForbidden, () => Effect.succeed(false)));
114
112
  if (allowed) {
115
113
  get.refresh(authSessionAtom(baseUrl));
116
114
  return { allowed: true };
@@ -0,0 +1,22 @@
1
+ export type OAuthConsentMessages = {
2
+ readonly title: string;
3
+ readonly description: (input: {
4
+ clientName: string;
5
+ }) => string;
6
+ readonly requestedScopes: string;
7
+ readonly allow: string;
8
+ readonly deny: string;
9
+ readonly error: string;
10
+ readonly invalidRequest: string;
11
+ readonly notice?: string;
12
+ readonly permissions?: Readonly<Record<string, {
13
+ readonly title: string;
14
+ readonly description?: string;
15
+ }>>;
16
+ };
17
+ /** Shared login-provider-aware consent. The signed OAuth query is sent intact;
18
+ * the provider, not the component, validates scopes, grants and callbacks. */
19
+ export declare const OAuthConsent: ({ messages, baseUrl: providedBaseUrl, }: {
20
+ readonly messages: OAuthConsentMessages;
21
+ readonly baseUrl?: string;
22
+ }) => import("react").JSX.Element;
@@ -0,0 +1,79 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useAtomSet, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
3
+ import { useRouterState } from "@tanstack/react-router";
4
+ import { Effect, Option, Schema } from "effect";
5
+ import { AsyncResult, Atom } from "effect/reactivity";
6
+ import { useMemo } from "react";
7
+ import { Bot, BookOpen, KeyRound, Mail, Pencil, RefreshCw, UserRound, } from "lucide-react";
8
+ import { Button } from "@/components/ui/button";
9
+ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card";
10
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
11
+ import { useKrakstackAuth } from "./auth-provider.js";
12
+ import { getOAuthAuthorizationQuery } from "../oauth/authorization.js";
13
+ const ConsentSearch = Schema.Struct({
14
+ client_id: Schema.NonEmptyString,
15
+ sig: Schema.NonEmptyString,
16
+ scope: Schema.optional(Schema.String),
17
+ }).annotate({ identifier: "OAuthConsentSearch" });
18
+ const scopeIcon = (scope) => {
19
+ switch (scope) {
20
+ case "mcp:read":
21
+ return BookOpen;
22
+ case "mcp:write":
23
+ return Pencil;
24
+ case "offline_access":
25
+ return RefreshCw;
26
+ case "openid":
27
+ case "profile":
28
+ return UserRound;
29
+ case "email":
30
+ return Mail;
31
+ default:
32
+ return KeyRound;
33
+ }
34
+ };
35
+ const clientAtom = Atom.family((baseUrl) => Atom.family((clientId) => authClientApi(baseUrl).query("auth", "oauthPublicClient", {
36
+ query: { client_id: clientId },
37
+ timeToLive: "5 minutes",
38
+ })));
39
+ const makeConsentAtom = (baseUrl, search) => {
40
+ const oauthQuery = getOAuthAuthorizationQuery(search) ?? "";
41
+ const scope = new URLSearchParams(oauthQuery).get("scope") ?? "";
42
+ return Atom.fn((accept) => authHttpClient(baseUrl).pipe(Effect.flatMap((api) => api.auth.oauthConsent({
43
+ payload: { accept, scope, oauth_query: oauthQuery },
44
+ }))));
45
+ };
46
+ /** Shared login-provider-aware consent. The signed OAuth query is sent intact;
47
+ * the provider, not the component, validates scopes, grants and callbacks. */
48
+ export const OAuthConsent = ({ messages, baseUrl: providedBaseUrl, }) => {
49
+ const auth = useKrakstackAuth();
50
+ const baseUrl = providedBaseUrl ?? auth?.baseUrl;
51
+ const search = useRouterState({
52
+ select: (state) => state.location.searchStr,
53
+ });
54
+ const oauthQuery = getOAuthAuthorizationQuery(search);
55
+ const decoded = Schema.decodeUnknownOption(ConsentSearch)(Object.fromEntries(new URLSearchParams(oauthQuery ?? "")));
56
+ const clientId = Option.isSome(decoded) ? decoded.value.client_id : "";
57
+ const scope = Option.isSome(decoded) ? (decoded.value.scope ?? "") : "";
58
+ const client = useAtomValue(clientAtom(baseUrl)(clientId));
59
+ const clientName = AsyncResult.isSuccess(client)
60
+ ? client.value.client_name || client.value.client_id
61
+ : clientId;
62
+ // A fresh atom per signed request prevents decisions/results leaking between
63
+ // successive consent screens for different agents or grants.
64
+ const submitAtom = useMemo(() => makeConsentAtom(baseUrl, search), [baseUrl, search]);
65
+ const submit = useAtomSet(submitAtom);
66
+ const result = useAtomValue(submitAtom);
67
+ useAtomSubscribe(submitAtom, (result) => {
68
+ if (AsyncResult.isSuccess(result))
69
+ window.location.assign(result.value.url);
70
+ });
71
+ const invalid = Option.isNone(decoded) || oauthQuery === null;
72
+ return (_jsxs(Card, { className: "w-full max-w-md rounded-2xl shadow-sm", children: [_jsxs(CardHeader, { className: "items-center gap-3 text-center", children: [_jsx("div", { className: "bg-primary/10 text-primary mx-auto flex size-12 items-center justify-center rounded-2xl", children: _jsx(Bot, { className: "size-6", "aria-hidden": "true" }) }), _jsx(CardTitle, { className: "text-xl", children: messages.title }), _jsx(CardDescription, { className: "text-pretty", children: invalid
73
+ ? messages.invalidRequest
74
+ : messages.description({ clientName }) })] }), _jsxs(CardContent, { className: "space-y-4", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: messages.requestedScopes }), _jsx("ul", { className: "space-y-2", children: Array.from(new Set(scope.split(/\s+/).filter(Boolean))).map((scope) => {
75
+ const permission = messages.permissions?.[scope];
76
+ const Icon = scopeIcon(scope);
77
+ return (_jsxs("li", { className: "bg-muted/50 flex items-start gap-3 rounded-xl p-3", children: [_jsx(Icon, { className: "text-muted-foreground mt-0.5 size-4 shrink-0", "aria-hidden": "true" }), _jsxs("div", { className: "space-y-0.5", children: [_jsx("p", { className: "text-sm font-medium", children: permission?.title ?? scope }), permission?.description && (_jsx("p", { className: "text-muted-foreground text-xs leading-relaxed", children: permission.description }))] })] }, scope));
78
+ }) }), AsyncResult.isFailure(result) && _jsx("p", { role: "alert", children: messages.error })] }), _jsxs(CardFooter, { className: "flex-col gap-2", children: [messages.notice && (_jsx("p", { className: "text-muted-foreground mb-2 text-center text-xs", children: messages.notice })), _jsx(Button, { disabled: invalid || result.waiting, onClick: () => submit(true), className: "w-full", children: messages.allow }), _jsx(Button, { disabled: invalid || result.waiting, variant: "ghost", onClick: () => submit(false), className: "w-full", children: messages.deny })] })] }));
79
+ };
@@ -0,0 +1,17 @@
1
+ import { Effect } from "effect";
2
+ import type { AuthMember, FullAuthOrganization } from "../auth/schema.js";
3
+ export declare const canDeleteOrganization: (organization: (Pick<FullAuthOrganization, "userId"> & {
4
+ readonly members: ReadonlyArray<Pick<AuthMember, "userId" | "role">>;
5
+ }) | null, userId: string | undefined) => boolean;
6
+ export declare const requestOrganizationDeletion: (organizationId: string, baseUrl?: string) => Effect.Effect<{
7
+ readonly id: string;
8
+ readonly name: string;
9
+ readonly slug: string;
10
+ readonly logo?: string | null | undefined;
11
+ readonly metadata?: string | {
12
+ readonly [x: string]: import("effect/Schema").Json;
13
+ } | null | undefined;
14
+ readonly userId?: string | null | undefined;
15
+ readonly parentId?: string | null | undefined;
16
+ readonly createdAt: Date;
17
+ }, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized | import("effect/http/HttpClientError").HttpClientError | import("effect/Schema").SchemaError, never>;
@@ -0,0 +1,9 @@
1
+ import { Effect } from "effect";
2
+ import { parseRoleList } from "../roles.js";
3
+ import { authHttpClient } from "./auth-client-api.js";
4
+ export const canDeleteOrganization = (organization, userId) => Boolean(organization &&
5
+ !organization.userId &&
6
+ userId &&
7
+ organization.members.some((member) => member.userId === userId &&
8
+ parseRoleList(member.role).includes("owner")));
9
+ export const requestOrganizationDeletion = (organizationId, baseUrl) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationDelete({ payload: { organizationId } })));
@@ -312,7 +312,7 @@ type OrganizationSummary = {
312
312
  id: string;
313
313
  name: string;
314
314
  slug: string;
315
- metadata?: unknown | undefined;
315
+ metadata?: unknown;
316
316
  userId?: string | null | undefined;
317
317
  parentId?: string | null | undefined;
318
318
  };