@kennra/app-sdk 0.0.0 → 0.2.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.
@@ -0,0 +1,1094 @@
1
+ /**
2
+ * The app manifest, `kennra-app.yaml` v1 (docs/15 §2). One file declares what an app is and what
3
+ * it may do; the consent screen, the directory, review and the runtime checks in the Kennra core
4
+ * are generated from it. What isn't declared is denied.
5
+ *
6
+ * This module is the contract: the core validates manifests with it, and apps use it to check
7
+ * theirs (`kennra apps validate`). No dependency on the Kennra core.
8
+ */
9
+ import { parse as parseYaml } from 'yaml';
10
+ import { z } from 'zod';
11
+ export const MANIFEST_API_VERSION = 'kennra.app/v1';
12
+ export const PII_LEVELS = ['none', 'pseudonymous', 'contact_basic', 'full'];
13
+ /**
14
+ * Scopes an app may request. `kennra:privacy`, workspace scopes and publishing the schema are never
15
+ * granted to apps; proposing schema changes (`kennra:schema:draft`) is.
16
+ */
17
+ export const APP_SCOPES = [
18
+ 'kennra:read',
19
+ 'kennra:party:write',
20
+ 'kennra:commerce:write',
21
+ 'kennra:interaction:write',
22
+ 'kennra:trait:write',
23
+ 'kennra:deal:write',
24
+ 'kennra:work:write',
25
+ 'kennra:consent:write',
26
+ 'kennra:import:backdate',
27
+ 'kennra:export',
28
+ // Segment membership for the app's segment-sync targets (docs/16 §7), per purpose.
29
+ 'kennra:segment:read',
30
+ // Proposing traits and custom Kinds (decision 20 November 2026): a proposal changes nothing until
31
+ // a schema owner publishes it (or the system does, in a test, development or demo workspace).
32
+ 'kennra:schema:draft',
33
+ // Passing on a member's own approve or reject of a suggestion (decision 21 November 2026): only
34
+ // when the app acts for that member (delegation) and attests the member's interaction (a button
35
+ // press it verified). Agents can never decide; the member decides only what they could in Kennra.
36
+ 'kennra:suggestions:decide',
37
+ // Marketing apps (decision 21 November 2026): a grant of consent a person gave in the app is
38
+ // recorded only with this scope (per purpose); withdrawals need only kennra:consent:write.
39
+ 'kennra:consent:grant',
40
+ // Engagement signals (delivered, opened, clicked …) a sending tool reports per person, kept by
41
+ // the core as aggregates per person and channel, never one record per message.
42
+ 'kennra:engagement:write',
43
+ // Historical consent with evidence (decision 21 November 2026): moving a list from another
44
+ // sending tool brings opt-ins older than 30 days. Only with this scope (per purpose), only with
45
+ // evidence of the opt-in, never over a newer withdrawal, capped per installation and day.
46
+ 'kennra:consent:import',
47
+ ];
48
+ /** The scope that lets an app pass on a member's decision on a suggestion (21 November 2026). */
49
+ export const SUGGESTIONS_DECIDE_SCOPE = 'kennra:suggestions:decide';
50
+ /** Scopes that need their own line on the consent screen and Kennra approval for listed apps. */
51
+ export const SENSITIVE_SCOPES = [
52
+ 'kennra:import:backdate',
53
+ 'kennra:export',
54
+ SUGGESTIONS_DECIDE_SCOPE,
55
+ 'kennra:consent:grant',
56
+ 'kennra:consent:import',
57
+ ];
58
+ /** The scope that lets an app record consent a person gave in it (decision 21 November 2026). */
59
+ export const CONSENT_GRANT_SCOPE = 'kennra:consent:grant';
60
+ /**
61
+ * The scope that lets an app import consent a person gave before Kennra knew them, with evidence
62
+ * (decision 21 November 2026, docs/15 §4.10). Apps only: agents and roles never hold it.
63
+ */
64
+ export const CONSENT_IMPORT_SCOPE = 'kennra:consent:import';
65
+ /** The scope for engagement signals (decision 21 November 2026). */
66
+ export const ENGAGEMENT_WRITE_SCOPE = 'kennra:engagement:write';
67
+ /** Engagement signals an app can report (`recordEngagement`). */
68
+ export const ENGAGEMENT_SIGNALS = [
69
+ 'delivered',
70
+ 'opened',
71
+ 'clicked',
72
+ 'bounced',
73
+ 'complained',
74
+ 'unsubscribed',
75
+ ];
76
+ /** Channels a target can ask contact points for (the address the app sends to). */
77
+ export const TARGET_CONTACT_CHANNELS = ['email', 'sms'];
78
+ /**
79
+ * Objects the core's lookup broker knows how to validate and serve (docs/15 §4.2).
80
+ * `organization.search` is a search in a public company register: the ref is
81
+ * `<country>:<text>` (ISO 3166-1 alpha-2 and what a person typed), e.g. `NO:fjellsport`.
82
+ */
83
+ export const LOOKUP_OBJECTS = [
84
+ 'order.details',
85
+ 'subscription.details',
86
+ // An invoice from an accounting app: lines, payments, reminders and a short-lived link to the
87
+ // PDF the app serves from the source (decision 21 November 2026). Kennra stores none of it.
88
+ 'invoice.details',
89
+ 'interaction.details',
90
+ 'organization.search',
91
+ // A company's public profile from a business register or similar source, by domain or registry
92
+ // identifier (docs/15 §4.2). Asked for when a suggested contact's company is created.
93
+ 'organization.profile',
94
+ // A company's logo by domain or registry identifier (docs/15 §4.2): an https URL on the app's
95
+ // `ui.domains` that Kennra fetches once, scales and keeps (decision 21 November 2026).
96
+ 'organization.logo',
97
+ // A document in the app's file store (docs/15 §4.13): metadata, a link, a thumbnail and a
98
+ // download link, live; the file itself is never stored in Kennra.
99
+ 'document.details',
100
+ // A contact's profile picture by a SHA-256 hash of their email address, never the address
101
+ // (docs/15 §4.2). Asked only while the workspace turned on contactPhotoLookup.
102
+ 'person.photo',
103
+ // External objects (`capabilities.objects`, decision 27 November 2026): a search for the picker
104
+ // of an `external` trait field, and the objects by id (live data and snapshot refresh). The ref
105
+ // is `<type>:…`; the question is in the request's `query`.
106
+ 'object.search',
107
+ 'object.resolve',
108
+ ];
109
+ /** The envelope every external object has; typed fields can't reuse these keys. */
110
+ export const ENVELOPE_KEYS = ['id', 'title', 'subtitle', 'imageUrl', 'url'];
111
+ /** Kinds an app may declare it writes. */
112
+ export const WRITABLE_KINDS = [
113
+ 'Person',
114
+ 'Organization',
115
+ 'CommerceFact',
116
+ 'Interaction',
117
+ 'Deal',
118
+ 'Task',
119
+ 'Note',
120
+ ];
121
+ const Localized = z.object({ en: z.string().min(1) }).catchall(z.string());
122
+ /** The Kinds a deep link (`capabilities.ui.links`) can be declared on. */
123
+ export const LINK_KINDS = ['Person', 'Organization', 'CommerceFact', 'Deal', 'Interaction'];
124
+ /** A label: plain English, or per language with English as the fallback (`{ en, nb }`). */
125
+ const Label = z.union([z.string().min(1), Localized]);
126
+ const Url = z.string().min(1);
127
+ /** A label in a language: the language, else English, else the plain string. */
128
+ export function localize(label, lang) {
129
+ if (label === undefined)
130
+ return undefined;
131
+ if (typeof label === 'string')
132
+ return label;
133
+ return label[lang ?? 'en'] ?? label['en'] ?? Object.values(label)[0];
134
+ }
135
+ /**
136
+ * Where a setting is shown: `default` in the install form, `advanced` behind "Advanced" (collapsed),
137
+ * `demo` only in demo and test workspaces (recorded data, fixtures). The core rejects demo-only
138
+ * settings in production workspaces.
139
+ */
140
+ export const SETTING_VISIBILITY = ['default', 'advanced', 'demo'];
141
+ const ScopeGrant = z.object({
142
+ scope: z.string(),
143
+ purposes: z.array(z.string().min(1)).min(1),
144
+ /**
145
+ * Why the app needs the scope, shown on the consent screen. A string (English) or translations
146
+ * keyed by language (`{ en, nb }`); the consent screen falls back to English.
147
+ */
148
+ why: z.union([z.string().min(1), Localized]),
149
+ });
150
+ const IdentifierScheme = z.object({
151
+ scheme: z.string(),
152
+ appliesTo: z.array(z.enum(['person', 'organization'])).min(1),
153
+ label: Localized,
154
+ description: z.string().optional(),
155
+ strength: z.enum(['strong', 'weak']).default('strong'),
156
+ normalize: z.enum(['trim', 'trim_lower', 'digits']).default('trim'),
157
+ piiClass: z.enum(['contact', 'none']).default('none'),
158
+ /** Identifier types used before apps; the core upcasts stored data with this mapping. */
159
+ legacyTypes: z.array(z.string()).default([]),
160
+ });
161
+ const Lookup = z.object({
162
+ object: z.enum(LOOKUP_OBJECTS),
163
+ /** Glob over refs the app answers for, e.g. `shop:*:order:*`. */
164
+ refPattern: z.string().min(1),
165
+ url: Url,
166
+ timeoutMs: z.number().int().positive().max(1_000).default(300),
167
+ cacheTtlSeconds: z.number().int().min(0).max(3_600).default(60),
168
+ purposes: z.array(z.string()).min(1),
169
+ /** Answers with a member's own connection (calendar, mailbox): the core decides access first. */
170
+ delegated: z.boolean().default(false),
171
+ });
172
+ /** The types a typed field of an external object can have (docs/15 §4.14). */
173
+ export const OBJECT_FIELD_TYPES = [
174
+ 'text',
175
+ 'number',
176
+ 'boolean',
177
+ 'date',
178
+ 'money',
179
+ 'textList',
180
+ 'attributes',
181
+ ];
182
+ /**
183
+ * An object type the app provides (`capabilities.objects`, decision 27 November 2026): a value of
184
+ * an `external` trait field points at one object of this type in the app's system. `contract` is
185
+ * versioned (`<app id>.<type>@<n>`): a later version that changes the meaning of a field is a new
186
+ * contract. `fields` are the typed snapshot fields Kennra keeps next to the envelope (id, title,
187
+ * subtitle, image, link); `scope` the filters a field may set (pickers use them, writes are
188
+ * checked against them on the snapshot field they name).
189
+ */
190
+ const ObjectType = z.object({
191
+ type: z.string().regex(/^[a-z][a-z0-9_]{1,39}$/),
192
+ contract: z.string().regex(/^[a-z][a-z0-9-]*\.[a-z][a-z0-9_]*@[1-9]\d{0,3}$/),
193
+ label: Localized,
194
+ description: Localized.optional(),
195
+ fields: z
196
+ .array(z.object({
197
+ key: z.string().regex(/^[a-z][A-Za-z0-9]{0,39}$/),
198
+ type: z.enum(OBJECT_FIELD_TYPES),
199
+ label: Localized,
200
+ description: Localized.optional(),
201
+ }))
202
+ .max(30)
203
+ .default([]),
204
+ scope: z
205
+ .array(z.object({
206
+ key: z.string().regex(/^[a-z][A-Za-z0-9]{0,39}$/),
207
+ label: Localized,
208
+ description: Localized.optional(),
209
+ /** The snapshot field the filter is checked on (a text or textList field). */
210
+ field: z.string(),
211
+ /** `equals`: one of the values; `prefix`: starts with one of them (a folder path). */
212
+ match: z.enum(['equals', 'prefix']),
213
+ }))
214
+ .max(10)
215
+ .default([]),
216
+ });
217
+ const Schedule = z.object({
218
+ id: z.string().regex(/^[a-z][a-z0-9-]{0,39}$/),
219
+ /** Interval like `15m`, `1h`, `1d`. Minimum 5 minutes. */
220
+ every: z
221
+ .string()
222
+ .regex(/^\d+[mhd]$/)
223
+ .optional(),
224
+ /** Daily cron, `M H * * *` (minute and hour, UTC). */
225
+ cron: z
226
+ .string()
227
+ .regex(/^\d{1,2} \d{1,2} \* \* \*$/)
228
+ .optional(),
229
+ lane: z.enum(['live', 'import']).default('live'),
230
+ url: Url,
231
+ /**
232
+ * The longest one run may take, in seconds (60 to 3,600; default 600). Kennra gives each run a
233
+ * lease that heartbeats extend up to this; the SDK aborts the handler's signal when it is reached,
234
+ * and the run saves its cursor and reports `partial` (docs/15 §4.7).
235
+ */
236
+ maxRunSeconds: z.number().int().min(60).max(3600).optional(),
237
+ });
238
+ /** A run's maximum duration when its schedule declares none (docs/15 §4.7). */
239
+ export const DEFAULT_MAX_RUN_SECONDS = 600;
240
+ /** How long a run's lease lasts after its start or its last heartbeat. */
241
+ export const RUN_LEASE_SECONDS = 600;
242
+ /** What a run gets past its maximum duration to save its cursor and report, before it is abandoned. */
243
+ export const RUN_GRACE_SECONDS = 120;
244
+ const SegmentSyncTarget = z.object({
245
+ id: z.string().regex(/^[a-z][a-z0-9-]{1,39}$/),
246
+ label: Localized,
247
+ description: Localized.optional(),
248
+ /** The Kinds of segment the target takes. */
249
+ kinds: z.array(z.enum(['person', 'organization'])).min(1),
250
+ /** Settings the admin gives per target (e.g. the group to sync into). */
251
+ config: z
252
+ .record(z.string(), z.object({ type: z.literal('string'), title: Label, required: z.boolean().default(false) }))
253
+ .default({}),
254
+ /** Consent every synced member must have, on top of the segment's own legal basis. */
255
+ requiredConsent: z.array(z.object({ purpose: z.string(), channel: z.string().optional() })).default([]),
256
+ /**
257
+ * The address the app sends to (decision 21 November 2026): each member carries its usable
258
+ * contact point on these channels (`contact.email`, `contact.phone`), and a member without one is
259
+ * skipped (`no_contact_point`) instead of needing an identifier under the app's issuer. Needs
260
+ * the PII level `contact_basic` or `full`.
261
+ */
262
+ contactPoints: z.array(z.enum(TARGET_CONTACT_CHANNELS)).default([]),
263
+ });
264
+ /**
265
+ * Segment sync (docs/16 §7): the app receives membership deltas for segments an admin connects
266
+ * to one of its targets (signed POSTs to `url`, answered with a receipt).
267
+ */
268
+ const SegmentSync = z.object({
269
+ url: Url,
270
+ batchSize: z.number().int().positive().max(1000).default(500),
271
+ targets: z.array(SegmentSyncTarget).min(1),
272
+ });
273
+ /**
274
+ * A program target (decision 21 November 2026, docs/15 §4.12): an admin connects a Program, or one
275
+ * of its stages, to the target (e.g. "start flow X" in a sending tool); the core POSTs the
276
+ * enrollments that entered, moved or left as a signed, idempotent delta, answered with a receipt.
277
+ */
278
+ const ProgramTarget = z.object({
279
+ id: z.string().regex(/^[a-z][a-z0-9-]{1,39}$/),
280
+ label: Localized,
281
+ description: Localized.optional(),
282
+ /** Settings the admin gives per target (e.g. the flow to start). */
283
+ config: z
284
+ .record(z.string(), z.object({ type: z.literal('string'), title: Label, required: z.boolean().default(false) }))
285
+ .default({}),
286
+ /** Consent every enrolled person must have before the app gets them. */
287
+ requiredConsent: z.array(z.object({ purpose: z.string(), channel: z.string().optional() })).default([]),
288
+ /** As for segment sync: the address the app sends to. */
289
+ contactPoints: z.array(z.enum(TARGET_CONTACT_CHANNELS)).default([]),
290
+ });
291
+ const ProgramTargets = z.object({
292
+ url: Url,
293
+ batchSize: z.number().int().positive().max(1000).default(500),
294
+ targets: z.array(ProgramTarget).min(1),
295
+ });
296
+ const TraitDefinitionRef = z.record(z.string(), z.unknown());
297
+ /**
298
+ * An MCP client the app stands for (docs/15 §4.8). The client is recognised by its client id (a
299
+ * Client ID Metadata Document URL) or, for a client that registers itself (RFC 7591), by its
300
+ * redirect URIs: every one of them must be listed here.
301
+ */
302
+ const McpClient = z.object({
303
+ /** Client ID Metadata Document URLs (https), or ids a client is known by. */
304
+ clientIds: z.array(z.string().min(1)).default([]),
305
+ /**
306
+ * Redirect URIs the client uses. A loopback http URI matches any port (RFC 8252). An https URI
307
+ * ending in `/*` matches every path below it on that host (a client that puts its own id in the
308
+ * path); the client still registers its exact URIs.
309
+ */
310
+ redirectUris: z.array(z.string().min(1)).default([]),
311
+ /**
312
+ * `rotate` (the default): every refresh gives a new refresh token, and an old one seen again
313
+ * ends the connection. `reuse`: the connection keeps one refresh token until it ends, for a
314
+ * client that cannot store a rotated one.
315
+ */
316
+ refreshTokens: z.enum(['rotate', 'reuse']).default('rotate'),
317
+ /** The template the consent screen preselects (see agentTemplates in the API). */
318
+ defaultTemplate: z
319
+ .string()
320
+ .regex(/^[a-z][a-z0-9_]{1,39}$/)
321
+ .default('read_only'),
322
+ /**
323
+ * A link that adds the workspace's MCP URL to the client, with `{url}` (the MCP URL) and
324
+ * `{name}` (a connector name) filled in, URL-encoded. Without it the app shows the URL to paste.
325
+ */
326
+ connectUrl: z.string().optional(),
327
+ /** How to connect, in a sentence or two (plain text). */
328
+ instructions: Localized.optional(),
329
+ });
330
+ export const AppManifestSchema = z.object({
331
+ apiVersion: z.literal(MANIFEST_API_VERSION),
332
+ id: z.string().regex(/^[a-z][a-z0-9-]{2,62}$/, 'lowercase letters, digits and hyphens, 3–63 characters'),
333
+ version: z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, 'semver, e.g. 1.4.0'),
334
+ name: z.string().min(1).max(80),
335
+ icon: z.string().optional(),
336
+ publisher: z.object({
337
+ name: z.string().min(1),
338
+ kind: z.enum(['first_party', 'partner', 'private']),
339
+ website: z.string().optional(),
340
+ support: z.string().optional(),
341
+ security: z.string().optional(),
342
+ privacyPolicy: z.string().optional(),
343
+ /** The app's own terms, accepted by the admin at install (docs/15 §11.1, per-app terms). */
344
+ terms: z.string().optional(),
345
+ dpa: z.string().optional(),
346
+ }),
347
+ description: Localized,
348
+ access: z.object({
349
+ piiLevel: z.enum(PII_LEVELS),
350
+ /** At least one, except for an app that only describes an MCP client (capabilities.mcpClient). */
351
+ scopes: z.array(ScopeGrant).default([]),
352
+ writes: z
353
+ .object({
354
+ kinds: z.array(z.enum(WRITABLE_KINDS)).default([]),
355
+ traits: z.array(z.string()).default([]),
356
+ externalIdentifiers: z.array(z.string()).default([]),
357
+ })
358
+ .default({ kinds: [], traits: [], externalIdentifiers: [] }),
359
+ reads: z.object({ fields: z.array(z.string()).default([]) }).default({ fields: [] }),
360
+ /**
361
+ * The app acts as the signed-in member (token exchange, docs/16 §3.6): its calls are the
362
+ * intersection of the member's access and the app's grant, and the audit shows "app on behalf of".
363
+ */
364
+ actsForMembers: z.boolean().default(false),
365
+ /**
366
+ * The app may act for members by delegation (docs/15 §3.5): it identifies the person itself
367
+ * (e.g. a verified email from a provider it signs people in with) and asks `POST /apps/token`
368
+ * for a token with `requested_subject`. Off in every installation until a workspace admin turns
369
+ * it on and picks the members; every call is the grant ∩ the member's access. Private apps
370
+ * have delegation without declaring it.
371
+ */
372
+ delegation: z.boolean().default(false),
373
+ }),
374
+ identifiers: z
375
+ .object({
376
+ /** A domain the app declares and verifies, like OIDC `iss` (docs/15 §11.1). */
377
+ issuer: z.string(),
378
+ schemes: z.array(IdentifierScheme).min(1),
379
+ })
380
+ .optional(),
381
+ capabilities: z
382
+ .object({
383
+ ingest: z
384
+ .object({
385
+ factTypes: z
386
+ .array(z.enum(['ORDER', 'QUOTE', 'SUBSCRIPTION', 'INVOICE', 'INTERACTION']))
387
+ .default([]),
388
+ /** The provenance label in data, e.g. `shop`. */
389
+ sourceSystem: z.string().regex(/^[a-z][a-z0-9_-]{1,39}$/),
390
+ urn: z.string().optional(),
391
+ lanes: z.array(z.enum(['live', 'import'])).default(['live']),
392
+ /**
393
+ * History backfill for a new contact (docs/15 §9.3): when a person or company becomes
394
+ * known, Kennra asks the app to look back for their addresses or domains. Kennra ticks
395
+ * `schedule` when there is a request; the app pulls requests (GET
396
+ * /apps/capture-backfills), captures what it finds through the ordinary capture path and
397
+ * reports progress. `yearsSetting`: the integer setting that says how many years back
398
+ * (Kennra shows it to members, at most 10). Needs kennra:interaction:write.
399
+ */
400
+ backfill: z
401
+ .object({
402
+ schedule: z.string().min(1),
403
+ yearsSetting: z.string().min(1).optional(),
404
+ })
405
+ .optional(),
406
+ })
407
+ .optional(),
408
+ lookups: z.array(Lookup).default([]),
409
+ /**
410
+ * Object types the app provides for `external` trait fields (docs/15 §4.14). Needs the
411
+ * lookups `object.search` (the picker) and `object.resolve` (live data and refresh).
412
+ */
413
+ objects: z.array(ObjectType).max(20).default([]),
414
+ schedules: z.array(Schedule).default([]),
415
+ webhooks: z.object({ url: Url, events: z.array(z.string()).min(1) }).optional(),
416
+ segmentSync: SegmentSync.optional(),
417
+ programTargets: ProgramTargets.optional(),
418
+ lifecycle: z.object({ url: Url }).optional(),
419
+ /**
420
+ * Kennra calls this (signed POST, `ConnectionTestRequest`) when an admin presses "Test
421
+ * connection" on the settings form: the app tries the typed settings against its provider
422
+ * and answers with a `ConnectionTestResult`. Nothing is saved.
423
+ */
424
+ connectionTest: z.object({ url: Url }).optional(),
425
+ /**
426
+ * Erasure (docs/16 §6.2): `receipt` apps answer Kennra's signed erasure call at `url` with a
427
+ * receipt (or later on POST /apps/privacy/receipts); `none` apps get a pending receipt the
428
+ * DPO closes by hand.
429
+ */
430
+ privacy: z
431
+ .object({
432
+ erasure: z.enum(['none', 'receipt']).default('none'),
433
+ storesPersonalData: z.boolean(),
434
+ url: Url.optional(),
435
+ })
436
+ .optional(),
437
+ traits: z
438
+ .object({
439
+ namespace: z.string().regex(/^[a-z][a-z0-9_]{1,39}$/),
440
+ definitions: z.array(TraitDefinitionRef).default([]),
441
+ })
442
+ .optional(),
443
+ /** Per-member connections (calendar, mailbox): each member connects their own (docs/15 §9.3). */
444
+ userConnections: z
445
+ .array(z.object({
446
+ kind: z.enum(['calendar', 'mailbox', 'drive', 'transcripts']),
447
+ label: Localized,
448
+ /** Where a member starts the app's own OAuth flow. */
449
+ connectUrl: Url,
450
+ /**
451
+ * Kennra calls this (signed POST) when a member disconnects in Kennra: the app
452
+ * revokes the token at the provider and deletes it. The core stops capture at once.
453
+ */
454
+ disconnectUrl: Url.optional(),
455
+ /**
456
+ * A boolean setting (under `settings.schema.properties`) that must be on before
457
+ * members can connect this kind, e.g. an opt-in feature the admin turns on first.
458
+ * While it is off, Kennra doesn't offer the connection and refuses to start it.
459
+ */
460
+ requiresSetting: z.string().optional(),
461
+ /**
462
+ * The permission the member ticks on the provider's consent screen, in the
463
+ * provider's words. When the provider grants less than the connection needs, Kennra
464
+ * asks the member to connect again and tick it.
465
+ */
466
+ consentLabel: Localized.optional(),
467
+ }))
468
+ .default([]),
469
+ /**
470
+ * The app's own setup flow after install (e.g. "Connect with <provider>"): Kennra sends the
471
+ * admin to `url` with a signed ticket; the app finishes setup with the provider, reports it
472
+ * (`POST /apps/installation/setup`) and sends the admin back to Kennra.
473
+ */
474
+ setup: z
475
+ .object({
476
+ url: Url,
477
+ /** The button, e.g. `{ en: Connect with Example, nb: Koble til Example }`. */
478
+ label: Localized,
479
+ /** One or two sentences under the button: what happens at the provider. */
480
+ description: Localized.optional(),
481
+ /**
482
+ * A help panel next to the button (plain text: paragraphs separated by a blank line,
483
+ * lines starting with `- ` are list items), e.g. what the provider's warnings mean.
484
+ */
485
+ help: z.object({ title: Localized, body: Localized }).optional(),
486
+ /** Setup can also connect the admin's own account of this kind (opt-in on the install screen). */
487
+ connects: z.enum(['calendar', 'mailbox', 'drive', 'transcripts']).optional(),
488
+ })
489
+ .optional(),
490
+ /**
491
+ * Documents (docs/15 §4.13): the app is a file store or signing service whose files people
492
+ * link to records. `hosts`: the hosts of the app's file links (lowercase, no wildcards), so a
493
+ * link a person pastes is shown as the app's. `picker`: a page of the app's own where a member
494
+ * picks files (Kennra opens it with a signed ticket naming the record; the app links what was
495
+ * picked with `POST /apps/documents/link`). Linking needs kennra:work:write.
496
+ */
497
+ documents: z
498
+ .object({
499
+ label: Localized,
500
+ hosts: z
501
+ .array(z.string().regex(/^[a-z0-9.-]+$/))
502
+ .max(20)
503
+ .default([]),
504
+ picker: z
505
+ .object({
506
+ url: Url,
507
+ label: Localized.optional(),
508
+ /**
509
+ * A boolean setting that must be on before Kennra offers the picker (e.g. the admin
510
+ * turns it on once the provider's picker is configured). Pasted links work regardless.
511
+ */
512
+ requiresSetting: z.string().optional(),
513
+ })
514
+ .optional(),
515
+ })
516
+ .optional(),
517
+ /**
518
+ * The app is an MCP client (docs/15 §4.8): installing it lets that client connect to the
519
+ * workspace through Kennra's OAuth, each connection an agent acting for the person who
520
+ * approves it. Data only: Kennra runs nothing for it.
521
+ */
522
+ mcpClient: McpClient.optional(),
523
+ ui: z
524
+ .object({
525
+ /**
526
+ * Deep links ("Open in <app>", docs/24 §3 step 1): a URL template per Kind, expanded by
527
+ * Kennra for each record and shown in its own UI. The host is literal and https; the
528
+ * template's tokens (`LinkToken`) come from settings and non-personal identifiers,
529
+ * never from personal data. A link whose token has no value on a record is not shown.
530
+ */
531
+ links: z
532
+ .array(z.object({
533
+ on: z.enum(LINK_KINDS),
534
+ label: Localized,
535
+ url: z.string(),
536
+ /** CommerceFact only: the fact types the link applies to (all when left out). */
537
+ when: z
538
+ .object({
539
+ factType: z.preprocess((v) => (typeof v === 'string' ? [v] : v), z.array(z.enum(['ORDER', 'QUOTE', 'SUBSCRIPTION', 'INVOICE'])).min(1)),
540
+ })
541
+ .optional(),
542
+ }))
543
+ .default([]),
544
+ /**
545
+ * The hosts the app's own pages and media live on (lowercase host names, no wildcards),
546
+ * e.g. `[app.example.com, media.example.com]`. A link an app returns (a lookup's `url`)
547
+ * must be https on one of these or on a host of `links`; Kennra fetches images for the
548
+ * app only from these hosts (docs/24 §5, `Link`).
549
+ */
550
+ domains: z.array(z.string()).default([]),
551
+ })
552
+ .optional(),
553
+ })
554
+ .default({ lookups: [], objects: [], schedules: [], userConnections: [] }),
555
+ settings: z
556
+ .object({
557
+ schema: z.object({
558
+ type: z.literal('object'),
559
+ required: z.array(z.string()).default([]),
560
+ properties: z.record(z.string(), z.object({
561
+ type: z.enum(['string', 'boolean', 'number', 'integer']),
562
+ title: Label.optional(),
563
+ description: Label.optional(),
564
+ format: z.string().optional(),
565
+ default: z.unknown().optional(),
566
+ visibility: z.enum(SETTING_VISIBILITY).default('default'),
567
+ /** Position in the form (default: the order in the manifest). */
568
+ order: z.number().int().optional(),
569
+ })),
570
+ }),
571
+ })
572
+ .optional(),
573
+ dataResidency: z
574
+ .object({ processing: z.array(z.string()).min(1), subprocessors: z.array(z.string()).default([]) })
575
+ .optional(),
576
+ limits: z
577
+ .object({
578
+ requestsPerMinute: z.number().int().positive().optional(),
579
+ ingestPerMinute: z.number().int().positive().optional(),
580
+ lookupConcurrency: z.number().int().positive().max(32).optional(),
581
+ })
582
+ .optional(),
583
+ health: z.object({ url: Url }).optional(),
584
+ });
585
+ const ISSUER_RE = /^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
586
+ const SCHEME_RE = /^[a-z][a-z0-9-]{0,62}$/;
587
+ const FORBIDDEN_SCOPES = ['kennra:privacy', 'kennra:subject', 'kennra:workspace:write', 'kennra:apps:manage'];
588
+ const WRITE_SCOPE_FOR_KIND = {
589
+ Person: 'kennra:party:write',
590
+ Organization: 'kennra:party:write',
591
+ CommerceFact: 'kennra:commerce:write',
592
+ Interaction: 'kennra:interaction:write',
593
+ Deal: 'kennra:deal:write',
594
+ Task: 'kennra:work:write',
595
+ Note: 'kennra:work:write',
596
+ };
597
+ /**
598
+ * Whether a URI may receive an authorization code: https without a fragment, or http on a loopback
599
+ * host (a native client, RFC 8252).
600
+ */
601
+ export function isRedirectUri(raw) {
602
+ try {
603
+ const u = new URL(raw);
604
+ if (u.hash || u.username || u.password)
605
+ return false;
606
+ if (u.protocol === 'https:')
607
+ return true;
608
+ return u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
609
+ }
610
+ catch {
611
+ return false;
612
+ }
613
+ }
614
+ /**
615
+ * Whether an app's redirect URI entry is a path prefix: https, ending in `/*`, with at least one
616
+ * path segment before it, no other `*`, no query and no fragment.
617
+ */
618
+ export function isRedirectUriPattern(raw) {
619
+ if (!raw.endsWith('/*') || raw.slice(0, -1).includes('*'))
620
+ return false;
621
+ const base = raw.slice(0, -1);
622
+ if (!isRedirectUri(base))
623
+ return false;
624
+ const u = new URL(base);
625
+ return u.protocol === 'https:' && !u.search && u.pathname.length > 1 && base === u.toString();
626
+ }
627
+ /** Interval in milliseconds for `every` (`15m`, `2h`, `1d`). */
628
+ export function intervalMs(every) {
629
+ const n = Number(every.slice(0, -1));
630
+ const unit = every.at(-1);
631
+ return n * (unit === 'm' ? 60_000 : unit === 'h' ? 3_600_000 : 86_400_000);
632
+ }
633
+ /**
634
+ * Purposes, scopes and manifest keys renamed on 20 November 2026 (naming rounds 4 and 5). A
635
+ * manifest with an old name is refused, and the problem names the current one. Nothing is read
636
+ * under an old name (no compatibility period before the API freeze).
637
+ */
638
+ export const RENAMED = {
639
+ company_management: 'organization.management',
640
+ clienteling: 'sales.clienteling',
641
+ personalization: 'service.personalization',
642
+ events: 'marketing.events',
643
+ 'kennra:attribute:write': 'kennra:trait:write',
644
+ 'kennra:proposal:decide': 'kennra:proposal:approve',
645
+ actsForUsers: 'actsForMembers',
646
+ };
647
+ /** ` It is called <new> now.` for a renamed name, else empty. */
648
+ export const renamedHint = (name) => RENAMED[name] ? ` It is called ${RENAMED[name]} now.` : '';
649
+ /** Problems for old names in a manifest, which the shape alone would not catch. */
650
+ function renamedProblems(raw) {
651
+ const problems = [];
652
+ const obj = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : null;
653
+ const m = obj(raw);
654
+ const access = obj(m?.['access']);
655
+ if (access && 'actsForUsers' in access)
656
+ problems.push({
657
+ path: 'access.actsForUsers',
658
+ code: 'UNKNOWN_KEY',
659
+ message: `Unknown key access.actsForUsers.${renamedHint('actsForUsers')}`,
660
+ });
661
+ const purposes = (list, path) => {
662
+ if (!Array.isArray(list))
663
+ return;
664
+ list.forEach((x, i) => {
665
+ const ps = obj(x)?.['purposes'];
666
+ if (Array.isArray(ps))
667
+ for (const p of ps)
668
+ if (typeof p === 'string' && RENAMED[p])
669
+ problems.push({
670
+ path: `${path}.${i}.purposes`,
671
+ code: 'UNKNOWN_PURPOSE',
672
+ message: `Unknown purpose ${p}.${renamedHint(p)}`,
673
+ });
674
+ });
675
+ };
676
+ purposes(access?.['scopes'], 'access.scopes');
677
+ purposes(obj(m?.['capabilities'])?.['lookups'], 'capabilities.lookups');
678
+ return problems;
679
+ }
680
+ /**
681
+ * Validates a manifest (an object, or YAML/JSON text). Returns the parsed manifest with defaults,
682
+ * or the problems. Rules beyond the shape (docs/15 §2.3): scopes from the app list with purposes;
683
+ * declared writes covered by write scopes; issuer and schemes well formed; at most 10 schedules,
684
+ * at least 5 minutes apart; health for apps with ingest, lookups or schedules; lifecycle, privacy
685
+ * and data residency for listed (first-party and partner) apps; no `kennra` or `custom` namespace.
686
+ */
687
+ export function validateManifest(input) {
688
+ let raw = input;
689
+ if (typeof input === 'string') {
690
+ try {
691
+ raw = parseYaml(input);
692
+ }
693
+ catch (e) {
694
+ return { ok: false, problems: [{ path: '', code: 'INVALID_YAML', message: e.message }] };
695
+ }
696
+ }
697
+ const renamed = renamedProblems(raw);
698
+ if (renamed.length)
699
+ return { ok: false, problems: renamed };
700
+ const parsed = AppManifestSchema.safeParse(raw);
701
+ if (!parsed.success)
702
+ return {
703
+ ok: false,
704
+ problems: parsed.error.issues.map((i) => ({
705
+ path: i.path.join('.'),
706
+ code: 'INVALID_SHAPE',
707
+ message: i.message,
708
+ })),
709
+ };
710
+ const m = parsed.data;
711
+ // Keep the form in manifest order also after storage (JSON objects in the database may reorder keys).
712
+ Object.values(m.settings?.schema.properties ?? {}).forEach((p, i) => {
713
+ p.order ??= i;
714
+ });
715
+ const problems = [];
716
+ const warnings = [];
717
+ const p = (path, code, message) => problems.push({ path, code, message });
718
+ const granted = new Set(m.access.scopes.map((s) => s.scope));
719
+ if (!m.access.scopes.length && !m.capabilities.mcpClient)
720
+ p('access.scopes', 'NO_SCOPES', 'An app asks for at least one scope');
721
+ m.access.scopes.forEach((s, i) => {
722
+ if (FORBIDDEN_SCOPES.includes(s.scope))
723
+ p(`access.scopes.${i}.scope`, 'SCOPE_NOT_FOR_APPS', `${s.scope} can never be requested by an app`);
724
+ // Proposing (kennra:schema:draft, in APP_SCOPES since 20 November 2026) is for apps; publishing,
725
+ // writing and every other schema scope are not.
726
+ else if (s.scope.startsWith('kennra:schema') && !APP_SCOPES.includes(s.scope))
727
+ p(`access.scopes.${i}.scope`, 'SCOPE_NOT_FOR_APPS', 'Trait definitions ship in capabilities.traits; an app may propose schema changes (kennra:schema:draft) but never publish them');
728
+ else if (!APP_SCOPES.includes(s.scope))
729
+ p(`access.scopes.${i}.scope`, 'UNKNOWN_SCOPE', `Unknown scope ${s.scope}.${renamedHint(s.scope)}`);
730
+ });
731
+ // Deciding is always for a member: an app that never acts for one could never use the scope.
732
+ if (granted.has(SUGGESTIONS_DECIDE_SCOPE) &&
733
+ !m.access.delegation &&
734
+ !m.access.actsForMembers &&
735
+ m.publisher.kind !== 'private')
736
+ p('access.scopes', 'DECIDE_WITHOUT_MEMBER', `${SUGGESTIONS_DECIDE_SCOPE} passes on a member's own decision, so the app must act for members: declare access.delegation or access.actsForMembers`);
737
+ for (const k of m.access.writes.kinds)
738
+ if (!granted.has(WRITE_SCOPE_FOR_KIND[k]))
739
+ p('access.writes.kinds', 'WRITE_WITHOUT_SCOPE', `Writing ${k} needs ${WRITE_SCOPE_FOR_KIND[k]}`);
740
+ if (m.access.writes.traits.length && !granted.has('kennra:trait:write') && !m.capabilities.traits)
741
+ p('access.writes.traits', 'WRITE_WITHOUT_SCOPE', 'Writing traits needs kennra:trait:write');
742
+ if (m.identifiers) {
743
+ if (!ISSUER_RE.test(m.identifiers.issuer))
744
+ p('identifiers.issuer', 'INVALID_ISSUER', 'The issuer is a lowercase domain, e.g. shop.example');
745
+ const seen = new Set();
746
+ m.identifiers.schemes.forEach((s, i) => {
747
+ if (!SCHEME_RE.test(s.scheme))
748
+ p(`identifiers.schemes.${i}.scheme`, 'INVALID_SCHEME', 'A scheme is a lowercase slug');
749
+ if (seen.has(s.scheme))
750
+ p(`identifiers.schemes.${i}.scheme`, 'DUPLICATE_SCHEME', `${s.scheme} is declared twice`);
751
+ seen.add(s.scheme);
752
+ if (!s.label['nb'])
753
+ warnings.push({
754
+ path: `identifiers.schemes.${i}.label`,
755
+ code: 'MISSING_LABEL',
756
+ message: 'Add a Norwegian (nb) label',
757
+ });
758
+ });
759
+ for (const x of m.access.writes.externalIdentifiers)
760
+ if (!seen.has(x))
761
+ p('access.writes.externalIdentifiers', 'UNKNOWN_SCHEME', `${x} is not declared under identifiers.schemes`);
762
+ }
763
+ m.access.scopes.forEach((s, i) => {
764
+ if (typeof s.why === 'string' || !s.why['nb'])
765
+ warnings.push({
766
+ path: `access.scopes.${i}.why`,
767
+ code: 'MISSING_TRANSLATION',
768
+ message: 'Add a Norwegian (nb) why text: the consent screen is shown in nb and en (English is the fallback)',
769
+ });
770
+ });
771
+ const c = m.capabilities;
772
+ if (c.privacy?.erasure === 'receipt' && !c.privacy.url)
773
+ p('capabilities.privacy.url', 'ERASURE_URL_REQUIRED', 'Apps that send erasure receipts declare privacy.url');
774
+ if (c.schedules.length > 10)
775
+ p('capabilities.schedules', 'TOO_MANY_SCHEDULES', 'At most 10 schedules per app');
776
+ c.schedules.forEach((s, i) => {
777
+ if (!s.every && !s.cron)
778
+ p(`capabilities.schedules.${i}`, 'SCHEDULE_WITHOUT_TIME', 'Give every or cron');
779
+ if (s.every && intervalMs(s.every) < 5 * 60_000)
780
+ p(`capabilities.schedules.${i}.every`, 'SCHEDULE_TOO_FREQUENT', 'The minimum interval is 5 minutes');
781
+ });
782
+ const objectTypes = new Set();
783
+ c.objects.forEach((o, i) => {
784
+ const path = `capabilities.objects.${i}`;
785
+ if (objectTypes.has(o.type))
786
+ p(`${path}.type`, 'DUPLICATE_OBJECT_TYPE', `${o.type} is declared twice`);
787
+ objectTypes.add(o.type);
788
+ if (!o.contract.startsWith(`${m.id}.`))
789
+ p(`${path}.contract`, 'CONTRACT_NOT_OWNED', `A contract is named after the app: ${m.id}.${o.type}@1`);
790
+ const keys = new Set();
791
+ o.fields.forEach((f, j) => {
792
+ if (keys.has(f.key) || ENVELOPE_KEYS.includes(f.key))
793
+ p(`${path}.fields.${j}.key`, 'DUPLICATE_FIELD', `${f.key} is declared twice or is an envelope key`);
794
+ keys.add(f.key);
795
+ });
796
+ const filters = new Set();
797
+ o.scope.forEach((f, j) => {
798
+ if (filters.has(f.key))
799
+ p(`${path}.scope.${j}.key`, 'DUPLICATE_FILTER', `${f.key} is declared twice`);
800
+ filters.add(f.key);
801
+ const field = o.fields.find((x) => x.key === f.field);
802
+ if (!field || (field.type !== 'text' && field.type !== 'textList'))
803
+ p(`${path}.scope.${j}.field`, 'UNKNOWN_FIELD', `A filter is checked on a text or textList field of the object: ${f.field} is not one`);
804
+ });
805
+ });
806
+ if (c.objects.length)
807
+ for (const object of ['object.search', 'object.resolve'])
808
+ if (!c.lookups.some((l) => l.object === object))
809
+ p('capabilities.objects', 'OBJECTS_WITHOUT_LOOKUPS', `Object types need the lookup ${object}`);
810
+ if (c.documents?.picker && !granted.has('kennra:work:write'))
811
+ p('capabilities.documents', 'DOCUMENTS_WITHOUT_SCOPE', 'Linking documents needs kennra:work:write');
812
+ if (c.segmentSync && !granted.has('kennra:segment:read'))
813
+ p('capabilities.segmentSync', 'SEGMENT_SYNC_WITHOUT_SCOPE', 'Segment sync needs kennra:segment:read');
814
+ const targetIds = new Set();
815
+ c.segmentSync?.targets.forEach((t, i) => {
816
+ if (targetIds.has(t.id))
817
+ p(`capabilities.segmentSync.targets.${i}.id`, 'DUPLICATE_TARGET', `${t.id} is declared twice`);
818
+ targetIds.add(t.id);
819
+ });
820
+ // Program targets receive enrollments of programs whose purpose the grant covers.
821
+ if (c.programTargets && !granted.has('kennra:segment:read'))
822
+ p('capabilities.programTargets', 'PROGRAM_TARGETS_WITHOUT_SCOPE', "Program targets need kennra:segment:read for the programs' purposes");
823
+ const programTargetIds = new Set();
824
+ c.programTargets?.targets.forEach((t, i) => {
825
+ if (programTargetIds.has(t.id))
826
+ p(`capabilities.programTargets.targets.${i}.id`, 'DUPLICATE_TARGET', `${t.id} is declared twice`);
827
+ programTargetIds.add(t.id);
828
+ });
829
+ const contactTargets = [...(c.segmentSync?.targets ?? []), ...(c.programTargets?.targets ?? [])].some((t) => t.contactPoints.length);
830
+ if (contactTargets && (m.access.piiLevel === 'none' || m.access.piiLevel === 'pseudonymous'))
831
+ p('access.piiLevel', 'CONTACT_POINTS_NEED_PII', 'A target with contactPoints sends addresses, so the app needs piiLevel contact_basic or full');
832
+ if (granted.has(CONSENT_GRANT_SCOPE) && !granted.has('kennra:consent:write'))
833
+ p('access.scopes', 'CONSENT_GRANT_WITHOUT_WRITE', `${CONSENT_GRANT_SCOPE} adds grants to consent changes, so the app also asks for kennra:consent:write`);
834
+ if (granted.has(CONSENT_IMPORT_SCOPE) && !granted.has(CONSENT_GRANT_SCOPE))
835
+ p('access.scopes', 'CONSENT_IMPORT_WITHOUT_GRANT', `${CONSENT_IMPORT_SCOPE} imports earlier grants, so the app also asks for ${CONSENT_GRANT_SCOPE} and kennra:consent:write`);
836
+ const bf = c.ingest?.backfill;
837
+ if (bf) {
838
+ if (!granted.has('kennra:interaction:write'))
839
+ p('capabilities.ingest.backfill', 'BACKFILL_WITHOUT_SCOPE', 'History backfill needs kennra:interaction:write');
840
+ if (!c.schedules.some((s) => s.id === bf.schedule))
841
+ p('capabilities.ingest.backfill.schedule', 'UNKNOWN_SCHEDULE', `No schedule ${bf.schedule} in capabilities.schedules`);
842
+ const prop = bf.yearsSetting
843
+ ? m.settings?.schema?.properties?.[bf.yearsSetting]
844
+ : undefined;
845
+ if (bf.yearsSetting && prop?.type !== 'integer')
846
+ p('capabilities.ingest.backfill.yearsSetting', 'UNKNOWN_SETTING', `${bf.yearsSetting} is not an integer setting in settings.schema`);
847
+ }
848
+ if (c.webhooks && !granted.has('kennra:read'))
849
+ p('capabilities.webhooks', 'WEBHOOKS_WITHOUT_READ', 'Event subscriptions need kennra:read');
850
+ if (c.traits && ['kennra', 'custom'].includes(c.traits.namespace))
851
+ p('capabilities.traits.namespace', 'RESERVED_NAMESPACE', 'kennra and custom are reserved');
852
+ c.traits?.definitions.forEach((d, i) => {
853
+ const name = String(d['name'] ?? '');
854
+ if (!name.startsWith(`${c.traits.namespace}.`))
855
+ p(`capabilities.traits.definitions.${i}.name`, 'OUTSIDE_NAMESPACE', `Trait ${name} is outside ${c.traits.namespace}.*`);
856
+ });
857
+ if ((c.ingest || c.lookups.length || c.schedules.length) && !m.health)
858
+ p('health', 'HEALTH_REQUIRED', 'Apps with ingest, lookups or schedules declare health.url');
859
+ if (c.mcpClient) {
860
+ const mc = c.mcpClient;
861
+ if (!mc.clientIds.length && !mc.redirectUris.length)
862
+ p('capabilities.mcpClient', 'MCP_CLIENT_UNIDENTIFIED', 'Give clientIds, redirectUris or both');
863
+ mc.clientIds.forEach((id, i) => {
864
+ // https with a path; http on a loopback host for local development (never fetched in production).
865
+ if (/^[a-z]+:/i.test(id) && !/^(https:\/\/[^/]+|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)\/.+/.test(id))
866
+ p(`capabilities.mcpClient.clientIds.${i}`, 'INVALID_CLIENT_ID', 'A client id URL is https with a path (a Client ID Metadata Document)');
867
+ });
868
+ mc.redirectUris.forEach((u, i) => {
869
+ const wildcard = u.includes('*');
870
+ if (wildcard ? !isRedirectUriPattern(u) : !isRedirectUri(u))
871
+ p(`capabilities.mcpClient.redirectUris.${i}`, 'INVALID_REDIRECT_URI', wildcard
872
+ ? 'A redirect URI with * is https and ends in /* after at least one path segment'
873
+ : 'A redirect URI is https, or http on localhost or 127.0.0.1');
874
+ });
875
+ if (mc.connectUrl && !/^https:\/\//.test(mc.connectUrl))
876
+ p('capabilities.mcpClient.connectUrl', 'INVALID_CONNECT_URL', 'The connect link is https');
877
+ }
878
+ if (m.publisher.kind !== 'private') {
879
+ // A data-only MCP client app has nothing to tell about its lifecycle.
880
+ if (!c.lifecycle && !(c.mcpClient && !m.access.scopes.length))
881
+ p('capabilities.lifecycle', 'REQUIRED_FOR_LISTED', 'Listed apps handle lifecycle calls');
882
+ if (!c.privacy)
883
+ p('capabilities.privacy', 'REQUIRED_FOR_LISTED', 'Listed apps declare their erasure behaviour');
884
+ if (!m.dataResidency)
885
+ p('dataResidency', 'REQUIRED_FOR_LISTED', 'Listed apps declare where they process data');
886
+ if (!m.publisher.privacyPolicy)
887
+ warnings.push({
888
+ path: 'publisher.privacyPolicy',
889
+ code: 'MISSING_PRIVACY_POLICY',
890
+ message: 'Listed apps link a privacy policy',
891
+ });
892
+ }
893
+ for (const [key, spec] of Object.entries(m.settings?.schema.properties ?? {}))
894
+ for (const field of ['title', 'description'])
895
+ if (spec[field] !== undefined && (typeof spec[field] === 'string' || !spec[field]['nb']))
896
+ warnings.push({
897
+ path: `settings.schema.properties.${key}.${field}`,
898
+ code: 'MISSING_LABEL',
899
+ message: 'Add a Norwegian (nb) label: { en: …, nb: … }',
900
+ });
901
+ for (const key of m.settings?.schema.required ?? [])
902
+ if (m.settings?.schema.properties[key]?.visibility === 'demo')
903
+ p('settings.schema.required', 'DEMO_SETTING_REQUIRED', `${key} is demo-only and can't be required`);
904
+ if (c.setup?.connects && !c.userConnections.some((u) => u.kind === c.setup.connects))
905
+ p('capabilities.setup.connects', 'UNKNOWN_CONNECTION', `Setup connects ${c.setup.connects}, which is not under capabilities.userConnections`);
906
+ c.userConnections.forEach((u, i) => {
907
+ if (u.requiresSetting && m.settings?.schema.properties[u.requiresSetting]?.type !== 'boolean')
908
+ p(`capabilities.userConnections.${i}.requiresSetting`, 'UNKNOWN_SETTING', `${u.requiresSetting} is not a boolean setting under settings.schema.properties`);
909
+ });
910
+ c.ui?.domains.forEach((d, i) => {
911
+ if (!HOST_RE.test(d))
912
+ p(`capabilities.ui.domains.${i}`, 'INVALID_DOMAIN', 'A domain is a lowercase host name, e.g. app.example.com');
913
+ });
914
+ c.ui?.links.forEach((l, i) => {
915
+ if (!/^https:\/\//.test(l.url))
916
+ p(`capabilities.ui.links.${i}.url`, 'INVALID_LINK', 'A link is https');
917
+ else if (!templateHost(l.url))
918
+ p(`capabilities.ui.links.${i}.url`, 'INVALID_LINK', 'A link has a literal host, without tokens');
919
+ for (const problem of linkTokenProblems(m, l))
920
+ p(`capabilities.ui.links.${i}.url`, 'INVALID_LINK', problem);
921
+ if (l.when && l.on !== 'CommerceFact')
922
+ p(`capabilities.ui.links.${i}.when`, 'INVALID_LINK', 'when applies to CommerceFact links only');
923
+ });
924
+ if (!m.description['nb'])
925
+ warnings.push({
926
+ path: 'description',
927
+ code: 'MISSING_LABEL',
928
+ message: 'Add a Norwegian (nb) description',
929
+ });
930
+ return problems.length ? { ok: false, problems } : { ok: true, manifest: m, warnings };
931
+ }
932
+ /** Like validateManifest, but throws with every problem listed. */
933
+ export function defineManifest(input) {
934
+ const r = validateManifest(input);
935
+ if (!r.ok)
936
+ throw new Error(`Invalid kennra-app manifest:\n${r.problems.map((x) => `- ${x.path || '(root)'}: ${x.message} [${x.code}]`).join('\n')}`);
937
+ return r.manifest;
938
+ }
939
+ const HOST_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
940
+ /** The literal host of a URL template (`https://app.example.com/@{settings.x}/…`), if it has one. */
941
+ function templateHost(url) {
942
+ const m = /^https:\/\/([^/{}?#]+)(?:[/?#]|$)/i.exec(url);
943
+ return m ? m[1].toLowerCase() : null;
944
+ }
945
+ /**
946
+ * The app's declared hosts (docs/24 §5, `Link`): `capabilities.ui.domains` and the hosts of its
947
+ * `capabilities.ui.links` templates. Empty when the manifest declares none.
948
+ */
949
+ /** Whether a boolean setting is on: the saved value, else the schema's default. */
950
+ export function settingOn(m, settings, key) {
951
+ const v = settings?.[key] ?? m.settings?.schema.properties[key]?.default;
952
+ return v === true;
953
+ }
954
+ /**
955
+ * The `userConnections` kinds members can connect now: a kind with `requiresSetting` only while
956
+ * that setting is on.
957
+ */
958
+ export function availableConnectionKinds(m, settings) {
959
+ return m.capabilities.userConnections
960
+ .filter((c) => !c.requiresSetting || settingOn(m, settings, c.requiresSetting))
961
+ .map((c) => c.kind);
962
+ }
963
+ export function declaredHosts(m) {
964
+ const ui = m.capabilities.ui;
965
+ return new Set([
966
+ ...(ui?.domains ?? []).map((d) => d.toLowerCase()),
967
+ ...(ui?.links ?? []).map((l) => templateHost(l.url)).filter((h) => !!h),
968
+ ...(m.capabilities.documents?.hosts ?? []).map((h) => h.toLowerCase()),
969
+ ]);
970
+ }
971
+ /**
972
+ * A link an app returns, as Kennra may show it: https, without credentials, and on the app's
973
+ * declared hosts when the manifest declares any. Anything else is `null` (the link is dropped).
974
+ */
975
+ export function appLink(raw, m) {
976
+ if (typeof raw !== 'string' || raw.length > 2048)
977
+ return null;
978
+ let u;
979
+ try {
980
+ u = new URL(raw);
981
+ }
982
+ catch {
983
+ return null;
984
+ }
985
+ if (u.protocol !== 'https:' || u.username || u.password)
986
+ return null;
987
+ const hosts = declaredHosts(m);
988
+ if (hosts.size && !hosts.has(u.hostname.toLowerCase()))
989
+ return null;
990
+ return u.href;
991
+ }
992
+ const TOKEN_RE = /\{([^{}]*)\}/g;
993
+ /** One token of a link template (the text between braces), or null when Kennra doesn't know it. */
994
+ export function parseLinkToken(raw) {
995
+ if (raw === 'id')
996
+ return { type: 'id' };
997
+ if (raw === 'sourceId')
998
+ return { type: 'sourceId' };
999
+ if (raw === 'instance')
1000
+ return { type: 'instance' };
1001
+ let m = /^settings\.([A-Za-z0-9_-]+)$/.exec(raw);
1002
+ if (m)
1003
+ return { type: 'setting', key: m[1] };
1004
+ m = /^identifier:([a-z0-9.-]+)\/([a-z0-9][a-z0-9_-]*)$/.exec(raw);
1005
+ if (m)
1006
+ return { type: 'identifier', issuer: m[1], scheme: m[2] };
1007
+ m = /^orgNumber:([A-Z]{2})$/.exec(raw);
1008
+ if (m)
1009
+ return { type: 'orgNumber', country: m[1] };
1010
+ return null;
1011
+ }
1012
+ /** Every token of a template, in order; `token` is null for one Kennra doesn't know. */
1013
+ export function linkTokens(url) {
1014
+ return [...url.matchAll(TOKEN_RE)].map((x) => ({ raw: x[1], token: parseLinkToken(x[1]) }));
1015
+ }
1016
+ const TOKEN_KINDS = {
1017
+ id: LINK_KINDS,
1018
+ setting: LINK_KINDS,
1019
+ identifier: ['Person', 'Organization'],
1020
+ orgNumber: ['Organization'],
1021
+ sourceId: ['CommerceFact', 'Interaction'],
1022
+ instance: ['CommerceFact'],
1023
+ };
1024
+ /** What is wrong with one link's tokens in this manifest (empty when nothing is). */
1025
+ function linkTokenProblems(m, l) {
1026
+ const out = [];
1027
+ if (/[{}]/.test(l.url.replace(TOKEN_RE, '')))
1028
+ out.push('A brace that does not close a token');
1029
+ for (const { raw, token } of linkTokens(l.url)) {
1030
+ if (!token) {
1031
+ out.push(`Unknown token {${raw}}`);
1032
+ continue;
1033
+ }
1034
+ if (!TOKEN_KINDS[token.type].includes(l.on)) {
1035
+ out.push(`{${raw}} is not available on ${l.on}`);
1036
+ continue;
1037
+ }
1038
+ if (token.type === 'setting') {
1039
+ const spec = m.settings?.schema.properties[token.key];
1040
+ if (!spec)
1041
+ out.push(`{${raw}}: ${token.key} is not under settings.schema.properties`);
1042
+ else if (spec.format === 'secret')
1043
+ out.push(`{${raw}}: a secret setting never goes into a link`);
1044
+ }
1045
+ if (token.type === 'identifier') {
1046
+ const scheme = m.identifiers?.issuer === token.issuer
1047
+ ? m.identifiers.schemes.find((s) => s.scheme === token.scheme)
1048
+ : undefined;
1049
+ if (!scheme)
1050
+ out.push(`{${raw}}: only the app's own identifier schemes (identifiers.schemes)`);
1051
+ else if (scheme.piiClass !== 'none')
1052
+ out.push(`{${raw}}: the scheme is personal data (piiClass ${scheme.piiClass}), never in a link`);
1053
+ else if (!scheme.appliesTo.includes(l.on === 'Person' ? 'person' : 'organization'))
1054
+ out.push(`{${raw}}: the scheme does not apply to ${l.on}`);
1055
+ }
1056
+ }
1057
+ return out;
1058
+ }
1059
+ /**
1060
+ * Expands a link template with the values `tokenValue` gives (percent-encoded), and returns the
1061
+ * URL as Kennra may show it (`appLink`: https, on the app's declared hosts, on the template's own
1062
+ * literal host). `null` when a token is unknown or has no value, or the result may not be shown.
1063
+ */
1064
+ export function expandLink(template, tokenValue, m) {
1065
+ const host = templateHost(template);
1066
+ if (!host)
1067
+ return null;
1068
+ let missing = false;
1069
+ const url = template.replace(TOKEN_RE, (_x, raw) => {
1070
+ const token = parseLinkToken(raw);
1071
+ const v = token ? tokenValue(token) : null;
1072
+ if (v === null || v === undefined || v === '') {
1073
+ missing = true;
1074
+ return '';
1075
+ }
1076
+ return encodeURIComponent(v);
1077
+ });
1078
+ if (missing)
1079
+ return null;
1080
+ const out = appLink(url, m);
1081
+ return out && new URL(out).hostname === host ? out : null;
1082
+ }
1083
+ /** The `(scope, purpose)` pairs a manifest asks for. */
1084
+ export function requestedGrant(m) {
1085
+ return m.access.scopes.map((s) => ({ scope: s.scope, purposes: [...s.purposes] }));
1086
+ }
1087
+ /** Whether a ref matches a glob pattern (`*` matches anything except nothing). */
1088
+ export function refMatches(pattern, ref) {
1089
+ const re = new RegExp(`^${pattern
1090
+ .split('*')
1091
+ .map((x) => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
1092
+ .join('.+')}$`);
1093
+ return re.test(ref);
1094
+ }