@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/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/addresses.d.ts +12 -0
- package/dist/addresses.js +105 -0
- package/dist/admin-links.d.ts +17 -0
- package/dist/admin-links.js +22 -0
- package/dist/app.d.ts +190 -0
- package/dist/app.js +448 -0
- package/dist/capture-backfill.d.ts +95 -0
- package/dist/capture-backfill.js +198 -0
- package/dist/capture.d.ts +110 -0
- package/dist/capture.js +321 -0
- package/dist/client.d.ts +172 -0
- package/dist/client.js +300 -0
- package/dist/hosting.d.ts +56 -0
- package/dist/hosting.js +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +32 -0
- package/dist/manifest.d.ts +618 -0
- package/dist/manifest.js +1094 -0
- package/dist/operations.d.ts +8 -0
- package/dist/operations.js +9 -0
- package/dist/protocol.d.ts +1105 -0
- package/dist/protocol.js +5 -0
- package/dist/signature.d.ts +69 -0
- package/dist/signature.js +108 -0
- package/dist/testing.d.ts +80 -0
- package/dist/testing.js +226 -0
- package/package.json +81 -7
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { CaptureBackfillReport, CaptureBackfillRequest, ConsentChangeInput, DocumentLinkRequest, DocumentLinkResult, 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
|
+
* Historical changes (`historical: true`, a list moved from another tool) may be older than 30
|
|
85
|
+
* days: a grant needs `kennra:consent:import` and `evidence`, and never wins over a newer
|
|
86
|
+
* withdrawal (`NEWER_WITHDRAWAL_WINS`). Their key is per person too
|
|
87
|
+
* (`consent-import:<person>:<purpose>:<channel>:<externalRef>`), and a batch of only historical
|
|
88
|
+
* changes goes in the import lane.
|
|
89
|
+
*/
|
|
90
|
+
recordConsentChanges(changes: ConsentChangeInput[]): Promise<IngestResponse['results']>;
|
|
91
|
+
/**
|
|
92
|
+
* Engagement signals (docs/15 §4.11): kept as aggregates per person and channel, deduplicated by
|
|
93
|
+
* `eventId` (also the idempotency key). `purpose` is the grant's purpose for
|
|
94
|
+
* `kennra:engagement:write` (default the first granted).
|
|
95
|
+
*/
|
|
96
|
+
recordEngagement(signals: EngagementSignalInput[], opts?: {
|
|
97
|
+
purpose?: string;
|
|
98
|
+
}): Promise<IngestResponse['results']>;
|
|
99
|
+
/**
|
|
100
|
+
* Reports a run's outcome, or with status `running` its heartbeat and progress. The answer says
|
|
101
|
+
* the run's status in Kennra: `abandoned` when its lease ran out (stop; the report is kept as
|
|
102
|
+
* information only).
|
|
103
|
+
*/
|
|
104
|
+
reportRun(report: SyncRunReport): Promise<SyncRunAck>;
|
|
105
|
+
/**
|
|
106
|
+
* History backfill (capabilities.ingest.backfill): the people and companies whose history this
|
|
107
|
+
* installation has not finished looking for, oldest first, at most 20.
|
|
108
|
+
*/
|
|
109
|
+
captureBackfills(): Promise<CaptureBackfillRequest[]>;
|
|
110
|
+
/** Progress on a history backfill request (running, done or failed, with counters). */
|
|
111
|
+
reportCaptureBackfill(report: CaptureBackfillReport): Promise<void>;
|
|
112
|
+
reportUserConnection(report: UserConnectionReport): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
|
|
115
|
+
* provider scopes) and detected settings. The ticket names the admin; the core verifies it.
|
|
116
|
+
*/
|
|
117
|
+
/**
|
|
118
|
+
* Links documents a member picked on the app's picker page (docs/15 §4.13) to the record the
|
|
119
|
+
* ticket names, as that member. `transientText` is read for suggested terms and dropped.
|
|
120
|
+
*/
|
|
121
|
+
linkDocuments(req: DocumentLinkRequest): Promise<DocumentLinkResult>;
|
|
122
|
+
completeSetup(report: SetupReport): Promise<void>;
|
|
123
|
+
/** The installation's per-member connections, with status and share level (the core decides). */
|
|
124
|
+
userConnections(): Promise<{
|
|
125
|
+
userId: string;
|
|
126
|
+
connectionKey: string;
|
|
127
|
+
kind: string;
|
|
128
|
+
status: string;
|
|
129
|
+
shareLevel: string;
|
|
130
|
+
/** The last error the app reported for the connection (null once it synced again). */
|
|
131
|
+
error: string | null;
|
|
132
|
+
}[]>;
|
|
133
|
+
/** Secrets the app keeps in its installation store (e.g. a member's refresh token). Never shown to admins. */
|
|
134
|
+
readonly secrets: {
|
|
135
|
+
put: (key: string, value: string | null) => Promise<void>;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* A persisted (or, with graphql:adhoc, ad hoc) GraphQL query with a purpose the app was granted.
|
|
139
|
+
* Read-your-writes: after a mutation, the next calls send its consistency token, so they see it.
|
|
140
|
+
*/
|
|
141
|
+
graphql<T = Record<string, unknown>>(query: {
|
|
142
|
+
query?: string;
|
|
143
|
+
extensions?: Record<string, unknown>;
|
|
144
|
+
variables?: Record<string, unknown>;
|
|
145
|
+
}, purpose: string): Promise<{
|
|
146
|
+
data?: T;
|
|
147
|
+
errors?: {
|
|
148
|
+
message: string;
|
|
149
|
+
extensions?: Record<string, unknown>;
|
|
150
|
+
}[];
|
|
151
|
+
}>;
|
|
152
|
+
/** The newest consistency token this client has seen (null before its first write). */
|
|
153
|
+
get lastConsistencyToken(): string | null;
|
|
154
|
+
private rememberConsistency;
|
|
155
|
+
}
|
|
156
|
+
/** One client per installation, sharing the app credentials. */
|
|
157
|
+
export declare class KennraAppClient {
|
|
158
|
+
readonly opts: KennraClientOptions;
|
|
159
|
+
private readonly clients;
|
|
160
|
+
constructor(opts: KennraClientOptions);
|
|
161
|
+
/**
|
|
162
|
+
* The app's installations whose setup reported this provider organization
|
|
163
|
+
* (`completeSetup({ externalOrganization })`), newest setup first: for requests that reach the
|
|
164
|
+
* app without an installation (one command URL for every customer of a chat platform, say).
|
|
165
|
+
*/
|
|
166
|
+
installationsFor(externalOrganization: string): Promise<{
|
|
167
|
+
installationId: string;
|
|
168
|
+
workspace: string;
|
|
169
|
+
status: string;
|
|
170
|
+
}[]>;
|
|
171
|
+
forInstallation(installationId: string): InstallationClient;
|
|
172
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
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
|
+
* Historical changes (`historical: true`, a list moved from another tool) may be older than 30
|
|
143
|
+
* days: a grant needs `kennra:consent:import` and `evidence`, and never wins over a newer
|
|
144
|
+
* withdrawal (`NEWER_WITHDRAWAL_WINS`). Their key is per person too
|
|
145
|
+
* (`consent-import:<person>:<purpose>:<channel>:<externalRef>`), and a batch of only historical
|
|
146
|
+
* changes goes in the import lane.
|
|
147
|
+
*/
|
|
148
|
+
async recordConsentChanges(changes) {
|
|
149
|
+
const lane = changes.length && changes.every((c) => c.historical) ? 'import' : 'live';
|
|
150
|
+
return this.ingest(lane, changes.map((c) => ({
|
|
151
|
+
idempotencyKey: c.historical
|
|
152
|
+
? `consent-import:${personKey(c)}:${c.purpose}:${c.channel}:${c.externalRef}`
|
|
153
|
+
: `consent:${c.externalRef}:${c.purpose}:${c.channel}`,
|
|
154
|
+
purpose: c.purpose,
|
|
155
|
+
command: 'recordConsentChange',
|
|
156
|
+
input: c,
|
|
157
|
+
})));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Engagement signals (docs/15 §4.11): kept as aggregates per person and channel, deduplicated by
|
|
161
|
+
* `eventId` (also the idempotency key). `purpose` is the grant's purpose for
|
|
162
|
+
* `kennra:engagement:write` (default the first granted).
|
|
163
|
+
*/
|
|
164
|
+
async recordEngagement(signals, opts = {}) {
|
|
165
|
+
return this.ingest('live', signals.map((s) => ({
|
|
166
|
+
idempotencyKey: `engagement:${s.eventId}`,
|
|
167
|
+
...(opts.purpose ? { purpose: opts.purpose } : {}),
|
|
168
|
+
command: 'recordEngagement',
|
|
169
|
+
input: s,
|
|
170
|
+
})));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Reports a run's outcome, or with status `running` its heartbeat and progress. The answer says
|
|
174
|
+
* the run's status in Kennra: `abandoned` when its lease ran out (stop; the report is kept as
|
|
175
|
+
* information only).
|
|
176
|
+
*/
|
|
177
|
+
async reportRun(report) {
|
|
178
|
+
const r = await this.request('POST', '/apps/runs', report);
|
|
179
|
+
return { ok: true, runId: report.runId, status: 'unknown', ...(r ?? {}) };
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* History backfill (capabilities.ingest.backfill): the people and companies whose history this
|
|
183
|
+
* installation has not finished looking for, oldest first, at most 20.
|
|
184
|
+
*/
|
|
185
|
+
async captureBackfills() {
|
|
186
|
+
return (await this.request('GET', '/apps/capture-backfills'))
|
|
187
|
+
.backfills;
|
|
188
|
+
}
|
|
189
|
+
/** Progress on a history backfill request (running, done or failed, with counters). */
|
|
190
|
+
async reportCaptureBackfill(report) {
|
|
191
|
+
await this.request('POST', '/apps/capture-backfills/report', report);
|
|
192
|
+
}
|
|
193
|
+
async reportUserConnection(report) {
|
|
194
|
+
await this.request('POST', '/apps/user-connections', report);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
|
|
198
|
+
* provider scopes) and detected settings. The ticket names the admin; the core verifies it.
|
|
199
|
+
*/
|
|
200
|
+
/**
|
|
201
|
+
* Links documents a member picked on the app's picker page (docs/15 §4.13) to the record the
|
|
202
|
+
* ticket names, as that member. `transientText` is read for suggested terms and dropped.
|
|
203
|
+
*/
|
|
204
|
+
async linkDocuments(req) {
|
|
205
|
+
return this.request('POST', '/apps/documents/link', req);
|
|
206
|
+
}
|
|
207
|
+
async completeSetup(report) {
|
|
208
|
+
await this.request('POST', '/apps/installation/setup', report);
|
|
209
|
+
this.info = null;
|
|
210
|
+
}
|
|
211
|
+
/** The installation's per-member connections, with status and share level (the core decides). */
|
|
212
|
+
async userConnections() {
|
|
213
|
+
return (await this.request('GET', '/apps/user-connections')).connections;
|
|
214
|
+
}
|
|
215
|
+
/** Secrets the app keeps in its installation store (e.g. a member's refresh token). Never shown to admins. */
|
|
216
|
+
secrets = {
|
|
217
|
+
put: async (key, value) => {
|
|
218
|
+
await this.request('PUT', `/apps/installation/secrets/${encodeURIComponent(key)}`, { value });
|
|
219
|
+
this.info = null;
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* A persisted (or, with graphql:adhoc, ad hoc) GraphQL query with a purpose the app was granted.
|
|
224
|
+
* Read-your-writes: after a mutation, the next calls send its consistency token, so they see it.
|
|
225
|
+
*/
|
|
226
|
+
async graphql(query, purpose) {
|
|
227
|
+
return this.request('POST', '/graphql', query, {
|
|
228
|
+
'kennra-purpose': purpose,
|
|
229
|
+
...(this.consistencyToken ? { [CONSISTENCY_HEADER]: this.consistencyToken } : {}),
|
|
230
|
+
}, (res) => this.rememberConsistency(res.headers.get(CONSISTENCY_HEADER)));
|
|
231
|
+
}
|
|
232
|
+
/** The newest consistency token this client has seen (null before its first write). */
|
|
233
|
+
get lastConsistencyToken() {
|
|
234
|
+
return this.consistencyToken;
|
|
235
|
+
}
|
|
236
|
+
rememberConsistency(token) {
|
|
237
|
+
if (!token || !/^\d+$/.test(token))
|
|
238
|
+
return;
|
|
239
|
+
if (!this.consistencyToken || Number(token) > Number(this.consistencyToken))
|
|
240
|
+
this.consistencyToken = token;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** One client per installation, sharing the app credentials. */
|
|
244
|
+
export class KennraAppClient {
|
|
245
|
+
opts;
|
|
246
|
+
clients = new Map();
|
|
247
|
+
constructor(opts) {
|
|
248
|
+
this.opts = opts;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* The app's installations whose setup reported this provider organization
|
|
252
|
+
* (`completeSetup({ externalOrganization })`), newest setup first: for requests that reach the
|
|
253
|
+
* app without an installation (one command URL for every customer of a chat platform, say).
|
|
254
|
+
*/
|
|
255
|
+
async installationsFor(externalOrganization) {
|
|
256
|
+
const f = this.opts.fetch ?? ((...a) => fetch(...a));
|
|
257
|
+
const res = await f(`${this.opts.baseUrl.replace(/\/$/, '')}/apps/installations/lookup`, {
|
|
258
|
+
method: 'POST',
|
|
259
|
+
headers: { 'content-type': 'application/json' },
|
|
260
|
+
body: JSON.stringify({
|
|
261
|
+
client_id: this.opts.clientId,
|
|
262
|
+
client_secret: this.opts.clientSecret,
|
|
263
|
+
externalOrganization,
|
|
264
|
+
}),
|
|
265
|
+
});
|
|
266
|
+
const body = (await res.json().catch(() => ({})));
|
|
267
|
+
if (!res.ok || !body.installations)
|
|
268
|
+
throw new KennraApiError(res.status, body.error ?? `http_${res.status}`, body.message ?? res.statusText);
|
|
269
|
+
return body.installations;
|
|
270
|
+
}
|
|
271
|
+
forInstallation(installationId) {
|
|
272
|
+
let c = this.clients.get(installationId);
|
|
273
|
+
if (!c) {
|
|
274
|
+
c = new InstallationClient(this.opts, installationId);
|
|
275
|
+
this.clients.set(installationId, c);
|
|
276
|
+
}
|
|
277
|
+
return c;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* A short, stable key for the person a consent change is about (no address in the key itself):
|
|
282
|
+
* the party id, or a 64-bit hash (two FNV-1a passes) of the identifier.
|
|
283
|
+
*/
|
|
284
|
+
function personKey(ref) {
|
|
285
|
+
if ('partyId' in ref && ref.partyId)
|
|
286
|
+
return ref.partyId;
|
|
287
|
+
const id = 'identifier' in ref ? ref.identifier : null;
|
|
288
|
+
const text = id
|
|
289
|
+
? JSON.stringify([id.type, 'issuer' in id ? id.issuer : '', id.value.trim().toLowerCase()])
|
|
290
|
+
: '';
|
|
291
|
+
const fnv = (seed) => {
|
|
292
|
+
let h = seed;
|
|
293
|
+
for (let i = 0; i < text.length; i++) {
|
|
294
|
+
h ^= text.charCodeAt(i);
|
|
295
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
296
|
+
}
|
|
297
|
+
return h.toString(16).padStart(8, '0');
|
|
298
|
+
};
|
|
299
|
+
return `id-${fnv(0x811c9dc5)}${fnv(0x01000193)}`;
|
|
300
|
+
}
|
|
@@ -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,30 @@
|
|
|
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 './admin-links.js';
|
|
7
|
+
export * from './app.js';
|
|
8
|
+
export * from './client.js';
|
|
9
|
+
export type * from './hosting.js';
|
|
10
|
+
export * from './manifest.js';
|
|
11
|
+
export * from './operations.js';
|
|
12
|
+
export type * from './protocol.js';
|
|
13
|
+
export * from './signature.js';
|
|
14
|
+
/**
|
|
15
|
+
* Local development against `bun run dev` (dev servers only): registers the app version with a
|
|
16
|
+
* base URL pointing at the app's own server and returns the client credentials. The workspace
|
|
17
|
+
* admin then installs it on the consent screen (or `kennra apps install`).
|
|
18
|
+
*/
|
|
19
|
+
export declare function registerWithDevServer(opts: {
|
|
20
|
+
kennraUrl: string;
|
|
21
|
+
manifest: unknown;
|
|
22
|
+
baseUrl: string;
|
|
23
|
+
clientSecret?: string;
|
|
24
|
+
fetch?: Fetch;
|
|
25
|
+
}): Promise<{
|
|
26
|
+
appId: string;
|
|
27
|
+
version: string;
|
|
28
|
+
clientId: string;
|
|
29
|
+
clientSecret: string;
|
|
30
|
+
}>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export * from "./admin-links.js";
|
|
2
|
+
export * from "./app.js";
|
|
3
|
+
export * from "./client.js";
|
|
4
|
+
export * from "./manifest.js";
|
|
5
|
+
export * from "./operations.js";
|
|
6
|
+
export * from "./signature.js";
|
|
7
|
+
/**
|
|
8
|
+
* Local development against `bun run dev` (dev servers only): registers the app version with a
|
|
9
|
+
* base URL pointing at the app's own server and returns the client credentials. The workspace
|
|
10
|
+
* admin then installs it on the consent screen (or `kennra apps install`).
|
|
11
|
+
*/
|
|
12
|
+
export async function registerWithDevServer(opts) {
|
|
13
|
+
const f = opts.fetch ?? fetch;
|
|
14
|
+
const res = await f(`${opts.kennraUrl.replace(/\/$/, '')}/dev/apps/register`, {
|
|
15
|
+
method: 'POST',
|
|
16
|
+
headers: { 'content-type': 'application/json' },
|
|
17
|
+
body: JSON.stringify({
|
|
18
|
+
manifest: opts.manifest,
|
|
19
|
+
baseUrl: opts.baseUrl,
|
|
20
|
+
...(opts.clientSecret ? { clientSecret: opts.clientSecret } : {}),
|
|
21
|
+
}),
|
|
22
|
+
});
|
|
23
|
+
const body = (await res.json());
|
|
24
|
+
if (!res.ok || !body.appId)
|
|
25
|
+
throw new Error(`Registering the app failed: ${body.error ?? res.status} ${JSON.stringify(body.problems ?? '')}`);
|
|
26
|
+
return {
|
|
27
|
+
appId: body.appId,
|
|
28
|
+
version: body.version,
|
|
29
|
+
clientId: body.appId,
|
|
30
|
+
clientSecret: body.clientSecret,
|
|
31
|
+
};
|
|
32
|
+
}
|