@cosmicdrift/kumiko-samples 0.410.0 → 0.412.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 (122) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +31 -1
  3. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +64 -3
  4. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +13 -130
  5. package/packages/bundled-features/src/agent-tools/api-docs/anchors.ts +60 -0
  6. package/packages/bundled-features/src/agent-tools/api-docs/check.ts +25 -0
  7. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +140 -0
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +175 -0
  9. package/packages/bundled-features/src/agent-tools/api-docs/curl.ts +28 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/error-table.ts +45 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/examples.ts +43 -0
  12. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +179 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/index-json.ts +29 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +21 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/list-parameters.ts +38 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/markdown.ts +70 -0
  17. package/packages/bundled-features/src/agent-tools/api-docs/menu-path.ts +82 -0
  18. package/packages/bundled-features/src/agent-tools/api-docs/model.ts +83 -0
  19. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +58 -0
  20. package/packages/bundled-features/src/agent-tools/api-docs/render-events.ts +76 -0
  21. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +216 -0
  22. package/packages/bundled-features/src/agent-tools/api-docs/render-overview.ts +86 -0
  23. package/packages/bundled-features/src/agent-tools/api-docs/render-reference.ts +79 -0
  24. package/packages/bundled-features/src/agent-tools/api-docs/render-tokens.ts +136 -0
  25. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +167 -0
  26. package/packages/bundled-features/src/agent-tools/api-docs/section-ids.ts +28 -0
  27. package/packages/bundled-features/src/agent-tools/api-docs/system-only.ts +11 -0
  28. package/packages/bundled-features/src/agent-tools/api-docs/texts/de.ts +166 -0
  29. package/packages/bundled-features/src/agent-tools/api-docs/texts/en.ts +159 -0
  30. package/packages/bundled-features/src/agent-tools/api-docs/texts/es.ts +162 -0
  31. package/packages/bundled-features/src/agent-tools/api-docs/texts/fr.ts +169 -0
  32. package/packages/bundled-features/src/agent-tools/api-docs/texts/index.ts +67 -0
  33. package/packages/bundled-features/src/agent-tools/api-docs/texts/it.ts +165 -0
  34. package/packages/bundled-features/src/agent-tools/api-docs/texts/types.ts +130 -0
  35. package/packages/bundled-features/src/agent-tools/api-docs/ui-writes.ts +81 -0
  36. package/packages/bundled-features/src/agent-tools/changes.json +24 -0
  37. package/packages/bundled-features/src/agent-tools/handler-schema.ts +45 -0
  38. package/packages/bundled-features/src/agent-tools/index.ts +24 -0
  39. package/packages/bundled-features/src/agent-tools/labels.ts +181 -0
  40. package/packages/bundled-features/src/auth-email-password/changes.json +24 -0
  41. package/packages/bundled-features/src/auth-email-password/seeding.ts +84 -6
  42. package/packages/bundled-features/src/auth-email-password/web/i18n.ts +1 -0
  43. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +48 -3
  44. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +190 -0
  45. package/packages/bundled-features/src/auth-email-password/web/static-client.ts +226 -0
  46. package/packages/bundled-features/src/foundation-shared/demo-admin-env.ts +11 -0
  47. package/packages/bundled-features/src/foundation-shared/index.ts +5 -1
  48. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  49. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +99 -71
  50. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +2 -2
  51. package/packages/bundled-features/src/inbound-provider-imap/changes.json +6 -0
  52. package/packages/bundled-features/src/inbound-provider-imap/imap-client.ts +3 -1
  53. package/packages/bundled-features/src/personal-access-tokens/changes.json +6 -0
  54. package/packages/bundled-features/src/personal-access-tokens/feature.ts +5 -2
  55. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +7 -2
  56. package/packages/bundled-features/src/personal-access-tokens/i18n.ts +6 -1
  57. package/packages/bundled-features/src/personal-access-tokens/index.ts +37 -2
  58. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +28 -0
  59. package/packages/bundled-features/src/personal-access-tokens/screens.ts +9 -1
  60. package/packages/bundled-features/src/personal-access-tokens/web/constants.ts +1 -0
  61. package/packages/bundled-features/src/personal-access-tokens/web/scopes.ts +14 -0
  62. package/packages/bundled-features/src/presence/changes.json +8 -0
  63. package/packages/bundled-features/src/presence/feature.ts +25 -0
  64. package/packages/bundled-features/src/presence/handlers/heartbeat.write.ts +52 -0
  65. package/packages/bundled-features/src/presence/handlers/leave.write.ts +41 -0
  66. package/packages/bundled-features/src/presence/handlers/list.query.ts +39 -0
  67. package/packages/bundled-features/src/presence/index.ts +7 -0
  68. package/packages/bundled-features/src/presence/options.ts +30 -0
  69. package/packages/bundled-features/src/presence/payloads.ts +26 -0
  70. package/packages/bundled-features/src/presence/room.ts +65 -0
  71. package/packages/bundled-features/src/presence/store.ts +185 -0
  72. package/packages/bundled-features/src/sessions/feature.ts +6 -2
  73. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +19 -0
  74. package/packages/bundled-features/src/tenant-inactivity/changes.json +12 -0
  75. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +14 -6
  76. package/packages/bundled-features/src/tenant-inactivity/constants.ts +4 -1
  77. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +2 -1
  78. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +2 -1
  79. package/packages/bundled-features/src/tenant-inactivity/options.ts +1 -0
  80. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +6 -1
  81. package/packages/bundled-features/src/tenant-inactivity/static-keep-account.ts +37 -0
  82. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +2 -0
  83. package/packages/bundled-features/src/tenant-lifecycle/handlers/cancel-destruction.write.ts +6 -2
  84. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +2 -1
  85. package/packages/bundled-features/src/tenant-lifecycle/index.ts +1 -0
  86. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  87. package/packages/bundled-features/src/waitlist/static-submit.ts +56 -0
  88. package/samples/apps/styleguide/src/features/widgets/i18n.ts +143 -0
  89. package/samples/apps/styleguide/src/features/widgets/web/VariantsDemo.tsx +276 -0
  90. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +3 -0
  91. package/samples/apps/styleguide/src/features/workboard/feature.ts +1 -0
  92. package/samples/apps/use-all-bundled/feature-manifest.json +23 -1
  93. package/samples/apps/use-all-bundled/src/run-config.ts +3 -0
  94. package/samples/recipes/api-docs/README.md +52 -0
  95. package/samples/recipes/api-docs/api-docs/de/events.md +62 -0
  96. package/samples/recipes/api-docs/api-docs/de/overview.md +100 -0
  97. package/samples/recipes/api-docs/api-docs/de/reference/tickets.md +305 -0
  98. package/samples/recipes/api-docs/api-docs/de/tokens.md +66 -0
  99. package/samples/recipes/api-docs/api-docs/en/events.md +62 -0
  100. package/samples/recipes/api-docs/api-docs/en/overview.md +100 -0
  101. package/samples/recipes/api-docs/api-docs/en/reference/tickets.md +305 -0
  102. package/samples/recipes/api-docs/api-docs/en/tokens.md +66 -0
  103. package/samples/recipes/api-docs/api-docs/index.json +371 -0
  104. package/samples/recipes/api-docs/api-docs/openapi.json +982 -0
  105. package/samples/recipes/api-docs/api-examples/ticket-close.json +21 -0
  106. package/samples/recipes/api-docs/api-examples/ticket-create.json +42 -0
  107. package/samples/recipes/api-docs/api-examples/ticket-detail.json +28 -0
  108. package/samples/recipes/api-docs/api-examples/ticket-list.json +31 -0
  109. package/samples/recipes/api-docs/api-examples/ticket-update.json +54 -0
  110. package/samples/recipes/api-docs/api-examples/webhooks/ticket-closed.json +8 -0
  111. package/samples/recipes/api-docs/api-examples/webhooks/ticket-created.json +10 -0
  112. package/samples/recipes/api-docs/kumiko.config.ts +33 -0
  113. package/samples/recipes/api-docs/package.json +14 -0
  114. package/samples/recipes/api-docs/src/feature.ts +218 -0
  115. package/samples/recipes/api-docs/tsconfig.json +22 -0
  116. package/samples/recipes/realtime-sse/README.md +1 -0
  117. package/samples/recipes/realtime-sse/package.json +1 -0
  118. package/samples/recipes/realtime-sse/src/feature.ts +9 -0
  119. package/samples/recipes/record-detail-layout/README.md +1 -0
  120. package/samples/recipes/record-detail-layout/src/feature.ts +10 -0
  121. package/samples/recipes/wizard-form/README.md +9 -0
  122. package/samples/recipes/wizard-form/src/feature.ts +13 -2
@@ -0,0 +1,181 @@
1
+ import type { TranslationEntry, TranslationKeys } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { translationValueOtherText } from "@cosmicdrift/kumiko-framework/ui-types";
3
+
4
+ const FALLBACK_LOCALE = "en";
5
+
6
+ // localeCompare depends on the runtime locale and ICU punctuation rules; qualified
7
+ // names contain `:`, so compare by code point instead for deterministic ordering.
8
+ export function compareIds(a: string, b: string): number {
9
+ return a < b ? -1 : a > b ? 1 : 0;
10
+ }
11
+
12
+ /** Requested locale, then English, then the first remaining locale in code-point
13
+ * order; `undefined` when the entry has no text at all (the key is then omitted). */
14
+ export function pickLabel(
15
+ labels: Readonly<Record<string, string>>,
16
+ locale: string,
17
+ ): string | undefined {
18
+ const nonEmpty = (value: string | undefined): string | undefined =>
19
+ value !== undefined && value !== "" ? value : undefined;
20
+ const firstLocale = Object.keys(labels)
21
+ .sort(compareIds)
22
+ .find((key) => nonEmpty(labels[key]));
23
+ return (
24
+ nonEmpty(labels[locale]) ??
25
+ nonEmpty(labels[FALLBACK_LOCALE]) ??
26
+ (firstLocale !== undefined ? labels[firstLocale] : undefined)
27
+ );
28
+ }
29
+
30
+ /** The manifest surfaces one string per locale — a plural entry reads as its
31
+ * CLDR `other` form since the manifest has no `count` to select a category. */
32
+ export function entryAsLabels(entry: TranslationEntry): Readonly<Record<string, string>> {
33
+ return Object.fromEntries(
34
+ Object.entries(entry).map(([locale, value]) => [locale, translationValueOtherText(value)]),
35
+ );
36
+ }
37
+
38
+ const labelsIndexByTranslations = new WeakMap<TranslationKeys, Map<string, SuffixMatch>>();
39
+
40
+ type SuffixMatch = { readonly key: string; readonly labels: Readonly<Record<string, string>> };
41
+
42
+ /** Every tail starting at a key boundary (`:` or `.`, with and without the
43
+ * separator) maps to the first key that ends with it. */
44
+ function buildSuffixIndex(translations: TranslationKeys): Map<string, SuffixMatch> {
45
+ const index = new Map<string, SuffixMatch>();
46
+ for (const [key, entry] of Object.entries(translations)) {
47
+ const match: SuffixMatch = { key, labels: entryAsLabels(entry) };
48
+ const addTail = (start: number): void => {
49
+ const tail = key.slice(start);
50
+ if (!index.has(tail)) index.set(tail, match);
51
+ };
52
+ addTail(0);
53
+ for (let position = 0; position < key.length; position++) {
54
+ if (key[position] === ":" || key[position] === ".") {
55
+ addTail(position);
56
+ addTail(position + 1);
57
+ }
58
+ }
59
+ }
60
+ return index;
61
+ }
62
+
63
+ /** Translation keys carry a feature prefix the manifest can't reconstruct
64
+ * (`showcase:entity:item:field:title`), so match on the suffix instead. The
65
+ * suffix must start at a `:` or `.` boundary of the key. */
66
+ export function labelsForSuffix(
67
+ translations: TranslationKeys,
68
+ suffix: string,
69
+ ): Readonly<Record<string, string>> {
70
+ return suffixMatch(translations, suffix)?.labels ?? {};
71
+ }
72
+
73
+ function suffixMatch(translations: TranslationKeys, suffix: string): SuffixMatch | undefined {
74
+ let index = labelsIndexByTranslations.get(translations);
75
+ if (index === undefined) {
76
+ index = buildSuffixIndex(translations);
77
+ labelsIndexByTranslations.set(translations, index);
78
+ }
79
+ return index.get(suffix);
80
+ }
81
+
82
+ const LOCALE_PACKAGE_PREFIX = "locale-";
83
+
84
+ const localePackageKeysByTranslations = new WeakMap<TranslationKeys, Map<string, string[]>>();
85
+
86
+ /** Locale packages register their entries as `locale-<xx>:<key>`; map each `<key>` to
87
+ * the registered keys that carry it, in code-point order. */
88
+ function localePackageKeys(translations: TranslationKeys): Map<string, string[]> {
89
+ let index = localePackageKeysByTranslations.get(translations);
90
+ if (index === undefined) {
91
+ index = new Map<string, string[]>();
92
+ for (const key of Object.keys(translations).sort(compareIds)) {
93
+ if (!key.startsWith(LOCALE_PACKAGE_PREFIX)) continue;
94
+ const name = key.slice(key.indexOf(":") + 1);
95
+ index.set(name, [...(index.get(name) ?? []), key]);
96
+ }
97
+ localePackageKeysByTranslations.set(translations, index);
98
+ }
99
+ return index;
100
+ }
101
+
102
+ /** The labels of `fullKey` per locale, completed by locale packages that translate it
103
+ * under `locale-<xx>:<fullKey>` or, for `<feature>:<key>`, under `locale-<xx>:<key>`.
104
+ * The owner's text wins, then the locale packages in code-point order. */
105
+ export function localizedLabels(
106
+ translations: TranslationKeys,
107
+ fullKey: string,
108
+ ): Readonly<Record<string, string>> {
109
+ const plainKey = fullKey.includes(":") ? fullKey.slice(fullKey.indexOf(":") + 1) : undefined;
110
+ const packages = localePackageKeys(translations);
111
+ const keys = [
112
+ ...(translations[fullKey] === undefined ? [] : [fullKey]),
113
+ ...[
114
+ ...new Set([
115
+ ...(packages.get(fullKey) ?? []),
116
+ ...(plainKey ? (packages.get(plainKey) ?? []) : []),
117
+ ]),
118
+ ].sort(compareIds),
119
+ ];
120
+ const merged: Record<string, string> = {};
121
+ for (const key of keys) {
122
+ for (const [locale, label] of Object.entries(entryAsLabels(translations[key] ?? {}))) {
123
+ if (merged[locale] === undefined) merged[locale] = label;
124
+ }
125
+ }
126
+ return merged;
127
+ }
128
+
129
+ /** `labelsForSuffix` with the locale-package completion of `localizedLabels`: the owner
130
+ * key behind the suffix is preferred over a locale package key that ends the same way. */
131
+ export function localizedLabelsForSuffix(
132
+ translations: TranslationKeys,
133
+ suffix: string,
134
+ ): Readonly<Record<string, string>> {
135
+ const match = suffixMatch(translations, suffix);
136
+ if (match === undefined) return {};
137
+ const owner = Object.keys(translations).find(
138
+ (key) => !key.startsWith(LOCALE_PACKAGE_PREFIX) && key.endsWith(suffix),
139
+ );
140
+ return localizedLabels(translations, owner ?? match.key);
141
+ }
142
+
143
+ /** Entity field label per locale; `field` may be a dotted path, only its last segment names the field. */
144
+ export function entityFieldLabels(
145
+ translations: TranslationKeys,
146
+ entity: string,
147
+ field: string,
148
+ ): Readonly<Record<string, string>> {
149
+ return localizedLabelsForSuffix(
150
+ translations,
151
+ `:entity:${entity}:field:${field.slice(field.lastIndexOf(".") + 1)}`,
152
+ );
153
+ }
154
+
155
+ function lastSegmentOf(qualifiedId: string): string {
156
+ return qualifiedId.slice(qualifiedId.lastIndexOf(":") + 1);
157
+ }
158
+
159
+ /** Screen titles live under the qualified id or, for feature-local screens, under
160
+ * `screen:<shortId>.title`. */
161
+ export function screenTitleLabels(
162
+ translations: TranslationKeys,
163
+ screenId: string,
164
+ ): Readonly<Record<string, string>> {
165
+ return entryAsLabels(
166
+ translations[`${screenId}.title`] ??
167
+ translations[`screen:${lastSegmentOf(screenId)}.title`] ??
168
+ {},
169
+ );
170
+ }
171
+
172
+ /** `screenTitleLabels` completed by locale packages (see `localizedLabels`). */
173
+ export function localizedScreenTitleLabels(
174
+ translations: TranslationKeys,
175
+ screenId: string,
176
+ ): Readonly<Record<string, string>> {
177
+ const own = localizedLabels(translations, `${screenId}.title`);
178
+ return Object.keys(own).length > 0
179
+ ? own
180
+ : localizedLabels(translations, `screen:${lastSegmentOf(screenId)}.title`);
181
+ }
@@ -1,4 +1,28 @@
1
1
  [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "improvement",
5
+ "title": "SignupScreen shows a closed state while self-registration is off",
6
+ "detail": "With a mounted dispatcher the screen asks `auth-email-password:query:signup-registration-status`. While `enabled` is false it renders the notice `auth.signup.closed` (de: \"Die Registrierung ist derzeit nur mit Einladung möglich.\") plus the login link instead of the form, and sends nothing. A failed status query reads as open. The status query needs a mounted `DispatcherProvider`; in standalone auth mounts without one the form always shows and the server still rejects `signup-request`. New key `auth.signup.closed` in en, de, es, fr and it."
7
+ },
8
+ {
9
+ "version": "0.411.0",
10
+ "type": "improvement",
11
+ "title": "auth-email-password/static-account, DOM-free account page clients",
12
+ "detail": "`@cosmicdrift/kumiko-bundled-features/auth-email-password/static-account` exports `fetchSignupRegistrationStatus`, `requestPasswordReset`, `resetPassword`, `verifyEmail`, `requestAccountUnlock`, `confirmAccountUnlock`, `logout`, `isSignedOutFailure`, `fetchInviteInfo`, `acceptInviteSignedIn`, `acceptInviteWithLogin` and `acceptInviteWithNewAccount` for plain Astro scripts, plus `takeUrlToken(\"query\" | \"fragment\")` to read a mail-link token and remove it from the address bar. Every call returns a `kind: \"success\" | \"failure\"` union with a `reason` and, for rate limits, `retryAfterSeconds`; a 401 without an error code reads as `unauthenticated`; none throws for an expected failure; a malformed CSRF cookie sends no CSRF header instead of failing the request. A `landingPath` from the server is passed on only when it is a safe same-origin path. The shared request core with the result types is exported as `auth-email-password/static-client`."
13
+ },
14
+ {
15
+ "version": "0.411.0",
16
+ "type": "improvement",
17
+ "title": "seedAdmin works without a password",
18
+ "detail": "`SeedAdminOptions.password` is optional. Without it the account is created without a password hash and sets one through the password-reset flow. An existing account with the same email keeps its hash, as before."
19
+ },
20
+ {
21
+ "version": "0.411.0",
22
+ "type": "fix",
23
+ "title": "Bootstrap admin seed is one-shot",
24
+ "detail": "`seedBootstrapAdmin` skips when the target tenant already has another member (also a removed one), so a deleted owner or one who changed their email is not re-created as a passwordless SystemAdmin on the next boot. Our own passwordless account without membership is still completed, and the has-password skip now re-checks the row right before the grants."
25
+ },
2
26
  {
3
27
  "version": "0.405.0",
4
28
  "type": "improvement",
@@ -29,6 +29,8 @@ import {
29
29
  import { ConflictError } from "@cosmicdrift/kumiko-framework/errors";
30
30
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
31
31
  import { hashPassword } from "../shared/index.ts";
32
+ // kumiko-lint-ignore cross-feature-import bootstrap admin seed checks whether the tenant already has members
33
+ import { tenantMembershipsTable } from "../tenant/membership-table.ts";
32
34
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
33
35
  import { type SeedTenantHooks, seedTenant, seedTenantMembership } from "../tenant/seeding.ts";
34
36
  // kumiko-lint-ignore cross-feature-import signup create-only guard reads the user projection by email
@@ -195,7 +197,8 @@ export async function provisionSignupAccount(
195
197
 
196
198
  export type SeedAdminOptions = {
197
199
  readonly email: string;
198
- readonly password: string;
200
+ /** Omit to seed an account without a password; it sets one via password reset. */
201
+ readonly password?: string;
199
202
  readonly displayName: string;
200
203
  /** Tenants where the admin is added as a member. Each tenant can have
201
204
  * its own role list, which lets the sample TenantSwitcher show different
@@ -234,14 +237,17 @@ export async function seedAdmin(
234
237
  await seedTenant(db, { id: m.tenantId, key: m.tenantKey, name: m.tenantName, ...byOption });
235
238
  }
236
239
 
237
- const { id: userId } = await seedUserWithPassword(db, {
240
+ const userFields = {
238
241
  email: options.email,
239
- password: options.password,
240
242
  displayName: options.displayName,
241
243
  ...(options.globalRoles !== undefined && { roles: options.globalRoles }),
242
244
  ...(options.emailVerified !== undefined && { emailVerified: options.emailVerified }),
243
245
  ...byOption,
244
- });
246
+ };
247
+ const { id: userId } =
248
+ options.password === undefined
249
+ ? await seedUser(db, userFields)
250
+ : await seedUserWithPassword(db, { ...userFields, password: options.password });
245
251
 
246
252
  for (const m of options.memberships) {
247
253
  await seedTenantMembership(db, {
@@ -344,6 +350,18 @@ async function findExistingUserIdForEmail(
344
350
  return matches.length === 0 ? undefined : pickCanonicalUserId(matches);
345
351
  }
346
352
 
353
+ async function seedAdminPlaintext(
354
+ db: DbConnection,
355
+ options: SeedAdminOptions,
356
+ mayGrantToExisting: ((row: Record<string, unknown>) => boolean) | undefined,
357
+ ): Promise<{ id: string }> {
358
+ if (mayGrantToExisting) {
359
+ const row = await fetchOne(db, userTable, { email: options.email, isDeleted: false });
360
+ if (row && !mayGrantToExisting(row)) return { id: String(row["id"]) };
361
+ }
362
+ return seedAdmin(db, options);
363
+ }
364
+
347
365
  /**
348
366
  * Boot-seed variant of seedAdmin that survives a blind-index miss on an
349
367
  * otherwise-existing account (see the module comment above). Not for the
@@ -361,9 +379,10 @@ async function findExistingUserIdForEmail(
361
379
  export async function seedAdminGuarded(
362
380
  db: DbConnection,
363
381
  options: SeedAdminOptions,
382
+ mayGrantToExisting?: (row: Record<string, unknown>) => boolean,
364
383
  ): Promise<{ id: string }> {
365
384
  const kms = configuredPiiSubjectKms();
366
- if (kms === undefined) return seedAdmin(db, options);
385
+ if (kms === undefined) return seedAdminPlaintext(db, options, mayGrantToExisting);
367
386
 
368
387
  // Without a bidx key every row seeded here gets a NULL email_bidx, which
369
388
  // neither seedAdmin's lookup nor the partial unique index can ever see.
@@ -383,8 +402,9 @@ export async function seedAdminGuarded(
383
402
  // Re-write the email so email_bidx is recomputed; without it the account
384
403
  // stays unfindable for login and every boot re-scans the whole table.
385
404
  await rewriteSeededUserEmail(db, existingRow, options.email, by);
405
+ const refreshed = (await fetchOne(db, userTable, { id: existingId })) ?? existingRow;
406
+ if (mayGrantToExisting && !mayGrantToExisting(refreshed)) return { id: existingId };
386
407
  if (options.emailVerified === true) {
387
- const refreshed = (await fetchOne(db, userTable, { id: existingId })) ?? existingRow;
388
408
  await reconcileSeededUserEmailVerified(db, refreshed, by);
389
409
  }
390
410
  }
@@ -399,3 +419,61 @@ export async function seedAdminGuarded(
399
419
  }
400
420
  return { id: existingId };
401
421
  }
422
+
423
+ async function findExistingUserRowForEmail(db: DbConnection, email: string) {
424
+ const kms = configuredPiiSubjectKms();
425
+ if (kms === undefined) return fetchOne(db, userTable, { email, isDeleted: false });
426
+ const existingId = await findExistingUserIdForEmail(db, kms, email);
427
+ return existingId === undefined ? undefined : fetchOne(db, userTable, { id: existingId });
428
+ }
429
+
430
+ function hasPassword(row: Record<string, unknown>): boolean {
431
+ return typeof row["passwordHash"] === "string" && row["passwordHash"] !== "";
432
+ }
433
+
434
+ /** Tenant already has a member other than `ownUserId` (soft-deleted memberships count). */
435
+ async function tenantHasForeignMember(
436
+ db: DbConnection,
437
+ tenantId: TenantId,
438
+ ownUserId: string | undefined,
439
+ ): Promise<boolean> {
440
+ const members = await selectMany(db, tenantMembershipsTable, { tenantId });
441
+ return members.some((member) => member["userId"] !== ownUserId);
442
+ }
443
+
444
+ /**
445
+ * One-shot boot seed for an account that sets its password later (password
446
+ * reset). Skipped when the account already has a password (owner after their
447
+ * reset, or a foreign self-registration: granting admin to the latter would be
448
+ * an escalation) and when the target tenant already has another member (owner
449
+ * deleted or changed their email: re-seeding would mint a new passwordless
450
+ * SystemAdmin). Only our own passwordless account is completed, so a partial
451
+ * earlier seed converges.
452
+ */
453
+ export async function seedBootstrapAdmin(
454
+ db: DbConnection,
455
+ options: SeedAdminOptions,
456
+ ): Promise<{ id: string } | { skipped: "has-password" | "tenant-has-members" }> {
457
+ const existing = await findExistingUserRowForEmail(db, options.email);
458
+ if (existing && hasPassword(existing)) {
459
+ log.info("seedBootstrapAdmin: the account already has a password, bootstrap seed skipped");
460
+ return { skipped: "has-password" };
461
+ }
462
+ const ownUserId = typeof existing?.["id"] === "string" ? existing["id"] : undefined;
463
+ for (const membership of options.memberships) {
464
+ if (await tenantHasForeignMember(db, membership.tenantId, ownUserId)) {
465
+ log.info("seedBootstrapAdmin: the tenant already has members, bootstrap seed skipped");
466
+ return { skipped: "tenant-has-members" };
467
+ }
468
+ }
469
+ let passwordAppeared = false;
470
+ const seeded = await seedAdminGuarded(db, options, (row) => {
471
+ passwordAppeared = hasPassword(row);
472
+ return !passwordAppeared;
473
+ });
474
+ if (passwordAppeared) {
475
+ log.info("seedBootstrapAdmin: the account got a password meanwhile, bootstrap seed skipped");
476
+ return { skipped: "has-password" };
477
+ }
478
+ return seeded;
479
+ }
@@ -98,6 +98,7 @@ export const defaultTranslations: TranslationsByLocale = {
98
98
  "auth.signup.title": "Create account",
99
99
  "auth.signup.intro":
100
100
  "Enter your email. We'll send you an activation link to set your password.",
101
+ "auth.signup.closed": "Sign-up is currently by invitation only.",
101
102
  "auth.signup.email": "Email",
102
103
  "auth.signup.submit": "Send activation link",
103
104
  "auth.signup.submitting": "…",
@@ -11,12 +11,18 @@
11
11
  // AuthGate). An apex marketing site can route its "Start for free" link to
12
12
  // the /signup path.
13
13
 
14
- import { usePrimitives, useTranslation } from "@cosmicdrift/kumiko-renderer";
14
+ import {
15
+ useOptionalDispatcher,
16
+ usePrimitives,
17
+ useQuery,
18
+ useTranslation,
19
+ } from "@cosmicdrift/kumiko-renderer";
15
20
  import { type FormEvent, type ReactNode, useState } from "react";
16
21
  import { requestSignup } from "./auth-client.ts";
17
22
  import { retryAfterMinutes } from "./auth-form-logic.ts";
18
23
  import { AuthCard } from "./auth-form-primitives.tsx";
19
24
  import { readReturnToFromWindow } from "./auth-redirect.ts";
25
+ import { AuthQueries } from "./constants.ts";
20
26
  import { isSafeReturnPath } from "./return-path.ts";
21
27
 
22
28
  export type SignupScreenProps = {
@@ -34,12 +40,13 @@ function resolveReturnTo(prop: string | undefined): string | undefined {
34
40
  return (isSafeReturnPath(prop) ? prop : readReturnToFromWindow()) ?? undefined;
35
41
  }
36
42
 
37
- export function SignupScreen({
43
+ function SignupScreenBody({
38
44
  title,
39
45
  subtitle,
40
46
  loginHref = "/login",
41
47
  returnTo,
42
- }: SignupScreenProps): ReactNode {
48
+ registrationOpen,
49
+ }: SignupScreenProps & { readonly registrationOpen: boolean | "unknown" }): ReactNode {
43
50
  const t = useTranslation();
44
51
  const { Form, Field, Input, Button, Banner, Link } = usePrimitives();
45
52
  const [email, setEmail] = useState("");
@@ -91,6 +98,25 @@ export function SignupScreen({
91
98
 
92
99
  const effectiveTitle = title ?? t("auth.signup.title");
93
100
 
101
+ if (registrationOpen === "unknown") {
102
+ return (
103
+ <AuthCard title={effectiveTitle} subtitle={subtitle}>
104
+ {null}
105
+ </AuthCard>
106
+ );
107
+ }
108
+
109
+ if (!registrationOpen) {
110
+ return (
111
+ <AuthCard title={effectiveTitle} subtitle={subtitle}>
112
+ <Banner variant="info">{t("auth.signup.closed")}</Banner>
113
+ <Link href={loginHref} variant="muted">
114
+ {t("auth.signup.haveAccount")}
115
+ </Link>
116
+ </AuthCard>
117
+ );
118
+ }
119
+
94
120
  return (
95
121
  <AuthCard title={effectiveTitle} subtitle={subtitle}>
96
122
  {done ? (
@@ -135,3 +161,22 @@ export function SignupScreen({
135
161
  </AuthCard>
136
162
  );
137
163
  }
164
+
165
+ type RegistrationStatus = { readonly enabled: boolean };
166
+
167
+ // A failed status query reads as open: signup-request itself stays the authority.
168
+ function SignupScreenWithQueriedStatus(props: SignupScreenProps): ReactNode {
169
+ const { data, loading } = useQuery<RegistrationStatus>(AuthQueries.signupRegistrationStatus, {});
170
+ const registrationOpen = loading && data === null ? "unknown" : data?.enabled !== false;
171
+ return <SignupScreenBody {...props} registrationOpen={registrationOpen} />;
172
+ }
173
+
174
+ // Without a mounted dispatcher (standalone mounts, tests) the status is not asked and the form shows.
175
+ export function SignupScreen(props: SignupScreenProps): ReactNode {
176
+ const dispatcher = useOptionalDispatcher();
177
+ return dispatcher === undefined ? (
178
+ <SignupScreenBody {...props} registrationOpen />
179
+ ) : (
180
+ <SignupScreenWithQueriedStatus {...props} />
181
+ );
182
+ }
@@ -0,0 +1,190 @@
1
+ // DOM-free account pages for static sites (plain Astro scripts): password reset, e-mail
2
+ // verification, invite acceptance and the signup registration status. Same import rules as
3
+ // static-login.ts: fetch plus pure logic, nothing that touches `window` at import time.
4
+
5
+ import { AuthQueries } from "./constants.ts";
6
+ import { isRecord } from "./login-failure.ts";
7
+ import { isSafeReturnPath } from "./return-path.ts";
8
+ import {
9
+ dispatchQuery,
10
+ postJson,
11
+ type StaticRequestOptions,
12
+ type StaticResult,
13
+ staticFailure,
14
+ staticSuccess,
15
+ } from "./static-client.ts";
16
+
17
+ export {
18
+ hrefWithoutUrlToken,
19
+ readUrlToken,
20
+ STATIC_MALFORMED_TOKEN_REASON,
21
+ STATIC_NETWORK_REASON,
22
+ STATIC_RATE_LIMITED_REASON,
23
+ type StaticFailure,
24
+ type StaticRequestOptions,
25
+ type StaticResult,
26
+ type StaticSuccess,
27
+ takeUrlToken,
28
+ type UrlTokenSource,
29
+ } from "./static-client.ts";
30
+
31
+ const UNEXPECTED_RESPONSE_REASON = "unexpected_response";
32
+
33
+ export type SignupRegistrationStatus = { readonly enabled: boolean };
34
+
35
+ /** A failed lookup should be read as open: signup-request itself stays the authority. */
36
+ export async function fetchSignupRegistrationStatus(): Promise<
37
+ StaticResult<SignupRegistrationStatus>
38
+ > {
39
+ const result = await dispatchQuery(AuthQueries.signupRegistrationStatus, {});
40
+ if (result.kind === "failure") return result;
41
+ if (!isRecord(result.data) || typeof result.data["enabled"] !== "boolean") {
42
+ return staticFailure(UNEXPECTED_RESPONSE_REASON);
43
+ }
44
+ return staticSuccess({ enabled: result.data["enabled"] });
45
+ }
46
+
47
+ async function postAuthRoute(
48
+ path: string,
49
+ payload: Record<string, unknown>,
50
+ options?: StaticRequestOptions,
51
+ ): Promise<StaticResult<undefined>> {
52
+ const result = await postJson(path, payload, options);
53
+ return result.kind === "success" ? staticSuccess(undefined) : result;
54
+ }
55
+
56
+ /** Answers success whether or not the address has an account, so it cannot be used to probe. */
57
+ export function requestPasswordReset(
58
+ email: string,
59
+ options: StaticRequestOptions & { readonly returnTo?: string } = {},
60
+ ): Promise<StaticResult<undefined>> {
61
+ const { returnTo, ...requestOptions } = options;
62
+ return postAuthRoute(
63
+ "/api/auth/request-password-reset",
64
+ { email, ...(isSafeReturnPath(returnTo) && { returnTo }) },
65
+ requestOptions,
66
+ );
67
+ }
68
+
69
+ export function resetPassword(
70
+ token: string,
71
+ newPassword: string,
72
+ options?: StaticRequestOptions,
73
+ ): Promise<StaticResult<undefined>> {
74
+ return postAuthRoute("/api/auth/reset-password", { token, newPassword }, options);
75
+ }
76
+
77
+ export function verifyEmail(
78
+ token: string,
79
+ options?: StaticRequestOptions,
80
+ ): Promise<StaticResult<undefined>> {
81
+ return postAuthRoute("/api/auth/verify-email", { token }, options);
82
+ }
83
+
84
+ /** Ends the current session; the server also clears the auth and CSRF cookies. */
85
+ export function logout(options?: StaticRequestOptions): Promise<StaticResult<undefined>> {
86
+ return postAuthRoute("/api/auth/logout", {}, options);
87
+ }
88
+
89
+ export { isSignedOutFailure } from "./static-client.ts";
90
+
91
+ export type InviteInfo = { readonly email: string; readonly hasAccount: boolean };
92
+
93
+ /** Reads the pending invitation without consuming the token. */
94
+ export async function fetchInviteInfo(
95
+ token: string,
96
+ options?: StaticRequestOptions,
97
+ ): Promise<StaticResult<InviteInfo>> {
98
+ const result = await postJson("/api/auth/invite-info", { token }, options);
99
+ if (result.kind === "failure") return result;
100
+ const { email, hasAccount } = result.data;
101
+ if (typeof email !== "string" || typeof hasAccount !== "boolean") {
102
+ return staticFailure(UNEXPECTED_RESPONSE_REASON);
103
+ }
104
+ return staticSuccess({ email, hasAccount });
105
+ }
106
+
107
+ export type InviteAccepted =
108
+ | {
109
+ readonly status: "accepted";
110
+ readonly tenantId: string;
111
+ readonly roles: readonly string[];
112
+ readonly landingPath?: string;
113
+ }
114
+ // The invitation is used up but no session was minted (MFA gate): send the user to login.
115
+ | { readonly status: "mfa-pending" };
116
+
117
+ function grantedRoles(body: Record<string, unknown>): readonly string[] {
118
+ const user = body["user"];
119
+ const sessionRoles = isRecord(user) ? user["roles"] : undefined;
120
+ if (Array.isArray(sessionRoles)) {
121
+ return sessionRoles.filter((role): role is string => typeof role === "string");
122
+ }
123
+ return typeof body["role"] === "string" ? [body["role"]] : [];
124
+ }
125
+
126
+ async function postInviteAccept(
127
+ path: string,
128
+ payload: Record<string, unknown>,
129
+ options?: StaticRequestOptions,
130
+ ): Promise<StaticResult<InviteAccepted>> {
131
+ const result = await postJson(path, payload, options);
132
+ if (result.kind === "failure") return result;
133
+ const body = result.data;
134
+ const tenantId = body["tenantId"];
135
+ if (typeof tenantId !== "string") return staticSuccess({ status: "mfa-pending" });
136
+ const landingPath = body["landingPath"];
137
+ return staticSuccess({
138
+ status: "accepted",
139
+ tenantId,
140
+ roles: grantedRoles(body),
141
+ ...(isSafeReturnPath(landingPath) && { landingPath }),
142
+ });
143
+ }
144
+
145
+ /** Visitor is signed in on this origin: attaches the invitation to that session. */
146
+ export function acceptInviteSignedIn(
147
+ token: string,
148
+ options?: StaticRequestOptions,
149
+ ): Promise<StaticResult<InviteAccepted>> {
150
+ return postInviteAccept("/api/auth/invite-accept", { token }, options);
151
+ }
152
+
153
+ /** Invited address already has an account: signs in and accepts. */
154
+ export function acceptInviteWithLogin(
155
+ token: string,
156
+ email: string,
157
+ password: string,
158
+ options?: StaticRequestOptions,
159
+ ): Promise<StaticResult<InviteAccepted>> {
160
+ return postInviteAccept(
161
+ "/api/auth/invite-accept-with-login",
162
+ { token, email, password },
163
+ options,
164
+ );
165
+ }
166
+
167
+ /** Invited address has no account yet: creates it with `password` and accepts. */
168
+ export function acceptInviteWithNewAccount(
169
+ token: string,
170
+ password: string,
171
+ options?: StaticRequestOptions,
172
+ ): Promise<StaticResult<InviteAccepted>> {
173
+ return postInviteAccept("/api/auth/invite-signup-complete", { token, password }, options);
174
+ }
175
+
176
+ /** Answers success whether or not the address exists or is locked, so it cannot be used to probe. */
177
+ export function requestAccountUnlock(
178
+ email: string,
179
+ options?: StaticRequestOptions,
180
+ ): Promise<StaticResult<undefined>> {
181
+ return postAuthRoute("/api/auth/request-account-unlock", { email }, options);
182
+ }
183
+
184
+ /** The mail link carries the token in the query (`?token=`). Confirming an unlocked account is a no-op. */
185
+ export function confirmAccountUnlock(
186
+ token: string,
187
+ options?: StaticRequestOptions,
188
+ ): Promise<StaticResult<undefined>> {
189
+ return postAuthRoute("/api/auth/confirm-account-unlock", { token }, options);
190
+ }