@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,185 @@
1
+ import type { Logger } from "@cosmicdrift/kumiko-framework/logging";
2
+ import type { PresenceActivity } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import type { Redis } from "ioredis";
4
+ import * as z from "zod";
5
+
6
+ export type PresenceRecord = {
7
+ readonly userId: string;
8
+ readonly activity: PresenceActivity;
9
+ readonly focus?: string;
10
+ readonly since: number;
11
+ readonly seenAt: number;
12
+ };
13
+
14
+ export type PresenceState = {
15
+ readonly activity: PresenceActivity;
16
+ readonly focus?: string;
17
+ };
18
+
19
+ // Presence is ephemeral and best-effort: implementations must never throw, a store that
20
+ // cannot answer behaves like an empty room.
21
+ export type PresenceStore = {
22
+ /** `changed` is true for a new entry or a changed activity/focus, false for a plain keep-alive. */
23
+ touch(
24
+ key: string,
25
+ userId: string,
26
+ state: PresenceState,
27
+ nowMs: number,
28
+ ttlMs: number,
29
+ ): Promise<{ readonly changed: boolean }>;
30
+ remove(key: string, userId: string): Promise<{ readonly existed: boolean }>;
31
+ /** Live entries only; expired ones are dropped on read. */
32
+ list(key: string, nowMs: number, ttlMs: number): Promise<readonly PresenceRecord[]>;
33
+ };
34
+
35
+ export function presenceKey(tenantId: string, entity: string, id: string): string {
36
+ return `presence:${tenantId}:${entity}:${id}`;
37
+ }
38
+
39
+ function isExpired(record: PresenceRecord, nowMs: number, ttlMs: number): boolean {
40
+ return record.seenAt + ttlMs < nowMs;
41
+ }
42
+
43
+ function sameState(record: PresenceRecord, state: PresenceState): boolean {
44
+ return record.activity === state.activity && record.focus === state.focus;
45
+ }
46
+
47
+ function nextRecord(
48
+ userId: string,
49
+ state: PresenceState,
50
+ previous: PresenceRecord | undefined,
51
+ nowMs: number,
52
+ ): PresenceRecord {
53
+ const unchanged = previous !== undefined && sameState(previous, state);
54
+ return {
55
+ userId,
56
+ activity: state.activity,
57
+ ...(state.focus !== undefined && { focus: state.focus }),
58
+ since: unchanged ? previous.since : nowMs,
59
+ seenAt: nowMs,
60
+ };
61
+ }
62
+
63
+ export type MemoryPresenceStore = PresenceStore & {
64
+ /** Rooms currently held, expired or not; lets tests observe the sweep. */
65
+ roomCount(): number;
66
+ };
67
+
68
+ export function createMemoryPresenceStore(): MemoryPresenceStore {
69
+ const rooms = new Map<string, Map<string, PresenceRecord>>();
70
+ let lastSweepMs = 0;
71
+
72
+ // Rooms whose last user left without a leave are never read again, so reads alone would keep
73
+ // them forever; a sweep per ttl on write bounds the map.
74
+ function sweepExpired(nowMs: number, ttlMs: number): void {
75
+ // skip: the last sweep is still within one ttl
76
+ if (nowMs - lastSweepMs < ttlMs) return;
77
+ lastSweepMs = nowMs;
78
+ for (const [key, room] of rooms) {
79
+ for (const [userId, record] of room) {
80
+ if (isExpired(record, nowMs, ttlMs)) room.delete(userId);
81
+ }
82
+ if (room.size === 0) rooms.delete(key);
83
+ }
84
+ }
85
+
86
+ return {
87
+ roomCount: () => rooms.size,
88
+ async touch(key, userId, state, nowMs, ttlMs) {
89
+ sweepExpired(nowMs, ttlMs);
90
+ const room = rooms.get(key) ?? new Map<string, PresenceRecord>();
91
+ rooms.set(key, room);
92
+ const existing = room.get(userId);
93
+ const previous = existing && !isExpired(existing, nowMs, ttlMs) ? existing : undefined;
94
+ room.set(userId, nextRecord(userId, state, previous, nowMs));
95
+ return { changed: previous === undefined || !sameState(previous, state) };
96
+ },
97
+ async remove(key, userId) {
98
+ const room = rooms.get(key);
99
+ const existed = room?.delete(userId) ?? false;
100
+ if (room?.size === 0) rooms.delete(key);
101
+ return { existed };
102
+ },
103
+ async list(key, nowMs, ttlMs) {
104
+ const room = rooms.get(key);
105
+ if (!room) return [];
106
+ for (const [userId, record] of room) {
107
+ if (isExpired(record, nowMs, ttlMs)) room.delete(userId);
108
+ }
109
+ if (room.size === 0) rooms.delete(key);
110
+ return [...room.values()];
111
+ },
112
+ };
113
+ }
114
+
115
+ const KEY_TTL_FACTOR = 2;
116
+
117
+ const storedRecordSchema = z.object({
118
+ activity: z.enum(["viewing", "editing"]),
119
+ focus: z.string().optional(),
120
+ since: z.number(),
121
+ seenAt: z.number(),
122
+ });
123
+
124
+ // Stored value carries no display name: Redis and the live frames hold ids only.
125
+ function parseRecord(userId: string, raw: string): PresenceRecord | undefined {
126
+ try {
127
+ const parsed = storedRecordSchema.safeParse(JSON.parse(raw));
128
+ if (!parsed.success) return undefined;
129
+ const { activity, focus, since, seenAt } = parsed.data;
130
+ return { userId, activity, ...(focus !== undefined && { focus }), since, seenAt };
131
+ } catch {
132
+ return undefined;
133
+ }
134
+ }
135
+
136
+ export function createRedisPresenceStore(redis: Redis, log: Logger): PresenceStore {
137
+ async function guarded<T>(fallback: T, run: () => Promise<T>): Promise<T> {
138
+ if (redis.status !== "ready") {
139
+ log.warn("presence store skipped: redis connection not ready", { status: redis.status });
140
+ return fallback;
141
+ }
142
+ try {
143
+ return await run();
144
+ } catch (err) {
145
+ log.warn("presence store command failed", { err });
146
+ return fallback;
147
+ }
148
+ }
149
+
150
+ async function read(key: string, userId: string): Promise<PresenceRecord | undefined> {
151
+ const raw = await redis.hget(key, userId);
152
+ return raw === null ? undefined : parseRecord(userId, raw);
153
+ }
154
+
155
+ return {
156
+ touch: (key, userId, state, nowMs, ttlMs) =>
157
+ guarded({ changed: false }, async () => {
158
+ const existing = await read(key, userId);
159
+ const previous = existing && !isExpired(existing, nowMs, ttlMs) ? existing : undefined;
160
+ const record = nextRecord(userId, state, previous, nowMs);
161
+ const { userId: _omit, ...stored } = record;
162
+ await redis
163
+ .multi()
164
+ .hset(key, userId, JSON.stringify(stored))
165
+ .expire(key, Math.ceil((ttlMs * KEY_TTL_FACTOR) / 1000))
166
+ .exec();
167
+ return { changed: previous === undefined || !sameState(previous, state) };
168
+ }),
169
+ remove: (key, userId) =>
170
+ guarded({ existed: false }, async () => ({ existed: (await redis.hdel(key, userId)) > 0 })),
171
+ list: (key, nowMs, ttlMs) =>
172
+ guarded<readonly PresenceRecord[]>([], async () => {
173
+ const all = await redis.hgetall(key);
174
+ const live: PresenceRecord[] = [];
175
+ const expired: string[] = [];
176
+ for (const [userId, raw] of Object.entries(all)) {
177
+ const record = parseRecord(userId, raw);
178
+ if (record && !isExpired(record, nowMs, ttlMs)) live.push(record);
179
+ else expired.push(userId);
180
+ }
181
+ if (expired.length > 0) await redis.hdel(key, ...expired);
182
+ return live;
183
+ }),
184
+ };
185
+ }
@@ -14,7 +14,10 @@ import { createLateBoundSlot, readFeatureExportFn } from "../shared/index.ts";
14
14
  import { USER_SESSION_ENTITY_NAME } from "./constants.ts";
15
15
  import { cleanupJob } from "./handlers/cleanup.job.ts";
16
16
  import { createDetailQuery } from "./handlers/detail.query.ts";
17
- import { registerLastActivityProbe } from "./handlers/last-activity-probe.route.ts";
17
+ import {
18
+ readProbeSecretFromEnv,
19
+ registerLastActivityProbe,
20
+ } from "./handlers/last-activity-probe.route.ts";
18
21
  import { createListQuery } from "./handlers/list.query.ts";
19
22
  import { mineQuery } from "./handlers/mine.query.ts";
20
23
  import { revokeWrite } from "./handlers/revoke.write.ts";
@@ -64,6 +67,7 @@ export type SessionsFeatureOptions = {
64
67
  readonly clock?: Clock;
65
68
  // Opt-in: serves GET /sessions/last-activity to a sibling app presenting this secret as a
66
69
  // Bearer token. Answers the newest session activity across every tenant of this app.
70
+ // Unset: falls back to the SESSIONS_LAST_ACTIVITY_PROBE_SECRET env (min. 32 characters).
67
71
  readonly lastActivityProbeSecret?: string;
68
72
  };
69
73
 
@@ -199,7 +203,7 @@ export function createSessionsFeature(options?: SessionsFeatureOptions): Feature
199
203
  ),
200
204
  });
201
205
 
202
- const probeSecret = options?.lastActivityProbeSecret;
206
+ const probeSecret = options?.lastActivityProbeSecret ?? readProbeSecretFromEnv();
203
207
  if (probeSecret !== undefined) registerLastActivityProbe(r, probeSecret);
204
208
 
205
209
  // Cross-feature entity hook on "user". `r.entityHook` (NOT `r.hook`) is
@@ -7,6 +7,25 @@ import {
7
7
  // The route is reachable anonymously, so a short secret would be guessable within the rate limit.
8
8
  const MIN_PROBE_SECRET_LENGTH = 32;
9
9
 
10
+ export const LAST_ACTIVITY_PROBE_SECRET_ENV = "SESSIONS_LAST_ACTIVITY_PROBE_SECRET";
11
+
12
+ // Env is the fallback for apps that mount sessions without options; the value is never echoed.
13
+ // The feature definition also runs in client bundles, where `process` may not exist.
14
+ export function readProbeSecretFromEnv(
15
+ env: Readonly<Record<string, string | undefined>> | undefined = typeof process === "undefined"
16
+ ? undefined
17
+ : process.env,
18
+ ): string | undefined {
19
+ const secret = env?.[LAST_ACTIVITY_PROBE_SECRET_ENV];
20
+ if (secret === undefined) return undefined;
21
+ if (secret.length < MIN_PROBE_SECRET_LENGTH) {
22
+ throw new Error(
23
+ `sessions: ${LAST_ACTIVITY_PROBE_SECRET_ENV} must be at least ${MIN_PROBE_SECRET_LENGTH} characters`,
24
+ );
25
+ }
26
+ return secret;
27
+ }
28
+
10
29
  export function registerLastActivityProbe(r: FeatureRegistrar, secret: string): void {
11
30
  if (secret.length < MIN_PROBE_SECRET_LENGTH) {
12
31
  throw new Error(
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "improvement",
5
+ "title": "Warning mails reach Admins, activity sources get the tenant db, sessions probe secret from env",
6
+ "detail": "The inactivity warning mail goes to every member with the `TenantOwner`, `TenantAdmin` or `Admin` role (`TENANT_KEEP_ACCOUNT_ROLES`, also the roles of the keep-account and state handlers), once per user. An activity source that reports a time in the future is capped at the current time. `TenantActivitySource` now receives `{ tenantId, now, db }` with `db: TenantDb`, so a source can read the tenant's own data; existing sources that ignore the extra field keep working. The sessions feature falls back to the `SESSIONS_LAST_ACTIVITY_PROBE_SECRET` environment variable when `lastActivityProbeSecret` is not set, so apps that mount sessions without options can serve the last-activity probe. A value shorter than 32 characters fails the boot with a message that names the variable but not its value; an unset variable keeps the probe off. Client code can import the handler names from `@cosmicdrift/kumiko-bundled-features/tenant-inactivity/constants` (`TenantInactivityHandlers`, `TenantInactivityJobs`) without pulling the server barrel (ioredis, `tls`) into the browser bundle."
7
+ },
8
+ {
9
+ "version": "0.411.0",
10
+ "type": "improvement",
11
+ "title": "tenant-inactivity/static-keep-account, a DOM-free keep-account client",
12
+ "detail": "`@cosmicdrift/kumiko-bundled-features/tenant-inactivity/static-keep-account` exports `keepAccount(token)`, which posts `tenant-inactivity:write:keep-account`, and `takeKeepAccountToken()`, which reads the `#token=` fragment of the mail link and removes it from the address bar. Results use the same `kind: \"success\" | \"failure\"` union as the other static clients; an expired or replaced link is a failure."
13
+ },
2
14
  {
3
15
  "version": "0.407.0",
4
16
  "type": "improvement",
@@ -1,4 +1,4 @@
1
- import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
1
+ import { fetchOne, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
2
  import type { JobContext, TenantId } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { hasMailTranslations, mailT } from "@cosmicdrift/kumiko-framework/i18n";
4
4
  import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
@@ -11,7 +11,7 @@ import {
11
11
  } from "../tenant/index.ts";
12
12
  import { requestTenantDestruction } from "../tenant-lifecycle/index.ts";
13
13
  import { userTable } from "../user/index.ts";
14
- import { TENANT_OWNER_ROLE } from "./constants.ts";
14
+ import { TENANT_KEEP_ACCOUNT_ROLES } from "./constants.ts";
15
15
  import { formatInactivityMailDate } from "./email-templates.ts";
16
16
  import {
17
17
  activityBase,
@@ -67,11 +67,15 @@ async function newestExternalActivity(
67
67
  options: TenantInactivityOptions,
68
68
  tenantId: TenantId,
69
69
  now: Temporal.Instant,
70
+ db: TenantDb,
70
71
  ): Promise<Temporal.Instant | null> {
71
72
  const found = await Promise.all(
72
- (options.activitySources ?? []).map((source) => source({ tenantId, now })),
73
+ (options.activitySources ?? []).map((source) => source({ tenantId, now, db })),
74
+ );
75
+ // A source reporting the future would postpone the deletion indefinitely.
76
+ return latestOf(
77
+ found.map((at) => (at !== null && Temporal.Instant.compare(at, now) > 0 ? now : at)),
73
78
  );
74
- return latestOf(found);
75
79
  }
76
80
 
77
81
  function isNewerThanBase(
@@ -89,8 +93,12 @@ async function loadOwners(ctx: JobContext): Promise<readonly OwnerRecipient[]> {
89
93
  {},
90
94
  );
91
95
  const owners: OwnerRecipient[] = [];
96
+ const seen = new Set<string>();
92
97
  for (const membership of memberships) {
93
- if (!parseRoles(membership.roles).includes(TENANT_OWNER_ROLE)) continue;
98
+ if (seen.has(membership.userId)) continue;
99
+ const roles = parseRoles(membership.roles);
100
+ if (!TENANT_KEEP_ACCOUNT_ROLES.some((role) => roles.includes(role))) continue;
101
+ seen.add(membership.userId);
94
102
  const user = await ctx.db
95
103
  .global(userTable)
96
104
  .fetchOne<{ locale: string | null }>({ id: membership.userId });
@@ -187,7 +195,7 @@ async function evaluate(
187
195
  if (decision.kind === "none") return state;
188
196
 
189
197
  // Steps with consequences ask other apps first: activity there counts too.
190
- const external = await newestExternalActivity(options, tenantId, now);
198
+ const external = await newestExternalActivity(options, tenantId, now, ctx.db);
191
199
  if (isNewerThanBase(external, state)) {
192
200
  return startNewCycle({ ...state, lastActivityAt: external });
193
201
  }
@@ -1,6 +1,9 @@
1
1
  export const TENANT_INACTIVITY_FEATURE = "tenant-inactivity";
2
2
  export const TENANT_INACTIVITY_STATE_ENTITY = "tenant-inactivity-state";
3
- export const TENANT_OWNER_ROLE = "TenantOwner";
3
+
4
+ // Everyone who may react to the warning: the account-close roles plus TenantAdmin, so the mail
5
+ // reaches exactly the people who can open the keep-account link and read the state.
6
+ export const TENANT_KEEP_ACCOUNT_ROLES = ["TenantOwner", "TenantAdmin", "Admin"] as const;
4
7
 
5
8
  export const TenantInactivityJobs = {
6
9
  check: `${TENANT_INACTIVITY_FEATURE}:job:check-inactive-tenants`,
@@ -2,6 +2,7 @@ import { createTenantDb, type TenantDb } from "@cosmicdrift/kumiko-framework/db"
2
2
  import { defineQueryHandler, parseTenantId } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { AccessDeniedError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import * as z from "zod";
5
+ import { TENANT_KEEP_ACCOUNT_ROLES } from "../constants.ts";
5
6
  import { describeOutlook, foldActivity } from "../inactivity-plan.ts";
6
7
  import { resolveInactivityRule, type TenantInactivityOptions } from "../options.ts";
7
8
  import { loadInactivityState, loadNewestSessionActivity } from "../state-store.ts";
@@ -17,7 +18,7 @@ export function createInactivityStateQuery<TTier extends string>(
17
18
  return defineQueryHandler({
18
19
  name: "state",
19
20
  schema: z.object({ tenantIdOverride: z.string().min(1).max(36).optional() }),
20
- access: { roles: ["TenantOwner", "TenantAdmin", "SystemAdmin"] },
21
+ access: { roles: [...TENANT_KEEP_ACCOUNT_ROLES, "SystemAdmin"] },
21
22
  escapeHatch: { grants: ["unsafeRaw"], reason: STATE_QUERY_ESCAPE_HATCH_REASON },
22
23
  description:
23
24
  "Returns whether the tenant is exempt from inactivity deletion, its last activity, the warnings already sent and the next step with its date; owners and admins see their own tenant, a SystemAdmin any tenant.",
@@ -2,6 +2,7 @@ import { fetchOne, updateMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import * as z from "zod";
5
+ import { TENANT_KEEP_ACCOUNT_ROLES } from "../constants.ts";
5
6
  import { redeemKeepAccountToken } from "../keep-token.ts";
6
7
  import { tenantInactivityStateTable } from "../state-table.ts";
7
8
 
@@ -13,7 +14,7 @@ export function createKeepAccountHandler(opts: { readonly keepAccountTokenSecret
13
14
  name: "keep-account",
14
15
  schema: z.object({ token: z.string().min(1) }),
15
16
  access: {
16
- roles: ["anonymous", "Member", "User", "TenantAdmin", "TenantOwner", "SystemAdmin"],
17
+ roles: ["anonymous", "Member", "User", ...TENANT_KEEP_ACCOUNT_ROLES, "SystemAdmin"],
17
18
  anySignedIn: true,
18
19
  },
19
20
  escapeHatch: { grants: ["unsafeRaw"], reason: KEEP_ACCOUNT_ESCAPE_HATCH_REASON },
@@ -7,6 +7,7 @@ import type { InactivityRule } from "./inactivity-plan.ts";
7
7
  export type TenantActivitySource = (args: {
8
8
  readonly tenantId: TenantId;
9
9
  readonly now: Temporal.Instant;
10
+ readonly db: TenantDb;
10
11
  }) => Promise<Temporal.Instant | null>;
11
12
 
12
13
  type SharedOptions = {
@@ -4,12 +4,15 @@ import * as z from "zod";
4
4
 
5
5
  const probeResponseSchema = z.object({ lastActivityAt: z.string().nullable() });
6
6
 
7
+ // A sleeping app (scale-to-zero) needs 23-24 s to wake and up to 45 s on its first start.
8
+ export const REMOTE_ACTIVITY_TIMEOUT_MS = 60_000;
9
+
7
10
  type SendRequest = (url: string, init: RequestInit) => Promise<Response>;
8
11
 
9
12
  /**
10
13
  * Asks a sibling app for its newest session activity (the sessions `lastActivityProbeSecret`
11
14
  * route). Use it inside a `TenantActivitySource` so a user active in the other app keeps the
12
- * account alive. Fails closed: any error throws, and the job then sends no mail and files no
15
+ * account alive. Fails closed: any error or timeout throws, and the job then sends no mail and files no
13
16
  * deletion request for that run. `send` exists for tests; production uses the internal egress
14
17
  * pinned to the origin of `url`.
15
18
  */
@@ -17,12 +20,14 @@ export async function fetchRemoteAppLastActivity(args: {
17
20
  readonly url: string;
18
21
  readonly secret: string;
19
22
  readonly send?: SendRequest;
23
+ readonly timeoutMs?: number;
20
24
  }): Promise<Temporal.Instant | null> {
21
25
  // Sibling apps sit in the same cluster on private addresses, which the external policy blocks.
22
26
  const send = args.send ?? egress({ kind: "internal", allowOrigins: [new URL(args.url).origin] });
23
27
  const response = await send(args.url, {
24
28
  method: "GET",
25
29
  headers: { authorization: `Bearer ${args.secret}` },
30
+ signal: AbortSignal.timeout(args.timeoutMs ?? REMOTE_ACTIVITY_TIMEOUT_MS),
26
31
  });
27
32
  if (!response.ok) {
28
33
  throw new Error(`remote activity probe answered ${response.status}`);
@@ -0,0 +1,37 @@
1
+ // DOM-free "keep my account" page for static sites: fetch plus pure logic only.
2
+ // The link in the warning mail carries the token in the URL fragment (`#token=`), which browsers
3
+ // never send to a server or in a Referer.
4
+
5
+ import {
6
+ dispatchWrite,
7
+ type StaticRequestOptions,
8
+ type StaticResult,
9
+ staticSuccess,
10
+ takeUrlToken,
11
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
12
+ import { TenantInactivityHandlers } from "./constants.ts";
13
+
14
+ export {
15
+ hrefWithoutUrlToken,
16
+ readUrlToken,
17
+ STATIC_NETWORK_REASON,
18
+ STATIC_RATE_LIMITED_REASON,
19
+ type StaticFailure,
20
+ type StaticRequestOptions,
21
+ type StaticResult,
22
+ type StaticSuccess,
23
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
24
+
25
+ /** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
26
+ export function takeKeepAccountToken(): string {
27
+ return takeUrlToken("fragment");
28
+ }
29
+
30
+ /** A used, replaced or expired link fails with reason `invalid_or_expired_token`. */
31
+ export async function keepAccount(
32
+ token: string,
33
+ options?: StaticRequestOptions,
34
+ ): Promise<StaticResult<undefined>> {
35
+ const result = await dispatchWrite(TenantInactivityHandlers.keepAccount, { token }, options);
36
+ return result.kind === "success" ? staticSuccess(undefined) : result;
37
+ }
@@ -1,5 +1,7 @@
1
1
  export const TENANT_LIFECYCLE_FEATURE = "tenant-lifecycle" as const;
2
2
 
3
+ export const TENANT_ACCOUNT_CLOSE_ROLES = ["TenantOwner", "Admin"] as const;
4
+
3
5
  export const TENANT_AGGREGATE_TYPE = "tenant" as const;
4
6
 
5
7
  const EVENT_PREFIX = `${TENANT_LIFECYCLE_FEATURE}:event:` as const;
@@ -5,7 +5,11 @@ import { appendDomainEventCore } from "@cosmicdrift/kumiko-framework/pipeline";
5
5
  import * as z from "zod";
6
6
  import { isWithinGracePeriod } from "../../shared/index.ts";
7
7
  import { type TenantLifecycleStatus, tenantEntity, tenantTable } from "../../tenant/index.ts";
8
- import { DESTRUCTION_CANCELLED_EVENT_QN, TENANT_LIFECYCLE_FEATURE } from "../constants.ts";
8
+ import {
9
+ DESTRUCTION_CANCELLED_EVENT_QN,
10
+ TENANT_ACCOUNT_CLOSE_ROLES,
11
+ TENANT_LIFECYCLE_FEATURE,
12
+ } from "../constants.ts";
9
13
  import { invalidateTenantLifecycleGate } from "../lifecycle-gate.ts";
10
14
 
11
15
  const crud = createEventStoreExecutor(tenantTable, tenantEntity, { entityName: "tenant" });
@@ -21,7 +25,7 @@ const CANCEL_DESTRUCTION_TENANT_ROW_REASON =
21
25
  export const cancelDestructionWrite = defineWriteHandler({
22
26
  name: "cancel-destruction",
23
27
  schema: z.object({}),
24
- access: { roles: ["TenantOwner", "Admin"] },
28
+ access: { roles: TENANT_ACCOUNT_CLOSE_ROLES },
25
29
  description:
26
30
  "Returns a tenant whose destruction was requested back to active and clears the grace period; use it to undo a close-account request while the grace period is still running.",
27
31
  escapeHatch: {
@@ -1,5 +1,6 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import * as z from "zod";
3
+ import { TENANT_ACCOUNT_CLOSE_ROLES } from "../constants.ts";
3
4
  import { requestTenantDestruction } from "../request-tenant-destruction.ts";
4
5
 
5
6
  const REQUEST_DESTRUCTION_TENANT_ROW_REASON =
@@ -8,7 +9,7 @@ const REQUEST_DESTRUCTION_TENANT_ROW_REASON =
8
9
  export const requestDestructionWrite = defineWriteHandler({
9
10
  name: "request-destruction",
10
11
  schema: z.object({}),
11
- access: { roles: ["TenantOwner", "Admin"] },
12
+ access: { roles: TENANT_ACCOUNT_CLOSE_ROLES },
12
13
  description:
13
14
  "Puts the caller's own tenant into destroyRequested, starts the compliance-profile grace period after which its data is erased, and revokes every session in the tenant; use it when an account owner asks to close their account.",
14
15
  agent: { risk: "high" },
@@ -4,6 +4,7 @@ export {
4
4
  TENANT_DESTROY_ARCHIVED_BY,
5
5
  } from "./archive-and-delete-tenant-rows.ts";
6
6
  export {
7
+ TENANT_ACCOUNT_CLOSE_ROLES,
7
8
  TENANT_DESTRUCTION_STAGE_FAILED_EVENT_QN,
8
9
  TENANT_DESTRUCTION_STAGE_PROGRESSED_EVENT_QN,
9
10
  TENANT_DESTRUCTION_STAGES,
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "improvement",
5
+ "title": "waitlist/static-submit, a DOM-free waitlist sign-up client",
6
+ "detail": "`@cosmicdrift/kumiko-bundled-features/waitlist/static-submit` exports `submitToWaitlist(submission)` for plain Astro scripts: fetch plus pure logic, no renderer, React or `window` at import time. It posts `waitlist:write:submit` same-origin with name, email, optional company, portfolio and message, the page locale (also sent as `X-Locale`) and the honeypot field `website`. Blank optional fields are dropped. The result is a discriminated union `{ kind: \"success\"; data } | { kind: \"failure\"; reason; message?; retryAfterSeconds? }`; a network error is the reason `network`, a 429 is `rate_limited`."
7
+ },
2
8
  {
3
9
  "version": "0.410.0",
4
10
  "type": "fix",
@@ -0,0 +1,56 @@
1
+ // DOM-free waitlist sign-up for static sites: fetch plus pure logic only.
2
+
3
+ import {
4
+ dispatchWrite,
5
+ type StaticResult,
6
+ staticSuccess,
7
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
8
+ import { WaitlistHandlers } from "./web/constants.ts";
9
+
10
+ export {
11
+ STATIC_NETWORK_REASON,
12
+ STATIC_RATE_LIMITED_REASON,
13
+ type StaticFailure,
14
+ type StaticResult,
15
+ type StaticSuccess,
16
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
17
+
18
+ export type WaitlistSubmission = {
19
+ readonly name: string;
20
+ readonly email: string;
21
+ readonly company?: string;
22
+ readonly portfolio?: string;
23
+ readonly message?: string;
24
+ /** BCP 47 tag of the page language; also picks the language of the confirmation mail. */
25
+ readonly locale: string;
26
+ /** Honeypot: render it as a hidden field named `website` and pass its value through unchanged. */
27
+ readonly website?: string;
28
+ };
29
+
30
+ function nonBlank(value: string | undefined): string | undefined {
31
+ return value === undefined || value.trim() === "" ? undefined : value;
32
+ }
33
+
34
+ /** Success reads the same for a new and an already listed address. */
35
+ export async function submitToWaitlist(
36
+ submission: WaitlistSubmission,
37
+ ): Promise<StaticResult<undefined>> {
38
+ const { name, email, locale, website } = submission;
39
+ const company = nonBlank(submission.company);
40
+ const portfolio = nonBlank(submission.portfolio);
41
+ const message = nonBlank(submission.message);
42
+ const result = await dispatchWrite(
43
+ WaitlistHandlers.submit,
44
+ {
45
+ name,
46
+ email,
47
+ locale,
48
+ ...(company !== undefined && { company }),
49
+ ...(portfolio !== undefined && { portfolio }),
50
+ ...(message !== undefined && { message }),
51
+ ...(website !== undefined && { website }),
52
+ },
53
+ { locale },
54
+ );
55
+ return result.kind === "success" ? staticSuccess(undefined) : result;
56
+ }