@cosmicdrift/kumiko-samples 0.411.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 (73) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -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/inbound-mail-foundation/changes.json +6 -0
  41. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +99 -71
  42. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +2 -2
  43. package/packages/bundled-features/src/personal-access-tokens/changes.json +6 -0
  44. package/packages/bundled-features/src/personal-access-tokens/feature.ts +5 -2
  45. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +7 -2
  46. package/packages/bundled-features/src/personal-access-tokens/i18n.ts +6 -1
  47. package/packages/bundled-features/src/personal-access-tokens/index.ts +37 -2
  48. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +28 -0
  49. package/packages/bundled-features/src/personal-access-tokens/screens.ts +9 -1
  50. package/packages/bundled-features/src/personal-access-tokens/web/constants.ts +1 -0
  51. package/packages/bundled-features/src/personal-access-tokens/web/scopes.ts +14 -0
  52. package/samples/recipes/api-docs/README.md +52 -0
  53. package/samples/recipes/api-docs/api-docs/de/events.md +62 -0
  54. package/samples/recipes/api-docs/api-docs/de/overview.md +100 -0
  55. package/samples/recipes/api-docs/api-docs/de/reference/tickets.md +305 -0
  56. package/samples/recipes/api-docs/api-docs/de/tokens.md +66 -0
  57. package/samples/recipes/api-docs/api-docs/en/events.md +62 -0
  58. package/samples/recipes/api-docs/api-docs/en/overview.md +100 -0
  59. package/samples/recipes/api-docs/api-docs/en/reference/tickets.md +305 -0
  60. package/samples/recipes/api-docs/api-docs/en/tokens.md +66 -0
  61. package/samples/recipes/api-docs/api-docs/index.json +371 -0
  62. package/samples/recipes/api-docs/api-docs/openapi.json +982 -0
  63. package/samples/recipes/api-docs/api-examples/ticket-close.json +21 -0
  64. package/samples/recipes/api-docs/api-examples/ticket-create.json +42 -0
  65. package/samples/recipes/api-docs/api-examples/ticket-detail.json +28 -0
  66. package/samples/recipes/api-docs/api-examples/ticket-list.json +31 -0
  67. package/samples/recipes/api-docs/api-examples/ticket-update.json +54 -0
  68. package/samples/recipes/api-docs/api-examples/webhooks/ticket-closed.json +8 -0
  69. package/samples/recipes/api-docs/api-examples/webhooks/ticket-created.json +10 -0
  70. package/samples/recipes/api-docs/kumiko.config.ts +33 -0
  71. package/samples/recipes/api-docs/package.json +14 -0
  72. package/samples/recipes/api-docs/src/feature.ts +218 -0
  73. package/samples/recipes/api-docs/tsconfig.json +22 -0
@@ -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,10 @@
1
1
  [
2
+ {
3
+ "version": "0.412.0",
4
+ "type": "fix",
5
+ "title": "documents filed from a mail attachment are visible to whoever may read the mail",
6
+ "detail": "The `inbound-message` read model now declares `access.read` for the member roles: shared mailboxes are readable by every member, a personal mailbox only by its owner, admins included. `createInboundMessageEntity(memberRoles)` builds the entity for the configured roles; `inboundMessageEntity` stays exported with the default roles. The message queries filter rows as before and do not use this rule."
7
+ },
2
8
  {
3
9
  "version": "0.409.0",
4
10
  "type": "fix",
@@ -1,5 +1,5 @@
1
1
  import { collectPiiSubjectFields } from "@cosmicdrift/kumiko-framework/crypto";
2
- import { deriveEntityTableMeta } from "@cosmicdrift/kumiko-framework/db";
2
+ import { deriveEntityTableMeta, physicalColumnName } from "@cosmicdrift/kumiko-framework/db";
3
3
  import {
4
4
  access,
5
5
  createBooleanField,
@@ -10,6 +10,8 @@ import {
10
10
  createTextField,
11
11
  createTimestampField,
12
12
  } from "@cosmicdrift/kumiko-framework/engine";
13
+ import type { OwnershipMap, OwnershipRule } from "@cosmicdrift/kumiko-types/ownership";
14
+ import { DEFAULT_INBOUND_MAIL_ADMIN_ROLES, DEFAULT_INBOUND_MAIL_USER_ROLES } from "./mail-roles.ts";
13
15
 
14
16
  // ============================================================================
15
17
  // Read models for the three event-sourced aggregates
@@ -80,79 +82,105 @@ export const mailAccountEntity = createEntity({
80
82
  },
81
83
  });
82
84
 
85
+ // Mirrors isVisibleToCaller (handlers/scope-visibility.ts) for the roles of the detail query:
86
+ // shared rows and the caller's own personal mailbox, no admin exception. The read gate of other
87
+ // entities (readGate.fileOwner) reads it; the hand-written message queries do not apply it.
88
+ function ownMailboxOrSharedRead(memberRoles: readonly string[]): OwnershipMap {
89
+ const rule: OwnershipRule = {
90
+ kind: "where",
91
+ where: (user, ctx) => {
92
+ const owner = `"${ctx.tableName}"."${physicalColumnName(ctx.table, "ownerUserId")}"`;
93
+ return {
94
+ sqlText: `(${owner} IS NULL OR ${owner} = '' OR ${owner} = $${ctx.paramStart})`,
95
+ params: [user.id],
96
+ };
97
+ },
98
+ };
99
+ return Object.fromEntries(memberRoles.map((role) => [role, rule]));
100
+ }
101
+
83
102
  /** An incoming mail (envelope + snippet, NO body — bodyRef
84
103
  * points to file-foundation). PK = aggregateId =
85
104
  * inboundMessageAggregateId(accountId, providerMessageId). */
86
- export const inboundMessageEntity = createEntity({
87
- table: "read_inbound_messages",
88
- fields: {
89
- accountId: createTextField({
90
- required: true,
91
- maxLength: 36,
92
- personal: false,
93
- reason: "technical_reference",
94
- }),
95
- // Scope is inherited from the account at ingest time: messages from a
96
- // personal mailbox are visible only to the owner, without joining read_mail_accounts.
97
- ownerUserId: createTextField({ maxLength: 36, personal: false, reason: "pseudonymous_fk" }),
98
- messageIdHeader: createTextField({
99
- required: true,
100
- maxLength: 500,
101
- personal: false,
102
- reason: "technical_reference",
103
- }),
104
- threadKey: createTextField({
105
- required: true,
106
- maxLength: 500,
107
- personal: false,
108
- reason: "technical_reference",
109
- }),
110
- from: createTextField({ required: true, maxLength: 2000, personal: "tenant", find: "none" }),
111
- // JSON-stringified string[] — als Ganzes encrypted.
112
- to: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
113
- cc: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
114
- subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
115
- snippet: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
116
- receivedAt: createTimestampField({ required: true }),
117
- bodyRef: createTextField({ maxLength: 500, personal: false, reason: "technical_reference" }),
118
- scope: createTextField({ maxLength: 200, personal: false, reason: "technical_reference" }),
119
- // Full plaintext, capped at 32_000 characters before encryption (ciphertext is ~2.3x plus envelope).
120
- // Null on rows from before the column; list-messages never selects it.
121
- bodyText: createLongTextField({ maxLength: 200_000, personal: "tenant", find: "none" }),
122
- bodyTextTruncated: createBooleanField(),
123
- // Sanitized HTML of the mail (sanitizeInboundHtml), null when the mail has none or it was too large.
124
- bodyHtml: createLongTextField({ maxLength: 500_000, personal: "tenant", find: "none" }),
125
- // Bound to the message (entityType = the aggregate type), so the file guard answers with the
126
- // mail's visibility. The fileRefs are bound at ingest, the projection copies the ids.
127
- attachmentFileIds: createFilesField({ personal: false, reason: "technical_reference" }),
128
- // JSON-stringified SkippedInboundAttachment[]: nullable JSON stays a text column
129
- // (jsonb fields are NOT NULL), like to/cc.
130
- skippedAttachments: createTextField({
131
- maxLength: 20_000,
132
- personal: false,
133
- reason: "technical_reference",
134
- }),
135
- // JSON-stringified SenderAuthentication or "null"; a SQL null (rows from before the column) reads as null.
136
- senderAuthentication: createTextField({
137
- maxLength: 4000,
138
- personal: false,
139
- reason: "technical_reference",
140
- }),
141
- // "complete" | "snippet" | "unavailable"; null counts as "snippet".
142
- contentState: createTextField({
143
- maxLength: 20,
144
- personal: false,
145
- reason: "technical_reference",
146
- }),
147
- // One of INBOUND_CONTENT_UNAVAILABLE_REASONS; null while the content is there or not yet missing.
148
- contentUnavailableReason: createTextField({
149
- maxLength: 30,
150
- personal: false,
151
- reason: "technical_reference",
152
- }),
153
- },
154
- attachedFileAccess: "record-only",
155
- });
105
+ export function createInboundMessageEntity(memberRoles: readonly string[]) {
106
+ return createEntity({
107
+ access: { read: ownMailboxOrSharedRead(memberRoles) },
108
+ table: "read_inbound_messages",
109
+ fields: {
110
+ accountId: createTextField({
111
+ required: true,
112
+ maxLength: 36,
113
+ personal: false,
114
+ reason: "technical_reference",
115
+ }),
116
+ // Scope is inherited from the account at ingest time: messages from a
117
+ // personal mailbox are visible only to the owner, without joining read_mail_accounts.
118
+ ownerUserId: createTextField({ maxLength: 36, personal: false, reason: "pseudonymous_fk" }),
119
+ messageIdHeader: createTextField({
120
+ required: true,
121
+ maxLength: 500,
122
+ personal: false,
123
+ reason: "technical_reference",
124
+ }),
125
+ threadKey: createTextField({
126
+ required: true,
127
+ maxLength: 500,
128
+ personal: false,
129
+ reason: "technical_reference",
130
+ }),
131
+ from: createTextField({ required: true, maxLength: 2000, personal: "tenant", find: "none" }),
132
+ // JSON-stringified string[] — als Ganzes encrypted.
133
+ to: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
134
+ cc: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
135
+ subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
136
+ snippet: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
137
+ receivedAt: createTimestampField({ required: true }),
138
+ bodyRef: createTextField({ maxLength: 500, personal: false, reason: "technical_reference" }),
139
+ scope: createTextField({ maxLength: 200, personal: false, reason: "technical_reference" }),
140
+ // Full plaintext, capped at 32_000 characters before encryption (ciphertext is ~2.3x plus envelope).
141
+ // Null on rows from before the column; list-messages never selects it.
142
+ bodyText: createLongTextField({ maxLength: 200_000, personal: "tenant", find: "none" }),
143
+ bodyTextTruncated: createBooleanField(),
144
+ // Sanitized HTML of the mail (sanitizeInboundHtml), null when the mail has none or it was too large.
145
+ bodyHtml: createLongTextField({ maxLength: 500_000, personal: "tenant", find: "none" }),
146
+ // Bound to the message (entityType = the aggregate type), so the file guard answers with the
147
+ // mail's visibility. The fileRefs are bound at ingest, the projection copies the ids.
148
+ attachmentFileIds: createFilesField({ personal: false, reason: "technical_reference" }),
149
+ // JSON-stringified SkippedInboundAttachment[]: nullable JSON stays a text column
150
+ // (jsonb fields are NOT NULL), like to/cc.
151
+ skippedAttachments: createTextField({
152
+ maxLength: 20_000,
153
+ personal: false,
154
+ reason: "technical_reference",
155
+ }),
156
+ // JSON-stringified SenderAuthentication or "null"; a SQL null (rows from before the column) reads as null.
157
+ senderAuthentication: createTextField({
158
+ maxLength: 4000,
159
+ personal: false,
160
+ reason: "technical_reference",
161
+ }),
162
+ // "complete" | "snippet" | "unavailable"; null counts as "snippet".
163
+ contentState: createTextField({
164
+ maxLength: 20,
165
+ personal: false,
166
+ reason: "technical_reference",
167
+ }),
168
+ // One of INBOUND_CONTENT_UNAVAILABLE_REASONS; null while the content is there or not yet missing.
169
+ contentUnavailableReason: createTextField({
170
+ maxLength: 30,
171
+ personal: false,
172
+ reason: "technical_reference",
173
+ }),
174
+ },
175
+ attachedFileAccess: "record-only",
176
+ });
177
+ }
178
+
179
+ // Same fields for every role set; table and PII lists do not depend on the roles.
180
+ export const inboundMessageEntity = createInboundMessageEntity([
181
+ ...DEFAULT_INBOUND_MAIL_ADMIN_ROLES,
182
+ ...DEFAULT_INBOUND_MAIL_USER_ROLES,
183
+ ]);
156
184
 
157
185
  /** Thread-Rollup. PK = aggregateId = mailThreadAggregateId(tenantId,
158
186
  * threadKey). */
@@ -24,7 +24,7 @@
24
24
  import { defineFeature, EXT_TENANT_DATA } from "@cosmicdrift/kumiko-framework/engine";
25
25
  import { INBOUND_MAIL_FOUNDATION_FEATURE, INBOUND_MAIL_PROVIDER_EXTENSION } from "./constants.ts";
26
26
  import {
27
- inboundMessageEntity,
27
+ createInboundMessageEntity,
28
28
  mailAccountEntity,
29
29
  mailThreadEntity,
30
30
  seenMessageTable,
@@ -208,7 +208,7 @@ export function createInboundMailFoundationFeature(options: InboundMailRoleOptio
208
208
  name: "inbound-message",
209
209
  source: INBOUND_MESSAGE_AGGREGATE_TYPE,
210
210
  table: inboundMessagesProjectionTable,
211
- entity: inboundMessageEntity,
211
+ entity: createInboundMessageEntity(roles.memberRoles),
212
212
  apply: {
213
213
  [INBOUND_MESSAGE_RECEIVED_EVENT_QN]: applyInboundMessageReceived,
214
214
  [INBOUND_MESSAGE_CONTENT_FETCHED_EVENT_QN]: applyInboundMessageContentFetched,
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.412.0",
4
+ "type": "improvement",
5
+ "title": "token scopes list the webhook events they release",
6
+ "detail": "`PatScopeDef.events` takes exact event names (no globs). Holding the scope at read or write level is enough to subscribe, `expandScopeEvents(config, granted)` returns the union. Boot fails when a scope lists an event without a public contract, for example an internal `r.defineEvent`. Revoking a token now has a title and a field label in every bundle locale."
7
+ },
2
8
  {
3
9
  "version": "0.385.0",
4
10
  "type": "improvement",
@@ -19,6 +19,7 @@ import { PAT_FEATURE_I18N, patScopeOptionTranslations } from "./i18n.ts";
19
19
  import { PAT_REVOKED_EVENT_SHORT, patRevokedSchema } from "./pat-revoked-event.ts";
20
20
  import { createPatResolver } from "./resolver.ts";
21
21
  import { apiTokenEntity } from "./schema/api-token.ts";
22
+ import { validateScopeEventContracts } from "./scope-events-check.ts";
22
23
  import { createPatMintScreen, patListScreen } from "./screens.ts";
23
24
  import {
24
25
  API_TOKEN_ENTITY_NAME,
@@ -84,6 +85,7 @@ export type PersonalAccessTokensOptions = {
84
85
 
85
86
  export type PatFeatureExports = {
86
87
  readonly rateLimit: PatRateLimit;
88
+ readonly scopes: PatScopeConfig;
87
89
  readonly bindAutoRevokeOnPasswordChange: BindPatAutoRevokeOnPasswordChange;
88
90
  };
89
91
 
@@ -138,6 +140,7 @@ export function createPersonalAccessTokensFeature(
138
140
  // different path. No projection: the payload IS the read, consumed
139
141
  // directly off the event-store NOTIFY.
140
142
  r.defineEvent(PAT_REVOKED_EVENT_SHORT, patRevokedSchema, { piiFields: "none" });
143
+ r.bootCheck(({ features }) => validateScopeEventContracts(scopes, features));
141
144
 
142
145
  // Password-change auto-revoke — mirrors sessions' own
143
146
  // autoRevokeOnPasswordChange postSave hook, including WHY it's a
@@ -195,12 +198,12 @@ export function createPersonalAccessTokensFeature(
195
198
 
196
199
  // rateLimit flows into feature.exports so run-prod-app builds the
197
200
  // limiter from the same declaration — single source of truth. `scopes`
198
- // is closed over directly by the useExtension build() above and by
199
- // available-scopes, so it doesn't need to round-trip through exports.
201
+ // is also exported so the API-docs generator can read the catalog.
200
202
  return {
201
203
  handlers,
202
204
  queries,
203
205
  bindAutoRevokeOnPasswordChange,
206
+ scopes,
204
207
  rateLimit: options.rateLimit ?? PAT_DEFAULT_RATE_LIMIT,
205
208
  } satisfies { handlers: unknown; queries: unknown } & PatFeatureExports;
206
209
  });
@@ -12,7 +12,12 @@ import { encryptForDirectWrite, unprocessable, verifyPassword } from "../../shar
12
12
  import { UserQueries } from "../../user/index.ts";
13
13
  import { mintPatToken } from "../hash.ts";
14
14
  import { apiTokenEntity, apiTokenTable } from "../schema/api-token.ts";
15
- import { API_TOKEN_ENTITY_NAME, PAT_DEFAULT_EXPIRES_IN_DAYS, PatErrors } from "../web/constants.ts";
15
+ import {
16
+ API_TOKEN_ENTITY_NAME,
17
+ PAT_DEFAULT_EXPIRES_IN_DAYS,
18
+ PAT_MAX_EXPIRES_IN_DAYS,
19
+ PatErrors,
20
+ } from "../web/constants.ts";
16
21
 
17
22
  export type PatMfaVerifyResult = { readonly enrolled: boolean; readonly ok: boolean };
18
23
 
@@ -49,7 +54,7 @@ export function createPatCreateHandler(opts: CreatePatOptions = {}) {
49
54
  schema: z.object({
50
55
  name: z.string().min(1).max(120),
51
56
  scopes: z.array(z.string().min(1)).min(1),
52
- expiresInDays: z.number().int().positive().max(3650).optional(),
57
+ expiresInDays: z.number().int().positive().max(PAT_MAX_EXPIRES_IN_DAYS).optional(),
53
58
  currentPassword: z.string().min(1),
54
59
  mfaCode: z.string().optional(),
55
60
  }),
@@ -1,6 +1,6 @@
1
1
  import { ACTION_FORM_ENTITY } from "@cosmicdrift/kumiko-framework/ui-types";
2
2
  import { fieldLabelKey, fieldOptionLabelKey } from "@cosmicdrift/kumiko-renderer/headless";
3
- import { PAT_FEATURE } from "./web/constants.ts";
3
+ import { PAT_FEATURE, PatHandlers } from "./web/constants.ts";
4
4
  import type { PatScopeConfig } from "./web/scopes.ts";
5
5
 
6
6
  const mintFieldKey = (field: string): string =>
@@ -12,6 +12,9 @@ const scopeOptionKey = (grant: string): string =>
12
12
  export const patScopeOptionKey = (domain: string, level: "read" | "write"): string =>
13
13
  scopeOptionKey(`${domain}:${level}`);
14
14
 
15
+ // The revoke handler has no entity and no action form, so its title and field label only exist here.
16
+ const patRevokeKey = (suffix: string): string => `${PatHandlers.revoke}:${suffix}`;
17
+
15
18
  type LocalizedString = { readonly en: string };
16
19
 
17
20
  export const PAT_FEATURE_I18N: Readonly<Record<string, LocalizedString>> = {
@@ -29,6 +32,8 @@ export const PAT_FEATURE_I18N: Readonly<Record<string, LocalizedString>> = {
29
32
  "pat.list.status.expired": { en: "Expired" },
30
33
  "pat.list.revoke": { en: "Revoke" },
31
34
  "pat.list.revoke.confirm": { en: "Revoke this token? Anything using it will stop working." },
35
+ [patRevokeKey("title")]: { en: "Revoke token" },
36
+ [patRevokeKey("field:id")]: { en: "Token" },
32
37
 
33
38
  "pat.create.title": { en: "Create a new token" },
34
39
  "pat.create.submit": { en: "Create token" },
@@ -1,5 +1,6 @@
1
1
  import type { FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { PAT_DEFAULT_RATE_LIMIT, type PatRateLimit } from "./web/constants.ts";
3
+ import type { PatScopeConfig, PatScopeDef } from "./web/scopes.ts";
3
4
 
4
5
  export type { BindPatAutoRevokeOnPasswordChange, PersonalAccessTokensOptions } from "./feature.ts";
5
6
  export {
@@ -20,9 +21,43 @@ export { createPatResolver } from "./resolver.ts";
20
21
  export { revokeAllPatTokensForUser } from "./revoke-for-user.ts";
21
22
  export { apiTokenEntity, apiTokenTable } from "./schema/api-token.ts";
22
23
  export type { PatRateLimit } from "./web/constants.ts";
23
- export { PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PatHandlers, PatQueries } from "./web/constants.ts";
24
+ export {
25
+ PAT_DEFAULT_EXPIRES_IN_DAYS,
26
+ PAT_DEFAULT_RATE_LIMIT,
27
+ PAT_FEATURE,
28
+ PAT_MAX_EXPIRES_IN_DAYS,
29
+ PAT_SCREEN_ID,
30
+ PatHandlers,
31
+ PatQueries,
32
+ } from "./web/constants.ts";
24
33
  export type { PatScopeConfig, PatScopeDef } from "./web/scopes.ts";
25
- export { expandScopes } from "./web/scopes.ts";
34
+ export { expandScopeEvents, expandScopes } from "./web/scopes.ts";
35
+
36
+ function isStringArray(value: unknown): value is readonly string[] {
37
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
38
+ }
39
+
40
+ function isPatScopeDef(value: unknown): value is PatScopeDef {
41
+ if (!value || typeof value !== "object") return false;
42
+ if (!("label" in value) || typeof value.label !== "string") return false;
43
+ if (!("read" in value) || !isStringArray(value.read)) return false;
44
+ if ("write" in value && value.write !== undefined && !isStringArray(value.write)) return false;
45
+ return !("events" in value) || value.events === undefined || isStringArray(value.events);
46
+ }
47
+
48
+ function isPatScopeConfig(value: unknown): value is PatScopeConfig {
49
+ return !!value && typeof value === "object" && Object.values(value).every(isPatScopeDef);
50
+ }
51
+
52
+ // Reads the scope catalog off a mounted PAT feature's exports; undefined for any other feature.
53
+ export function patScopesFromFeature(feature: FeatureDefinition): PatScopeConfig | undefined {
54
+ const exports = feature.exports;
55
+ if (exports && typeof exports === "object" && "scopes" in exports) {
56
+ const { scopes } = exports;
57
+ if (isPatScopeConfig(scopes)) return scopes;
58
+ }
59
+ return undefined;
60
+ }
26
61
 
27
62
  // Reads the per-token rate-limit config off a mounted PAT feature's exports.
28
63
  // Falls back to the default when absent. run-prod-app uses this to build the
@@ -0,0 +1,28 @@
1
+ import {
2
+ createWebhookContractResolver,
3
+ type FeatureDefinition,
4
+ } from "@cosmicdrift/kumiko-framework/engine";
5
+ import { PAT_FEATURE } from "./web/constants.ts";
6
+ import type { PatScopeConfig } from "./web/scopes.ts";
7
+
8
+ function entityNameOf(qualifiedName: string): string {
9
+ const dot = qualifiedName.lastIndexOf(".");
10
+ return dot > 0 ? qualifiedName.slice(0, dot) : qualifiedName;
11
+ }
12
+
13
+ export function validateScopeEventContracts(
14
+ scopes: PatScopeConfig,
15
+ features: readonly FeatureDefinition[],
16
+ ): void {
17
+ const resolver = createWebhookContractResolver(features);
18
+ for (const [domain, def] of Object.entries(scopes)) {
19
+ for (const qn of def.events ?? []) {
20
+ if (resolver.get(qn)) continue;
21
+ throw new Error(
22
+ `[${PAT_FEATURE}] scope "${domain}" lists event "${qn}" without a public contract. ` +
23
+ "Declare it with r.defineWebhookEvent(...), or set webhookEvents: true on the entity to release its <entity>.created/.updated/.deleted events " +
24
+ `(entity "${entityNameOf(qn)}" has no such opt-in); internal r.defineEvent events are never released.`,
25
+ );
26
+ }
27
+ }
28
+ }
@@ -7,7 +7,9 @@ import {
7
7
  import { ACTION_FORM_ENTITY } from "@cosmicdrift/kumiko-framework/ui-types";
8
8
  import { fieldOptionLabelKeyPrefix } from "@cosmicdrift/kumiko-renderer/headless";
9
9
  import {
10
+ PAT_DEFAULT_EXPIRES_IN_DAYS,
10
11
  PAT_FEATURE,
12
+ PAT_MAX_EXPIRES_IN_DAYS,
11
13
  PAT_MINT_SCREEN_ID,
12
14
  PAT_SCREEN_ID,
13
15
  PatHandlers,
@@ -136,7 +138,13 @@ export function createPatMintScreen(scopes: PatScopeConfig): SecretMintScreenDef
136
138
  display: "checkboxes",
137
139
  options: patGrantOptions(scopes),
138
140
  },
139
- expiresInDays: { type: "number", integer: true, min: 1, max: 3650, default: 90 },
141
+ expiresInDays: {
142
+ type: "number",
143
+ integer: true,
144
+ min: 1,
145
+ max: PAT_MAX_EXPIRES_IN_DAYS,
146
+ default: PAT_DEFAULT_EXPIRES_IN_DAYS,
147
+ },
140
148
  currentPassword: { type: "text", required: true, format: "password", sensitive: true },
141
149
  mfaCode: { type: "text" },
142
150
  },
@@ -15,6 +15,7 @@ export const PatErrors = {
15
15
  // default is a standing-credential risk; the existing 3650-day cap still
16
16
  // lets callers who genuinely want a long-lived token pass it explicitly.
17
17
  export const PAT_DEFAULT_EXPIRES_IN_DAYS = 90;
18
+ export const PAT_MAX_EXPIRES_IN_DAYS = 3650;
18
19
 
19
20
  // Declarative projectionList screen id — the caller's own tokens, revoke as a
20
21
  // row action. The app places it via r.nav.
@@ -10,6 +10,9 @@ export type PatScopeDef = {
10
10
  readonly read: readonly string[];
11
11
  // Omit for a read-only domain — the UI then offers only "no access" / "read".
12
12
  readonly write?: readonly string[];
13
+ // Exact webhook event QNs (no globs): a subscriber must know exactly what it gets. Every entry
14
+ // needs a public contract (r.defineWebhookEvent or an entity event); the boot check enforces it.
15
+ readonly events?: readonly string[];
13
16
  };
14
17
 
15
18
  export type PatScopeConfig = Readonly<Record<string, PatScopeDef>>;
@@ -24,6 +27,17 @@ export function parseGrant(grant: string): { domain: string; level: string } | n
24
27
  return { domain: grant.slice(0, idx), level: grant.slice(idx + 1) };
25
28
  }
26
29
 
30
+ // Union of the webhook events of every granted domain; read level already suffices to subscribe.
31
+ export function expandScopeEvents(config: PatScopeConfig, granted: readonly string[]): string[] {
32
+ const out = new Set<string>();
33
+ for (const grant of granted) {
34
+ const parsed = parseGrant(grant);
35
+ if (!parsed) continue;
36
+ for (const qn of config[parsed.domain]?.events ?? []) out.add(qn);
37
+ }
38
+ return [...out];
39
+ }
40
+
27
41
  // Expand granted "<domain>:<level>" entries into the union of QN globs: read
28
42
  // always grants the read QNs; write additionally grants the write QNs. Unknown
29
43
  // domains contribute nothing (fail-closed — a scope dropped from config after a