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