@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/client.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
export class KennraApiError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
constructor(status, code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
11
|
+
/** Returned by the API on every write; sent back on reads to see that write (read-your-writes). */
|
|
12
|
+
export const CONSISTENCY_HEADER = 'kennra-consistency-token';
|
|
13
|
+
/**
|
|
14
|
+
* A Kennra client for one installation: client-credentials tokens cached until shortly before
|
|
15
|
+
* expiry, the installation store, batched ingest with stable idempotency keys, and run and
|
|
16
|
+
* connection reports. Uses only the public API.
|
|
17
|
+
*/
|
|
18
|
+
export class InstallationClient {
|
|
19
|
+
opts;
|
|
20
|
+
installationId;
|
|
21
|
+
requestedSubject;
|
|
22
|
+
token = null;
|
|
23
|
+
info = null;
|
|
24
|
+
f;
|
|
25
|
+
/** The newest consistency token from a write by this client; later GraphQL calls send it. */
|
|
26
|
+
consistencyToken = null;
|
|
27
|
+
/** For a member client: the member's user id, once Kennra has issued a token for them. */
|
|
28
|
+
onBehalfOf = null;
|
|
29
|
+
constructor(opts, installationId,
|
|
30
|
+
/**
|
|
31
|
+
* Delegation (docs/15 §3.5): the member this client acts for (email or `usr_…`). Its tokens
|
|
32
|
+
* come from the token exchange with `requested_subject`; every call is the installation's
|
|
33
|
+
* grant ∩ the member's access. Without it, the installation acts as itself.
|
|
34
|
+
*/
|
|
35
|
+
requestedSubject) {
|
|
36
|
+
this.opts = opts;
|
|
37
|
+
this.installationId = installationId;
|
|
38
|
+
this.requestedSubject = requestedSubject;
|
|
39
|
+
this.f = opts.fetch ?? ((...a) => fetch(...a));
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A client that acts for a member by delegation (the app declares `access.delegation`, or is a
|
|
43
|
+
* private app, and an admin turned delegation on for the member). The first call fails with
|
|
44
|
+
* `invalid_grant` when Kennra can't act for that person: the answer is the same for an unknown
|
|
45
|
+
* email, an unlisted member and an inactive one.
|
|
46
|
+
*/
|
|
47
|
+
forMember(subject) {
|
|
48
|
+
return new InstallationClient(this.opts, this.installationId, subject);
|
|
49
|
+
}
|
|
50
|
+
url(path) {
|
|
51
|
+
return `${this.opts.baseUrl.replace(/\/$/, '')}${path}`;
|
|
52
|
+
}
|
|
53
|
+
/** An installation token (cached until 60 s before it expires). */
|
|
54
|
+
async accessToken() {
|
|
55
|
+
if (this.token && this.token.expires > Date.now() + 60_000)
|
|
56
|
+
return this.token.value;
|
|
57
|
+
const res = await this.f(this.url('/apps/token'), {
|
|
58
|
+
method: 'POST',
|
|
59
|
+
headers: { 'content-type': 'application/json' },
|
|
60
|
+
body: JSON.stringify({
|
|
61
|
+
grant_type: this.requestedSubject
|
|
62
|
+
? 'urn:ietf:params:oauth:grant-type:token-exchange'
|
|
63
|
+
: 'client_credentials',
|
|
64
|
+
client_id: this.opts.clientId,
|
|
65
|
+
client_secret: this.opts.clientSecret,
|
|
66
|
+
installation: this.installationId,
|
|
67
|
+
...(this.requestedSubject ? { requested_subject: this.requestedSubject } : {}),
|
|
68
|
+
}),
|
|
69
|
+
});
|
|
70
|
+
const body = (await res.json().catch(() => ({})));
|
|
71
|
+
if (!res.ok || !body.access_token)
|
|
72
|
+
throw new KennraApiError(res.status, body.error ?? 'token_failed', body.message ?? 'No installation token');
|
|
73
|
+
this.token = { value: body.access_token, expires: Date.now() + (body.expires_in ?? 900) * 1000 };
|
|
74
|
+
this.onBehalfOf = body.on_behalf_of ?? null;
|
|
75
|
+
return this.token.value;
|
|
76
|
+
}
|
|
77
|
+
/** Calls the API with the installation token; retries 429/503 honouring Retry-After. */
|
|
78
|
+
async request(method, path, body, headers = {}, onResponse) {
|
|
79
|
+
for (let attempt = 0;; attempt++) {
|
|
80
|
+
const res = await this.f(this.url(path), {
|
|
81
|
+
method,
|
|
82
|
+
headers: {
|
|
83
|
+
'content-type': 'application/json',
|
|
84
|
+
authorization: `Bearer ${await this.accessToken()}`,
|
|
85
|
+
...headers,
|
|
86
|
+
},
|
|
87
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
88
|
+
});
|
|
89
|
+
if ((res.status === 429 || res.status === 503) && attempt < (this.opts.retries ?? 3)) {
|
|
90
|
+
await sleep(Number(res.headers.get('retry-after') ?? 1) * 1000);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
onResponse?.(res);
|
|
94
|
+
const json = (await res.json().catch(() => ({})));
|
|
95
|
+
if (!res.ok) {
|
|
96
|
+
if (res.status === 401)
|
|
97
|
+
this.token = null;
|
|
98
|
+
throw new KennraApiError(res.status, json.error ?? `http_${res.status}`, json.message ?? res.statusText);
|
|
99
|
+
}
|
|
100
|
+
return json;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Settings and signing secrets of the installation (cached 60 s). The app's own secrets only with
|
|
105
|
+
* `secrets: true` (review L8): the API returns them only when asked, and they are cached apart.
|
|
106
|
+
*/
|
|
107
|
+
async installation(opts = {}) {
|
|
108
|
+
const slot = opts.secrets ? 'withSecrets' : 'plain';
|
|
109
|
+
const hit = this.info?.[slot];
|
|
110
|
+
if (!opts.fresh && hit && Date.now() - hit.at < 60_000)
|
|
111
|
+
return hit.value;
|
|
112
|
+
const value = await this.request('GET', opts.secrets ? '/apps/installation?include=secrets' : '/apps/installation');
|
|
113
|
+
this.info = { ...this.info, [slot]: { value, at: Date.now() } };
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
state = {
|
|
117
|
+
get: async (key) => (await this.request('GET', `/apps/installation/state/${encodeURIComponent(key)}`))
|
|
118
|
+
.value,
|
|
119
|
+
put: async (key, value) => {
|
|
120
|
+
await this.request('PUT', `/apps/installation/state/${encodeURIComponent(key)}`, { value });
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Sends items in chunks of at most `chunk` (default 200) in a lane. Idempotency keys are the
|
|
125
|
+
* caller's and must be stable across retries and versions. Returns every per-item result.
|
|
126
|
+
*/
|
|
127
|
+
async ingest(lane, items, opts = {}) {
|
|
128
|
+
const out = [];
|
|
129
|
+
const size = opts.chunk ?? 200;
|
|
130
|
+
for (let i = 0; i < items.length; i += size) {
|
|
131
|
+
const r = await this.request('POST', '/ingest', { lane, items: items.slice(i, i + size) }, { 'kennra-lane': lane });
|
|
132
|
+
out.push(...r.results);
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Consent changes people made in the app (docs/15 §4.10): one ingest item each, purpose = the
|
|
138
|
+
* consent purpose, idempotency key `consent:<externalRef>:<purpose>:<channel>`. Withdrawals and
|
|
139
|
+
* suppressions always apply; a grant only with `kennra:consent:grant` and only when it is newer
|
|
140
|
+
* than Kennra's own latest consent event (else `outcome: ignored`).
|
|
141
|
+
*/
|
|
142
|
+
async recordConsentChanges(changes) {
|
|
143
|
+
return this.ingest('live', changes.map((c) => ({
|
|
144
|
+
idempotencyKey: `consent:${c.externalRef}:${c.purpose}:${c.channel}`,
|
|
145
|
+
purpose: c.purpose,
|
|
146
|
+
command: 'recordConsentChange',
|
|
147
|
+
input: c,
|
|
148
|
+
})));
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Engagement signals (docs/15 §4.11): kept as aggregates per person and channel, deduplicated by
|
|
152
|
+
* `eventId` (also the idempotency key). `purpose` is the grant's purpose for
|
|
153
|
+
* `kennra:engagement:write` (default the first granted).
|
|
154
|
+
*/
|
|
155
|
+
async recordEngagement(signals, opts = {}) {
|
|
156
|
+
return this.ingest('live', signals.map((s) => ({
|
|
157
|
+
idempotencyKey: `engagement:${s.eventId}`,
|
|
158
|
+
...(opts.purpose ? { purpose: opts.purpose } : {}),
|
|
159
|
+
command: 'recordEngagement',
|
|
160
|
+
input: s,
|
|
161
|
+
})));
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Reports a run's outcome, or with status `running` its heartbeat and progress. The answer says
|
|
165
|
+
* the run's status in Kennra: `abandoned` when its lease ran out (stop; the report is kept as
|
|
166
|
+
* information only).
|
|
167
|
+
*/
|
|
168
|
+
async reportRun(report) {
|
|
169
|
+
const r = await this.request('POST', '/apps/runs', report);
|
|
170
|
+
return { ok: true, runId: report.runId, status: 'unknown', ...(r ?? {}) };
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* History backfill (capabilities.ingest.backfill): the people and companies whose history this
|
|
174
|
+
* installation has not finished looking for, oldest first, at most 20.
|
|
175
|
+
*/
|
|
176
|
+
async captureBackfills() {
|
|
177
|
+
return (await this.request('GET', '/apps/capture-backfills'))
|
|
178
|
+
.backfills;
|
|
179
|
+
}
|
|
180
|
+
/** Progress on a history backfill request (running, done or failed, with counters). */
|
|
181
|
+
async reportCaptureBackfill(report) {
|
|
182
|
+
await this.request('POST', '/apps/capture-backfills/report', report);
|
|
183
|
+
}
|
|
184
|
+
async reportUserConnection(report) {
|
|
185
|
+
await this.request('POST', '/apps/user-connections', report);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
|
|
189
|
+
* provider scopes) and detected settings. The ticket names the admin; the core verifies it.
|
|
190
|
+
*/
|
|
191
|
+
async completeSetup(report) {
|
|
192
|
+
await this.request('POST', '/apps/installation/setup', report);
|
|
193
|
+
this.info = null;
|
|
194
|
+
}
|
|
195
|
+
/** The installation's per-employee connections, with status and share level (the core decides). */
|
|
196
|
+
async userConnections() {
|
|
197
|
+
return (await this.request('GET', '/apps/user-connections')).connections;
|
|
198
|
+
}
|
|
199
|
+
/** Secrets the app keeps in its installation store (e.g. an employee's refresh token). Never shown to admins. */
|
|
200
|
+
secrets = {
|
|
201
|
+
put: async (key, value) => {
|
|
202
|
+
await this.request('PUT', `/apps/installation/secrets/${encodeURIComponent(key)}`, { value });
|
|
203
|
+
this.info = null;
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* A persisted (or, with graphql:adhoc, ad hoc) GraphQL query with a purpose the app was granted.
|
|
208
|
+
* Read-your-writes: after a mutation, the next calls send its consistency token, so they see it.
|
|
209
|
+
*/
|
|
210
|
+
async graphql(query, purpose) {
|
|
211
|
+
return this.request('POST', '/graphql', query, {
|
|
212
|
+
'kennra-purpose': purpose,
|
|
213
|
+
...(this.consistencyToken ? { [CONSISTENCY_HEADER]: this.consistencyToken } : {}),
|
|
214
|
+
}, (res) => this.rememberConsistency(res.headers.get(CONSISTENCY_HEADER)));
|
|
215
|
+
}
|
|
216
|
+
/** The newest consistency token this client has seen (null before its first write). */
|
|
217
|
+
get lastConsistencyToken() {
|
|
218
|
+
return this.consistencyToken;
|
|
219
|
+
}
|
|
220
|
+
rememberConsistency(token) {
|
|
221
|
+
if (!token || !/^\d+$/.test(token))
|
|
222
|
+
return;
|
|
223
|
+
if (!this.consistencyToken || Number(token) > Number(this.consistencyToken))
|
|
224
|
+
this.consistencyToken = token;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** One client per installation, sharing the app credentials. */
|
|
228
|
+
export class KennraAppClient {
|
|
229
|
+
opts;
|
|
230
|
+
clients = new Map();
|
|
231
|
+
constructor(opts) {
|
|
232
|
+
this.opts = opts;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The app's installations whose setup reported this provider organization
|
|
236
|
+
* (`completeSetup({ externalOrganization })`), newest setup first: for requests that reach the
|
|
237
|
+
* app without an installation (one command URL for every customer of a chat platform, say).
|
|
238
|
+
*/
|
|
239
|
+
async installationsFor(externalOrganization) {
|
|
240
|
+
const f = this.opts.fetch ?? ((...a) => fetch(...a));
|
|
241
|
+
const res = await f(`${this.opts.baseUrl.replace(/\/$/, '')}/apps/installations/lookup`, {
|
|
242
|
+
method: 'POST',
|
|
243
|
+
headers: { 'content-type': 'application/json' },
|
|
244
|
+
body: JSON.stringify({
|
|
245
|
+
client_id: this.opts.clientId,
|
|
246
|
+
client_secret: this.opts.clientSecret,
|
|
247
|
+
externalOrganization,
|
|
248
|
+
}),
|
|
249
|
+
});
|
|
250
|
+
const body = (await res.json().catch(() => ({})));
|
|
251
|
+
if (!res.ok || !body.installations)
|
|
252
|
+
throw new KennraApiError(res.status, body.error ?? `http_${res.status}`, body.message ?? res.statusText);
|
|
253
|
+
return body.installations;
|
|
254
|
+
}
|
|
255
|
+
forInstallation(installationId) {
|
|
256
|
+
let c = this.clients.get(installationId);
|
|
257
|
+
if (!c) {
|
|
258
|
+
c = new InstallationClient(this.opts, installationId);
|
|
259
|
+
this.clients.set(installationId, c);
|
|
260
|
+
}
|
|
261
|
+
return c;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hosted first-party apps (docs/15 §5.1): Kennra's own apps run together in one service, the app
|
|
3
|
+
* host (`apps/app-host`), each as a module under its own path (`<host URL>/<appId>/…`). A module
|
|
4
|
+
* is an ordinary Kennra app: the host gives it its own client credentials and its public URL, and
|
|
5
|
+
* it talks to Kennra only through the public API, like any partner's app.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* export const module: HostedAppModule = {
|
|
9
|
+
* id: 'example',
|
|
10
|
+
* create: ({ kennra, publicUrl }) => createApp({ manifest, kennra }).lookup(…),
|
|
11
|
+
* };
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
import type { RunningJob } from './app.js';
|
|
15
|
+
import type { KennraClientOptions } from './client.js';
|
|
16
|
+
export interface HostedAppOptions {
|
|
17
|
+
/** Kennra's public API and the app's own client credentials (client id = the app id). */
|
|
18
|
+
kennra: KennraClientOptions;
|
|
19
|
+
/** Where the internet reaches this app, e.g. `https://apps.kennra.com/<appId>` (null when unknown). */
|
|
20
|
+
publicUrl: string | null;
|
|
21
|
+
/** The host's environment, for the module's own settings (e.g. a provider's OAuth client). */
|
|
22
|
+
env: Record<string, string | undefined>;
|
|
23
|
+
}
|
|
24
|
+
export interface HostedApp {
|
|
25
|
+
/** The app's handler; requests arrive with the URL the caller used, under `publicUrl`. */
|
|
26
|
+
fetch(req: Request): Promise<Response>;
|
|
27
|
+
/** Waits for the app's background work (shutdown, tests). */
|
|
28
|
+
idle?(): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Graceful shutdown: refuse new ticks and fire every handler's `ctx.signal`, so running work
|
|
31
|
+
* saves its cursor and reports `interrupted`. A `KennraApp` has it.
|
|
32
|
+
*/
|
|
33
|
+
stop?(): void;
|
|
34
|
+
/** The schedule runs in progress (the host's `/healthz`). A `KennraApp` has it. */
|
|
35
|
+
runs?(): RunningJob[];
|
|
36
|
+
}
|
|
37
|
+
export interface HostedAppModule {
|
|
38
|
+
/** The app id of the manifest; also the module's path on the host. */
|
|
39
|
+
id: string;
|
|
40
|
+
create(opts: HostedAppOptions): HostedApp;
|
|
41
|
+
/**
|
|
42
|
+
* What the module needs from the host's environment besides its client secret: the names that
|
|
43
|
+
* are missing. A module with any missing is not mounted (`not_configured`), like one without a
|
|
44
|
+
* client secret. Default: nothing more.
|
|
45
|
+
*/
|
|
46
|
+
missing?(env: Record<string, string | undefined>): string[];
|
|
47
|
+
/**
|
|
48
|
+
* Isolation on a shared host: at most `concurrency` requests in flight (more get 503), each
|
|
49
|
+
* answered within `timeoutMs` (else 504). Defaults: 32 and 30 s. Background work started by a
|
|
50
|
+
* request is the app's to bound (e.g. one backfill per installation).
|
|
51
|
+
*/
|
|
52
|
+
limits?: {
|
|
53
|
+
concurrency?: number;
|
|
54
|
+
timeoutMs?: number;
|
|
55
|
+
};
|
|
56
|
+
}
|
package/dist/hosting.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@kennra/app-sdk` (docs/15 §6): build Kennra apps. Web-standard Request/Response; runs on Node,
|
|
3
|
+
* Bun, Deno, serverless functions and edge runtimes. Uses only Kennra's public API.
|
|
4
|
+
*/
|
|
5
|
+
import type { Fetch } from './protocol.js';
|
|
6
|
+
export * from './app.js';
|
|
7
|
+
export * from './client.js';
|
|
8
|
+
export type * from './hosting.js';
|
|
9
|
+
export * from './manifest.js';
|
|
10
|
+
export * from './operations.js';
|
|
11
|
+
export type * from './protocol.js';
|
|
12
|
+
export * from './signature.js';
|
|
13
|
+
/**
|
|
14
|
+
* Local development against `bun run dev` (dev servers only): registers the app version with a
|
|
15
|
+
* base URL pointing at the app's own server and returns the client credentials. The workspace
|
|
16
|
+
* admin then installs it on the consent screen (or `kennra apps install`).
|
|
17
|
+
*/
|
|
18
|
+
export declare function registerWithDevServer(opts: {
|
|
19
|
+
kennraUrl: string;
|
|
20
|
+
manifest: unknown;
|
|
21
|
+
baseUrl: string;
|
|
22
|
+
clientSecret?: string;
|
|
23
|
+
fetch?: Fetch;
|
|
24
|
+
}): Promise<{
|
|
25
|
+
appId: string;
|
|
26
|
+
version: string;
|
|
27
|
+
clientId: string;
|
|
28
|
+
clientSecret: string;
|
|
29
|
+
}>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export * from "./app.js";
|
|
2
|
+
export * from "./client.js";
|
|
3
|
+
export * from "./manifest.js";
|
|
4
|
+
export * from "./operations.js";
|
|
5
|
+
export * from "./signature.js";
|
|
6
|
+
/**
|
|
7
|
+
* Local development against `bun run dev` (dev servers only): registers the app version with a
|
|
8
|
+
* base URL pointing at the app's own server and returns the client credentials. The workspace
|
|
9
|
+
* admin then installs it on the consent screen (or `kennra apps install`).
|
|
10
|
+
*/
|
|
11
|
+
export async function registerWithDevServer(opts) {
|
|
12
|
+
const f = opts.fetch ?? fetch;
|
|
13
|
+
const res = await f(`${opts.kennraUrl.replace(/\/$/, '')}/dev/apps/register`, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
headers: { 'content-type': 'application/json' },
|
|
16
|
+
body: JSON.stringify({
|
|
17
|
+
manifest: opts.manifest,
|
|
18
|
+
baseUrl: opts.baseUrl,
|
|
19
|
+
...(opts.clientSecret ? { clientSecret: opts.clientSecret } : {}),
|
|
20
|
+
}),
|
|
21
|
+
});
|
|
22
|
+
const body = (await res.json());
|
|
23
|
+
if (!res.ok || !body.appId)
|
|
24
|
+
throw new Error(`Registering the app failed: ${body.error ?? res.status} ${JSON.stringify(body.problems ?? '')}`);
|
|
25
|
+
return {
|
|
26
|
+
appId: body.appId,
|
|
27
|
+
version: body.version,
|
|
28
|
+
clientId: body.appId,
|
|
29
|
+
clientSecret: body.clientSecret,
|
|
30
|
+
};
|
|
31
|
+
}
|