@cosmicdrift/kumiko-bundled-features 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 (151) hide show
  1. package/dist/agent-tools/agent-doc-lint.d.ts +9 -0
  2. package/dist/agent-tools/agent-doc-lint.js +42 -5
  3. package/dist/agent-tools/agent-manifest.d.ts +0 -1
  4. package/dist/agent-tools/agent-manifest.js +9 -99
  5. package/dist/agent-tools/api-docs/anchors.d.ts +14 -0
  6. package/dist/agent-tools/api-docs/anchors.js +49 -0
  7. package/dist/agent-tools/api-docs/check.d.ts +7 -0
  8. package/dist/agent-tools/api-docs/check.js +15 -0
  9. package/dist/agent-tools/api-docs/collect-events.d.ts +10 -0
  10. package/dist/agent-tools/api-docs/collect-events.js +90 -0
  11. package/dist/agent-tools/api-docs/collect.d.ts +15 -0
  12. package/dist/agent-tools/api-docs/collect.js +108 -0
  13. package/dist/agent-tools/api-docs/curl.d.ts +5 -0
  14. package/dist/agent-tools/api-docs/curl.js +24 -0
  15. package/dist/agent-tools/api-docs/error-table.d.ts +9 -0
  16. package/dist/agent-tools/api-docs/error-table.js +31 -0
  17. package/dist/agent-tools/api-docs/examples.d.ts +16 -0
  18. package/dist/agent-tools/api-docs/examples.js +25 -0
  19. package/dist/agent-tools/api-docs/generate.d.ts +19 -0
  20. package/dist/agent-tools/api-docs/generate.js +104 -0
  21. package/dist/agent-tools/api-docs/index-json.d.ts +15 -0
  22. package/dist/agent-tools/api-docs/index-json.js +6 -0
  23. package/dist/agent-tools/api-docs/index.d.ts +9 -0
  24. package/dist/agent-tools/api-docs/index.js +6 -0
  25. package/dist/agent-tools/api-docs/list-parameters.d.ts +61 -0
  26. package/dist/agent-tools/api-docs/list-parameters.js +28 -0
  27. package/dist/agent-tools/api-docs/markdown.d.ts +29 -0
  28. package/dist/agent-tools/api-docs/markdown.js +48 -0
  29. package/dist/agent-tools/api-docs/menu-path.d.ts +8 -0
  30. package/dist/agent-tools/api-docs/menu-path.js +60 -0
  31. package/dist/agent-tools/api-docs/model.d.ts +76 -0
  32. package/dist/agent-tools/api-docs/model.js +1 -0
  33. package/dist/agent-tools/api-docs/problems.d.ts +32 -0
  34. package/dist/agent-tools/api-docs/problems.js +28 -0
  35. package/dist/agent-tools/api-docs/render-events.d.ts +12 -0
  36. package/dist/agent-tools/api-docs/render-events.js +55 -0
  37. package/dist/agent-tools/api-docs/render-openapi.d.ts +10 -0
  38. package/dist/agent-tools/api-docs/render-openapi.js +170 -0
  39. package/dist/agent-tools/api-docs/render-overview.d.ts +11 -0
  40. package/dist/agent-tools/api-docs/render-overview.js +60 -0
  41. package/dist/agent-tools/api-docs/render-reference.d.ts +14 -0
  42. package/dist/agent-tools/api-docs/render-reference.js +50 -0
  43. package/dist/agent-tools/api-docs/render-tokens.d.ts +12 -0
  44. package/dist/agent-tools/api-docs/render-tokens.js +101 -0
  45. package/dist/agent-tools/api-docs/schema-fields.d.ts +16 -0
  46. package/dist/agent-tools/api-docs/schema-fields.js +141 -0
  47. package/dist/agent-tools/api-docs/section-ids.d.ts +25 -0
  48. package/dist/agent-tools/api-docs/section-ids.js +26 -0
  49. package/dist/agent-tools/api-docs/system-only.d.ts +5 -0
  50. package/dist/agent-tools/api-docs/system-only.js +7 -0
  51. package/dist/agent-tools/api-docs/texts/de.d.ts +123 -0
  52. package/dist/agent-tools/api-docs/texts/de.js +123 -0
  53. package/dist/agent-tools/api-docs/texts/en.d.ts +123 -0
  54. package/dist/agent-tools/api-docs/texts/en.js +123 -0
  55. package/dist/agent-tools/api-docs/texts/es.d.ts +123 -0
  56. package/dist/agent-tools/api-docs/texts/es.js +123 -0
  57. package/dist/agent-tools/api-docs/texts/fr.d.ts +123 -0
  58. package/dist/agent-tools/api-docs/texts/fr.js +123 -0
  59. package/dist/agent-tools/api-docs/texts/index.d.ts +14 -0
  60. package/dist/agent-tools/api-docs/texts/index.js +55 -0
  61. package/dist/agent-tools/api-docs/texts/it.d.ts +123 -0
  62. package/dist/agent-tools/api-docs/texts/it.js +123 -0
  63. package/dist/agent-tools/api-docs/texts/types.d.ts +18 -0
  64. package/dist/agent-tools/api-docs/texts/types.js +104 -0
  65. package/dist/agent-tools/api-docs/ui-writes.d.ts +12 -0
  66. package/dist/agent-tools/api-docs/ui-writes.js +73 -0
  67. package/dist/agent-tools/handler-schema.d.ts +5 -0
  68. package/dist/agent-tools/handler-schema.js +37 -0
  69. package/dist/agent-tools/index.d.ts +2 -1
  70. package/dist/agent-tools/index.js +2 -1
  71. package/dist/agent-tools/labels.d.ts +26 -0
  72. package/dist/agent-tools/labels.js +131 -0
  73. package/dist/auth-email-password/seeding.d.ts +17 -2
  74. package/dist/auth-email-password/seeding.js +68 -6
  75. package/dist/auth-email-password/web/i18n.js +1 -0
  76. package/dist/auth-email-password/web/signup-screen.d.ts +1 -1
  77. package/dist/auth-email-password/web/signup-screen.js +20 -2
  78. package/dist/auth-email-password/web/static-account.d.ts +40 -0
  79. package/dist/auth-email-password/web/static-account.js +94 -0
  80. package/dist/auth-email-password/web/static-client.d.ts +38 -0
  81. package/dist/auth-email-password/web/static-client.js +169 -0
  82. package/dist/foundation-shared/demo-admin-env.d.ts +4 -0
  83. package/dist/foundation-shared/demo-admin-env.js +7 -0
  84. package/dist/foundation-shared/index.d.ts +1 -1
  85. package/dist/foundation-shared/index.js +1 -1
  86. package/dist/inbound-mail-foundation/entities.d.ts +84 -0
  87. package/dist/inbound-mail-foundation/entities.js +96 -71
  88. package/dist/inbound-mail-foundation/feature.js +2 -2
  89. package/dist/inbound-provider-imap/imap-client.d.ts +1 -1
  90. package/dist/inbound-provider-imap/imap-client.js +3 -1
  91. package/dist/personal-access-tokens/feature.d.ts +1 -0
  92. package/dist/personal-access-tokens/feature.js +4 -2
  93. package/dist/personal-access-tokens/handlers/create.write.js +2 -2
  94. package/dist/personal-access-tokens/i18n.js +5 -1
  95. package/dist/personal-access-tokens/index.d.ts +4 -2
  96. package/dist/personal-access-tokens/index.js +29 -2
  97. package/dist/personal-access-tokens/scope-events-check.d.ts +3 -0
  98. package/dist/personal-access-tokens/scope-events-check.js +18 -0
  99. package/dist/personal-access-tokens/screens.js +8 -2
  100. package/dist/personal-access-tokens/web/constants.d.ts +1 -0
  101. package/dist/personal-access-tokens/web/constants.js +1 -0
  102. package/dist/personal-access-tokens/web/scopes.d.ts +2 -0
  103. package/dist/personal-access-tokens/web/scopes.js +12 -0
  104. package/dist/presence/feature.d.ts +3 -0
  105. package/dist/presence/feature.js +20 -0
  106. package/dist/presence/handlers/heartbeat.write.d.ts +12 -0
  107. package/dist/presence/handlers/heartbeat.write.js +31 -0
  108. package/dist/presence/handlers/leave.write.d.ts +8 -0
  109. package/dist/presence/handlers/leave.write.js +33 -0
  110. package/dist/presence/handlers/list.query.d.ts +7 -0
  111. package/dist/presence/handlers/list.query.js +28 -0
  112. package/dist/presence/index.d.ts +3 -0
  113. package/dist/presence/index.js +2 -0
  114. package/dist/presence/options.d.ts +17 -0
  115. package/dist/presence/options.js +13 -0
  116. package/dist/presence/payloads.d.ts +18 -0
  117. package/dist/presence/payloads.js +18 -0
  118. package/dist/presence/room.d.ts +13 -0
  119. package/dist/presence/room.js +35 -0
  120. package/dist/presence/store.d.ts +32 -0
  121. package/dist/presence/store.js +140 -0
  122. package/dist/sessions/feature.js +2 -2
  123. package/dist/sessions/handlers/last-activity-probe.route.d.ts +2 -0
  124. package/dist/sessions/handlers/last-activity-probe.route.js +14 -0
  125. package/dist/tenant-inactivity/check-inactive-tenants.js +12 -6
  126. package/dist/tenant-inactivity/constants.d.ts +1 -1
  127. package/dist/tenant-inactivity/constants.js +3 -1
  128. package/dist/tenant-inactivity/handlers/inactivity-state.query.js +2 -1
  129. package/dist/tenant-inactivity/handlers/keep-account.write.js +2 -1
  130. package/dist/tenant-inactivity/options.d.ts +1 -0
  131. package/dist/tenant-inactivity/remote-activity.d.ts +3 -1
  132. package/dist/tenant-inactivity/remote-activity.js +4 -1
  133. package/dist/tenant-inactivity/static-keep-account.d.ts +6 -0
  134. package/dist/tenant-inactivity/static-keep-account.js +15 -0
  135. package/dist/tenant-lifecycle/constants.d.ts +1 -0
  136. package/dist/tenant-lifecycle/constants.js +1 -0
  137. package/dist/tenant-lifecycle/handlers/cancel-destruction.write.js +2 -2
  138. package/dist/tenant-lifecycle/handlers/request-destruction.write.js +2 -1
  139. package/dist/tenant-lifecycle/index.d.ts +1 -1
  140. package/dist/tenant-lifecycle/index.js +1 -1
  141. package/dist/waitlist/static-submit.d.ts +15 -0
  142. package/dist/waitlist/static-submit.js +24 -0
  143. package/package.json +59 -11
  144. package/src/agent-tools/changes.json +24 -0
  145. package/src/auth-email-password/changes.json +24 -0
  146. package/src/inbound-mail-foundation/changes.json +6 -0
  147. package/src/inbound-provider-imap/changes.json +6 -0
  148. package/src/personal-access-tokens/changes.json +6 -0
  149. package/src/presence/changes.json +8 -0
  150. package/src/tenant-inactivity/changes.json +12 -0
  151. package/src/waitlist/changes.json +6 -0
@@ -0,0 +1,131 @@
1
+ import { translationValueOtherText } from "@cosmicdrift/kumiko-framework/ui-types";
2
+ const FALLBACK_LOCALE = "en";
3
+ // localeCompare depends on the runtime locale and ICU punctuation rules; qualified
4
+ // names contain `:`, so compare by code point instead for deterministic ordering.
5
+ export function compareIds(a, b) {
6
+ return a < b ? -1 : a > b ? 1 : 0;
7
+ }
8
+ /** Requested locale, then English, then the first remaining locale in code-point
9
+ * order; `undefined` when the entry has no text at all (the key is then omitted). */
10
+ export function pickLabel(labels, locale) {
11
+ const nonEmpty = (value) => value !== undefined && value !== "" ? value : undefined;
12
+ const firstLocale = Object.keys(labels)
13
+ .sort(compareIds)
14
+ .find((key) => nonEmpty(labels[key]));
15
+ return (nonEmpty(labels[locale]) ??
16
+ nonEmpty(labels[FALLBACK_LOCALE]) ??
17
+ (firstLocale !== undefined ? labels[firstLocale] : undefined));
18
+ }
19
+ /** The manifest surfaces one string per locale — a plural entry reads as its
20
+ * CLDR `other` form since the manifest has no `count` to select a category. */
21
+ export function entryAsLabels(entry) {
22
+ return Object.fromEntries(Object.entries(entry).map(([locale, value]) => [locale, translationValueOtherText(value)]));
23
+ }
24
+ const labelsIndexByTranslations = new WeakMap();
25
+ /** Every tail starting at a key boundary (`:` or `.`, with and without the
26
+ * separator) maps to the first key that ends with it. */
27
+ function buildSuffixIndex(translations) {
28
+ const index = new Map();
29
+ for (const [key, entry] of Object.entries(translations)) {
30
+ const match = { key, labels: entryAsLabels(entry) };
31
+ const addTail = (start) => {
32
+ const tail = key.slice(start);
33
+ if (!index.has(tail))
34
+ index.set(tail, match);
35
+ };
36
+ addTail(0);
37
+ for (let position = 0; position < key.length; position++) {
38
+ if (key[position] === ":" || key[position] === ".") {
39
+ addTail(position);
40
+ addTail(position + 1);
41
+ }
42
+ }
43
+ }
44
+ return index;
45
+ }
46
+ /** Translation keys carry a feature prefix the manifest can't reconstruct
47
+ * (`showcase:entity:item:field:title`), so match on the suffix instead. The
48
+ * suffix must start at a `:` or `.` boundary of the key. */
49
+ export function labelsForSuffix(translations, suffix) {
50
+ return suffixMatch(translations, suffix)?.labels ?? {};
51
+ }
52
+ function suffixMatch(translations, suffix) {
53
+ let index = labelsIndexByTranslations.get(translations);
54
+ if (index === undefined) {
55
+ index = buildSuffixIndex(translations);
56
+ labelsIndexByTranslations.set(translations, index);
57
+ }
58
+ return index.get(suffix);
59
+ }
60
+ const LOCALE_PACKAGE_PREFIX = "locale-";
61
+ const localePackageKeysByTranslations = new WeakMap();
62
+ /** Locale packages register their entries as `locale-<xx>:<key>`; map each `<key>` to
63
+ * the registered keys that carry it, in code-point order. */
64
+ function localePackageKeys(translations) {
65
+ let index = localePackageKeysByTranslations.get(translations);
66
+ if (index === undefined) {
67
+ index = new Map();
68
+ for (const key of Object.keys(translations).sort(compareIds)) {
69
+ if (!key.startsWith(LOCALE_PACKAGE_PREFIX))
70
+ continue;
71
+ const name = key.slice(key.indexOf(":") + 1);
72
+ index.set(name, [...(index.get(name) ?? []), key]);
73
+ }
74
+ localePackageKeysByTranslations.set(translations, index);
75
+ }
76
+ return index;
77
+ }
78
+ /** The labels of `fullKey` per locale, completed by locale packages that translate it
79
+ * under `locale-<xx>:<fullKey>` or, for `<feature>:<key>`, under `locale-<xx>:<key>`.
80
+ * The owner's text wins, then the locale packages in code-point order. */
81
+ export function localizedLabels(translations, fullKey) {
82
+ const plainKey = fullKey.includes(":") ? fullKey.slice(fullKey.indexOf(":") + 1) : undefined;
83
+ const packages = localePackageKeys(translations);
84
+ const keys = [
85
+ ...(translations[fullKey] === undefined ? [] : [fullKey]),
86
+ ...[
87
+ ...new Set([
88
+ ...(packages.get(fullKey) ?? []),
89
+ ...(plainKey ? (packages.get(plainKey) ?? []) : []),
90
+ ]),
91
+ ].sort(compareIds),
92
+ ];
93
+ const merged = {};
94
+ for (const key of keys) {
95
+ for (const [locale, label] of Object.entries(entryAsLabels(translations[key] ?? {}))) {
96
+ if (merged[locale] === undefined)
97
+ merged[locale] = label;
98
+ }
99
+ }
100
+ return merged;
101
+ }
102
+ /** `labelsForSuffix` with the locale-package completion of `localizedLabels`: the owner
103
+ * key behind the suffix is preferred over a locale package key that ends the same way. */
104
+ export function localizedLabelsForSuffix(translations, suffix) {
105
+ const match = suffixMatch(translations, suffix);
106
+ if (match === undefined)
107
+ return {};
108
+ const owner = Object.keys(translations).find((key) => !key.startsWith(LOCALE_PACKAGE_PREFIX) && key.endsWith(suffix));
109
+ return localizedLabels(translations, owner ?? match.key);
110
+ }
111
+ /** Entity field label per locale; `field` may be a dotted path, only its last segment names the field. */
112
+ export function entityFieldLabels(translations, entity, field) {
113
+ return localizedLabelsForSuffix(translations, `:entity:${entity}:field:${field.slice(field.lastIndexOf(".") + 1)}`);
114
+ }
115
+ function lastSegmentOf(qualifiedId) {
116
+ return qualifiedId.slice(qualifiedId.lastIndexOf(":") + 1);
117
+ }
118
+ /** Screen titles live under the qualified id or, for feature-local screens, under
119
+ * `screen:<shortId>.title`. */
120
+ export function screenTitleLabels(translations, screenId) {
121
+ return entryAsLabels(translations[`${screenId}.title`] ??
122
+ translations[`screen:${lastSegmentOf(screenId)}.title`] ??
123
+ {});
124
+ }
125
+ /** `screenTitleLabels` completed by locale packages (see `localizedLabels`). */
126
+ export function localizedScreenTitleLabels(translations, screenId) {
127
+ const own = localizedLabels(translations, `${screenId}.title`);
128
+ return Object.keys(own).length > 0
129
+ ? own
130
+ : localizedLabels(translations, `screen:${lastSegmentOf(screenId)}.title`);
131
+ }
@@ -71,7 +71,8 @@ export declare function provisionSignupAccount(db: DbConnection, options: Provis
71
71
  }>;
72
72
  export type SeedAdminOptions = {
73
73
  readonly email: string;
74
- readonly password: string;
74
+ /** Omit to seed an account without a password; it sets one via password reset. */
75
+ readonly password?: string;
75
76
  readonly displayName: string;
76
77
  /** Tenants where the admin is added as a member. Each tenant can have
77
78
  * its own role list, which lets the sample TenantSwitcher show different
@@ -116,6 +117,20 @@ export declare function seedAdmin(db: DbConnection, options: SeedAdminOptions):
116
117
  * skipping the scan entirely when no KMS is configured at all (plaintext
117
118
  * DBs have no bidx ambiguity to guard against in the first place).
118
119
  */
119
- export declare function seedAdminGuarded(db: DbConnection, options: SeedAdminOptions): Promise<{
120
+ export declare function seedAdminGuarded(db: DbConnection, options: SeedAdminOptions, mayGrantToExisting?: (row: Record<string, unknown>) => boolean): Promise<{
121
+ id: string;
122
+ }>;
123
+ /**
124
+ * One-shot boot seed for an account that sets its password later (password
125
+ * reset). Skipped when the account already has a password (owner after their
126
+ * reset, or a foreign self-registration: granting admin to the latter would be
127
+ * an escalation) and when the target tenant already has another member (owner
128
+ * deleted or changed their email: re-seeding would mint a new passwordless
129
+ * SystemAdmin). Only our own passwordless account is completed, so a partial
130
+ * earlier seed converges.
131
+ */
132
+ export declare function seedBootstrapAdmin(db: DbConnection, options: SeedAdminOptions): Promise<{
120
133
  id: string;
134
+ } | {
135
+ skipped: "has-password" | "tenant-has-members";
121
136
  }>;
@@ -17,6 +17,8 @@ import { createSystemUser, SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framewo
17
17
  import { ConflictError } from "@cosmicdrift/kumiko-framework/errors";
18
18
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
19
19
  import { hashPassword } from "../shared/index.js";
20
+ // kumiko-lint-ignore cross-feature-import bootstrap admin seed checks whether the tenant already has members
21
+ import { tenantMembershipsTable } from "../tenant/membership-table.js";
20
22
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
21
23
  import { seedTenant, seedTenantMembership } from "../tenant/seeding.js";
22
24
  // kumiko-lint-ignore cross-feature-import signup create-only guard reads the user projection by email
@@ -133,14 +135,16 @@ export async function seedAdmin(db, options) {
133
135
  for (const m of options.memberships) {
134
136
  await seedTenant(db, { id: m.tenantId, key: m.tenantKey, name: m.tenantName, ...byOption });
135
137
  }
136
- const { id: userId } = await seedUserWithPassword(db, {
138
+ const userFields = {
137
139
  email: options.email,
138
- password: options.password,
139
140
  displayName: options.displayName,
140
141
  ...(options.globalRoles !== undefined && { roles: options.globalRoles }),
141
142
  ...(options.emailVerified !== undefined && { emailVerified: options.emailVerified }),
142
143
  ...byOption,
143
- });
144
+ };
145
+ const { id: userId } = options.password === undefined
146
+ ? await seedUser(db, userFields)
147
+ : await seedUserWithPassword(db, { ...userFields, password: options.password });
144
148
  for (const m of options.memberships) {
145
149
  await seedTenantMembership(db, {
146
150
  userId,
@@ -213,6 +217,14 @@ async function findExistingUserIdForEmail(db, kms, email) {
213
217
  }
214
218
  return matches.length === 0 ? undefined : pickCanonicalUserId(matches);
215
219
  }
220
+ async function seedAdminPlaintext(db, options, mayGrantToExisting) {
221
+ if (mayGrantToExisting) {
222
+ const row = await fetchOne(db, userTable, { email: options.email, isDeleted: false });
223
+ if (row && !mayGrantToExisting(row))
224
+ return { id: String(row["id"]) };
225
+ }
226
+ return seedAdmin(db, options);
227
+ }
216
228
  /**
217
229
  * Boot-seed variant of seedAdmin that survives a blind-index miss on an
218
230
  * otherwise-existing account (see the module comment above). Not for the
@@ -227,10 +239,10 @@ async function findExistingUserIdForEmail(db, kms, email) {
227
239
  * skipping the scan entirely when no KMS is configured at all (plaintext
228
240
  * DBs have no bidx ambiguity to guard against in the first place).
229
241
  */
230
- export async function seedAdminGuarded(db, options) {
242
+ export async function seedAdminGuarded(db, options, mayGrantToExisting) {
231
243
  const kms = configuredPiiSubjectKms();
232
244
  if (kms === undefined)
233
- return seedAdmin(db, options);
245
+ return seedAdminPlaintext(db, options, mayGrantToExisting);
234
246
  // Without a bidx key every row seeded here gets a NULL email_bidx, which
235
247
  // neither seedAdmin's lookup nor the partial unique index can ever see.
236
248
  if (configuredBlindIndexKey() === undefined) {
@@ -246,8 +258,10 @@ export async function seedAdminGuarded(db, options) {
246
258
  // Re-write the email so email_bidx is recomputed; without it the account
247
259
  // stays unfindable for login and every boot re-scans the whole table.
248
260
  await rewriteSeededUserEmail(db, existingRow, options.email, by);
261
+ const refreshed = (await fetchOne(db, userTable, { id: existingId })) ?? existingRow;
262
+ if (mayGrantToExisting && !mayGrantToExisting(refreshed))
263
+ return { id: existingId };
249
264
  if (options.emailVerified === true) {
250
- const refreshed = (await fetchOne(db, userTable, { id: existingId })) ?? existingRow;
251
265
  await reconcileSeededUserEmailVerified(db, refreshed, by);
252
266
  }
253
267
  }
@@ -262,3 +276,51 @@ export async function seedAdminGuarded(db, options) {
262
276
  }
263
277
  return { id: existingId };
264
278
  }
279
+ async function findExistingUserRowForEmail(db, email) {
280
+ const kms = configuredPiiSubjectKms();
281
+ if (kms === undefined)
282
+ return fetchOne(db, userTable, { email, isDeleted: false });
283
+ const existingId = await findExistingUserIdForEmail(db, kms, email);
284
+ return existingId === undefined ? undefined : fetchOne(db, userTable, { id: existingId });
285
+ }
286
+ function hasPassword(row) {
287
+ return typeof row["passwordHash"] === "string" && row["passwordHash"] !== "";
288
+ }
289
+ /** Tenant already has a member other than `ownUserId` (soft-deleted memberships count). */
290
+ async function tenantHasForeignMember(db, tenantId, ownUserId) {
291
+ const members = await selectMany(db, tenantMembershipsTable, { tenantId });
292
+ return members.some((member) => member["userId"] !== ownUserId);
293
+ }
294
+ /**
295
+ * One-shot boot seed for an account that sets its password later (password
296
+ * reset). Skipped when the account already has a password (owner after their
297
+ * reset, or a foreign self-registration: granting admin to the latter would be
298
+ * an escalation) and when the target tenant already has another member (owner
299
+ * deleted or changed their email: re-seeding would mint a new passwordless
300
+ * SystemAdmin). Only our own passwordless account is completed, so a partial
301
+ * earlier seed converges.
302
+ */
303
+ export async function seedBootstrapAdmin(db, options) {
304
+ const existing = await findExistingUserRowForEmail(db, options.email);
305
+ if (existing && hasPassword(existing)) {
306
+ log.info("seedBootstrapAdmin: the account already has a password, bootstrap seed skipped");
307
+ return { skipped: "has-password" };
308
+ }
309
+ const ownUserId = typeof existing?.["id"] === "string" ? existing["id"] : undefined;
310
+ for (const membership of options.memberships) {
311
+ if (await tenantHasForeignMember(db, membership.tenantId, ownUserId)) {
312
+ log.info("seedBootstrapAdmin: the tenant already has members, bootstrap seed skipped");
313
+ return { skipped: "tenant-has-members" };
314
+ }
315
+ }
316
+ let passwordAppeared = false;
317
+ const seeded = await seedAdminGuarded(db, options, (row) => {
318
+ passwordAppeared = hasPassword(row);
319
+ return !passwordAppeared;
320
+ });
321
+ if (passwordAppeared) {
322
+ log.info("seedBootstrapAdmin: the account got a password meanwhile, bootstrap seed skipped");
323
+ return { skipped: "has-password" };
324
+ }
325
+ return seeded;
326
+ }
@@ -83,6 +83,7 @@ export const defaultTranslations = {
83
83
  "auth.unlockAccount.missingToken": "Unlock link is missing a token.",
84
84
  "auth.signup.title": "Create account",
85
85
  "auth.signup.intro": "Enter your email. We'll send you an activation link to set your password.",
86
+ "auth.signup.closed": "Sign-up is currently by invitation only.",
86
87
  "auth.signup.email": "Email",
87
88
  "auth.signup.submit": "Send activation link",
88
89
  "auth.signup.submitting": "…",
@@ -9,4 +9,4 @@ export type SignupScreenProps = {
9
9
  * parameter of this page. Unsafe values are dropped. */
10
10
  readonly returnTo?: string;
11
11
  };
12
- export declare function SignupScreen({ title, subtitle, loginHref, returnTo, }: SignupScreenProps): ReactNode;
12
+ export declare function SignupScreen(props: SignupScreenProps): ReactNode;
@@ -11,17 +11,18 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
11
11
  // /signup) and making it anonymously reachable (AuthPathGate before
12
12
  // AuthGate). An apex marketing site can route its "Start for free" link to
13
13
  // the /signup path.
14
- import { usePrimitives, useTranslation } from "@cosmicdrift/kumiko-renderer";
14
+ import { useOptionalDispatcher, usePrimitives, useQuery, useTranslation, } from "@cosmicdrift/kumiko-renderer";
15
15
  import { useState } from "react";
16
16
  import { requestSignup } from "./auth-client.js";
17
17
  import { retryAfterMinutes } from "./auth-form-logic.js";
18
18
  import { AuthCard } from "./auth-form-primitives.js";
19
19
  import { readReturnToFromWindow } from "./auth-redirect.js";
20
+ import { AuthQueries } from "./constants.js";
20
21
  import { isSafeReturnPath } from "./return-path.js";
21
22
  function resolveReturnTo(prop) {
22
23
  return (isSafeReturnPath(prop) ? prop : readReturnToFromWindow()) ?? undefined;
23
24
  }
24
- export function SignupScreen({ title, subtitle, loginHref = "/login", returnTo, }) {
25
+ function SignupScreenBody({ title, subtitle, loginHref = "/login", returnTo, registrationOpen, }) {
25
26
  const t = useTranslation();
26
27
  const { Form, Field, Input, Button, Banner, Link } = usePrimitives();
27
28
  const [email, setEmail] = useState("");
@@ -71,5 +72,22 @@ export function SignupScreen({ title, subtitle, loginHref = "/login", returnTo,
71
72
  }
72
73
  };
73
74
  const effectiveTitle = title ?? t("auth.signup.title");
75
+ if (registrationOpen === "unknown") {
76
+ return (_jsx(AuthCard, { title: effectiveTitle, subtitle: subtitle, children: null }));
77
+ }
78
+ if (!registrationOpen) {
79
+ return (_jsxs(AuthCard, { title: effectiveTitle, subtitle: subtitle, children: [_jsx(Banner, { variant: "info", children: t("auth.signup.closed") }), _jsx(Link, { href: loginHref, variant: "muted", children: t("auth.signup.haveAccount") })] }));
80
+ }
74
81
  return (_jsx(AuthCard, { title: effectiveTitle, subtitle: subtitle, children: done ? (_jsxs(_Fragment, { children: [_jsxs(Banner, { variant: "info", children: [_jsx("p", { className: "font-medium text-foreground", children: t("auth.signup.successTitle") }), _jsx("p", { className: "mt-1", children: t("auth.signup.successBody") })] }), _jsx(Button, { variant: "secondary", onClick: onResend, disabled: submitting, children: t("auth.signup.resend") }), _jsx(Link, { href: loginHref, variant: "muted", children: t("auth.signup.haveAccount") })] })) : (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-sm text-muted-foreground", children: t("auth.signup.intro") }), _jsxs(Form, { onSubmit: onSubmit, children: [_jsx(Field, { id: "signup-email", label: t("auth.signup.email"), required: true, children: _jsx(Input, { kind: "email", id: "signup-email", name: "signup-email", value: email, onChange: setEmail, disabled: submitting, required: true, autoComplete: "email" }) }), error !== null && _jsx(Banner, { variant: "error", children: error }), _jsx(Button, { type: "submit", loading: submitting, disabled: submitting, children: submitting ? t("auth.signup.submitting") : t("auth.signup.submit") })] }), _jsx(Link, { href: loginHref, variant: "muted", className: "self-center", children: t("auth.signup.haveAccount") })] })) }));
75
82
  }
83
+ // A failed status query reads as open: signup-request itself stays the authority.
84
+ function SignupScreenWithQueriedStatus(props) {
85
+ const { data, loading } = useQuery(AuthQueries.signupRegistrationStatus, {});
86
+ const registrationOpen = loading && data === null ? "unknown" : data?.enabled !== false;
87
+ return _jsx(SignupScreenBody, { ...props, registrationOpen: registrationOpen });
88
+ }
89
+ // Without a mounted dispatcher (standalone mounts, tests) the status is not asked and the form shows.
90
+ export function SignupScreen(props) {
91
+ const dispatcher = useOptionalDispatcher();
92
+ return dispatcher === undefined ? (_jsx(SignupScreenBody, { ...props, registrationOpen: true })) : (_jsx(SignupScreenWithQueriedStatus, { ...props }));
93
+ }
@@ -0,0 +1,40 @@
1
+ import { type StaticRequestOptions, type StaticResult } from "./static-client.ts";
2
+ export { hrefWithoutUrlToken, readUrlToken, STATIC_MALFORMED_TOKEN_REASON, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, type StaticFailure, type StaticRequestOptions, type StaticResult, type StaticSuccess, takeUrlToken, type UrlTokenSource, } from "./static-client.ts";
3
+ export type SignupRegistrationStatus = {
4
+ readonly enabled: boolean;
5
+ };
6
+ /** A failed lookup should be read as open: signup-request itself stays the authority. */
7
+ export declare function fetchSignupRegistrationStatus(): Promise<StaticResult<SignupRegistrationStatus>>;
8
+ /** Answers success whether or not the address has an account, so it cannot be used to probe. */
9
+ export declare function requestPasswordReset(email: string, options?: StaticRequestOptions & {
10
+ readonly returnTo?: string;
11
+ }): Promise<StaticResult<undefined>>;
12
+ export declare function resetPassword(token: string, newPassword: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
13
+ export declare function verifyEmail(token: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
14
+ /** Ends the current session; the server also clears the auth and CSRF cookies. */
15
+ export declare function logout(options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
16
+ export { isSignedOutFailure } from "./static-client.ts";
17
+ export type InviteInfo = {
18
+ readonly email: string;
19
+ readonly hasAccount: boolean;
20
+ };
21
+ /** Reads the pending invitation without consuming the token. */
22
+ export declare function fetchInviteInfo(token: string, options?: StaticRequestOptions): Promise<StaticResult<InviteInfo>>;
23
+ export type InviteAccepted = {
24
+ readonly status: "accepted";
25
+ readonly tenantId: string;
26
+ readonly roles: readonly string[];
27
+ readonly landingPath?: string;
28
+ } | {
29
+ readonly status: "mfa-pending";
30
+ };
31
+ /** Visitor is signed in on this origin: attaches the invitation to that session. */
32
+ export declare function acceptInviteSignedIn(token: string, options?: StaticRequestOptions): Promise<StaticResult<InviteAccepted>>;
33
+ /** Invited address already has an account: signs in and accepts. */
34
+ export declare function acceptInviteWithLogin(token: string, email: string, password: string, options?: StaticRequestOptions): Promise<StaticResult<InviteAccepted>>;
35
+ /** Invited address has no account yet: creates it with `password` and accepts. */
36
+ export declare function acceptInviteWithNewAccount(token: string, password: string, options?: StaticRequestOptions): Promise<StaticResult<InviteAccepted>>;
37
+ /** Answers success whether or not the address exists or is locked, so it cannot be used to probe. */
38
+ export declare function requestAccountUnlock(email: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
39
+ /** The mail link carries the token in the query (`?token=`). Confirming an unlocked account is a no-op. */
40
+ export declare function confirmAccountUnlock(token: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
@@ -0,0 +1,94 @@
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
+ import { AuthQueries } from "./constants.js";
5
+ import { isRecord } from "./login-failure.js";
6
+ import { isSafeReturnPath } from "./return-path.js";
7
+ import { dispatchQuery, postJson, staticFailure, staticSuccess, } from "./static-client.js";
8
+ export { hrefWithoutUrlToken, readUrlToken, STATIC_MALFORMED_TOKEN_REASON, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, takeUrlToken, } from "./static-client.js";
9
+ const UNEXPECTED_RESPONSE_REASON = "unexpected_response";
10
+ /** A failed lookup should be read as open: signup-request itself stays the authority. */
11
+ export async function fetchSignupRegistrationStatus() {
12
+ const result = await dispatchQuery(AuthQueries.signupRegistrationStatus, {});
13
+ if (result.kind === "failure")
14
+ return result;
15
+ if (!isRecord(result.data) || typeof result.data["enabled"] !== "boolean") {
16
+ return staticFailure(UNEXPECTED_RESPONSE_REASON);
17
+ }
18
+ return staticSuccess({ enabled: result.data["enabled"] });
19
+ }
20
+ async function postAuthRoute(path, payload, options) {
21
+ const result = await postJson(path, payload, options);
22
+ return result.kind === "success" ? staticSuccess(undefined) : result;
23
+ }
24
+ /** Answers success whether or not the address has an account, so it cannot be used to probe. */
25
+ export function requestPasswordReset(email, options = {}) {
26
+ const { returnTo, ...requestOptions } = options;
27
+ return postAuthRoute("/api/auth/request-password-reset", { email, ...(isSafeReturnPath(returnTo) && { returnTo }) }, requestOptions);
28
+ }
29
+ export function resetPassword(token, newPassword, options) {
30
+ return postAuthRoute("/api/auth/reset-password", { token, newPassword }, options);
31
+ }
32
+ export function verifyEmail(token, options) {
33
+ return postAuthRoute("/api/auth/verify-email", { token }, options);
34
+ }
35
+ /** Ends the current session; the server also clears the auth and CSRF cookies. */
36
+ export function logout(options) {
37
+ return postAuthRoute("/api/auth/logout", {}, options);
38
+ }
39
+ export { isSignedOutFailure } from "./static-client.js";
40
+ /** Reads the pending invitation without consuming the token. */
41
+ export async function fetchInviteInfo(token, options) {
42
+ const result = await postJson("/api/auth/invite-info", { token }, options);
43
+ if (result.kind === "failure")
44
+ return result;
45
+ const { email, hasAccount } = result.data;
46
+ if (typeof email !== "string" || typeof hasAccount !== "boolean") {
47
+ return staticFailure(UNEXPECTED_RESPONSE_REASON);
48
+ }
49
+ return staticSuccess({ email, hasAccount });
50
+ }
51
+ function grantedRoles(body) {
52
+ const user = body["user"];
53
+ const sessionRoles = isRecord(user) ? user["roles"] : undefined;
54
+ if (Array.isArray(sessionRoles)) {
55
+ return sessionRoles.filter((role) => typeof role === "string");
56
+ }
57
+ return typeof body["role"] === "string" ? [body["role"]] : [];
58
+ }
59
+ async function postInviteAccept(path, payload, options) {
60
+ const result = await postJson(path, payload, options);
61
+ if (result.kind === "failure")
62
+ return result;
63
+ const body = result.data;
64
+ const tenantId = body["tenantId"];
65
+ if (typeof tenantId !== "string")
66
+ return staticSuccess({ status: "mfa-pending" });
67
+ const landingPath = body["landingPath"];
68
+ return staticSuccess({
69
+ status: "accepted",
70
+ tenantId,
71
+ roles: grantedRoles(body),
72
+ ...(isSafeReturnPath(landingPath) && { landingPath }),
73
+ });
74
+ }
75
+ /** Visitor is signed in on this origin: attaches the invitation to that session. */
76
+ export function acceptInviteSignedIn(token, options) {
77
+ return postInviteAccept("/api/auth/invite-accept", { token }, options);
78
+ }
79
+ /** Invited address already has an account: signs in and accepts. */
80
+ export function acceptInviteWithLogin(token, email, password, options) {
81
+ return postInviteAccept("/api/auth/invite-accept-with-login", { token, email, password }, options);
82
+ }
83
+ /** Invited address has no account yet: creates it with `password` and accepts. */
84
+ export function acceptInviteWithNewAccount(token, password, options) {
85
+ return postInviteAccept("/api/auth/invite-signup-complete", { token, password }, options);
86
+ }
87
+ /** Answers success whether or not the address exists or is locked, so it cannot be used to probe. */
88
+ export function requestAccountUnlock(email, options) {
89
+ return postAuthRoute("/api/auth/request-account-unlock", { email }, options);
90
+ }
91
+ /** The mail link carries the token in the query (`?token=`). Confirming an unlocked account is a no-op. */
92
+ export function confirmAccountUnlock(token, options) {
93
+ return postAuthRoute("/api/auth/confirm-account-unlock", { token }, options);
94
+ }
@@ -0,0 +1,38 @@
1
+ import { type KnownLoginFailureReason } from "./login-failure.ts";
2
+ export declare const STATIC_NETWORK_REASON = "network";
3
+ export declare const STATIC_RATE_LIMITED_REASON = "rate_limited";
4
+ export declare const STATIC_UNKNOWN_REASON = "unknown";
5
+ export declare const STATIC_UNAUTHENTICATED_REASON = "unauthenticated";
6
+ export declare const STATIC_MALFORMED_TOKEN_REASON = "malformed_token";
7
+ export type StaticFailure = {
8
+ readonly kind: "failure";
9
+ readonly reason: KnownLoginFailureReason | (string & {});
10
+ readonly message?: string;
11
+ readonly retryAfterSeconds?: number;
12
+ };
13
+ export type StaticSuccess<TData> = {
14
+ readonly kind: "success";
15
+ readonly data: TData;
16
+ };
17
+ export type StaticResult<TData> = StaticSuccess<TData> | StaticFailure;
18
+ export type StaticRequestOptions = {
19
+ /** Sent as `X-Locale`, which picks the language of mails the request triggers. */
20
+ readonly locale?: string;
21
+ };
22
+ export declare function staticFailure(reason: string, extras?: {
23
+ readonly message?: string;
24
+ readonly retryAfterSeconds?: number;
25
+ }): StaticFailure;
26
+ export declare function staticSuccess<TData>(data: TData): StaticSuccess<TData>;
27
+ export declare function csrfHeaderFromCookie(cookieSource: string): Record<string, string>;
28
+ /** True when the server says there is no usable session; wrong credentials are not signed-out. */
29
+ export declare function isSignedOutFailure(result: StaticResult<unknown>): boolean;
30
+ export declare function postJson(path: string, payload: Record<string, unknown>, options?: StaticRequestOptions): Promise<StaticResult<Record<string, unknown>>>;
31
+ export declare function dispatchWrite(type: string, payload: Record<string, unknown>, options?: StaticRequestOptions): Promise<StaticResult<unknown>>;
32
+ export declare function dispatchQuery(type: string, payload: Record<string, unknown>, options?: StaticRequestOptions): Promise<StaticResult<unknown>>;
33
+ export type UrlTokenSource = "query" | "fragment";
34
+ export declare const URL_TOKEN_PARAM = "token";
35
+ export declare function readUrlToken(href: string, source: UrlTokenSource): string;
36
+ export declare function hrefWithoutUrlToken(href: string, source: UrlTokenSource): string;
37
+ /** Reads the token from the current page and removes it from the address bar. Browser only. */
38
+ export declare function takeUrlToken(source: UrlTokenSource): string;