@cosmicdrift/kumiko-samples 0.410.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 (51) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +31 -1
  3. package/packages/bundled-features/src/auth-email-password/changes.json +24 -0
  4. package/packages/bundled-features/src/auth-email-password/seeding.ts +84 -6
  5. package/packages/bundled-features/src/auth-email-password/web/i18n.ts +1 -0
  6. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +48 -3
  7. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +190 -0
  8. package/packages/bundled-features/src/auth-email-password/web/static-client.ts +226 -0
  9. package/packages/bundled-features/src/foundation-shared/demo-admin-env.ts +11 -0
  10. package/packages/bundled-features/src/foundation-shared/index.ts +5 -1
  11. package/packages/bundled-features/src/inbound-provider-imap/changes.json +6 -0
  12. package/packages/bundled-features/src/inbound-provider-imap/imap-client.ts +3 -1
  13. package/packages/bundled-features/src/presence/changes.json +8 -0
  14. package/packages/bundled-features/src/presence/feature.ts +25 -0
  15. package/packages/bundled-features/src/presence/handlers/heartbeat.write.ts +52 -0
  16. package/packages/bundled-features/src/presence/handlers/leave.write.ts +41 -0
  17. package/packages/bundled-features/src/presence/handlers/list.query.ts +39 -0
  18. package/packages/bundled-features/src/presence/index.ts +7 -0
  19. package/packages/bundled-features/src/presence/options.ts +30 -0
  20. package/packages/bundled-features/src/presence/payloads.ts +26 -0
  21. package/packages/bundled-features/src/presence/room.ts +65 -0
  22. package/packages/bundled-features/src/presence/store.ts +185 -0
  23. package/packages/bundled-features/src/sessions/feature.ts +6 -2
  24. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +19 -0
  25. package/packages/bundled-features/src/tenant-inactivity/changes.json +12 -0
  26. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +14 -6
  27. package/packages/bundled-features/src/tenant-inactivity/constants.ts +4 -1
  28. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +2 -1
  29. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +2 -1
  30. package/packages/bundled-features/src/tenant-inactivity/options.ts +1 -0
  31. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +6 -1
  32. package/packages/bundled-features/src/tenant-inactivity/static-keep-account.ts +37 -0
  33. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +2 -0
  34. package/packages/bundled-features/src/tenant-lifecycle/handlers/cancel-destruction.write.ts +6 -2
  35. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +2 -1
  36. package/packages/bundled-features/src/tenant-lifecycle/index.ts +1 -0
  37. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  38. package/packages/bundled-features/src/waitlist/static-submit.ts +56 -0
  39. package/samples/apps/styleguide/src/features/widgets/i18n.ts +143 -0
  40. package/samples/apps/styleguide/src/features/widgets/web/VariantsDemo.tsx +276 -0
  41. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +3 -0
  42. package/samples/apps/styleguide/src/features/workboard/feature.ts +1 -0
  43. package/samples/apps/use-all-bundled/feature-manifest.json +23 -1
  44. package/samples/apps/use-all-bundled/src/run-config.ts +3 -0
  45. package/samples/recipes/realtime-sse/README.md +1 -0
  46. package/samples/recipes/realtime-sse/package.json +1 -0
  47. package/samples/recipes/realtime-sse/src/feature.ts +9 -0
  48. package/samples/recipes/record-detail-layout/README.md +1 -0
  49. package/samples/recipes/record-detail-layout/src/feature.ts +10 -0
  50. package/samples/recipes/wizard-form/README.md +9 -0
  51. 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,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 },
@@ -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
+ }
@@ -0,0 +1,7 @@
1
+ export { createPresenceFeature } from "./feature.ts";
2
+ export type { PresenceOptions } from "./options.ts";
3
+ export {
4
+ createMemoryPresenceStore,
5
+ createRedisPresenceStore,
6
+ type PresenceStore,
7
+ } from "./store.ts";
@@ -0,0 +1,30 @@
1
+ export const PRESENCE_DEFAULT_ROLES: readonly string[] = ["TenantAdmin", "TenantMember"];
2
+ export const PRESENCE_DEFAULT_TTL_SECONDS = 45;
3
+
4
+ export type PresenceOptions = {
5
+ /** Entities whose rows may carry presence. Default none: a heartbeat for an entity that is not
6
+ * listed is rejected. */
7
+ readonly entities?: readonly string[];
8
+ /** Roles allowed to send heartbeats and read presence. Default TenantAdmin and TenantMember. */
9
+ readonly roles?: readonly string[];
10
+ /** Seconds a user stays listed without a heartbeat. Default 45 (three missed 15 s beats). */
11
+ readonly ttlSeconds?: number;
12
+ };
13
+
14
+ export type PresenceSettings = {
15
+ readonly entities: ReadonlySet<string>;
16
+ readonly roles: readonly string[];
17
+ readonly ttlMs: number;
18
+ };
19
+
20
+ export function resolvePresenceSettings(options: PresenceOptions): PresenceSettings {
21
+ const ttlSeconds = options.ttlSeconds ?? PRESENCE_DEFAULT_TTL_SECONDS;
22
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
23
+ throw new Error(`presence: ttlSeconds must be a positive number, got ${ttlSeconds}`);
24
+ }
25
+ return {
26
+ entities: new Set(options.entities ?? []),
27
+ roles: options.roles ?? PRESENCE_DEFAULT_ROLES,
28
+ ttlMs: ttlSeconds * 1000,
29
+ };
30
+ }
@@ -0,0 +1,26 @@
1
+ import {
2
+ PRESENCE_FOCUS_MAX_LENGTH,
3
+ PRESENCE_LIST_MAX_IDS,
4
+ } from "@cosmicdrift/kumiko-types/presence-types";
5
+ import * as z from "zod";
6
+
7
+ const ENTITY_NAME_MAX = 64;
8
+ const ROW_ID_MAX = 64;
9
+ const FOCUS_PATTERN = /^[\w:.-]+$/;
10
+
11
+ const entity = z.string().min(1).max(ENTITY_NAME_MAX);
12
+ const rowId = z.string().min(1).max(ROW_ID_MAX);
13
+
14
+ export const HeartbeatSchema = z.object({
15
+ entity,
16
+ id: rowId,
17
+ activity: z.enum(["viewing", "editing"]),
18
+ focus: z.string().max(PRESENCE_FOCUS_MAX_LENGTH).regex(FOCUS_PATTERN).optional(),
19
+ });
20
+
21
+ export const LeaveSchema = z.object({ entity, id: rowId });
22
+
23
+ export const ListSchema = z.object({
24
+ entity,
25
+ ids: z.array(rowId).min(1).max(PRESENCE_LIST_MAX_IDS),
26
+ });
@@ -0,0 +1,65 @@
1
+ import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { PresenceEntry } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { parentRowIsVisible } from "../shared/index.ts";
4
+ import { resolveUserDisplayNames, USER_FEATURE } from "../user/index.ts";
5
+ import type { PresenceSettings } from "./options.ts";
6
+ import {
7
+ createRedisPresenceStore,
8
+ type PresenceRecord,
9
+ type PresenceStore,
10
+ presenceKey,
11
+ } from "./store.ts";
12
+
13
+ export type PresenceRuntime = {
14
+ readonly settings: PresenceSettings;
15
+ readonly memoryStore: PresenceStore;
16
+ };
17
+
18
+ export function storeFor(runtime: PresenceRuntime, ctx: HandlerContext): PresenceStore {
19
+ const redis = ctx.services.redis;
20
+ return redis ? createRedisPresenceStore(redis, ctx.obs.log) : runtime.memoryStore;
21
+ }
22
+
23
+ export function roomKey(ctx: HandlerContext, entity: string, id: string): string {
24
+ return presenceKey(ctx.user.tenantId, entity, id);
25
+ }
26
+
27
+ // Not-allowed and not-visible are indistinguishable to the caller, so the endpoint is no
28
+ // existence oracle for rows or entity names.
29
+ export async function canUseRoom(
30
+ runtime: PresenceRuntime,
31
+ ctx: HandlerContext,
32
+ entity: string,
33
+ id: string,
34
+ ): Promise<boolean> {
35
+ if (!runtime.settings.entities.has(entity)) return false;
36
+ return parentRowIsVisible(ctx.registry, entity, id, ctx.user, ctx.db);
37
+ }
38
+
39
+ export function othersOf(
40
+ records: readonly PresenceRecord[],
41
+ userId: string,
42
+ ): readonly PresenceRecord[] {
43
+ return records.filter((record) => record.userId !== userId);
44
+ }
45
+
46
+ // Names are looked up per response and never stored, so an erased user leaves no name behind.
47
+ export async function toEntries(
48
+ ctx: HandlerContext,
49
+ records: readonly PresenceRecord[],
50
+ ): Promise<readonly PresenceEntry[]> {
51
+ if (records.length === 0) return [];
52
+ const names = ctx.registry.getFeature(USER_FEATURE)
53
+ ? await resolveUserDisplayNames(
54
+ ctx.db,
55
+ records.map((record) => record.userId),
56
+ )
57
+ : new Map<string, string>();
58
+ return records.map((record) => ({
59
+ userId: record.userId,
60
+ displayName: names.get(record.userId) ?? record.userId,
61
+ activity: record.activity,
62
+ ...(record.focus !== undefined && { focus: record.focus }),
63
+ since: Temporal.Instant.fromEpochMilliseconds(record.since).toString(),
64
+ }));
65
+ }