@cosmicdrift/kumiko-samples 0.409.0 → 0.411.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 (82) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +36 -1
  3. package/packages/bundled-features/src/auth-email-password/changes.json +24 -0
  4. package/packages/bundled-features/src/auth-email-password/handlers/login-options.query.ts +1 -1
  5. package/packages/bundled-features/src/auth-email-password/handlers/self-registration-status.query.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/seeding.ts +84 -6
  7. package/packages/bundled-features/src/auth-email-password/web/i18n.ts +1 -0
  8. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +48 -3
  9. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +190 -0
  10. package/packages/bundled-features/src/auth-email-password/web/static-client.ts +226 -0
  11. package/packages/bundled-features/src/compliance-profiles/handlers/sub-processors.query.ts +4 -1
  12. package/packages/bundled-features/src/contact/changes.json +6 -0
  13. package/packages/bundled-features/src/contact/client/contact-website-client.ts +29 -0
  14. package/packages/bundled-features/src/contact/client/index.ts +9 -0
  15. package/packages/bundled-features/src/contact/feature.ts +3 -0
  16. package/packages/bundled-features/src/contact/handlers/access.ts +1 -1
  17. package/packages/bundled-features/src/contact/handlers/challenge.query.ts +1 -1
  18. package/packages/bundled-features/src/contact/handlers/submit.write.ts +1 -1
  19. package/packages/bundled-features/src/contact/i18n.ts +4 -1
  20. package/packages/bundled-features/src/contact/options.ts +1 -1
  21. package/packages/bundled-features/src/contact/screens.ts +1 -0
  22. package/packages/bundled-features/src/file-derivatives/handlers/public-variant-by-file-ref.query.ts +1 -1
  23. package/packages/bundled-features/src/file-derivatives/handlers/public-variant.query.ts +1 -1
  24. package/packages/bundled-features/src/foundation-shared/demo-admin-env.ts +11 -0
  25. package/packages/bundled-features/src/foundation-shared/index.ts +5 -1
  26. package/packages/bundled-features/src/inbound-provider-imap/changes.json +6 -0
  27. package/packages/bundled-features/src/inbound-provider-imap/imap-client.ts +3 -1
  28. package/packages/bundled-features/src/managed-pages/handlers/branding.query.ts +1 -1
  29. package/packages/bundled-features/src/managed-pages/handlers/by-slug.query.ts +1 -1
  30. package/packages/bundled-features/src/managed-pages/handlers/by-tenant-published.query.ts +1 -1
  31. package/packages/bundled-features/src/presence/changes.json +8 -0
  32. package/packages/bundled-features/src/presence/feature.ts +25 -0
  33. package/packages/bundled-features/src/presence/handlers/heartbeat.write.ts +52 -0
  34. package/packages/bundled-features/src/presence/handlers/leave.write.ts +41 -0
  35. package/packages/bundled-features/src/presence/handlers/list.query.ts +39 -0
  36. package/packages/bundled-features/src/presence/index.ts +7 -0
  37. package/packages/bundled-features/src/presence/options.ts +30 -0
  38. package/packages/bundled-features/src/presence/payloads.ts +26 -0
  39. package/packages/bundled-features/src/presence/room.ts +65 -0
  40. package/packages/bundled-features/src/presence/store.ts +185 -0
  41. package/packages/bundled-features/src/seo/handlers/seo-config.query.ts +1 -1
  42. package/packages/bundled-features/src/sessions/feature.ts +6 -2
  43. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +19 -0
  44. package/packages/bundled-features/src/subscription-paddle/checkout-config.query.ts +1 -1
  45. package/packages/bundled-features/src/template-resolver/handlers/by-slug.query.ts +1 -1
  46. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +1 -1
  47. package/packages/bundled-features/src/tenant-inactivity/changes.json +12 -0
  48. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +14 -6
  49. package/packages/bundled-features/src/tenant-inactivity/constants.ts +4 -1
  50. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +2 -1
  51. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +5 -1
  52. package/packages/bundled-features/src/tenant-inactivity/options.ts +1 -0
  53. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +6 -1
  54. package/packages/bundled-features/src/tenant-inactivity/static-keep-account.ts +37 -0
  55. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +2 -0
  56. package/packages/bundled-features/src/tenant-lifecycle/handlers/cancel-destruction.write.ts +6 -2
  57. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +2 -1
  58. package/packages/bundled-features/src/tenant-lifecycle/index.ts +1 -0
  59. package/packages/bundled-features/src/user-data-rights/handlers/confirm-deletion-by-token.write.ts +4 -1
  60. package/packages/bundled-features/src/user-data-rights/handlers/download-by-token.query.ts +1 -0
  61. package/packages/bundled-features/src/user-data-rights/handlers/request-deletion-by-email.write.ts +4 -1
  62. package/packages/bundled-features/src/waitlist/changes.json +12 -0
  63. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +1 -2
  64. package/packages/bundled-features/src/waitlist/static-submit.ts +56 -0
  65. package/samples/apps/styleguide/src/features/widgets/i18n.ts +143 -0
  66. package/samples/apps/styleguide/src/features/widgets/web/VariantsDemo.tsx +276 -0
  67. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +3 -0
  68. package/samples/apps/styleguide/src/features/workboard/feature.ts +1 -0
  69. package/samples/apps/use-all-bundled/feature-manifest.json +26 -25
  70. package/samples/apps/use-all-bundled/playwright.config.ts +0 -2
  71. package/samples/apps/use-all-bundled/src/run-config.ts +6 -15
  72. package/samples/recipes/anonymous-access/README.md +2 -0
  73. package/samples/recipes/anonymous-access/src/feature.ts +7 -1
  74. package/samples/recipes/contact/README.md +10 -4
  75. package/samples/recipes/contact/src/feature.ts +1 -1
  76. package/samples/recipes/realtime-sse/README.md +1 -0
  77. package/samples/recipes/realtime-sse/package.json +1 -0
  78. package/samples/recipes/realtime-sse/src/feature.ts +9 -0
  79. package/samples/recipes/record-detail-layout/README.md +1 -0
  80. package/samples/recipes/record-detail-layout/src/feature.ts +10 -0
  81. package/samples/recipes/wizard-form/README.md +9 -0
  82. package/samples/recipes/wizard-form/src/feature.ts +13 -2
@@ -0,0 +1,226 @@
1
+ // DOM-free request core for the static clients (plain Astro scripts): fetch plus pure logic only.
2
+ // It must not import the renderer, React or anything that touches `window` at import time.
3
+
4
+ import {
5
+ CSRF_COOKIE_BASE,
6
+ sessionCookieNameCandidates,
7
+ } from "@cosmicdrift/kumiko-types/session-cookies";
8
+ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
9
+ import {
10
+ failureFromErrorField,
11
+ isRecord,
12
+ type KnownLoginFailureReason,
13
+ parseRetryAfterSeconds,
14
+ } from "./login-failure.ts";
15
+
16
+ export const STATIC_NETWORK_REASON = "network";
17
+ export const STATIC_RATE_LIMITED_REASON = "rate_limited" satisfies KnownLoginFailureReason;
18
+ export const STATIC_UNKNOWN_REASON = "unknown";
19
+ export const STATIC_UNAUTHENTICATED_REASON = "unauthenticated";
20
+ // A mail client that cuts the link short sends a token below the schema's minimum length; pages
21
+ // show that as the invalid-link state, not as a generic failure.
22
+ export const STATIC_MALFORMED_TOKEN_REASON = "malformed_token";
23
+
24
+ export type StaticFailure = {
25
+ readonly kind: "failure";
26
+ readonly reason: KnownLoginFailureReason | (string & {});
27
+ readonly message?: string;
28
+ readonly retryAfterSeconds?: number;
29
+ };
30
+
31
+ export type StaticSuccess<TData> = { readonly kind: "success"; readonly data: TData };
32
+
33
+ export type StaticResult<TData> = StaticSuccess<TData> | StaticFailure;
34
+
35
+ export type StaticRequestOptions = {
36
+ /** Sent as `X-Locale`, which picks the language of mails the request triggers. */
37
+ readonly locale?: string;
38
+ };
39
+
40
+ const CSRF_HEADER_NAME = "X-CSRF-Token";
41
+ const LOCALE_HEADER_NAME = "X-Locale";
42
+ const WRITE_PATH = "/api/write";
43
+ const QUERY_PATH = "/api/query";
44
+
45
+ export function staticFailure(
46
+ reason: string,
47
+ extras: { readonly message?: string; readonly retryAfterSeconds?: number } = {},
48
+ ): StaticFailure {
49
+ return {
50
+ kind: "failure",
51
+ reason,
52
+ ...(extras.message !== undefined && { message: extras.message }),
53
+ ...(extras.retryAfterSeconds !== undefined && { retryAfterSeconds: extras.retryAfterSeconds }),
54
+ };
55
+ }
56
+
57
+ export function staticSuccess<TData>(data: TData): StaticSuccess<TData> {
58
+ return { kind: "success", data };
59
+ }
60
+
61
+ function readDocumentCookie(): string {
62
+ const cookie = propertyOf(propertyOf(globalThis, "document"), "cookie");
63
+ return typeof cookie === "string" ? cookie : "";
64
+ }
65
+
66
+ // A malformed escape in a foreign cookie must not break the request; it just carries no CSRF header.
67
+ function decodeURIComponentOrNull(value: string): string | null {
68
+ try {
69
+ return decodeURIComponent(value);
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ // Anonymous visitors have no CSRF cookie and send no header; a visitor who is signed in on the
76
+ // same origin (invite acceptance) echoes it like the SPA does.
77
+ export function csrfHeaderFromCookie(cookieSource: string): Record<string, string> {
78
+ const valuesByName = new Map<string, string>();
79
+ for (const pair of cookieSource.split(/;\s*/)) {
80
+ const eq = pair.indexOf("=");
81
+ if (eq < 0) continue;
82
+ const name = pair.slice(0, eq);
83
+ if (!valuesByName.has(name)) valuesByName.set(name, pair.slice(eq + 1));
84
+ }
85
+ for (const name of sessionCookieNameCandidates(CSRF_COOKIE_BASE)) {
86
+ const value = valuesByName.get(name);
87
+ if (value !== undefined && value.length > 0) {
88
+ const decoded = decodeURIComponentOrNull(value);
89
+ if (decoded !== null) return { [CSRF_HEADER_NAME]: decoded };
90
+ }
91
+ }
92
+ return {};
93
+ }
94
+
95
+ function failsOnlyOnToken(error: unknown): boolean {
96
+ if (!isRecord(error) || error["code"] !== "validation_error") return false;
97
+ const details = error["details"];
98
+ const fields = isRecord(details) ? details["fields"] : undefined;
99
+ return (
100
+ Array.isArray(fields) &&
101
+ fields.length > 0 &&
102
+ fields.every((field) => isRecord(field) && field["path"] === "token")
103
+ );
104
+ }
105
+
106
+ function failureFromBody(body: Record<string, unknown>): StaticFailure {
107
+ const error = body["error"];
108
+ if (failsOnlyOnToken(error)) return staticFailure(STATIC_MALFORMED_TOKEN_REASON);
109
+ const { reason, message, retryAfterSeconds } = failureFromErrorField(
110
+ error,
111
+ STATIC_UNKNOWN_REASON,
112
+ );
113
+ return staticFailure(reason, { message, retryAfterSeconds });
114
+ }
115
+
116
+ // Mirrors the 401 members of `MiddlewareRejectCode` in framework/src/api/auth-middleware.ts
117
+ // (not exported there, and the server must not be imported into browser code).
118
+ const SIGNED_OUT_REASONS: ReadonlySet<string> = new Set([
119
+ STATIC_UNAUTHENTICATED_REASON,
120
+ "missing_token",
121
+ "invalid_token",
122
+ "session_invalid",
123
+ ]);
124
+
125
+ /** True when the server says there is no usable session; wrong credentials are not signed-out. */
126
+ export function isSignedOutFailure(result: StaticResult<unknown>): boolean {
127
+ return result.kind === "failure" && SIGNED_OUT_REASONS.has(result.reason);
128
+ }
129
+
130
+ async function readJsonRecord(res: Response): Promise<Record<string, unknown>> {
131
+ const parsed: unknown = await res.json().catch(() => ({}));
132
+ return isRecord(parsed) ? parsed : {};
133
+ }
134
+
135
+ export async function postJson(
136
+ path: string,
137
+ payload: Record<string, unknown>,
138
+ options: StaticRequestOptions = {},
139
+ ): Promise<StaticResult<Record<string, unknown>>> {
140
+ let res: Response;
141
+ try {
142
+ res = await fetch(path, {
143
+ method: "POST",
144
+ credentials: "same-origin",
145
+ headers: {
146
+ "Content-Type": "application/json",
147
+ ...(options.locale !== undefined && { [LOCALE_HEADER_NAME]: options.locale }),
148
+ ...csrfHeaderFromCookie(readDocumentCookie()),
149
+ },
150
+ body: JSON.stringify(payload),
151
+ });
152
+ } catch {
153
+ return staticFailure(STATIC_NETWORK_REASON);
154
+ }
155
+ const body = await readJsonRecord(res);
156
+ if (res.status === 429) {
157
+ const fromBody = failureFromBody(body).retryAfterSeconds;
158
+ const retryAfterSeconds = parseRetryAfterSeconds(res.headers.get("Retry-After")) ?? fromBody;
159
+ return staticFailure(STATIC_RATE_LIMITED_REASON, { retryAfterSeconds });
160
+ }
161
+ if (!res.ok || body["isSuccess"] === false) {
162
+ const failure = failureFromBody(body);
163
+ // Session-less calls to session-only routes may answer 401 without a usable code.
164
+ return res.status === 401 && failure.reason === STATIC_UNKNOWN_REASON
165
+ ? staticFailure(STATIC_UNAUTHENTICATED_REASON, {
166
+ message: failure.message,
167
+ retryAfterSeconds: failure.retryAfterSeconds,
168
+ })
169
+ : failure;
170
+ }
171
+ return staticSuccess(body);
172
+ }
173
+
174
+ export async function dispatchWrite(
175
+ type: string,
176
+ payload: Record<string, unknown>,
177
+ options?: StaticRequestOptions,
178
+ ): Promise<StaticResult<unknown>> {
179
+ const result = await postJson(WRITE_PATH, { type, payload }, options);
180
+ return result.kind === "success" ? staticSuccess(result.data["data"]) : result;
181
+ }
182
+
183
+ export async function dispatchQuery(
184
+ type: string,
185
+ payload: Record<string, unknown>,
186
+ options?: StaticRequestOptions,
187
+ ): Promise<StaticResult<unknown>> {
188
+ const result = await postJson(QUERY_PATH, { type, payload }, options);
189
+ return result.kind === "success" ? staticSuccess(result.data["data"]) : result;
190
+ }
191
+
192
+ export type UrlTokenSource = "query" | "fragment";
193
+
194
+ export const URL_TOKEN_PARAM = "token";
195
+
196
+ function paramsOf(url: URL, source: UrlTokenSource): URLSearchParams {
197
+ return source === "query" ? url.searchParams : new URLSearchParams(url.hash.replace(/^#/, ""));
198
+ }
199
+
200
+ export function readUrlToken(href: string, source: UrlTokenSource): string {
201
+ return paramsOf(new URL(href), source).get(URL_TOKEN_PARAM) ?? "";
202
+ }
203
+
204
+ // Single-use tokens must not linger in history or the Referer once the page has read them.
205
+ export function hrefWithoutUrlToken(href: string, source: UrlTokenSource): string {
206
+ const url = new URL(href);
207
+ const params = paramsOf(url, source);
208
+ if (!params.has(URL_TOKEN_PARAM)) return href;
209
+ params.delete(URL_TOKEN_PARAM);
210
+ if (source === "query") {
211
+ url.search = params.toString();
212
+ } else {
213
+ const rest = params.toString();
214
+ url.hash = rest === "" ? "" : `#${rest}`;
215
+ }
216
+ return url.toString();
217
+ }
218
+
219
+ /** Reads the token from the current page and removes it from the address bar. Browser only. */
220
+ export function takeUrlToken(source: UrlTokenSource): string {
221
+ const href = window.location.href;
222
+ const token = readUrlToken(href, source);
223
+ const scrubbed = hrefWithoutUrlToken(href, source);
224
+ if (scrubbed !== href) window.history.replaceState(null, "", scrubbed);
225
+ return token;
226
+ }
@@ -22,7 +22,10 @@ import * as z from "zod";
22
22
  export const subProcessorsQuery = defineQueryHandler({
23
23
  name: "sub-processors",
24
24
  schema: z.object({}),
25
- access: { roles: ["anonymous", "Member", "User", "TenantAdmin", "SystemAdmin"] },
25
+ access: {
26
+ roles: ["anonymous", "Member", "User", "TenantAdmin", "SystemAdmin"],
27
+ anySignedIn: true,
28
+ },
26
29
  rateLimit: { per: "ip+handler", limit: 30, windowSeconds: 60 },
27
30
  description:
28
31
  "Returns the publicly readable Kumiko sub-processor list split into active and planned entries, for the GDPR Art. 28(2) disclosure a privacy policy or data-processing agreement links to.",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.410.0",
4
+ "type": "improvement",
5
+ "title": "contact/client subpath, app name in the report hint, Telegram documented as optional",
6
+ "detail": "`@cosmicdrift/kumiko-bundled-features/contact/client` exports `CONTACT_CLIENT_SOURCE` and the website client types `ContactWebsiteClient`, `ContactWebsiteWindow`, `ContactWebsiteSubmitFields`, `ContactWebsiteSubmitResult`, `ContactWebsiteFormOptions` and `ContactWebsiteKind`. The report form hint reads \"Goes straight to the {appName} team\" with the `appName` option (de, en, es, fr, it). With the default `telegram: false` the feature lists `channel-telegram` as an optional dependency only; the feature manifest, the recipe and the docs no longer show the Telegram config key or `contact:write:send-test` for that default. A signed-in visitor with any role can submit the website form and fetch the challenge."
7
+ },
2
8
  {
3
9
  "version": "0.409.0",
4
10
  "type": "improvement",
@@ -0,0 +1,29 @@
1
+ import type * as z from "zod";
2
+ import type { ContactSubmitSchema } from "../payloads.ts";
3
+ import type { CONTACT_WEBSITE_KINDS, ContactPhoneMode } from "../web/constants.ts";
4
+
5
+ export type ContactWebsiteKind = (typeof CONTACT_WEBSITE_KINDS)[number];
6
+
7
+ export type ContactWebsiteFormOptions = {
8
+ readonly phone: ContactPhoneMode;
9
+ readonly kinds: readonly ContactWebsiteKind[];
10
+ };
11
+
12
+ // The client adds challenge and nonce itself and falls back to the page language for locale.
13
+ export type ContactWebsiteSubmitFields = Omit<
14
+ z.input<typeof ContactSubmitSchema>,
15
+ "challenge" | "nonce" | "locale"
16
+ > & { readonly locale?: z.input<typeof ContactSubmitSchema>["locale"] };
17
+
18
+ export type ContactWebsiteSubmitResult =
19
+ | { readonly kind: "sent" }
20
+ | { readonly kind: "rate-limited"; readonly retryAfterSeconds?: number }
21
+ | { readonly kind: "failed" };
22
+
23
+ export type ContactWebsiteClient = {
24
+ load(): Promise<ContactWebsiteFormOptions>;
25
+ submit(fields: ContactWebsiteSubmitFields): Promise<ContactWebsiteSubmitResult>;
26
+ };
27
+
28
+ // Registered by CONTACT_CLIENT_SOURCE as window.KumikoContact.
29
+ export type ContactWebsiteWindow = { readonly KumikoContact?: ContactWebsiteClient };
@@ -0,0 +1,9 @@
1
+ export { CONTACT_CLIENT_SOURCE } from "./contact-client-source.ts";
2
+ export type {
3
+ ContactWebsiteClient,
4
+ ContactWebsiteFormOptions,
5
+ ContactWebsiteKind,
6
+ ContactWebsiteSubmitFields,
7
+ ContactWebsiteSubmitResult,
8
+ ContactWebsiteWindow,
9
+ } from "./contact-website-client.ts";
@@ -71,7 +71,10 @@ export function createContactFeature(opts: ContactOptions): FeatureDefinition {
71
71
  r.uiHints({ displayLabel: "Contact", category: "communication", recommended: false });
72
72
  r.systemScope();
73
73
  r.requires({ features: ["config", "delivery", "user-data-rights", "files", "notes-history"] });
74
+ // The feature manifest and reference are built from one mounted instance, so the off
75
+ // default still names Telegram as an optional dependency.
74
76
  if (telegram) r.requires({ features: [TELEGRAM_FEATURE] });
77
+ else r.optionalRequires(TELEGRAM_FEATURE);
75
78
  r.adoptsBundledLists();
76
79
  r.translations({ keys: createContactI18n() });
77
80
 
@@ -1,6 +1,6 @@
1
1
  import { access } from "@cosmicdrift/kumiko-framework/engine";
2
2
 
3
- // The website client sends without a session (credentials: "omit"), so it always arrives as anonymous; the signed-in roles only cover other callers.
3
+ // The website client sends without a session (credentials: "omit"), so it arrives as anonymous; other callers that carry a session pass through anySignedIn on the handlers.
4
4
  export const SUBMIT_ROLES = access.roles(
5
5
  ...access.anonymous,
6
6
  ...access.authenticated,
@@ -17,7 +17,7 @@ export function createChallengeQuery(settings: ContactSettings) {
17
17
  return defineQueryHandler({
18
18
  name: "challenge",
19
19
  schema: ContactEmptySchema,
20
- access: { roles: SUBMIT_ROLES, personalData: "public-intake" },
20
+ access: { roles: SUBMIT_ROLES, personalData: "public-intake", anySignedIn: true },
21
21
  rateLimit: CHALLENGE_RATE_LIMIT,
22
22
  agent: { expose: false },
23
23
  description:
@@ -119,7 +119,7 @@ export function createSubmitHandler(opts: ContactOptions, settings: ContactSetti
119
119
  return defineWriteHandler<"submit", typeof ContactSubmitSchema, ContactSubmitData>({
120
120
  name: "submit",
121
121
  schema: ContactSubmitSchema,
122
- access: { roles: SUBMIT_ROLES, personalData: "public-intake" },
122
+ access: { roles: SUBMIT_ROLES, personalData: "public-intake", anySignedIn: true },
123
123
  rateLimit: opts.rateLimit ?? DEFAULT_SUBMIT_RATE_LIMIT,
124
124
  agent: { expose: false },
125
125
  description:
@@ -45,7 +45,10 @@ export function createContactI18n(): Readonly<Record<string, LocalizedString>> {
45
45
  "contact:entity:contact-request:field:answeredAt": { en: "Answered", de: "Beantwortet" },
46
46
  "contact:entity:contact-request:field:closedAt": { en: "Closed", de: "Abgeschlossen" },
47
47
  "contact:entity:contact-request:field:replyCount": { en: "Replies", de: "Antworten" },
48
- "contact:report.hint": { en: "Goes straight to our team", de: "Geht direkt an unser Team" },
48
+ "contact:report.hint": {
49
+ en: "Goes straight to the {appName} team",
50
+ de: "Geht direkt an das Team von {appName}",
51
+ },
49
52
  "contact:config.send-test.description": {
50
53
  en: "Now sends a test message to the chat.",
51
54
  de: "Schickt jetzt eine Testnachricht an den Chat.",
@@ -11,7 +11,7 @@ import {
11
11
  } from "./web/constants.ts";
12
12
 
13
13
  export type ContactOptions = {
14
- /** Name shown in the notification mails ("Testnachricht von <appName>"); the static screen texts do not name it. */
14
+ /** Name shown in the notification mails ("Testnachricht von <appName>") and in the hint of the report form. */
15
15
  readonly appName: string;
16
16
  /** Default { phone: "off" }. Controls both the public form (challenge query reports it) and the admin report form. */
17
17
  readonly fields?: { readonly phone?: ContactPhoneMode };
@@ -56,6 +56,7 @@ function createReportScreen(
56
56
  summary: {
57
57
  title: `${CONTACT_FEATURE}:report.hint`,
58
58
  subtitle: `${CONTACT_FEATURE}:report.summary`,
59
+ params: { appName: opts.appName },
59
60
  },
60
61
  fields: {
61
62
  kind: { type: "select", options: CONTACT_ADMIN_KINDS, required: true, display: "radio" },
@@ -31,7 +31,7 @@ export const PUBLIC_VARIANT_BY_FILE_REF_QN = "file-derivatives:query:public-vari
31
31
  export const publicVariantByFileRefQuery = defineQueryHandler({
32
32
  name: "public-variant-by-file-ref",
33
33
  schema: publicVariantPayloadSchema,
34
- access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"] },
34
+ access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"], anySignedIn: true },
35
35
  agent: { expose: false },
36
36
  rateLimit: { per: "ip", limit: 60, windowSeconds: 60 },
37
37
  escapeHatch: {
@@ -93,7 +93,7 @@ export const publicVariantPayloadSchema = z.object({
93
93
  export const publicVariantQuery = defineQueryHandler({
94
94
  name: "public-variant",
95
95
  schema: publicVariantPayloadSchema,
96
- access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"] },
96
+ access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"], anySignedIn: true },
97
97
  agent: { expose: false },
98
98
  // ponytail: "ip" is the ONLY throttle on an anonymous, internet-facing
99
99
  // render/storage-cost route — its accuracy depends on the server's
@@ -22,3 +22,14 @@ export const demoAdminEnvSchema = z.object({
22
22
  DEMO_SYSADMIN_PASSWORD: seedPassword("Password of the seeded SystemAdmin."),
23
23
  DEMO_TENANT_ID: z.uuid().optional().describe("Id of the seeded demo tenant. Default: generated."),
24
24
  });
25
+
26
+ export const BOOTSTRAP_ADMIN_EMAIL_ENV = "KUMIKO_BOOTSTRAP_ADMIN_EMAIL";
27
+
28
+ export const bootstrapAdminEnvSchema = z.object({
29
+ [BOOTSTRAP_ADMIN_EMAIL_ENV]: z
30
+ .email()
31
+ .optional()
32
+ .describe(
33
+ "Login of the person who created the app; the first start makes it the admin without a password, set via password reset.",
34
+ ),
35
+ });
@@ -3,7 +3,11 @@
3
3
 
4
4
  export { buildInfoEnvSchema } from "./build-info-env.ts";
5
5
  export { requireDefined, requireNonEmpty, requireSecretSet } from "./config-helpers.ts";
6
- export { demoAdminEnvSchema } from "./demo-admin-env.ts";
6
+ export {
7
+ BOOTSTRAP_ADMIN_EMAIL_ENV,
8
+ bootstrapAdminEnvSchema,
9
+ demoAdminEnvSchema,
10
+ } from "./demo-admin-env.ts";
7
11
  export { isHostAllowlisted, readHostAllowlistFromEnv } from "./host-allowlist.ts";
8
12
  export { sanitizeMailDisplayName } from "./mail-display-name.ts";
9
13
  export {
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "fix",
5
+ "title": "IMAP polling works again for mailboxes given as a host name",
6
+ "detail": "Since 0.393 the host guard resolves every host name to its IP, and the IMAP client then overrode the TLS `servername` with undefined, so the certificate was checked against the IP and every poll ended in InboundTransientError. The pinned host name now goes to tls as the servername; IP-literal hosts still connect without SNI. SMTP was not affected: nodemailer receives the original name as `servername`."
7
+ },
2
8
  {
3
9
  "version": "0.395.0",
4
10
  "type": "fix",
@@ -90,6 +90,8 @@ export async function createImapClient(
90
90
  // ("servername argument must be an string"). Overriding it through `tls` with undefined makes the
91
91
  // socket connect without SNI; the certificate is still verified against the IP. Not setting the
92
92
  // option at all (as for SMTP, where nodemailer omits a falsy servername) does not help here.
93
+ // A host pinned to its resolved IP carries the original name, which must reach tls as the SNI name
94
+ // and certificate identity instead of being blanked.
93
95
  export function imapClientOptions(
94
96
  doc: ImapCredentialDocument,
95
97
  target: Awaited<ReturnType<typeof resolveMailConnectTarget>>,
@@ -99,7 +101,7 @@ export function imapClientOptions(
99
101
  port: doc.port,
100
102
  secure: doc.secure,
101
103
  ...(target.servername && { servername: target.servername }),
102
- ...(isIP(target.host) !== 0 && { tls: { servername: undefined } }),
104
+ ...(isIP(target.host) !== 0 && { tls: { servername: target.servername } }),
103
105
  auth: doc.password
104
106
  ? { user: doc.user, pass: doc.password }
105
107
  : { user: doc.user, accessToken: doc.accessToken as string },
@@ -18,7 +18,7 @@ export function createBrandingQuery(opts: { readonly allowCustomCss: boolean })
18
18
  return defineQueryHandler({
19
19
  name: "branding",
20
20
  schema: z.object({}),
21
- access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"] },
21
+ access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"], anySignedIn: true },
22
22
  rateLimit: { per: "ip+handler", limit: 60, windowSeconds: 60 },
23
23
  description:
24
24
  "Reads the tenant's public branding values for the rendered page shell, adding the raw custom CSS only when the app opted in and the per-tenant CSS toggle is on; anonymous callers may read it because it dresses public pages.",
@@ -15,7 +15,7 @@ export const bySlugQuery = defineQueryHandler({
15
15
  slug: z.string().min(1).max(64),
16
16
  lang: z.string().min(2).max(8),
17
17
  }),
18
- access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"] },
18
+ access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"], anySignedIn: true },
19
19
  rateLimit: { per: "ip+handler", limit: 60, windowSeconds: 60 },
20
20
  description:
21
21
  "Reads the body and metadata of one published managed page of the caller's tenant by slug and language, returning null for drafts and bodyless pages; use it to render a public page, not to load one for editing.",
@@ -23,7 +23,7 @@ export const byTenantPublishedQuery = defineQueryHandler({
23
23
  * logic in by-slug.query. */
24
24
  tenantIdOverride: z.string().min(1).optional(),
25
25
  }),
26
- access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"] },
26
+ access: { roles: ["anonymous", "User", "TenantAdmin", "SystemAdmin"], anySignedIn: true },
27
27
  rateLimit: { per: "ip+handler", limit: 60, windowSeconds: 60 },
28
28
  description:
29
29
  "Lists every published page of a tenant with slug, language, title and last-change time but no body; use it to enumerate the public pages for sitemap.xml or llms.txt, rather than by-slug which fetches one page's content.",
@@ -0,0 +1,8 @@
1
+ [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "improvement",
5
+ "title": "New bundled feature presence: who else is on this record right now",
6
+ "detail": "`createPresenceFeature({ entities, roles?, ttlSeconds? })` lets a browser announce that the user is viewing or editing one row of an allow-listed entity (`presence:write:heartbeat` every 15 seconds, `presence:write:leave` on close) and answers with the other people on it; `presence:query:list` returns them for up to 100 rows of a list. It only informs and never locks. State is ephemeral in a Redis hash per session tenant, entity and row (in memory without Redis), holds user ids only and expires after `ttlSeconds` (default 45) without a heartbeat; display names are resolved per response. A caller sees presence only for rows they can read; other rows answer 404. Defaults to TenantAdmin and TenantMember, entities default to none, the handlers are hidden from the AI agent. A Redis or SSE outage logs a warning and answers with an empty room. On a change the other people on the row get an addressed live signal through the new handler service `ctx.services.userLiveSignals`, which pushes SSE frames to named users of the caller's own tenant. The renderer hooks `usePresence` and `usePresenceList` and the widgets `PresenceNotice` and `PresenceAvatars` stay silent when the feature is not mounted."
7
+ }
8
+ ]
@@ -0,0 +1,25 @@
1
+ import { defineFeature, type FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { PRESENCE_FEATURE } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { createHeartbeatHandler } from "./handlers/heartbeat.write.ts";
4
+ import { createLeaveHandler } from "./handlers/leave.write.ts";
5
+ import { createListQuery } from "./handlers/list.query.ts";
6
+ import { type PresenceOptions, resolvePresenceSettings } from "./options.ts";
7
+ import type { PresenceRuntime } from "./room.ts";
8
+ import { createMemoryPresenceStore } from "./store.ts";
9
+
10
+ export function createPresenceFeature(options: PresenceOptions = {}): FeatureDefinition {
11
+ const settings = resolvePresenceSettings(options);
12
+ // Without Redis the room lives in this process only, which is right for a single instance.
13
+ const runtime: PresenceRuntime = { settings, memoryStore: createMemoryPresenceStore() };
14
+ const access = { roles: settings.roles };
15
+
16
+ return defineFeature(PRESENCE_FEATURE, (r) => {
17
+ r.describe(
18
+ 'Who else is on this record right now: a browser sends a heartbeat every 15 seconds for one row of an allow-listed entity and gets the other viewers and editors back, with a live signal to them on a change. State is ephemeral (Redis hash per tenant, entity and row, in-memory without Redis), keyed by the session tenant, expires after ttlSeconds without a heartbeat and holds user ids only; display names are looked up per response. A caller sees presence only for rows visible to them. Mount with createPresenceFeature({ entities: ["task"] }).',
19
+ );
20
+ r.uiHints({ displayLabel: "Presence", category: "communication", recommended: false });
21
+ r.writeHandler(createHeartbeatHandler(runtime, access));
22
+ r.writeHandler(createLeaveHandler(runtime, access));
23
+ r.queryHandler(createListQuery(runtime, access));
24
+ });
25
+ }
@@ -0,0 +1,52 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import {
4
+ PRESENCE_CHANGED_EVENT,
5
+ type PresenceHeartbeatResult,
6
+ } from "@cosmicdrift/kumiko-types/presence-types";
7
+ import { HeartbeatSchema } from "../payloads.ts";
8
+ import {
9
+ canUseRoom,
10
+ othersOf,
11
+ type PresenceRuntime,
12
+ roomKey,
13
+ storeFor,
14
+ toEntries,
15
+ } from "../room.ts";
16
+
17
+ export function createHeartbeatHandler(runtime: PresenceRuntime, access: AccessRule) {
18
+ return defineWriteHandler<"heartbeat", typeof HeartbeatSchema, PresenceHeartbeatResult>({
19
+ name: "heartbeat",
20
+ schema: HeartbeatSchema,
21
+ access,
22
+ agent: { expose: false },
23
+ // Presence lives in Redis or memory, never Postgres: no transaction per 15 s heartbeat.
24
+ transaction: "perCommand",
25
+ description:
26
+ "Announces that the caller is looking at or editing one row and answers with the other people currently on it; the browser sends it every 15 seconds while a record is open.",
27
+ handler: async (event, ctx) => {
28
+ const { entity, id, activity, focus } = event.payload;
29
+ if (!(await canUseRoom(runtime, ctx, entity, id))) {
30
+ return writeFailure(new NotFoundError(entity, id));
31
+ }
32
+ const store = storeFor(runtime, ctx);
33
+ const key = roomKey(ctx, entity, id);
34
+ const nowMs = ctx.tz.now().epochMilliseconds;
35
+ const { changed } = await store.touch(
36
+ key,
37
+ event.user.id,
38
+ { activity, ...(focus !== undefined && { focus }) },
39
+ nowMs,
40
+ runtime.settings.ttlMs,
41
+ );
42
+ const others = othersOf(await store.list(key, nowMs, runtime.settings.ttlMs), event.user.id);
43
+ if (changed && others.length > 0) {
44
+ await ctx.services.userLiveSignals?.push(
45
+ others.map((record) => record.userId),
46
+ { type: PRESENCE_CHANGED_EVENT, entity, id },
47
+ );
48
+ }
49
+ return { isSuccess: true, data: { others: await toEntries(ctx, others) } };
50
+ },
51
+ });
52
+ }
@@ -0,0 +1,41 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { PRESENCE_CHANGED_EVENT } from "@cosmicdrift/kumiko-types/presence-types";
4
+ import { LeaveSchema } from "../payloads.ts";
5
+ import { canUseRoom, othersOf, type PresenceRuntime, roomKey, storeFor } from "../room.ts";
6
+
7
+ export function createLeaveHandler(runtime: PresenceRuntime, access: AccessRule) {
8
+ return defineWriteHandler<"leave", typeof LeaveSchema, { readonly left: boolean }>({
9
+ name: "leave",
10
+ schema: LeaveSchema,
11
+ access,
12
+ agent: { expose: false },
13
+ // Presence lives in Redis or memory, never Postgres: no transaction per 15 s heartbeat.
14
+ transaction: "perCommand",
15
+ description:
16
+ "Removes the caller from one row's presence list right away, so others do not wait for the entry to expire; the browser sends it when a record is closed.",
17
+ handler: async (event, ctx) => {
18
+ const { entity, id } = event.payload;
19
+ if (!(await canUseRoom(runtime, ctx, entity, id))) {
20
+ return writeFailure(new NotFoundError(entity, id));
21
+ }
22
+ const store = storeFor(runtime, ctx);
23
+ const key = roomKey(ctx, entity, id);
24
+ const { existed } = await store.remove(key, event.user.id);
25
+ if (existed) {
26
+ const nowMs = ctx.tz.now().epochMilliseconds;
27
+ const others = othersOf(
28
+ await store.list(key, nowMs, runtime.settings.ttlMs),
29
+ event.user.id,
30
+ );
31
+ if (others.length > 0) {
32
+ await ctx.services.userLiveSignals?.push(
33
+ others.map((record) => record.userId),
34
+ { type: PRESENCE_CHANGED_EVENT, entity, id },
35
+ );
36
+ }
37
+ }
38
+ return { isSuccess: true, data: { left: existed } };
39
+ },
40
+ });
41
+ }
@@ -0,0 +1,39 @@
1
+ import { type AccessRule, defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { PresenceEntry, PresenceListResult } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { ListSchema } from "../payloads.ts";
4
+ import {
5
+ canUseRoom,
6
+ othersOf,
7
+ type PresenceRuntime,
8
+ roomKey,
9
+ storeFor,
10
+ toEntries,
11
+ } from "../room.ts";
12
+
13
+ export function createListQuery(runtime: PresenceRuntime, access: AccessRule) {
14
+ return defineQueryHandler({
15
+ name: "list",
16
+ schema: ListSchema,
17
+ access,
18
+ agent: { expose: false },
19
+ description:
20
+ "Lists the other people currently on each of up to 100 rows of one entity, for badges in a list; rows the caller cannot see are left out without a hint.",
21
+ handler: async (event, ctx): Promise<PresenceListResult> => {
22
+ const { entity, ids } = event.payload;
23
+ if (!runtime.settings.entities.has(entity)) return { byId: {} };
24
+ const store = storeFor(runtime, ctx);
25
+ const nowMs = ctx.tz.now().epochMilliseconds;
26
+ const byId: Record<string, readonly PresenceEntry[]> = {};
27
+ for (const id of new Set(ids)) {
28
+ const others = othersOf(
29
+ await store.list(roomKey(ctx, entity, id), nowMs, runtime.settings.ttlMs),
30
+ event.user.id,
31
+ );
32
+ // Visibility is checked only where someone is present, so an empty row costs no lookup.
33
+ if (others.length === 0 || !(await canUseRoom(runtime, ctx, entity, id))) continue;
34
+ byId[id] = await toEntries(ctx, others);
35
+ }
36
+ return { byId };
37
+ },
38
+ });
39
+ }