@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.
package/dist/app.js ADDED
@@ -0,0 +1,448 @@
1
+ import { KennraAppClient } from "./client.js";
2
+ import { DEFAULT_MAX_RUN_SECONDS, defineManifest, } from "./manifest.js";
3
+ import { SignatureError, verify } from "./signature.js";
4
+ /** The status a run reports when its signal fired and it returned (docs/15 §4.7). */
5
+ const STOPPED_STATUS = {
6
+ max_duration: 'partial',
7
+ shutdown: 'interrupted',
8
+ abandoned: 'partial',
9
+ };
10
+ /**
11
+ * The status for work whose signal fired (`partial` at its deadline, `interrupted` on shutdown),
12
+ * or null while it may go on. For an app's own runs outside a tick (reportRun with its own id).
13
+ */
14
+ export function stoppedStatus(signal) {
15
+ if (!signal.aborted)
16
+ return null;
17
+ return STOPPED_STATUS[signal.reason] ?? 'interrupted';
18
+ }
19
+ /** Explicit heartbeats closer than this only keep their progress for the next one. */
20
+ const MIN_HEARTBEAT_MS = 5_000;
21
+ const pathOf = (url) => /^https?:\/\//.test(url) ? new URL(url).pathname : url.startsWith('/') ? url : `/${url}`;
22
+ /**
23
+ * A Kennra app as one web-standard `fetch` handler (Node, Bun, Deno, edge). Routes come from the
24
+ * manifest (lookup, schedule, webhook, lifecycle and health URLs); every request from Kennra is
25
+ * verified (Standard Webhooks) with the installation's signing secret before a handler runs.
26
+ *
27
+ * ```ts
28
+ * export default createApp({ manifest, kennra: { baseUrl, clientId, clientSecret } })
29
+ * .lookup('order.details', async ({ ref, ctx }) => ({ data: await load(ref, ctx.secrets) }))
30
+ * .schedule('poll', async ({ ctx }) => ({ counters: { orders: 3 } }));
31
+ * ```
32
+ */
33
+ export class KennraApp {
34
+ opts;
35
+ manifest;
36
+ client;
37
+ lookups = new Map();
38
+ schedules = new Map();
39
+ events = new Map();
40
+ routes = new Map();
41
+ disconnects = new Map();
42
+ lifecycleHandler = null;
43
+ erasureHandler = null;
44
+ segmentSyncHandler = null;
45
+ programTargetHandler = null;
46
+ connectionTestHandler = null;
47
+ /** Background work started by ticks (tests await it). */
48
+ pending = new Set();
49
+ /** Fires when the app stops (`stop()`): every handler's `ctx.signal` follows it. */
50
+ lifetime = new AbortController();
51
+ active = new Map();
52
+ constructor(opts) {
53
+ this.opts = opts;
54
+ this.manifest = defineManifest(opts.manifest);
55
+ this.client = new KennraAppClient(opts.kennra);
56
+ }
57
+ lookup(object, handler) {
58
+ if (!this.manifest.capabilities.lookups.some((l) => l.object === object))
59
+ throw new Error(`The manifest declares no lookup for ${object}`);
60
+ this.lookups.set(object, handler);
61
+ return this;
62
+ }
63
+ schedule(id, handler) {
64
+ if (!this.manifest.capabilities.schedules.some((s) => s.id === id))
65
+ throw new Error(`The manifest declares no schedule ${id}`);
66
+ this.schedules.set(id, handler);
67
+ return this;
68
+ }
69
+ on(eventType, handler) {
70
+ this.events.set(eventType, handler);
71
+ return this;
72
+ }
73
+ /** A member disconnected in Kennra (`userConnections[].disconnectUrl`): revoke and delete the token. */
74
+ onDisconnect(kind, handler) {
75
+ if (!this.manifest.capabilities.userConnections.some((c) => c.kind === kind && c.disconnectUrl))
76
+ throw new Error(`The manifest declares no disconnectUrl for ${kind} connections`);
77
+ this.disconnects.set(kind, handler);
78
+ return this;
79
+ }
80
+ onLifecycle(handler) {
81
+ this.lifecycleHandler = handler;
82
+ return this;
83
+ }
84
+ /** Erasure of a person (manifest `capabilities.privacy.erasure: receipt`): answer with a receipt. */
85
+ onErasure(handler) {
86
+ if (this.manifest.capabilities.privacy?.erasure !== 'receipt')
87
+ throw new Error('The manifest declares no erasure receipts (capabilities.privacy.erasure: receipt)');
88
+ this.erasureHandler = handler;
89
+ return this;
90
+ }
91
+ /** Segment membership deltas (`capabilities.segmentSync`): apply them idempotently and answer with a receipt. */
92
+ segmentSync(handler) {
93
+ if (!this.manifest.capabilities.segmentSync)
94
+ throw new Error('The manifest declares no segmentSync capability');
95
+ this.segmentSyncHandler = handler;
96
+ return this;
97
+ }
98
+ /** "Test connection" on the settings form (`capabilities.connectionTest`): try the typed settings. */
99
+ onConnectionTest(handler) {
100
+ if (!this.manifest.capabilities.connectionTest)
101
+ throw new Error('The manifest declares no connectionTest capability');
102
+ this.connectionTestHandler = handler;
103
+ return this;
104
+ }
105
+ /** Program enrollment deltas (`capabilities.programTargets`): apply them idempotently and answer with a receipt. */
106
+ programTarget(handler) {
107
+ if (!this.manifest.capabilities.programTargets)
108
+ throw new Error('The manifest declares no programTargets capability');
109
+ this.programTargetHandler = handler;
110
+ return this;
111
+ }
112
+ /** An extra route the app serves itself (e.g. an OAuth callback). Not signed by Kennra. */
113
+ route(method, path, handler) {
114
+ this.routes.set(`${method.toUpperCase()} ${path}`, handler);
115
+ return this;
116
+ }
117
+ /** The context for an installation (settings and secrets from the installation store). */
118
+ async context(installationId, info) {
119
+ const kennra = this.client.forInstallation(installationId);
120
+ // Signature checks read the installation without secrets; handlers get them (asked for explicitly).
121
+ const i = info?.secretKeys && !info.secretKeys.length ? info : await kennra.installation({ secrets: true });
122
+ return {
123
+ installationId,
124
+ workspace: i.workspace,
125
+ config: i.settings,
126
+ secrets: i.secrets,
127
+ state: kennra.state,
128
+ kennra,
129
+ signal: this.lifetime.signal,
130
+ };
131
+ }
132
+ /** Fires when the app stops: for the app's own background work (a sync started by a connect). */
133
+ get signal() {
134
+ return this.lifetime.signal;
135
+ }
136
+ /** True once `stop()` was called: new schedule ticks are refused (503). */
137
+ get stopping() {
138
+ return this.lifetime.signal.aborted;
139
+ }
140
+ /**
141
+ * Stops the app (graceful shutdown): new ticks get 503, and every handler's signal fires, so
142
+ * running work saves its cursor and reports `interrupted`. Await `idle()` after it.
143
+ */
144
+ stop(reason = 'shutdown') {
145
+ if (!this.lifetime.signal.aborted)
146
+ this.lifetime.abort(reason);
147
+ for (const r of this.active.values())
148
+ r.stop(reason);
149
+ }
150
+ /** The schedule runs in progress in this process, with their last heartbeat and progress. */
151
+ runs() {
152
+ return [...this.active.values()].map(({ stop: _stop, ...r }) => ({
153
+ ...r,
154
+ progress: r.progress ? { ...r.progress } : null,
155
+ }));
156
+ }
157
+ /** Runs one schedule tick: a lease kept alive by heartbeats, a deadline, a signal and the report. */
158
+ async runTick(tick, handler, base) {
159
+ const kennra = base.kennra;
160
+ const controller = new AbortController();
161
+ const startedAt = new Date();
162
+ const declared = this.manifest.capabilities.schedules.find((s) => s.id === tick.scheduleId);
163
+ const maxSeconds = tick.maxRunSeconds ?? declared?.maxRunSeconds ?? DEFAULT_MAX_RUN_SECONDS;
164
+ const deadline = new Date(startedAt.getTime() + maxSeconds * 1000);
165
+ const job = {
166
+ runId: tick.runId,
167
+ scheduleId: tick.scheduleId,
168
+ installationId: base.installationId,
169
+ startedAt: startedAt.toISOString(),
170
+ lastHeartbeatAt: null,
171
+ deadline: deadline.toISOString(),
172
+ progress: null,
173
+ stopping: null,
174
+ stop: (reason) => {
175
+ if (controller.signal.aborted)
176
+ return;
177
+ job.stopping = reason;
178
+ controller.abort(reason);
179
+ },
180
+ };
181
+ this.active.set(tick.runId, job);
182
+ const onStop = () => job.stop('shutdown');
183
+ this.lifetime.signal.addEventListener('abort', onStop, { once: true });
184
+ if (this.lifetime.signal.aborted)
185
+ job.stop('shutdown');
186
+ const maxTimer = setTimeout(() => job.stop('max_duration'), maxSeconds * 1000);
187
+ maxTimer.unref?.();
188
+ let lastSent = 0;
189
+ let beating = null;
190
+ const beat = () => {
191
+ if (beating)
192
+ return beating;
193
+ lastSent = Date.now();
194
+ beating = kennra
195
+ .reportRun({
196
+ runId: tick.runId,
197
+ scheduleId: tick.scheduleId,
198
+ status: 'running',
199
+ ...(job.progress ? { counters: { ...job.progress } } : {}),
200
+ })
201
+ .then((ack) => {
202
+ job.lastHeartbeatAt = new Date().toISOString();
203
+ // Kennra gave the run up (its lease ran out): stop; the outcome is kept as information.
204
+ if (ack.status === 'abandoned')
205
+ job.stop('abandoned');
206
+ })
207
+ .catch(() => { })
208
+ .finally(() => {
209
+ beating = null;
210
+ });
211
+ return beating;
212
+ };
213
+ const beatTimer = setInterval(() => void beat(), this.opts.heartbeatMs ?? 60_000);
214
+ beatTimer.unref?.();
215
+ const run = {
216
+ runId: tick.runId,
217
+ scheduleId: tick.scheduleId,
218
+ startedAt,
219
+ deadline,
220
+ signal: controller.signal,
221
+ get stopReason() {
222
+ return job.stopping;
223
+ },
224
+ heartbeat: async (progress) => {
225
+ if (progress)
226
+ job.progress = { ...progress };
227
+ if (Date.now() - lastSent < MIN_HEARTBEAT_MS)
228
+ return;
229
+ await beat();
230
+ },
231
+ };
232
+ const ctx = { ...base, signal: controller.signal };
233
+ let report;
234
+ try {
235
+ const r = await handler({ tick, lane: tick.lane, ctx, run });
236
+ let status = r.status ?? 'completed';
237
+ // Stopped early (its deadline, a shutdown): what it did is saved, the rest is for the next tick.
238
+ if (job.stopping && status === 'completed')
239
+ status = STOPPED_STATUS[job.stopping];
240
+ report = { ...r, runId: tick.runId, scheduleId: tick.scheduleId, status };
241
+ }
242
+ catch (e) {
243
+ report = {
244
+ runId: tick.runId,
245
+ scheduleId: tick.scheduleId,
246
+ status: job.stopping ? STOPPED_STATUS[job.stopping] : 'failed',
247
+ errors: [{ message: String(e?.message ?? e).slice(0, 300) }],
248
+ };
249
+ }
250
+ finally {
251
+ clearTimeout(maxTimer);
252
+ clearInterval(beatTimer);
253
+ this.lifetime.signal.removeEventListener('abort', onStop);
254
+ this.active.delete(tick.runId);
255
+ }
256
+ await kennra.reportRun(report).catch(() => { });
257
+ }
258
+ /** Verifies a request from Kennra and returns the body and the installation's context. */
259
+ async verified(req) {
260
+ const installationId = req.headers.get('kennra-installation');
261
+ if (!installationId)
262
+ return Response.json({ error: 'missing kennra-installation' }, { status: 400 });
263
+ const text = await req.text();
264
+ const kennra = this.client.forInstallation(installationId);
265
+ let info;
266
+ try {
267
+ info = await kennra.installation();
268
+ try {
269
+ await verify(info.signingSecrets, text, req.headers, {
270
+ toleranceSeconds: this.opts.toleranceSeconds ?? 300,
271
+ });
272
+ }
273
+ catch (e) {
274
+ // The secret may have been rotated since it was cached: read it again once.
275
+ if (!(e instanceof SignatureError) || e.code !== 'INVALID_SIGNATURE')
276
+ throw e;
277
+ info = await kennra.installation({ fresh: true });
278
+ await verify(info.signingSecrets, text, req.headers, {
279
+ toleranceSeconds: this.opts.toleranceSeconds ?? 300,
280
+ });
281
+ }
282
+ }
283
+ catch (e) {
284
+ return Response.json({ error: e instanceof SignatureError ? e.code : 'unauthorized', message: e.message }, { status: 401 });
285
+ }
286
+ return {
287
+ body: JSON.parse(text),
288
+ ctx: await this.context(installationId, info),
289
+ };
290
+ }
291
+ /** The fetch handler. */
292
+ fetch = async (req) => {
293
+ const url = new URL(req.url);
294
+ const custom = this.routes.get(`${req.method} ${url.pathname}`);
295
+ if (custom)
296
+ return custom(req, { client: this.client, manifest: this.manifest });
297
+ const c = this.manifest.capabilities;
298
+ if (this.manifest.health && url.pathname === pathOf(this.manifest.health.url))
299
+ return Response.json({ ok: true, app: this.manifest.id, version: this.manifest.version });
300
+ if (req.method !== 'POST')
301
+ return new Response('Not found', { status: 404 });
302
+ if (c.lifecycle && url.pathname === pathOf(c.lifecycle.url)) {
303
+ const v = await this.verified(req);
304
+ if (v instanceof Response) {
305
+ // After uninstall the installation can't be read any more; the lifecycle call is still acknowledged.
306
+ return v;
307
+ }
308
+ await this.lifecycleHandler?.({ event: v.body, ctx: v.ctx });
309
+ return Response.json({ ok: true });
310
+ }
311
+ if (c.connectionTest && url.pathname === pathOf(c.connectionTest.url)) {
312
+ const v = await this.verified(req);
313
+ if (v instanceof Response)
314
+ return v;
315
+ if (!this.connectionTestHandler)
316
+ return Response.json({ error: 'no handler' }, { status: 501 });
317
+ try {
318
+ const r = await this.connectionTestHandler({
319
+ request: v.body,
320
+ ctx: v.ctx,
321
+ });
322
+ return Response.json(r);
323
+ }
324
+ catch (e) {
325
+ return Response.json({
326
+ ok: false,
327
+ code: 'error',
328
+ message: e.message.slice(0, 300),
329
+ });
330
+ }
331
+ }
332
+ const lookup = c.lookups.find((l) => pathOf(l.url) === url.pathname);
333
+ if (lookup) {
334
+ const v = await this.verified(req);
335
+ if (v instanceof Response)
336
+ return v;
337
+ const r = v.body;
338
+ const handler = this.lookups.get(r.object);
339
+ if (!handler)
340
+ return Response.json({ error: 'no handler' }, { status: 501 });
341
+ try {
342
+ const out = await handler({ req: r, ref: r.ref, ctx: v.ctx });
343
+ if ('notFound' in out)
344
+ return Response.json({ error: 'not_found' }, { status: 404 });
345
+ if ('noAccess' in out)
346
+ return Response.json({ error: 'no_access' }, { status: 403 });
347
+ return Response.json({ data: out.data, fetchedAt: new Date().toISOString() });
348
+ }
349
+ catch (e) {
350
+ return Response.json({ error: 'source_error', message: e.message.slice(0, 200) }, { status: 502 });
351
+ }
352
+ }
353
+ const schedule = c.schedules.find((s) => pathOf(s.url) === url.pathname);
354
+ if (schedule) {
355
+ const v = await this.verified(req);
356
+ if (v instanceof Response)
357
+ return v;
358
+ const tick = v.body;
359
+ const handler = this.schedules.get(tick.scheduleId);
360
+ if (!handler)
361
+ return Response.json({ error: 'no handler' }, { status: 501 });
362
+ // Shutting down: the run is abandoned when its lease ends, and the next tick comes as usual.
363
+ if (this.stopping)
364
+ return Response.json({ error: 'stopping' }, { status: 503, headers: { 'retry-after': '30' } });
365
+ const work = this.runTick(tick, handler, v.ctx);
366
+ if (this.opts.background === false)
367
+ await work;
368
+ else {
369
+ this.pending.add(work);
370
+ void work.finally(() => this.pending.delete(work));
371
+ }
372
+ return Response.json({ accepted: true, runId: tick.runId }, { status: 202 });
373
+ }
374
+ if (c.segmentSync && url.pathname === pathOf(c.segmentSync.url)) {
375
+ const v = await this.verified(req);
376
+ if (v instanceof Response)
377
+ return v;
378
+ if (!this.segmentSyncHandler)
379
+ return Response.json({ error: 'no handler' }, { status: 501 });
380
+ const delta = v.body;
381
+ try {
382
+ const r = await this.segmentSyncHandler({ delta, ctx: v.ctx });
383
+ return Response.json({ ...r, deliveryId: delta.deliveryId });
384
+ }
385
+ catch (e) {
386
+ return Response.json({ error: 'source_error', message: e.message.slice(0, 200) }, { status: 502 });
387
+ }
388
+ }
389
+ if (c.programTargets && url.pathname === pathOf(c.programTargets.url)) {
390
+ const v = await this.verified(req);
391
+ if (v instanceof Response)
392
+ return v;
393
+ if (!this.programTargetHandler)
394
+ return Response.json({ error: 'no handler' }, { status: 501 });
395
+ const delta = v.body;
396
+ try {
397
+ const r = await this.programTargetHandler({ delta, ctx: v.ctx });
398
+ return Response.json({ ...r, deliveryId: delta.deliveryId });
399
+ }
400
+ catch (e) {
401
+ return Response.json({ error: 'source_error', message: e.message.slice(0, 200) }, { status: 502 });
402
+ }
403
+ }
404
+ if (c.privacy?.url && url.pathname === pathOf(c.privacy.url)) {
405
+ const v = await this.verified(req);
406
+ if (v instanceof Response)
407
+ return v;
408
+ if (!this.erasureHandler)
409
+ return Response.json({ status: 'pending', detail: 'No erasure handler' });
410
+ const receipt = await this.erasureHandler({ request: v.body, ctx: v.ctx });
411
+ return Response.json(receipt);
412
+ }
413
+ const disconnect = c.userConnections.find((u) => u.disconnectUrl && pathOf(u.disconnectUrl) === url.pathname);
414
+ if (disconnect) {
415
+ const v = await this.verified(req);
416
+ if (v instanceof Response)
417
+ return v;
418
+ const r = v.body;
419
+ const handler = this.disconnects.get(r.kind);
420
+ if (!handler)
421
+ return Response.json({ error: 'no handler' }, { status: 501 });
422
+ try {
423
+ await handler({ req: r, ctx: v.ctx });
424
+ return Response.json({ ok: true });
425
+ }
426
+ catch (e) {
427
+ return Response.json({ error: 'source_error', message: e.message.slice(0, 200) }, { status: 502 });
428
+ }
429
+ }
430
+ if (c.webhooks && url.pathname === pathOf(c.webhooks.url)) {
431
+ const v = await this.verified(req);
432
+ if (v instanceof Response)
433
+ return v;
434
+ const ev = v.body;
435
+ await this.events.get(ev.type)?.({ event: ev, ctx: v.ctx });
436
+ return Response.json({ ok: true });
437
+ }
438
+ return new Response('Not found', { status: 404 });
439
+ };
440
+ /** Waits for background schedule work (tests). */
441
+ async idle() {
442
+ while (this.pending.size)
443
+ await Promise.all([...this.pending]);
444
+ }
445
+ }
446
+ export function createApp(opts) {
447
+ return new KennraApp(opts);
448
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * History backfill for a new contact, provider-neutral (docs/15 §9.3, decision 21 November 2026).
3
+ *
4
+ * When a person or company becomes known in Kennra, Kennra asks capture apps to look back. For
5
+ * every member who connected their own calendar or mailbox in the installation, the app searches
6
+ * back `historyYears` for the person's addresses or the company's domains and sends each item
7
+ * through its ordinary capture path. This module runs the requests: the cursor per request in the
8
+ * installation state (`backfill:<partyId>`), calendars before mailboxes, a budget per run, a rate
9
+ * limit that pauses only that connection, and the progress reports (`running`, `partial` with what
10
+ * waits, `done`, `failed`). The app supplies the searches: one page of its provider's calendar or
11
+ * mailbox for a task, as capture items.
12
+ */
13
+ import type { AppContext } from './app.js';
14
+ import type { IngestItem } from './protocol.js';
15
+ export declare const DEFAULT_HISTORY_YEARS = 3;
16
+ export declare const MAX_HISTORY_YEARS = 10;
17
+ /** How many years back the installation looks for a new contact (the `historyYears` setting, clamped). */
18
+ export declare function historyYearsOf(ctx: Pick<AppContext, 'config'>): number;
19
+ /** One search: a member's calendar or mailbox, for one address or domain (or all of a request's). */
20
+ export interface BackfillTask {
21
+ kind: 'calendar' | 'mailbox';
22
+ userId: string;
23
+ connectionKey: string;
24
+ /** The address or domain; for a search over all of a request's terms, them joined by commas. */
25
+ term: string;
26
+ /** Every term this task searches, when the search takes them all at once (`perTerm: false`). */
27
+ terms?: string[];
28
+ pageToken?: string;
29
+ done?: boolean;
30
+ error?: string;
31
+ }
32
+ /** The run's budget, spent by the searches: calendar pages and messages read. */
33
+ export interface BackfillBudget {
34
+ messages: number;
35
+ pages: number;
36
+ }
37
+ /** One page of a search, as capture items for the ordinary capture path. */
38
+ export interface BackfillPage {
39
+ items: IngestItem[];
40
+ /** Items looked at on this page. */
41
+ seen: number;
42
+ /** Items left out before they were sent (spam, drafts, notifications, automated mail). */
43
+ skipped?: number;
44
+ /** The next page; none when the search is done. */
45
+ nextPageToken?: string;
46
+ }
47
+ export interface BackfillSearch {
48
+ /** Which budget the search spends: `pages` (calendar) or `messages` (mailbox). */
49
+ budget: keyof BackfillBudget;
50
+ /** One task per address or domain (default), or one per connection with every term. */
51
+ perTerm?: boolean;
52
+ /** Reads one page and spends from `budget`. */
53
+ page(input: {
54
+ task: BackfillTask;
55
+ token: string;
56
+ since: Date;
57
+ now: Date;
58
+ budget: BackfillBudget;
59
+ signal: AbortSignal;
60
+ }): Promise<BackfillPage>;
61
+ }
62
+ export interface CaptureBackfillDeps {
63
+ searches: {
64
+ calendar: BackfillSearch;
65
+ mailbox: BackfillSearch;
66
+ };
67
+ accessToken: (userId: string, connectionKey: string) => Promise<string | null>;
68
+ internalDomains: readonly string[];
69
+ now: () => Date;
70
+ /** The provider refused for now (quota): pause the connection for this run and keep the cursor. */
71
+ rateLimited: (e: unknown) => boolean;
72
+ /** The provider's name in the run's errors ("<provider> asks to slow down"). */
73
+ provider: string;
74
+ /** The run's budget (default 300 messages and 20 calendar pages). */
75
+ limits?: Partial<BackfillBudget>;
76
+ }
77
+ /** Messages read per tick across every request. */
78
+ export declare const BACKFILL_MESSAGES_PER_RUN = 300;
79
+ /** Calendar pages per tick across every request. */
80
+ export declare const BACKFILL_EVENT_PAGES_PER_RUN = 20;
81
+ export interface BackfillRunReport {
82
+ requests: number;
83
+ finished: number;
84
+ meetings: number;
85
+ emails: number;
86
+ seen: number;
87
+ /** Requests where all that is left waits for the provider's rate limit. */
88
+ waiting: number;
89
+ errors: string[];
90
+ }
91
+ export declare const emptyBackfillReport: () => BackfillRunReport;
92
+ /** An address or domain an item is with (an attendee or the organizer). */
93
+ export declare function hasTerm(emails: readonly string[], term: string): boolean;
94
+ /** One tick: the requests Kennra has for this installation, oldest first, within the run's budget. */
95
+ export declare function runCaptureBackfills(ctx: AppContext, deps: CaptureBackfillDeps): Promise<BackfillRunReport>;