@cosmicdrift/kumiko-bundled-features 0.404.0 → 0.405.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 (131) hide show
  1. package/dist/auth-email-password/mail-notifications.d.ts +3 -3
  2. package/dist/auth-email-password/mail-notifications.js +10 -34
  3. package/dist/auth-email-password/web/auth-gate.js +4 -0
  4. package/dist/auth-email-password/web/default-topbar-actions.d.ts +6 -1
  5. package/dist/auth-email-password/web/default-topbar-actions.js +2 -2
  6. package/dist/auth-email-password/web/index.d.ts +2 -0
  7. package/dist/auth-email-password/web/index.js +1 -0
  8. package/dist/auth-email-password/web/invite-accept-screen.js +6 -41
  9. package/dist/auth-email-password/web/tenant-label.d.ts +2 -0
  10. package/dist/auth-email-password/web/tenant-label.js +10 -0
  11. package/dist/auth-email-password/web/tenant-menu-items.js +2 -7
  12. package/dist/auth-email-password/web/tenant-switcher.js +5 -12
  13. package/dist/auth-email-password/web/use-redirect-authed-from-login.d.ts +7 -0
  14. package/dist/auth-email-password/web/use-redirect-authed-from-login.js +30 -0
  15. package/dist/auth-foundation/feature.js +8 -21
  16. package/dist/auth-mfa/handlers/reencrypt.job.js +7 -15
  17. package/dist/auth-mfa/hmac-token-codec.d.ts +6 -1
  18. package/dist/auth-mfa/hmac-token-codec.js +8 -10
  19. package/dist/auth-mfa/mfa-challenge-token.js +2 -8
  20. package/dist/auth-mfa/mfa-preauth-setup-token.js +2 -8
  21. package/dist/auth-mfa/mfa-setup-token.d.ts +2 -8
  22. package/dist/auth-mfa/mfa-setup-token.js +8 -45
  23. package/dist/billing-foundation/consumer-protection/termination-revoke.js +3 -11
  24. package/dist/billing-foundation/feature.js +1 -5
  25. package/dist/billing-foundation/handlers/process-event.write.js +2 -6
  26. package/dist/billing-foundation/handlers/process-payment-event.write.js +2 -6
  27. package/dist/billing-foundation/index.d.ts +2 -0
  28. package/dist/billing-foundation/index.js +2 -0
  29. package/dist/billing-foundation/projection.js +12 -21
  30. package/dist/billing-foundation/provider-event-seen.d.ts +5 -0
  31. package/dist/billing-foundation/provider-event-seen.js +7 -0
  32. package/dist/billing-foundation/provider-shared.d.ts +11 -0
  33. package/dist/billing-foundation/provider-shared.js +44 -0
  34. package/dist/billing-foundation/tenant-destroy-hook.js +5 -4
  35. package/dist/channel-email/feature.js +1 -1
  36. package/dist/config/handlers/reencrypt.job.js +7 -15
  37. package/dist/delivery/delivery-service.js +2 -8
  38. package/dist/file-derivatives/feature.js +9 -21
  39. package/dist/file-foundation/feature.js +2 -6
  40. package/dist/files-tenant-data/hooks.js +1 -6
  41. package/dist/folders/feature.js +2 -9
  42. package/dist/folders/web/folder-manager.js +7 -26
  43. package/dist/folders/web/folder-section.js +5 -24
  44. package/dist/form-draft/handlers/save.write.d.ts +9 -0
  45. package/dist/form-draft/handlers/save.write.js +3 -7
  46. package/dist/inbound-mail-foundation/feature.js +2 -6
  47. package/dist/inbound-mail-foundation/handlers/thread-rollup.js +1 -0
  48. package/dist/inbound-mail-foundation/oauth-state.js +5 -13
  49. package/dist/inbound-mail-foundation/tenant-destroy-hook.d.ts +1 -1
  50. package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -18
  51. package/dist/jobs/handlers/tenant-failures.query.js +1 -15
  52. package/dist/jobs/handlers/tenant-runs.query.js +1 -14
  53. package/dist/jobs/job-run-logger.js +19 -23
  54. package/dist/jobs/parse-subject.d.ts +1 -0
  55. package/dist/jobs/parse-subject.js +15 -0
  56. package/dist/ledger/feature.js +2 -8
  57. package/dist/mail-foundation/feature.js +3 -7
  58. package/dist/managed-pages/render-page-body.js +4 -12
  59. package/dist/notes-history/feature.js +2 -9
  60. package/dist/personal-access-tokens/handlers/list.query.js +1 -9
  61. package/dist/personal-access-tokens/hash.js +2 -2
  62. package/dist/personal-access-tokens/parse-scope-names.d.ts +1 -0
  63. package/dist/personal-access-tokens/parse-scope-names.js +10 -0
  64. package/dist/personal-access-tokens/resolver.js +1 -9
  65. package/dist/renderer-foundation/feature.js +3 -14
  66. package/dist/secrets/handlers/rotate.job.js +7 -18
  67. package/dist/shared/collect-extension-options.d.ts +4 -0
  68. package/dist/shared/collect-extension-options.js +8 -0
  69. package/dist/shared/hmac-signature.d.ts +2 -0
  70. package/dist/shared/hmac-signature.js +10 -0
  71. package/dist/shared/index.d.ts +6 -0
  72. package/dist/shared/index.js +6 -0
  73. package/dist/shared/is-unique-constraint-failure.d.ts +2 -0
  74. package/dist/shared/is-unique-constraint-failure.js +7 -0
  75. package/dist/shared/mail-locale-templates.d.ts +12 -0
  76. package/dist/shared/mail-locale-templates.js +36 -0
  77. package/dist/shared/resolve-feature-access.d.ts +7 -0
  78. package/dist/shared/resolve-feature-access.js +8 -0
  79. package/dist/shared/signed-token.js +4 -14
  80. package/dist/shared/single-use-token-store.js +2 -2
  81. package/dist/shared/stream-tenant-derived-state.js +1 -5
  82. package/dist/shared/tenant-db-cache.d.ts +3 -0
  83. package/dist/shared/tenant-db-cache.js +14 -0
  84. package/dist/shared/web/status-banner.d.ts +15 -0
  85. package/dist/shared/web/status-banner.js +13 -0
  86. package/dist/shared/web/use-dispatched-writes.d.ts +8 -0
  87. package/dist/shared/web/use-dispatched-writes.js +29 -0
  88. package/dist/subscription-paddle/feature.js +2 -15
  89. package/dist/subscription-paddle/price-methods.d.ts +2 -5
  90. package/dist/subscription-paddle/price-methods.js +5 -26
  91. package/dist/subscription-paddle/runtime.d.ts +1 -1
  92. package/dist/subscription-paddle/runtime.js +3 -16
  93. package/dist/subscription-stripe/feature.js +2 -17
  94. package/dist/subscription-stripe/plugin-methods.d.ts +2 -5
  95. package/dist/subscription-stripe/plugin-methods.js +3 -18
  96. package/dist/subscription-stripe/runtime.js +3 -19
  97. package/dist/tags/feature.js +2 -9
  98. package/dist/tags/web/tag-manager.js +5 -24
  99. package/dist/tags/web/tag-section.js +3 -12
  100. package/dist/template-resolver/document-sanitizer.js +3 -2
  101. package/dist/template-resolver/handlers/tenant-overrides.query.js +3 -9
  102. package/dist/template-resolver/web/collection-entry-create-form.js +1 -0
  103. package/dist/tenant/handlers/decrypt-member-users.d.ts +10 -0
  104. package/dist/tenant/handlers/decrypt-member-users.js +17 -0
  105. package/dist/tenant/handlers/members.query.js +2 -17
  106. package/dist/tenant/handlers/team-list.query.js +4 -17
  107. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.d.ts +5 -0
  108. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.js +20 -0
  109. package/dist/tenant-lifecycle/index.d.ts +1 -0
  110. package/dist/tenant-lifecycle/index.js +1 -0
  111. package/dist/tier-engine/feature.js +1 -1
  112. package/dist/user-data-rights/build-hook-db.d.ts +11 -0
  113. package/dist/user-data-rights/build-hook-db.js +22 -0
  114. package/dist/user-data-rights/handlers/request-export.write.js +2 -12
  115. package/dist/user-data-rights/mail-notifications.d.ts +3 -3
  116. package/dist/user-data-rights/mail-notifications.js +10 -34
  117. package/dist/user-data-rights/run-forget-cleanup.d.ts +1 -1
  118. package/dist/user-data-rights/run-forget-cleanup.js +2 -21
  119. package/dist/user-data-rights/run-user-export.d.ts +1 -1
  120. package/dist/user-data-rights/run-user-export.js +2 -21
  121. package/dist/user-data-rights/token-helpers.js +2 -14
  122. package/dist/user-data-rights/web/privacy-center-screen.js +1 -11
  123. package/dist/user-data-rights/web/public-deletion-gate.js +1 -0
  124. package/dist/user-profile/web/profile-screen.js +1 -11
  125. package/package.json +35 -35
  126. package/src/auth-email-password/changes.json +6 -0
  127. package/src/auth-mfa/changes.json +6 -0
  128. package/src/billing-foundation/changes.json +6 -0
  129. package/src/documents/changes.json +8 -0
  130. package/src/shared/changes.json +6 -0
  131. package/src/tenant-lifecycle/changes.json +6 -0
@@ -1,4 +1,4 @@
1
- import { type NotificationLocalizedTemplate, type TemplateVariables } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { type TemplateVariables } from "@cosmicdrift/kumiko-framework/engine";
2
2
  export declare const AUTH_MAIL_KINDS: {
3
3
  readonly passwordReset: {
4
4
  readonly name: "password-reset";
@@ -25,8 +25,8 @@ export type AuthMailKind = keyof typeof AUTH_MAIL_KINDS;
25
25
  type MagicLinkFlowOptions = Partial<Record<"passwordReset" | "emailVerification" | "signup" | "invite" | "accountUnlock", unknown>>;
26
26
  export declare function sendsMagicLinkMail(flows: MagicLinkFlowOptions): boolean;
27
27
  export declare const AuthMailNotificationTypes: Readonly<Record<AuthMailKind, string>>;
28
- export declare function authMailTemplateLocale(notificationType: string, requestedLocale: string): string;
28
+ export declare const authMailTemplateLocale: (notificationType: string, requestedLocale: string) => string;
29
29
  export declare const AUTH_MAIL_VARIABLES: TemplateVariables;
30
30
  export declare const INVITE_MAIL_VARIABLES: TemplateVariables;
31
- export declare function authMailLocalizedTemplate(kind: AuthMailKind): () => NotificationLocalizedTemplate;
31
+ export declare const authMailLocalizedTemplate: (kind: "accountUnlock" | "emailVerification" | "invite" | "passwordReset" | "signupActivation") => () => import("@cosmicdrift/kumiko-types/config").NotificationLocalizedTemplate;
32
32
  export {};
@@ -1,6 +1,7 @@
1
1
  import { QnTypes, qn, templateVariable, } from "@cosmicdrift/kumiko-framework/engine";
2
- import { hasMailTranslationKey, listMailLocales, mailT, resolveMailLocale, } from "@cosmicdrift/kumiko-framework/i18n";
2
+ import { mailT } from "@cosmicdrift/kumiko-framework/i18n";
3
3
  import { escapeHtml, escapeHtmlAttr } from "@cosmicdrift/kumiko-renderer/headless";
4
+ import { createMailLocaleTemplates } from "../shared/index.js";
4
5
  import { AUTH_EMAIL_PASSWORD_FEATURE } from "./web/constants.js";
5
6
  export const AUTH_MAIL_KINDS = {
6
7
  passwordReset: { name: "password-reset", translationKey: "reset" },
@@ -36,15 +37,13 @@ const ALL_AUTH_MAIL_KINDS = [
36
37
  "signupActivation",
37
38
  "invite",
38
39
  ];
39
- const SUBJECT_KEY_BY_TYPE = new Map(ALL_AUTH_MAIL_KINDS.map((kind) => [AuthMailNotificationTypes[kind], subjectKey(kind)]));
40
- // A registered locale whose bundle lacks the subject key has no template (see
41
- // authMailLocalizedTemplate); the renderer has no locale fallback, so the
42
- // sender must pick a locale that has one or the mail would not go out at all.
43
- export function authMailTemplateLocale(notificationType, requestedLocale) {
44
- const locale = resolveMailLocale(requestedLocale);
45
- const key = SUBJECT_KEY_BY_TYPE.get(notificationType);
46
- return key !== undefined && hasMailTranslationKey(locale, key) ? locale : "en";
47
- }
40
+ const mailLocaleTemplates = createMailLocaleTemplates({
41
+ kinds: ALL_AUTH_MAIL_KINDS,
42
+ notificationTypes: AuthMailNotificationTypes,
43
+ subjectKey,
44
+ bodyFor: (kind, locale) => mailBody(locale, AUTH_MAIL_KINDS[kind].translationKey),
45
+ });
46
+ export const authMailTemplateLocale = mailLocaleTemplates.templateLocale;
48
47
  export const AUTH_MAIL_VARIABLES = {
49
48
  appName: templateVariable.text({ required: true }),
50
49
  actionUrl: templateVariable.link({ required: true }),
@@ -90,27 +89,4 @@ function mailBody(locale, translationKey) {
90
89
  `<p>${html("ignore")}</p>`,
91
90
  ].join("");
92
91
  }
93
- // Evaluated when the registry is built, after every locale feature has
94
- // registered its mail translations. English always ships; another locale only
95
- // gets a template when it has its own subject, so a missing translation never
96
- // silently becomes an English mail in that locale's slot.
97
- export function authMailLocalizedTemplate(kind) {
98
- const { translationKey } = AUTH_MAIL_KINDS[kind];
99
- const kindSubjectKey = subjectKey(kind);
100
- return () => {
101
- const locales = [
102
- "en",
103
- ...listMailLocales().filter((locale) => locale !== "en" && hasMailTranslationKey(locale, kindSubjectKey)),
104
- ];
105
- return Object.fromEntries(locales.map((locale) => [
106
- locale,
107
- {
108
- body: mailBody(locale, translationKey),
109
- meta: {
110
- subject: mailT(locale, kindSubjectKey, { app: "{{appName}}" }),
111
- category: "transactional",
112
- },
113
- },
114
- ]));
115
- };
116
- }
92
+ export const authMailLocalizedTemplate = mailLocaleTemplates.localizedTemplate;
@@ -29,6 +29,7 @@ export function createLoginRoute(opts = {}) {
29
29
  const LoginComponent = opts.loginScreen ?? LoginScreen;
30
30
  const MfaVerifyComponent = opts.mfaVerifyScreen;
31
31
  const MfaSetupComponent = opts.mfaSetupScreen;
32
+ // biome-ignore lint/correctness/noComponentHookFactories: setup-time factory (module scope or makeAuthGate); the route takes no props, so opts are bound here
32
33
  function LoginRoute() {
33
34
  const { status, refresh, bootstrapFailure, logout } = useSession();
34
35
  const { onAuthenticated } = opts;
@@ -107,6 +108,7 @@ function resolveLoginRedirectOrNull(loginUrl, locale, location) {
107
108
  return resolveLoginRedirect(loginUrl, locale, location);
108
109
  }
109
110
  catch (error) {
111
+ // biome-ignore lint/suspicious/noConsole: the browser console is the only place a broken loginUrl builder shows up, the visitor just sees the built-in login
110
112
  console.error("Auth gate: loginUrl could not be resolved, showing the built-in login", error);
111
113
  return null;
112
114
  }
@@ -116,6 +118,7 @@ export function makeAuthGate(opts = {}) {
116
118
  if (typeof loginUrl === "string")
117
119
  assertNavigableUrl(loginUrl, "loginUrl");
118
120
  const LoginRoute = createLoginRoute(opts);
121
+ // biome-ignore lint/correctness/noComponentHookFactories: setup-time factory (makeSessionAuthGate or an app's mount function); gates only receive children, so opts are bound here
119
122
  function AuthGate({ children }) {
120
123
  const { status } = useSession();
121
124
  const locale = useLocale().locale();
@@ -145,6 +148,7 @@ export function makeSessionAuthGate(opts = {}) {
145
148
  if (postLogoutUrl !== undefined)
146
149
  assertNavigableUrl(postLogoutUrl, "postLogoutUrl");
147
150
  const AuthGate = makeAuthGate(opts);
151
+ // biome-ignore lint/correctness/noComponentHookFactories: setup-time factory, called once per emailPasswordClient(); gates only receive children, so opts are bound here
148
152
  function SessionAuthGate({ children }) {
149
153
  return (_jsx(SessionProvider, { postLogoutUrl: postLogoutUrl, children: _jsx(AuthGate, { children: children }) }));
150
154
  }
@@ -13,5 +13,10 @@ export type DefaultTopbarActionsProps = {
13
13
  readonly lightIcon?: ReactNode;
14
14
  /** Dark-Mode-Icon. Default: Unicode ☾. */
15
15
  readonly darkIcon?: ReactNode;
16
+ /** Render the UserMenu. Default true; false for apps whose account/logout
17
+ * lives elsewhere (for example a sidebar profile). */
18
+ readonly userMenu?: boolean;
19
+ /** data-testid forwarded to the ThemeToggle button. */
20
+ readonly themeToggleTestId?: string;
16
21
  };
17
- export declare function DefaultTopbarActions({ tenantName, extras, lightIcon, darkIcon, }?: DefaultTopbarActionsProps): ReactNode;
22
+ export declare function DefaultTopbarActions({ tenantName, extras, lightIcon, darkIcon, userMenu, themeToggleTestId, }?: DefaultTopbarActionsProps): ReactNode;
@@ -8,6 +8,6 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
8
8
  import { ThemeToggle } from "@cosmicdrift/kumiko-renderer/web";
9
9
  import { TenantSwitcher } from "./tenant-switcher.js";
10
10
  import { UserMenu } from "./user-menu.js";
11
- export function DefaultTopbarActions({ tenantName, extras, lightIcon, darkIcon, } = {}) {
12
- return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(TenantSwitcher, { ...(tenantName !== undefined && { tenantName }) }), extras, _jsx(ThemeToggle, { ...(lightIcon !== undefined && { lightIcon }), ...(darkIcon !== undefined && { darkIcon }) }), _jsx(UserMenu, {})] }));
11
+ export function DefaultTopbarActions({ tenantName, extras, lightIcon, darkIcon, userMenu = true, themeToggleTestId, } = {}) {
12
+ return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(TenantSwitcher, { ...(tenantName !== undefined && { tenantName }) }), extras, _jsx(ThemeToggle, { ...(lightIcon !== undefined && { lightIcon }), ...(darkIcon !== undefined && { darkIcon }), ...(themeToggleTestId !== undefined && { testId: themeToggleTestId }) }), userMenu && _jsx(UserMenu, {})] }));
13
13
  }
@@ -36,6 +36,8 @@ export type { TenantMenuItemsProps } from "./tenant-menu-items.tsx";
36
36
  export { TenantMenuItems } from "./tenant-menu-items.tsx";
37
37
  export type { TenantSwitcherProps } from "./tenant-switcher.tsx";
38
38
  export { TenantSwitcher } from "./tenant-switcher.tsx";
39
+ export type { UseRedirectAuthedFromLoginOptions } from "./use-redirect-authed-from-login.ts";
40
+ export { isAuthedOnLoginPath, useRedirectAuthedFromLogin, } from "./use-redirect-authed-from-login.ts";
39
41
  export type { ShellUser } from "./use-shell-user.ts";
40
42
  export { useShellUser } from "./use-shell-user.ts";
41
43
  export type { UserMenuProps } from "./user-menu.tsx";
@@ -24,6 +24,7 @@ export { SignupCompleteScreen } from "./signup-complete-screen.js";
24
24
  export { SignupScreen } from "./signup-screen.js";
25
25
  export { TenantMenuItems } from "./tenant-menu-items.js";
26
26
  export { TenantSwitcher } from "./tenant-switcher.js";
27
+ export { isAuthedOnLoginPath, useRedirectAuthedFromLogin, } from "./use-redirect-authed-from-login.js";
27
28
  export { useShellUser } from "./use-shell-user.js";
28
29
  export { UserMenu } from "./user-menu.js";
29
30
  export { VerifyEmailScreen } from "./verify-email-screen.js";
@@ -57,53 +57,15 @@ export function InviteAcceptScreen({ title, token: tokenProp, loggedInHref = "/"
57
57
  roles: grantedRoles(data),
58
58
  }));
59
59
  };
60
- const acceptLoggedIn = async () => {
60
+ const postInviteAccept = async (path, body) => {
61
61
  setSubmitting(true);
62
62
  setError(null);
63
63
  // kumiko-lint-ignore no-raw-hooks not yet converted to the framework hook set
64
- const res = await fetch("/api/auth/invite-accept", {
64
+ const res = await fetch(path, {
65
65
  method: "POST",
66
66
  credentials: "same-origin",
67
67
  headers: { "Content-Type": "application/json", ...csrfHeader() },
68
- body: JSON.stringify({ token }),
69
- });
70
- setSubmitting(false);
71
- if (res.ok) {
72
- // @cast-boundary engine-payload — auth route JSON
73
- const data = (await res.json());
74
- finishAccept(data);
75
- return;
76
- }
77
- setError(t("auth.errors.invalidInviteToken"));
78
- };
79
- const acceptAnonExisting = async () => {
80
- setSubmitting(true);
81
- setError(null);
82
- // kumiko-lint-ignore no-raw-hooks not yet converted to the framework hook set
83
- const res = await fetch("/api/auth/invite-accept-with-login", {
84
- method: "POST",
85
- credentials: "same-origin",
86
- headers: { "Content-Type": "application/json", ...csrfHeader() },
87
- body: JSON.stringify({ token, email, password }),
88
- });
89
- setSubmitting(false);
90
- if (res.ok) {
91
- // @cast-boundary engine-payload — auth route JSON
92
- const data = (await res.json());
93
- finishAccept(data);
94
- return;
95
- }
96
- setError(t("auth.errors.invalidInviteToken"));
97
- };
98
- const acceptAnonNew = async () => {
99
- setSubmitting(true);
100
- setError(null);
101
- // kumiko-lint-ignore no-raw-hooks not yet converted to the framework hook set
102
- const res = await fetch("/api/auth/invite-signup-complete", {
103
- method: "POST",
104
- credentials: "same-origin",
105
- headers: { "Content-Type": "application/json", ...csrfHeader() },
106
- body: JSON.stringify({ token, password }),
68
+ body: JSON.stringify(body),
107
69
  });
108
70
  setSubmitting(false);
109
71
  if (res.ok) {
@@ -114,6 +76,9 @@ export function InviteAcceptScreen({ title, token: tokenProp, loggedInHref = "/"
114
76
  }
115
77
  setError(t("auth.errors.invalidInviteToken"));
116
78
  };
79
+ const acceptLoggedIn = () => postInviteAccept("/api/auth/invite-accept", { token });
80
+ const acceptAnonExisting = () => postInviteAccept("/api/auth/invite-accept-with-login", { token, email, password });
81
+ const acceptAnonNew = () => postInviteAccept("/api/auth/invite-signup-complete", { token, password });
117
82
  const onSubmit = (e) => {
118
83
  e?.preventDefault();
119
84
  if (mode === "loggedin") {
@@ -0,0 +1,2 @@
1
+ import type { TenantSummary } from "./auth-client.ts";
2
+ export declare function tenantLabel(tenants: readonly TenantSummary[], tenantId: string, tenantName: ((tenantId: string) => string) | undefined): string;
@@ -0,0 +1,10 @@
1
+ // Label priority: app-provided resolver > server-provided name/key from
2
+ // /auth/tenants > UUID prefix. The prefix is only a last resort — it is
3
+ // indistinguishable for seeded tenants (00000000-…).
4
+ export function tenantLabel(tenants, tenantId, tenantName) {
5
+ if (tenantName !== undefined)
6
+ return tenantName(tenantId);
7
+ const membership = tenants.find((m) => m.tenantId === tenantId);
8
+ // || instead of ??: an empty name/key string must not be used as a label.
9
+ return membership?.name || membership?.key || tenantId.slice(0, 8);
10
+ }
@@ -4,20 +4,15 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
4
4
  import { useTranslation } from "@cosmicdrift/kumiko-renderer";
5
5
  import { DropdownMenuCheckboxItem, DropdownMenuLabel, DropdownMenuSeparator, } from "@cosmicdrift/kumiko-renderer/web";
6
6
  import { useSession } from "./session.js";
7
+ import { tenantLabel } from "./tenant-label.js";
7
8
  export function TenantMenuItems({ tenantName }) {
8
9
  const t = useTranslation();
9
10
  const { user, tenants, activeTenantId, switchTenant } = useSession();
10
11
  if (user === null || tenants.length <= 1)
11
12
  return null;
12
- const nameOf = (tenantId) => {
13
- if (tenantName !== undefined)
14
- return tenantName(tenantId);
15
- const membership = tenants.find((m) => m.tenantId === tenantId);
16
- return membership?.name || membership?.key || tenantId.slice(0, 8);
17
- };
18
13
  return (_jsxs(_Fragment, { children: [_jsx(DropdownMenuLabel, { children: t("auth.tenant.switcher.label") }), tenants.map((membership) => (_jsx(DropdownMenuCheckboxItem, { checked: membership.tenantId === activeTenantId, onSelect: (event) => {
19
14
  event.preventDefault();
20
15
  if (membership.tenantId !== activeTenantId)
21
16
  void switchTenant(membership.tenantId);
22
- }, children: _jsx("span", { className: "truncate", children: nameOf(membership.tenantId) }) }, membership.tenantId))), _jsx(DropdownMenuSeparator, {})] }));
17
+ }, children: _jsx("span", { className: "truncate", children: tenantLabel(tenants, membership.tenantId, tenantName) }) }, membership.tenantId))), _jsx(DropdownMenuSeparator, {})] }));
23
18
  }
@@ -17,6 +17,7 @@ import { cn, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, Dropdo
17
17
  import { Building2, ChevronDown } from "lucide-react";
18
18
  import { useCallback, useState } from "react";
19
19
  import { useSession } from "./session.js";
20
+ import { tenantLabel } from "./tenant-label.js";
20
21
  export function TenantSwitcher({ tenantName }) {
21
22
  const t = useTranslation();
22
23
  const { user, tenants, activeTenantId, switchTenant } = useSession();
@@ -36,27 +37,19 @@ export function TenantSwitcher({ tenantName }) {
36
37
  setSwitching(null);
37
38
  }
38
39
  }, [activeTenantId, switchTenant]);
39
- // Label priority: app-provided resolver (prop) > server-provided
40
- // name/key from /auth/tenants > UUID prefix. The latter is only a
41
- // last resort — it is indistinguishable for seeded tenants (00000000-…).
42
- const nameOf = (tenantId) => {
43
- if (tenantName !== undefined)
44
- return tenantName(tenantId);
45
- const membership = tenants.find((m) => m.tenantId === tenantId);
46
- // || instead of ??: an empty name/key string must not be used as a label.
47
- return membership?.name || membership?.key || tenantId.slice(0, 8);
48
- };
49
40
  // Rendering gate: no user → nothing; only one tenant → nothing as well
50
41
  // (single-tenant apps do not need a switcher).
51
42
  if (user === null || tenants.length <= 1)
52
43
  return null;
53
- const activeLabel = activeTenantId !== null ? nameOf(activeTenantId) : t("auth.tenant.switcher.none");
44
+ const activeLabel = activeTenantId !== null
45
+ ? tenantLabel(tenants, activeTenantId, tenantName)
46
+ : t("auth.tenant.switcher.none");
54
47
  return (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsxs("button", { type: "button", className: cn("inline-flex items-center gap-2 rounded-md border border-input bg-background px-2 py-1 text-sm", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"), children: [_jsx(Building2, { className: "h-3.5 w-3.5 text-muted-foreground" }), _jsx("span", { className: "max-w-[14ch] truncate", children: activeLabel }), _jsx(ChevronDown, { className: "h-3 w-3 text-muted-foreground" })] }) }), _jsxs(DropdownMenuContent, { align: "end", className: "min-w-[14rem]", children: [_jsx(DropdownMenuLabel, { children: t("auth.tenant.switcher.label") }), tenants.map((membership) => {
55
48
  const isActive = membership.tenantId === activeTenantId;
56
49
  const isSwitching = switching === membership.tenantId;
57
50
  return (_jsx(DropdownMenuCheckboxItem, { checked: isActive, disabled: isSwitching, onSelect: (e) => {
58
51
  e.preventDefault();
59
52
  void handleSwitch(membership.tenantId);
60
- }, children: _jsxs("div", { className: "flex flex-col items-start min-w-0", children: [_jsx("span", { className: "truncate font-medium", children: nameOf(membership.tenantId) }), membership.roles.length > 0 && (_jsx("span", { className: "text-xs text-muted-foreground truncate", children: membership.roles.join(", ") }))] }) }, membership.tenantId));
53
+ }, children: _jsxs("div", { className: "flex flex-col items-start min-w-0", children: [_jsx("span", { className: "truncate font-medium", children: tenantLabel(tenants, membership.tenantId, tenantName) }), membership.roles.length > 0 && (_jsx("span", { className: "text-xs text-muted-foreground truncate", children: membership.roles.join(", ") }))] }) }, membership.tenantId));
61
54
  })] })] }));
62
55
  }
@@ -0,0 +1,7 @@
1
+ import { type NavTarget } from "@cosmicdrift/kumiko-renderer";
2
+ export declare function isAuthedOnLoginPath(authed: boolean, pathname: string, loginPath: string): boolean;
3
+ export type UseRedirectAuthedFromLoginOptions = {
4
+ readonly loginPath: string;
5
+ readonly target: NavTarget;
6
+ };
7
+ export declare function useRedirectAuthedFromLogin({ loginPath, target, }: UseRedirectAuthedFromLoginOptions): void;
@@ -0,0 +1,30 @@
1
+ import { useNav } from "@cosmicdrift/kumiko-renderer";
2
+ import { useEffect, useRef } from "react";
3
+ import { useSession } from "./session.js";
4
+ export function isAuthedOnLoginPath(authed, pathname, loginPath) {
5
+ return authed && pathname === loginPath;
6
+ }
7
+ // The SPA has no screen at the login path: after a login the URL stays there, and marketing
8
+ // links land there directly. replace, not navigate: a push would make Browser-Back from the
9
+ // target land on the login path again, which redirects forward again (history ping-pong).
10
+ export function useRedirectAuthedFromLogin({ loginPath, target, }) {
11
+ const session = useSession();
12
+ const nav = useNav();
13
+ const authed = session.user !== null;
14
+ // Callers pass an inline object; a ref keeps it out of the effect deps.
15
+ const targetRef = useRef(target);
16
+ targetRef.current = target;
17
+ useEffect(() => {
18
+ // skip: no browser location to inspect (native or server render)
19
+ if (typeof window === "undefined")
20
+ return;
21
+ const redirectIfStranded = () => {
22
+ if (isAuthedOnLoginPath(authed, window.location.pathname, loginPath))
23
+ nav.replace(targetRef.current);
24
+ };
25
+ redirectIfStranded();
26
+ // Browser-Back to the login path changes neither authed nor nav, so the effect alone would not re-fire.
27
+ window.addEventListener("popstate", redirectIfStranded);
28
+ return () => window.removeEventListener("popstate", redirectIfStranded);
29
+ }, [authed, nav, loginPath]);
30
+ }
@@ -23,30 +23,17 @@ export function createAuthFoundationFeature() {
23
23
  category: "identity",
24
24
  recommended: false,
25
25
  });
26
- r.extendsRegistrar(EXT_TOKEN_VERIFIER, {
27
- onRegister: () => {
28
- // No side-effects at register-time — registry stores the usage,
29
- // resolveTokenVerifier looks it up at request-time.
30
- },
31
- });
26
+ // Registry stores the usage, resolveTokenVerifier looks it up at request-time.
27
+ r.extendsRegistrar(EXT_TOKEN_VERIFIER, {});
32
28
  r.bootCheck(({ features }) => validateTokenVerifierMultiplicity(features));
33
- r.extendsRegistrar(EXT_SESSION_STORE, {
34
- onRegister: () => {
35
- // No side-effects at register-time — resolveSessionStore at boot/request.
36
- },
37
- });
29
+ // resolveSessionStore looks the usage up at boot/request-time.
30
+ r.extendsRegistrar(EXT_SESSION_STORE, {});
38
31
  r.bootCheck(({ features }) => validateSessionStoreMultiplicity(features));
39
- r.extendsRegistrar(EXT_TENANT_RESOLVER, {
40
- onRegister: () => {
41
- // Optional — zero providers is fine (single-tenant / header-cookie).
42
- },
43
- });
32
+ // Optional — zero providers is fine (single-tenant / header-cookie).
33
+ r.extendsRegistrar(EXT_TENANT_RESOLVER, {});
44
34
  r.bootCheck(({ features }) => validateTenantResolverMultiplicity(features));
45
- r.extendsRegistrar(EXT_TENANT_EXISTENCE, {
46
- onRegister: () => {
47
- // Optional — zero providers skips the existence check.
48
- },
49
- });
35
+ // Optional — zero providers skips the existence check.
36
+ r.extendsRegistrar(EXT_TENANT_EXISTENCE, {});
50
37
  r.bootCheck(({ features }) => validateTenantExistenceMultiplicity(features));
51
38
  }, { dedupeOptions: {} });
52
39
  }
@@ -25,7 +25,7 @@
25
25
  import { collectPiiSubjectFields, configuredPiiSubjectKms, decryptPiiFieldValues, } from "@cosmicdrift/kumiko-framework/crypto";
26
26
  import { configuredEntityFieldEncryption, createEventStoreExecutor, createTenantDb, selectMany, } from "@cosmicdrift/kumiko-framework/db";
27
27
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
28
- import { classifyStoredEnvelope, runChunkedMigration, } from "../../shared/index.js";
28
+ import { classifyStoredEnvelope, createTenantDbCache, runChunkedMigration, } from "../../shared/index.js";
29
29
  import { userMfaEntity, userMfaTable } from "../schema/user-mfa.js";
30
30
  const DEFAULT_BATCH_SIZE = 100;
31
31
  const DEFAULT_MAX_FAILURES = 10;
@@ -61,20 +61,12 @@ export async function mfaReencryptJob(rawPayload, ctx, db) {
61
61
  const deadline = payload.maxDurationMs
62
62
  ? Date.now() + payload.maxDurationMs
63
63
  : Number.POSITIVE_INFINITY;
64
- const tdbCache = new Map();
65
- function tdbFor(tenantId) {
66
- let existing = tdbCache.get(tenantId);
67
- if (!existing) {
68
- existing = createTenantDb({
69
- db,
70
- tenantId,
71
- mode: "system",
72
- reason: "MFA key re-encryption job rewrites enrollments of every tenant",
73
- });
74
- tdbCache.set(tenantId, existing);
75
- }
76
- return existing;
77
- }
64
+ const tdbFor = createTenantDbCache((tenantId) => createTenantDb({
65
+ db,
66
+ tenantId,
67
+ mode: "system",
68
+ reason: "MFA key re-encryption job rewrites enrollments of every tenant",
69
+ }));
78
70
  let alreadyCurrent = 0;
79
71
  const targetVersion = provider.currentVersion();
80
72
  // ponytail: one full candidate scan — MFA rows are user-scale, not
@@ -1,3 +1,4 @@
1
+ import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
1
2
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
3
  export type HmacTokenVerifyResult<TPayload> = {
3
4
  readonly ok: true;
@@ -7,9 +8,13 @@ export type HmacTokenVerifyResult<TPayload> = {
7
8
  readonly ok: false;
8
9
  readonly reason: "malformed" | "bad_signature" | "expired";
9
10
  };
11
+ export type UserTenantPayload = {
12
+ readonly userId: string;
13
+ readonly tenantId: TenantId;
14
+ };
15
+ export declare function isUserTenantPayload(value: unknown): value is UserTenantPayload;
10
16
  export declare function createHmacTokenCodec<TPayload extends {
11
17
  readonly userId: string;
12
- readonly tenantId: string;
13
18
  }>(domain: string, isPayload: (value: unknown) => value is TPayload): {
14
19
  sign(payload: TPayload, ttlMinutes: number, secret: string, now?: Temporal.Instant): {
15
20
  token: string;
@@ -1,8 +1,10 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
1
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
3
2
  import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
4
- function hmacSign(input, secret) {
5
- return createHmac("sha256", secret).update(input).digest("base64url");
3
+ import { hmacSignatureMatches, signHmacSha256Base64Url } from "../shared/index.js";
4
+ export function isUserTenantPayload(value) {
5
+ if (!isPlainObject(value))
6
+ return false;
7
+ return typeof value["userId"] === "string" && typeof value["tenantId"] === "string";
6
8
  }
7
9
  // `domain` is part of the signed input: it is the only thing that stops a token
8
10
  // minted for one MFA step from verifying as another (e.g. a preauth-setup token
@@ -22,7 +24,7 @@ export function createHmacTokenCodec(domain, isPayload) {
22
24
  const expiresAt = now.add({ minutes: ttlMinutes });
23
25
  const body = { ...payload, expiresAtMs: expiresAt.epochMilliseconds };
24
26
  const bodyB64 = Buffer.from(JSON.stringify(body)).toString("base64url");
25
- const signature = hmacSign(`${domain}:${bodyB64}`, secret);
27
+ const signature = signHmacSha256Base64Url(`${domain}:${bodyB64}`, secret);
26
28
  return { token: `${bodyB64}.${signature}`, expiresAt };
27
29
  },
28
30
  verify(token, secret, now = Temporal.Now.instant()) {
@@ -32,12 +34,8 @@ export function createHmacTokenCodec(domain, isPayload) {
32
34
  const [bodyB64, providedSig] = parts;
33
35
  if (!bodyB64 || !providedSig)
34
36
  return { ok: false, reason: "malformed" };
35
- const expected = hmacSign(`${domain}:${bodyB64}`, secret);
36
- const expectedBuf = Buffer.from(expected, "base64url");
37
- const providedBuf = Buffer.from(providedSig, "base64url");
38
- if (expectedBuf.length !== providedBuf.length)
39
- return { ok: false, reason: "bad_signature" };
40
- if (!timingSafeEqual(expectedBuf, providedBuf))
37
+ const expected = signHmacSha256Base64Url(`${domain}:${bodyB64}`, secret);
38
+ if (!hmacSignatureMatches(expected, providedSig))
41
39
  return { ok: false, reason: "bad_signature" };
42
40
  let parsed;
43
41
  try {
@@ -1,16 +1,10 @@
1
1
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
- import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
3
- import { createHmacTokenCodec } from "./hmac-token-codec.js";
4
- function isPayload(value) {
5
- if (!isPlainObject(value))
6
- return false;
7
- return typeof value["userId"] === "string" && typeof value["tenantId"] === "string";
8
- }
2
+ import { createHmacTokenCodec, isUserTenantPayload, } from "./hmac-token-codec.js";
9
3
  // Domain-separated from mfa-preauth-setup (see hmac-token-codec). Single-use is
10
4
  // enforced by the consumer via burnToken (purpose "mfa-challenge"); this codec
11
5
  // only signs and verifies. Brute-forcing the code behind a valid token is
12
6
  // limited separately in mfa-verify-attempts.ts.
13
- const codec = createHmacTokenCodec("mfa-challenge", isPayload);
7
+ const codec = createHmacTokenCodec("mfa-challenge", isUserTenantPayload);
14
8
  export function signMfaChallengeToken(payload, ttlMinutes, secret, now = Temporal.Now.instant()) {
15
9
  return codec.sign(payload, ttlMinutes, secret, now);
16
10
  }
@@ -1,15 +1,9 @@
1
1
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
- import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
3
- import { createHmacTokenCodec } from "./hmac-token-codec.js";
4
- function isPayload(value) {
5
- if (!isPlainObject(value))
6
- return false;
7
- return typeof value["userId"] === "string" && typeof value["tenantId"] === "string";
8
- }
2
+ import { createHmacTokenCodec, isUserTenantPayload, } from "./hmac-token-codec.js";
9
3
  // Domain "mfa-preauth-setup" must never equal the challenge domain: a setup
10
4
  // token has to fail verification as a challenge token and vice versa. The
11
5
  // challenge token secret is reused deliberately; the domain carries the separation.
12
- const codec = createHmacTokenCodec("mfa-preauth-setup", isPayload);
6
+ const codec = createHmacTokenCodec("mfa-preauth-setup", isUserTenantPayload);
13
7
  export function signMfaPreauthSetupToken(payload, ttlMinutes, secret, now = Temporal.Now.instant()) {
14
8
  return codec.sign(payload, ttlMinutes, secret, now);
15
9
  }
@@ -1,4 +1,5 @@
1
1
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
+ import { type HmacTokenVerifyResult } from "./hmac-token-codec.ts";
2
3
  export type MfaSetupPayload = {
3
4
  readonly userId: string;
4
5
  readonly totpSecretBase32: string;
@@ -9,12 +10,5 @@ export declare function signMfaSetupToken(payload: MfaSetupPayload, ttlMinutes:
9
10
  token: string;
10
11
  expiresAt: Temporal.Instant;
11
12
  };
12
- export type VerifyMfaSetupResult = {
13
- readonly ok: true;
14
- readonly payload: MfaSetupPayload;
15
- readonly expiresAtMs: number;
16
- } | {
17
- readonly ok: false;
18
- readonly reason: "malformed" | "bad_signature" | "expired";
19
- };
13
+ export type VerifyMfaSetupResult = HmacTokenVerifyResult<MfaSetupPayload>;
20
14
  export declare function verifyMfaSetupToken(token: string, secret: string, now?: Temporal.Instant): VerifyMfaSetupResult;
@@ -6,60 +6,23 @@
6
6
  // the same response — the token exists to avoid a second round-trip to
7
7
  // regenerate it, not to hide it.
8
8
  //
9
- // Format: <base64url(JSON body)>.<hmac-base64url>. Distinct from
10
- // signed-token.ts (userId-only payload) because setup needs to carry
11
- // generated secret material, not just re-derive it from a lookup.
12
- import { createHmac, timingSafeEqual } from "node:crypto";
9
+ // Wire format and signing live in hmac-token-codec.ts.
13
10
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
14
11
  import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
15
- function sign(input, secret) {
16
- return createHmac("sha256", secret).update(input).digest("base64url");
17
- }
18
- export function signMfaSetupToken(payload, ttlMinutes, secret, now = Temporal.Now.instant()) {
19
- const expiresAt = now.add({ minutes: ttlMinutes });
20
- const body = { ...payload, expiresAtMs: expiresAt.epochMilliseconds };
21
- const bodyB64 = Buffer.from(JSON.stringify(body)).toString("base64url");
22
- const signature = sign(`mfa-setup:${bodyB64}`, secret);
23
- return { token: `${bodyB64}.${signature}`, expiresAt };
24
- }
25
- function isEncodedBody(value) {
12
+ import { createHmacTokenCodec } from "./hmac-token-codec.js";
13
+ function isMfaSetupPayload(value) {
26
14
  if (!isPlainObject(value))
27
15
  return false;
28
16
  return (typeof value["userId"] === "string" &&
29
17
  typeof value["totpSecretBase32"] === "string" &&
30
18
  Array.isArray(value["recoveryCodeHashes"]) &&
31
19
  value["recoveryCodeHashes"].every((h) => typeof h === "string") &&
32
- typeof value["expiresAtMs"] === "number" &&
33
20
  (value["tenantId"] === undefined || typeof value["tenantId"] === "string"));
34
21
  }
22
+ const codec = createHmacTokenCodec("mfa-setup", isMfaSetupPayload);
23
+ export function signMfaSetupToken(payload, ttlMinutes, secret, now = Temporal.Now.instant()) {
24
+ return codec.sign(payload, ttlMinutes, secret, now);
25
+ }
35
26
  export function verifyMfaSetupToken(token, secret, now = Temporal.Now.instant()) {
36
- const parts = token.split(".");
37
- if (parts.length !== 2)
38
- return { ok: false, reason: "malformed" };
39
- const [bodyB64, providedSig] = parts;
40
- if (!bodyB64 || !providedSig)
41
- return { ok: false, reason: "malformed" };
42
- const expected = sign(`mfa-setup:${bodyB64}`, secret);
43
- const expectedBuf = Buffer.from(expected, "base64url");
44
- const providedBuf = Buffer.from(providedSig, "base64url");
45
- // Length check before timingSafeEqual — a length mismatch throws inside
46
- // timingSafeEqual, and that throw is itself a timing signal.
47
- if (expectedBuf.length !== providedBuf.length)
48
- return { ok: false, reason: "bad_signature" };
49
- if (!timingSafeEqual(expectedBuf, providedBuf))
50
- return { ok: false, reason: "bad_signature" };
51
- let parsed;
52
- try {
53
- parsed = JSON.parse(Buffer.from(bodyB64, "base64url").toString("utf8"));
54
- }
55
- catch {
56
- return { ok: false, reason: "malformed" };
57
- }
58
- if (!isEncodedBody(parsed))
59
- return { ok: false, reason: "malformed" };
60
- if (Temporal.Instant.compare(now, Temporal.Instant.fromEpochMilliseconds(parsed.expiresAtMs)) > 0) {
61
- return { ok: false, reason: "expired" };
62
- }
63
- const { expiresAtMs, ...payload } = parsed;
64
- return { ok: true, payload, expiresAtMs };
27
+ return codec.verify(token, secret, now);
65
28
  }