@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.
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/dist/app.d.ts +190 -0
- package/dist/app.js +448 -0
- package/dist/client.d.ts +161 -0
- package/dist/client.js +263 -0
- package/dist/hosting.d.ts +56 -0
- package/dist/hosting.js +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +31 -0
- package/dist/manifest.d.ts +495 -0
- package/dist/manifest.js +956 -0
- package/dist/operations.d.ts +8 -0
- package/dist/operations.js +9 -0
- package/dist/protocol.d.ts +851 -0
- package/dist/protocol.js +5 -0
- package/dist/signature.d.ts +61 -0
- package/dist/signature.js +108 -0
- package/dist/testing.d.ts +80 -0
- package/dist/testing.js +226 -0
- package/package.json +74 -4
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
|
+
/** An employee 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
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { CaptureBackfillReport, CaptureBackfillRequest, ConsentChangeInput, EngagementSignalInput, Fetch, IngestItem, IngestResponse, InstallationInfo, Lane, SetupReport, SyncRunAck, SyncRunReport, UserConnectionReport } from './protocol.js';
|
|
2
|
+
export interface KennraClientOptions {
|
|
3
|
+
/** The Kennra API, e.g. `http://localhost:4000` from `bun run dev`. */
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
/** The app id (client id) and its client secret (dev; `private_key_jwt` at the identity provider in production). */
|
|
6
|
+
clientId: string;
|
|
7
|
+
clientSecret: string;
|
|
8
|
+
fetch?: Fetch;
|
|
9
|
+
/** Retries on 429/503 with Retry-After (default 3). */
|
|
10
|
+
retries?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare class KennraApiError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly code: string;
|
|
15
|
+
constructor(status: number, code: string, message: string);
|
|
16
|
+
}
|
|
17
|
+
/** Returned by the API on every write; sent back on reads to see that write (read-your-writes). */
|
|
18
|
+
export declare const CONSISTENCY_HEADER = "kennra-consistency-token";
|
|
19
|
+
/**
|
|
20
|
+
* A Kennra client for one installation: client-credentials tokens cached until shortly before
|
|
21
|
+
* expiry, the installation store, batched ingest with stable idempotency keys, and run and
|
|
22
|
+
* connection reports. Uses only the public API.
|
|
23
|
+
*/
|
|
24
|
+
export declare class InstallationClient {
|
|
25
|
+
private readonly opts;
|
|
26
|
+
readonly installationId: string;
|
|
27
|
+
/**
|
|
28
|
+
* Delegation (docs/15 §3.5): the member this client acts for (email or `usr_…`). Its tokens
|
|
29
|
+
* come from the token exchange with `requested_subject`; every call is the installation's
|
|
30
|
+
* grant ∩ the member's access. Without it, the installation acts as itself.
|
|
31
|
+
*/
|
|
32
|
+
readonly requestedSubject?: string | undefined;
|
|
33
|
+
private token;
|
|
34
|
+
private info;
|
|
35
|
+
private readonly f;
|
|
36
|
+
/** The newest consistency token from a write by this client; later GraphQL calls send it. */
|
|
37
|
+
private consistencyToken;
|
|
38
|
+
/** For a member client: the member's user id, once Kennra has issued a token for them. */
|
|
39
|
+
onBehalfOf: string | null;
|
|
40
|
+
constructor(opts: KennraClientOptions, installationId: string,
|
|
41
|
+
/**
|
|
42
|
+
* Delegation (docs/15 §3.5): the member this client acts for (email or `usr_…`). Its tokens
|
|
43
|
+
* come from the token exchange with `requested_subject`; every call is the installation's
|
|
44
|
+
* grant ∩ the member's access. Without it, the installation acts as itself.
|
|
45
|
+
*/
|
|
46
|
+
requestedSubject?: string | undefined);
|
|
47
|
+
/**
|
|
48
|
+
* A client that acts for a member by delegation (the app declares `access.delegation`, or is a
|
|
49
|
+
* private app, and an admin turned delegation on for the member). The first call fails with
|
|
50
|
+
* `invalid_grant` when Kennra can't act for that person: the answer is the same for an unknown
|
|
51
|
+
* email, an unlisted member and an inactive one.
|
|
52
|
+
*/
|
|
53
|
+
forMember(subject: string): InstallationClient;
|
|
54
|
+
private url;
|
|
55
|
+
/** An installation token (cached until 60 s before it expires). */
|
|
56
|
+
accessToken(): Promise<string>;
|
|
57
|
+
/** Calls the API with the installation token; retries 429/503 honouring Retry-After. */
|
|
58
|
+
request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>, onResponse?: (res: Response) => void): Promise<T>;
|
|
59
|
+
/**
|
|
60
|
+
* Settings and signing secrets of the installation (cached 60 s). The app's own secrets only with
|
|
61
|
+
* `secrets: true` (review L8): the API returns them only when asked, and they are cached apart.
|
|
62
|
+
*/
|
|
63
|
+
installation(opts?: {
|
|
64
|
+
fresh?: boolean;
|
|
65
|
+
secrets?: boolean;
|
|
66
|
+
}): Promise<InstallationInfo>;
|
|
67
|
+
readonly state: {
|
|
68
|
+
get: <T = unknown>(key: string) => Promise<T | null>;
|
|
69
|
+
put: (key: string, value: unknown) => Promise<void>;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Sends items in chunks of at most `chunk` (default 200) in a lane. Idempotency keys are the
|
|
73
|
+
* caller's and must be stable across retries and versions. Returns every per-item result.
|
|
74
|
+
*/
|
|
75
|
+
ingest(lane: Lane, items: IngestItem[], opts?: {
|
|
76
|
+
chunk?: number;
|
|
77
|
+
}): Promise<IngestResponse['results']>;
|
|
78
|
+
/**
|
|
79
|
+
* Consent changes people made in the app (docs/15 §4.10): one ingest item each, purpose = the
|
|
80
|
+
* consent purpose, idempotency key `consent:<externalRef>:<purpose>:<channel>`. Withdrawals and
|
|
81
|
+
* suppressions always apply; a grant only with `kennra:consent:grant` and only when it is newer
|
|
82
|
+
* than Kennra's own latest consent event (else `outcome: ignored`).
|
|
83
|
+
*/
|
|
84
|
+
recordConsentChanges(changes: ConsentChangeInput[]): Promise<IngestResponse['results']>;
|
|
85
|
+
/**
|
|
86
|
+
* Engagement signals (docs/15 §4.11): kept as aggregates per person and channel, deduplicated by
|
|
87
|
+
* `eventId` (also the idempotency key). `purpose` is the grant's purpose for
|
|
88
|
+
* `kennra:engagement:write` (default the first granted).
|
|
89
|
+
*/
|
|
90
|
+
recordEngagement(signals: EngagementSignalInput[], opts?: {
|
|
91
|
+
purpose?: string;
|
|
92
|
+
}): Promise<IngestResponse['results']>;
|
|
93
|
+
/**
|
|
94
|
+
* Reports a run's outcome, or with status `running` its heartbeat and progress. The answer says
|
|
95
|
+
* the run's status in Kennra: `abandoned` when its lease ran out (stop; the report is kept as
|
|
96
|
+
* information only).
|
|
97
|
+
*/
|
|
98
|
+
reportRun(report: SyncRunReport): Promise<SyncRunAck>;
|
|
99
|
+
/**
|
|
100
|
+
* History backfill (capabilities.ingest.backfill): the people and companies whose history this
|
|
101
|
+
* installation has not finished looking for, oldest first, at most 20.
|
|
102
|
+
*/
|
|
103
|
+
captureBackfills(): Promise<CaptureBackfillRequest[]>;
|
|
104
|
+
/** Progress on a history backfill request (running, done or failed, with counters). */
|
|
105
|
+
reportCaptureBackfill(report: CaptureBackfillReport): Promise<void>;
|
|
106
|
+
reportUserConnection(report: UserConnectionReport): Promise<void>;
|
|
107
|
+
/**
|
|
108
|
+
* The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
|
|
109
|
+
* provider scopes) and detected settings. The ticket names the admin; the core verifies it.
|
|
110
|
+
*/
|
|
111
|
+
completeSetup(report: SetupReport): Promise<void>;
|
|
112
|
+
/** The installation's per-employee connections, with status and share level (the core decides). */
|
|
113
|
+
userConnections(): Promise<{
|
|
114
|
+
userId: string;
|
|
115
|
+
connectionKey: string;
|
|
116
|
+
kind: string;
|
|
117
|
+
status: string;
|
|
118
|
+
shareLevel: string;
|
|
119
|
+
/** The last error the app reported for the connection (null once it synced again). */
|
|
120
|
+
error: string | null;
|
|
121
|
+
}[]>;
|
|
122
|
+
/** Secrets the app keeps in its installation store (e.g. an employee's refresh token). Never shown to admins. */
|
|
123
|
+
readonly secrets: {
|
|
124
|
+
put: (key: string, value: string | null) => Promise<void>;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* A persisted (or, with graphql:adhoc, ad hoc) GraphQL query with a purpose the app was granted.
|
|
128
|
+
* Read-your-writes: after a mutation, the next calls send its consistency token, so they see it.
|
|
129
|
+
*/
|
|
130
|
+
graphql<T = Record<string, unknown>>(query: {
|
|
131
|
+
query?: string;
|
|
132
|
+
extensions?: Record<string, unknown>;
|
|
133
|
+
variables?: Record<string, unknown>;
|
|
134
|
+
}, purpose: string): Promise<{
|
|
135
|
+
data?: T;
|
|
136
|
+
errors?: {
|
|
137
|
+
message: string;
|
|
138
|
+
extensions?: Record<string, unknown>;
|
|
139
|
+
}[];
|
|
140
|
+
}>;
|
|
141
|
+
/** The newest consistency token this client has seen (null before its first write). */
|
|
142
|
+
get lastConsistencyToken(): string | null;
|
|
143
|
+
private rememberConsistency;
|
|
144
|
+
}
|
|
145
|
+
/** One client per installation, sharing the app credentials. */
|
|
146
|
+
export declare class KennraAppClient {
|
|
147
|
+
readonly opts: KennraClientOptions;
|
|
148
|
+
private readonly clients;
|
|
149
|
+
constructor(opts: KennraClientOptions);
|
|
150
|
+
/**
|
|
151
|
+
* The app's installations whose setup reported this provider organization
|
|
152
|
+
* (`completeSetup({ externalOrganization })`), newest setup first: for requests that reach the
|
|
153
|
+
* app without an installation (one command URL for every customer of a chat platform, say).
|
|
154
|
+
*/
|
|
155
|
+
installationsFor(externalOrganization: string): Promise<{
|
|
156
|
+
installationId: string;
|
|
157
|
+
workspace: string;
|
|
158
|
+
status: string;
|
|
159
|
+
}[]>;
|
|
160
|
+
forInstallation(installationId: string): InstallationClient;
|
|
161
|
+
}
|