@cosmicdrift/kumiko-bundled-features 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 (92) 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/inbound-mail-foundation/entities.d.ts +84 -0
  74. package/dist/inbound-mail-foundation/entities.js +96 -71
  75. package/dist/inbound-mail-foundation/feature.js +2 -2
  76. package/dist/personal-access-tokens/feature.d.ts +1 -0
  77. package/dist/personal-access-tokens/feature.js +4 -2
  78. package/dist/personal-access-tokens/handlers/create.write.js +2 -2
  79. package/dist/personal-access-tokens/i18n.js +5 -1
  80. package/dist/personal-access-tokens/index.d.ts +4 -2
  81. package/dist/personal-access-tokens/index.js +29 -2
  82. package/dist/personal-access-tokens/scope-events-check.d.ts +3 -0
  83. package/dist/personal-access-tokens/scope-events-check.js +18 -0
  84. package/dist/personal-access-tokens/screens.js +8 -2
  85. package/dist/personal-access-tokens/web/constants.d.ts +1 -0
  86. package/dist/personal-access-tokens/web/constants.js +1 -0
  87. package/dist/personal-access-tokens/web/scopes.d.ts +2 -0
  88. package/dist/personal-access-tokens/web/scopes.js +12 -0
  89. package/package.json +11 -11
  90. package/src/agent-tools/changes.json +24 -0
  91. package/src/inbound-mail-foundation/changes.json +6 -0
  92. package/src/personal-access-tokens/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
+ }
@@ -48,6 +48,90 @@ export declare const mailAccountEntity: import("@cosmicdrift/kumiko-types/fields
48
48
  /** An incoming mail (envelope + snippet, NO body — bodyRef
49
49
  * points to file-foundation). PK = aggregateId =
50
50
  * inboundMessageAggregateId(accountId, providerMessageId). */
51
+ export declare function createInboundMessageEntity(memberRoles: readonly string[]): import("@cosmicdrift/kumiko-types/fields").EntityDefinition<{
52
+ readonly accountId: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
53
+ required: true;
54
+ };
55
+ readonly ownerUserId: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
56
+ required: false;
57
+ };
58
+ readonly messageIdHeader: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
59
+ required: true;
60
+ };
61
+ readonly threadKey: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
62
+ required: true;
63
+ };
64
+ readonly from: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
65
+ required: true;
66
+ };
67
+ readonly to: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
68
+ required: false;
69
+ };
70
+ readonly cc: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
71
+ required: false;
72
+ };
73
+ readonly subject: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
74
+ required: false;
75
+ };
76
+ readonly snippet: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
77
+ required: false;
78
+ };
79
+ readonly receivedAt: {
80
+ readonly type: "timestamp";
81
+ readonly description?: string;
82
+ readonly required?: boolean;
83
+ readonly sortable?: boolean;
84
+ readonly sortNulls?: import("@cosmicdrift/kumiko-types/fields").SortNulls;
85
+ readonly filterable?: boolean;
86
+ readonly sensitive?: boolean;
87
+ readonly access?: import("@cosmicdrift/kumiko-types/fields").FieldAccess;
88
+ readonly locatedBy?: string;
89
+ readonly min?: string;
90
+ readonly max?: string;
91
+ readonly locale?: string;
92
+ } & import("@cosmicdrift/kumiko-types/fields").ResolvedPiiFlags & import("@cosmicdrift/kumiko-types/fields").FieldStateConditions & {
93
+ required: true;
94
+ };
95
+ readonly bodyRef: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
96
+ required: false;
97
+ };
98
+ readonly scope: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
99
+ required: false;
100
+ };
101
+ readonly bodyText: import("@cosmicdrift/kumiko-types/fields").EntityLongTextFieldDef & {
102
+ required: false;
103
+ };
104
+ readonly bodyTextTruncated: {
105
+ readonly type: "boolean";
106
+ readonly description?: string;
107
+ readonly required?: boolean;
108
+ readonly sortable?: boolean;
109
+ readonly sortNulls?: import("@cosmicdrift/kumiko-types/fields").SortNulls;
110
+ readonly filterable?: boolean;
111
+ readonly sensitive?: boolean;
112
+ readonly default?: boolean;
113
+ readonly access?: import("@cosmicdrift/kumiko-types/fields").FieldAccess;
114
+ } & import("@cosmicdrift/kumiko-types/fields").FieldStateConditions & {
115
+ required: false;
116
+ default: boolean;
117
+ };
118
+ readonly bodyHtml: import("@cosmicdrift/kumiko-types/fields").EntityLongTextFieldDef & {
119
+ required: false;
120
+ };
121
+ readonly attachmentFileIds: import("@cosmicdrift/kumiko-types/fields").FilesFieldDef;
122
+ readonly skippedAttachments: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
123
+ required: false;
124
+ };
125
+ readonly senderAuthentication: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
126
+ required: false;
127
+ };
128
+ readonly contentState: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
129
+ required: false;
130
+ };
131
+ readonly contentUnavailableReason: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
132
+ required: false;
133
+ };
134
+ }, "tenant">;
51
135
  export declare const inboundMessageEntity: import("@cosmicdrift/kumiko-types/fields").EntityDefinition<{
52
136
  readonly accountId: import("@cosmicdrift/kumiko-types/fields").EntityTextFieldDef & {
53
137
  required: true;
@@ -1,6 +1,7 @@
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 { access, createBooleanField, createEntity, createFilesField, createLongTextField, createNumberField, createTextField, createTimestampField, } from "@cosmicdrift/kumiko-framework/engine";
4
+ import { DEFAULT_INBOUND_MAIL_ADMIN_ROLES, DEFAULT_INBOUND_MAIL_USER_ROLES } from "./mail-roles.js";
4
5
  // ============================================================================
5
6
  // Read models for the three event-sourced aggregates
6
7
  // ============================================================================
@@ -68,79 +69,103 @@ export const mailAccountEntity = createEntity({
68
69
  connectedAt: createTimestampField({ required: true }),
69
70
  },
70
71
  });
72
+ // Mirrors isVisibleToCaller (handlers/scope-visibility.ts) for the roles of the detail query:
73
+ // shared rows and the caller's own personal mailbox, no admin exception. The read gate of other
74
+ // entities (readGate.fileOwner) reads it; the hand-written message queries do not apply it.
75
+ function ownMailboxOrSharedRead(memberRoles) {
76
+ const rule = {
77
+ kind: "where",
78
+ where: (user, ctx) => {
79
+ const owner = `"${ctx.tableName}"."${physicalColumnName(ctx.table, "ownerUserId")}"`;
80
+ return {
81
+ sqlText: `(${owner} IS NULL OR ${owner} = '' OR ${owner} = $${ctx.paramStart})`,
82
+ params: [user.id],
83
+ };
84
+ },
85
+ };
86
+ return Object.fromEntries(memberRoles.map((role) => [role, rule]));
87
+ }
71
88
  /** An incoming mail (envelope + snippet, NO body — bodyRef
72
89
  * points to file-foundation). PK = aggregateId =
73
90
  * inboundMessageAggregateId(accountId, providerMessageId). */
74
- export const inboundMessageEntity = createEntity({
75
- table: "read_inbound_messages",
76
- fields: {
77
- accountId: createTextField({
78
- required: true,
79
- maxLength: 36,
80
- personal: false,
81
- reason: "technical_reference",
82
- }),
83
- // Scope is inherited from the account at ingest time: messages from a
84
- // personal mailbox are visible only to the owner, without joining read_mail_accounts.
85
- ownerUserId: createTextField({ maxLength: 36, personal: false, reason: "pseudonymous_fk" }),
86
- messageIdHeader: createTextField({
87
- required: true,
88
- maxLength: 500,
89
- personal: false,
90
- reason: "technical_reference",
91
- }),
92
- threadKey: createTextField({
93
- required: true,
94
- maxLength: 500,
95
- personal: false,
96
- reason: "technical_reference",
97
- }),
98
- from: createTextField({ required: true, maxLength: 2000, personal: "tenant", find: "none" }),
99
- // JSON-stringified string[] — als Ganzes encrypted.
100
- to: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
101
- cc: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
102
- subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
103
- snippet: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
104
- receivedAt: createTimestampField({ required: true }),
105
- bodyRef: createTextField({ maxLength: 500, personal: false, reason: "technical_reference" }),
106
- scope: createTextField({ maxLength: 200, personal: false, reason: "technical_reference" }),
107
- // Full plaintext, capped at 32_000 characters before encryption (ciphertext is ~2.3x plus envelope).
108
- // Null on rows from before the column; list-messages never selects it.
109
- bodyText: createLongTextField({ maxLength: 200_000, personal: "tenant", find: "none" }),
110
- bodyTextTruncated: createBooleanField(),
111
- // Sanitized HTML of the mail (sanitizeInboundHtml), null when the mail has none or it was too large.
112
- bodyHtml: createLongTextField({ maxLength: 500_000, personal: "tenant", find: "none" }),
113
- // Bound to the message (entityType = the aggregate type), so the file guard answers with the
114
- // mail's visibility. The fileRefs are bound at ingest, the projection copies the ids.
115
- attachmentFileIds: createFilesField({ personal: false, reason: "technical_reference" }),
116
- // JSON-stringified SkippedInboundAttachment[]: nullable JSON stays a text column
117
- // (jsonb fields are NOT NULL), like to/cc.
118
- skippedAttachments: createTextField({
119
- maxLength: 20_000,
120
- personal: false,
121
- reason: "technical_reference",
122
- }),
123
- // JSON-stringified SenderAuthentication or "null"; a SQL null (rows from before the column) reads as null.
124
- senderAuthentication: createTextField({
125
- maxLength: 4000,
126
- personal: false,
127
- reason: "technical_reference",
128
- }),
129
- // "complete" | "snippet" | "unavailable"; null counts as "snippet".
130
- contentState: createTextField({
131
- maxLength: 20,
132
- personal: false,
133
- reason: "technical_reference",
134
- }),
135
- // One of INBOUND_CONTENT_UNAVAILABLE_REASONS; null while the content is there or not yet missing.
136
- contentUnavailableReason: createTextField({
137
- maxLength: 30,
138
- personal: false,
139
- reason: "technical_reference",
140
- }),
141
- },
142
- attachedFileAccess: "record-only",
143
- });
91
+ export function createInboundMessageEntity(memberRoles) {
92
+ return createEntity({
93
+ access: { read: ownMailboxOrSharedRead(memberRoles) },
94
+ table: "read_inbound_messages",
95
+ fields: {
96
+ accountId: createTextField({
97
+ required: true,
98
+ maxLength: 36,
99
+ personal: false,
100
+ reason: "technical_reference",
101
+ }),
102
+ // Scope is inherited from the account at ingest time: messages from a
103
+ // personal mailbox are visible only to the owner, without joining read_mail_accounts.
104
+ ownerUserId: createTextField({ maxLength: 36, personal: false, reason: "pseudonymous_fk" }),
105
+ messageIdHeader: createTextField({
106
+ required: true,
107
+ maxLength: 500,
108
+ personal: false,
109
+ reason: "technical_reference",
110
+ }),
111
+ threadKey: createTextField({
112
+ required: true,
113
+ maxLength: 500,
114
+ personal: false,
115
+ reason: "technical_reference",
116
+ }),
117
+ from: createTextField({ required: true, maxLength: 2000, personal: "tenant", find: "none" }),
118
+ // JSON-stringified string[] — als Ganzes encrypted.
119
+ to: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
120
+ cc: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
121
+ subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
122
+ snippet: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
123
+ receivedAt: createTimestampField({ required: true }),
124
+ bodyRef: createTextField({ maxLength: 500, personal: false, reason: "technical_reference" }),
125
+ scope: createTextField({ maxLength: 200, personal: false, reason: "technical_reference" }),
126
+ // Full plaintext, capped at 32_000 characters before encryption (ciphertext is ~2.3x plus envelope).
127
+ // Null on rows from before the column; list-messages never selects it.
128
+ bodyText: createLongTextField({ maxLength: 200_000, personal: "tenant", find: "none" }),
129
+ bodyTextTruncated: createBooleanField(),
130
+ // Sanitized HTML of the mail (sanitizeInboundHtml), null when the mail has none or it was too large.
131
+ bodyHtml: createLongTextField({ maxLength: 500_000, personal: "tenant", find: "none" }),
132
+ // Bound to the message (entityType = the aggregate type), so the file guard answers with the
133
+ // mail's visibility. The fileRefs are bound at ingest, the projection copies the ids.
134
+ attachmentFileIds: createFilesField({ personal: false, reason: "technical_reference" }),
135
+ // JSON-stringified SkippedInboundAttachment[]: nullable JSON stays a text column
136
+ // (jsonb fields are NOT NULL), like to/cc.
137
+ skippedAttachments: createTextField({
138
+ maxLength: 20_000,
139
+ personal: false,
140
+ reason: "technical_reference",
141
+ }),
142
+ // JSON-stringified SenderAuthentication or "null"; a SQL null (rows from before the column) reads as null.
143
+ senderAuthentication: createTextField({
144
+ maxLength: 4000,
145
+ personal: false,
146
+ reason: "technical_reference",
147
+ }),
148
+ // "complete" | "snippet" | "unavailable"; null counts as "snippet".
149
+ contentState: createTextField({
150
+ maxLength: 20,
151
+ personal: false,
152
+ reason: "technical_reference",
153
+ }),
154
+ // One of INBOUND_CONTENT_UNAVAILABLE_REASONS; null while the content is there or not yet missing.
155
+ contentUnavailableReason: createTextField({
156
+ maxLength: 30,
157
+ personal: false,
158
+ reason: "technical_reference",
159
+ }),
160
+ },
161
+ attachedFileAccess: "record-only",
162
+ });
163
+ }
164
+ // Same fields for every role set; table and PII lists do not depend on the roles.
165
+ export const inboundMessageEntity = createInboundMessageEntity([
166
+ ...DEFAULT_INBOUND_MAIL_ADMIN_ROLES,
167
+ ...DEFAULT_INBOUND_MAIL_USER_ROLES,
168
+ ]);
144
169
  /** Thread-Rollup. PK = aggregateId = mailThreadAggregateId(tenantId,
145
170
  * threadKey). */
146
171
  export const mailThreadEntity = createEntity({
@@ -22,7 +22,7 @@
22
22
  // archives all streams and deletes the rows.
23
23
  import { defineFeature, EXT_TENANT_DATA } from "@cosmicdrift/kumiko-framework/engine";
24
24
  import { INBOUND_MAIL_FOUNDATION_FEATURE, INBOUND_MAIL_PROVIDER_EXTENSION } from "./constants.js";
25
- import { inboundMessageEntity, mailAccountEntity, mailThreadEntity, seenMessageTable, syncCursorTable, } from "./entities.js";
25
+ import { createInboundMessageEntity, mailAccountEntity, mailThreadEntity, seenMessageTable, syncCursorTable, } from "./entities.js";
26
26
  import { INBOUND_MESSAGE_AGGREGATE_TYPE, INBOUND_MESSAGE_CONTENT_FETCHED_EVENT_QN, INBOUND_MESSAGE_CONTENT_FETCHED_EVENT_SHORT, INBOUND_MESSAGE_RECEIVED_EVENT_QN, INBOUND_MESSAGE_RECEIVED_EVENT_SHORT, inboundMessageContentFetchedEventPayloadSchema, inboundMessageEventPayloadSchema, MAIL_ACCOUNT_AGGREGATE_TYPE, MAIL_ACCOUNT_CONNECTED_EVENT_QN, MAIL_ACCOUNT_CONNECTED_EVENT_SHORT, MAIL_ACCOUNT_DISCONNECTED_EVENT_QN, MAIL_ACCOUNT_DISCONNECTED_EVENT_SHORT, MAIL_ACCOUNT_UPDATED_EVENT_QN, MAIL_ACCOUNT_UPDATED_EVENT_SHORT, MAIL_THREAD_AGGREGATE_TYPE, MAIL_THREAD_UPDATED_EVENT_QN, MAIL_THREAD_UPDATED_EVENT_SHORT, mailAccountEventPayloadSchema, mailThreadEventPayloadSchema, } from "./events.js";
27
27
  import { createAcknowledgeQuarantineHandler } from "./handlers/acknowledge-quarantine.write.js";
28
28
  import { attachMessageContentHandler } from "./handlers/attach-message-content.write.js";
@@ -151,7 +151,7 @@ export function createInboundMailFoundationFeature(options = {}) {
151
151
  name: "inbound-message",
152
152
  source: INBOUND_MESSAGE_AGGREGATE_TYPE,
153
153
  table: inboundMessagesProjectionTable,
154
- entity: inboundMessageEntity,
154
+ entity: createInboundMessageEntity(roles.memberRoles),
155
155
  apply: {
156
156
  [INBOUND_MESSAGE_RECEIVED_EVENT_QN]: applyInboundMessageReceived,
157
157
  [INBOUND_MESSAGE_CONTENT_FETCHED_EVENT_QN]: applyInboundMessageContentFetched,
@@ -25,6 +25,7 @@ export type PersonalAccessTokensOptions = {
25
25
  };
26
26
  export type PatFeatureExports = {
27
27
  readonly rateLimit: PatRateLimit;
28
+ readonly scopes: PatScopeConfig;
28
29
  readonly bindAutoRevokeOnPasswordChange: BindPatAutoRevokeOnPasswordChange;
29
30
  };
30
31
  export declare function createPersonalAccessTokensFeature(options: PersonalAccessTokensOptions): FeatureDefinition;
@@ -12,6 +12,7 @@ import { PAT_FEATURE_I18N, patScopeOptionTranslations } from "./i18n.js";
12
12
  import { PAT_REVOKED_EVENT_SHORT, patRevokedSchema } from "./pat-revoked-event.js";
13
13
  import { createPatResolver } from "./resolver.js";
14
14
  import { apiTokenEntity } from "./schema/api-token.js";
15
+ import { validateScopeEventContracts } from "./scope-events-check.js";
15
16
  import { createPatMintScreen, patListScreen } from "./screens.js";
16
17
  import { API_TOKEN_ENTITY_NAME, PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, } from "./web/constants.js";
17
18
  // Password-change is the only field-level trigger — see the postSave hook
@@ -70,6 +71,7 @@ export function createPersonalAccessTokensFeature(options) {
70
71
  // different path. No projection: the payload IS the read, consumed
71
72
  // directly off the event-store NOTIFY.
72
73
  r.defineEvent(PAT_REVOKED_EVENT_SHORT, patRevokedSchema, { piiFields: "none" });
74
+ r.bootCheck(({ features }) => validateScopeEventContracts(scopes, features));
73
75
  // Password-change auto-revoke — mirrors sessions' own
74
76
  // autoRevokeOnPasswordChange postSave hook, including WHY it's a
75
77
  // late-bind callback rather than direct ctx.db use: user:write:user:update
@@ -123,12 +125,12 @@ export function createPersonalAccessTokensFeature(options) {
123
125
  r.translations({ keys: { ...PAT_FEATURE_I18N, ...patScopeOptionTranslations(scopes) } });
124
126
  // rateLimit flows into feature.exports so run-prod-app builds the
125
127
  // limiter from the same declaration — single source of truth. `scopes`
126
- // is closed over directly by the useExtension build() above and by
127
- // available-scopes, so it doesn't need to round-trip through exports.
128
+ // is also exported so the API-docs generator can read the catalog.
128
129
  return {
129
130
  handlers,
130
131
  queries,
131
132
  bindAutoRevokeOnPasswordChange,
133
+ scopes,
132
134
  rateLimit: options.rateLimit ?? PAT_DEFAULT_RATE_LIMIT,
133
135
  };
134
136
  });
@@ -7,7 +7,7 @@ import { encryptForDirectWrite, unprocessable, verifyPassword } from "../../shar
7
7
  import { UserQueries } from "../../user/index.js";
8
8
  import { mintPatToken } from "../hash.js";
9
9
  import { apiTokenEntity, apiTokenTable } from "../schema/api-token.js";
10
- import { API_TOKEN_ENTITY_NAME, PAT_DEFAULT_EXPIRES_IN_DAYS, PatErrors } from "../web/constants.js";
10
+ import { API_TOKEN_ENTITY_NAME, PAT_DEFAULT_EXPIRES_IN_DAYS, PAT_MAX_EXPIRES_IN_DAYS, PatErrors, } from "../web/constants.js";
11
11
  // @wrapper-known error-helper
12
12
  function reauthFailed() {
13
13
  return unprocessable(PatErrors.reauthRequired, "errors.reauthRequired");
@@ -27,7 +27,7 @@ export function createPatCreateHandler(opts = {}) {
27
27
  schema: z.object({
28
28
  name: z.string().min(1).max(120),
29
29
  scopes: z.array(z.string().min(1)).min(1),
30
- expiresInDays: z.number().int().positive().max(3650).optional(),
30
+ expiresInDays: z.number().int().positive().max(PAT_MAX_EXPIRES_IN_DAYS).optional(),
31
31
  currentPassword: z.string().min(1),
32
32
  mfaCode: z.string().optional(),
33
33
  }),
@@ -1,10 +1,12 @@
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.js";
3
+ import { PAT_FEATURE, PatHandlers } from "./web/constants.js";
4
4
  const mintFieldKey = (field) => fieldLabelKey(PAT_FEATURE, ACTION_FORM_ENTITY, field);
5
5
  const scopeOptionKey = (grant) => fieldOptionLabelKey(PAT_FEATURE, ACTION_FORM_ENTITY, "scopes", grant);
6
6
  // The generated scope labels are English only; apps translate them under this key.
7
7
  export const patScopeOptionKey = (domain, level) => scopeOptionKey(`${domain}:${level}`);
8
+ // The revoke handler has no entity and no action form, so its title and field label only exist here.
9
+ const patRevokeKey = (suffix) => `${PatHandlers.revoke}:${suffix}`;
8
10
  export const PAT_FEATURE_I18N = {
9
11
  "screen:api-tokens.title": { en: "Personal Access Tokens" },
10
12
  "screen:api-token-create.title": { en: "Create a new token" },
@@ -19,6 +21,8 @@ export const PAT_FEATURE_I18N = {
19
21
  "pat.list.status.expired": { en: "Expired" },
20
22
  "pat.list.revoke": { en: "Revoke" },
21
23
  "pat.list.revoke.confirm": { en: "Revoke this token? Anything using it will stop working." },
24
+ [patRevokeKey("title")]: { en: "Revoke token" },
25
+ [patRevokeKey("field:id")]: { en: "Token" },
22
26
  "pat.create.title": { en: "Create a new token" },
23
27
  "pat.create.submit": { en: "Create token" },
24
28
  "pat.create.reauth": { en: "Confirm your identity" },
@@ -1,5 +1,6 @@
1
1
  import type { FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { type PatRateLimit } from "./web/constants.ts";
3
+ import type { PatScopeConfig } from "./web/scopes.ts";
3
4
  export type { BindPatAutoRevokeOnPasswordChange, PersonalAccessTokensOptions } from "./feature.ts";
4
5
  export { bindPatAutoRevokeOnPasswordChangeFromFeature, createPersonalAccessTokensFeature, } from "./feature.ts";
5
6
  export type { CreatePatOptions, PatMfaVerifyResult } from "./handlers/create.write.ts";
@@ -10,7 +11,8 @@ export { createPatResolver } from "./resolver.ts";
10
11
  export { revokeAllPatTokensForUser } from "./revoke-for-user.ts";
11
12
  export { apiTokenEntity, apiTokenTable } from "./schema/api-token.ts";
12
13
  export type { PatRateLimit } from "./web/constants.ts";
13
- export { PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PatHandlers, PatQueries } from "./web/constants.ts";
14
+ export { PAT_DEFAULT_EXPIRES_IN_DAYS, PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PAT_MAX_EXPIRES_IN_DAYS, PAT_SCREEN_ID, PatHandlers, PatQueries, } from "./web/constants.ts";
14
15
  export type { PatScopeConfig, PatScopeDef } from "./web/scopes.ts";
15
- export { expandScopes } from "./web/scopes.ts";
16
+ export { expandScopeEvents, expandScopes } from "./web/scopes.ts";
17
+ export declare function patScopesFromFeature(feature: FeatureDefinition): PatScopeConfig | undefined;
16
18
  export declare function patRateLimitFromFeature(feature: FeatureDefinition): PatRateLimit;
@@ -6,8 +6,35 @@ export { PAT_REVOKED_AGGREGATE_TYPE, PAT_REVOKED_EVENT_QN, PAT_REVOKED_EVENT_SHO
6
6
  export { createPatResolver } from "./resolver.js";
7
7
  export { revokeAllPatTokensForUser } from "./revoke-for-user.js";
8
8
  export { apiTokenEntity, apiTokenTable } from "./schema/api-token.js";
9
- export { PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PatHandlers, PatQueries } from "./web/constants.js";
10
- export { expandScopes } from "./web/scopes.js";
9
+ export { PAT_DEFAULT_EXPIRES_IN_DAYS, PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PAT_MAX_EXPIRES_IN_DAYS, PAT_SCREEN_ID, PatHandlers, PatQueries, } from "./web/constants.js";
10
+ export { expandScopeEvents, expandScopes } from "./web/scopes.js";
11
+ function isStringArray(value) {
12
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
13
+ }
14
+ function isPatScopeDef(value) {
15
+ if (!value || typeof value !== "object")
16
+ return false;
17
+ if (!("label" in value) || typeof value.label !== "string")
18
+ return false;
19
+ if (!("read" in value) || !isStringArray(value.read))
20
+ return false;
21
+ if ("write" in value && value.write !== undefined && !isStringArray(value.write))
22
+ return false;
23
+ return !("events" in value) || value.events === undefined || isStringArray(value.events);
24
+ }
25
+ function isPatScopeConfig(value) {
26
+ return !!value && typeof value === "object" && Object.values(value).every(isPatScopeDef);
27
+ }
28
+ // Reads the scope catalog off a mounted PAT feature's exports; undefined for any other feature.
29
+ export function patScopesFromFeature(feature) {
30
+ const exports = feature.exports;
31
+ if (exports && typeof exports === "object" && "scopes" in exports) {
32
+ const { scopes } = exports;
33
+ if (isPatScopeConfig(scopes))
34
+ return scopes;
35
+ }
36
+ return undefined;
37
+ }
11
38
  // Reads the per-token rate-limit config off a mounted PAT feature's exports.
12
39
  // Falls back to the default when absent. run-prod-app uses this to build the
13
40
  // limiter from the same declaration the feature was given.
@@ -0,0 +1,3 @@
1
+ import { type FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { PatScopeConfig } from "./web/scopes.ts";
3
+ export declare function validateScopeEventContracts(scopes: PatScopeConfig, features: readonly FeatureDefinition[]): void;
@@ -0,0 +1,18 @@
1
+ import { createWebhookContractResolver, } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { PAT_FEATURE } from "./web/constants.js";
3
+ function entityNameOf(qualifiedName) {
4
+ const dot = qualifiedName.lastIndexOf(".");
5
+ return dot > 0 ? qualifiedName.slice(0, dot) : qualifiedName;
6
+ }
7
+ export function validateScopeEventContracts(scopes, features) {
8
+ const resolver = createWebhookContractResolver(features);
9
+ for (const [domain, def] of Object.entries(scopes)) {
10
+ for (const qn of def.events ?? []) {
11
+ if (resolver.get(qn))
12
+ continue;
13
+ throw new Error(`[${PAT_FEATURE}] scope "${domain}" lists event "${qn}" without a public contract. ` +
14
+ "Declare it with r.defineWebhookEvent(...), or set webhookEvents: true on the entity to release its <entity>.created/.updated/.deleted events " +
15
+ `(entity "${entityNameOf(qn)}" has no such opt-in); internal r.defineEvent events are never released.`);
16
+ }
17
+ }
18
+ }
@@ -1,7 +1,7 @@
1
1
  import { i18nKey, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { ACTION_FORM_ENTITY } from "@cosmicdrift/kumiko-framework/ui-types";
3
3
  import { fieldOptionLabelKeyPrefix } from "@cosmicdrift/kumiko-renderer/headless";
4
- import { PAT_FEATURE, PAT_MINT_SCREEN_ID, PAT_SCREEN_ID, PatHandlers, PatQueries, } from "./web/constants.js";
4
+ import { PAT_DEFAULT_EXPIRES_IN_DAYS, PAT_FEATURE, PAT_MAX_EXPIRES_IN_DAYS, PAT_MINT_SCREEN_ID, PAT_SCREEN_ID, PatHandlers, PatQueries, } from "./web/constants.js";
5
5
  const PAT_STATUS_OPTION_KEY_PREFIX = "pat.list.status.";
6
6
  // Same keys the mint form's `scopes` multiSelect options resolve through
7
7
  // (see patScopeOptionTranslations), so list and form show identical labels.
@@ -114,7 +114,13 @@ export function createPatMintScreen(scopes) {
114
114
  display: "checkboxes",
115
115
  options: patGrantOptions(scopes),
116
116
  },
117
- expiresInDays: { type: "number", integer: true, min: 1, max: 3650, default: 90 },
117
+ expiresInDays: {
118
+ type: "number",
119
+ integer: true,
120
+ min: 1,
121
+ max: PAT_MAX_EXPIRES_IN_DAYS,
122
+ default: PAT_DEFAULT_EXPIRES_IN_DAYS,
123
+ },
118
124
  currentPassword: { type: "text", required: true, format: "password", sensitive: true },
119
125
  mfaCode: { type: "text" },
120
126
  },
@@ -5,6 +5,7 @@ export declare const PatErrors: {
5
5
  readonly reauthRequired: "reauth_required";
6
6
  };
7
7
  export declare const PAT_DEFAULT_EXPIRES_IN_DAYS = 90;
8
+ export declare const PAT_MAX_EXPIRES_IN_DAYS = 3650;
8
9
  export declare const PAT_SCREEN_ID = "api-tokens";
9
10
  export declare const PAT_MINT_SCREEN_ID = "api-token-create";
10
11
  export declare const PatHandlers: {