@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/protocol.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard Webhooks signatures (https://www.standardwebhooks.com/), used both ways between the
|
|
3
|
+
* Kennra core and apps (docs/15 §3.3): every request Kennra sends an app (lifecycle, webhooks,
|
|
4
|
+
* lookups, schedule ticks) carries `webhook-id`, `webhook-timestamp` and `webhook-signature`
|
|
5
|
+
* (`v1,<base64 HMAC-SHA256 of "id.timestamp.body">`) with the installation's signing secret
|
|
6
|
+
* (`whsec_<base64>`), plus `kennra-installation`. Web Crypto only: runs on Node, Bun, Deno and
|
|
7
|
+
* edge runtimes.
|
|
8
|
+
*/
|
|
9
|
+
/** A new signing secret: `whsec_` + 32 random bytes in base64. */
|
|
10
|
+
export declare function generateSigningSecret(): string;
|
|
11
|
+
export interface SignedHeaders {
|
|
12
|
+
'webhook-id': string;
|
|
13
|
+
'webhook-timestamp': string;
|
|
14
|
+
'webhook-signature': string;
|
|
15
|
+
}
|
|
16
|
+
/** Signs a body. `id` is unique per message (retries reuse it); `timestamp` in seconds. */
|
|
17
|
+
export declare function sign(secret: string, body: string, opts?: {
|
|
18
|
+
id?: string;
|
|
19
|
+
timestamp?: number;
|
|
20
|
+
}): Promise<SignedHeaders>;
|
|
21
|
+
export declare class SignatureError extends Error {
|
|
22
|
+
readonly code: 'MISSING_HEADERS' | 'TIMESTAMP_OUT_OF_TOLERANCE' | 'INVALID_SIGNATURE';
|
|
23
|
+
constructor(code: 'MISSING_HEADERS' | 'TIMESTAMP_OUT_OF_TOLERANCE' | 'INVALID_SIGNATURE', message: string);
|
|
24
|
+
}
|
|
25
|
+
type HeaderSource = Headers | Record<string, string | undefined>;
|
|
26
|
+
/**
|
|
27
|
+
* Verifies a signed body against one or more secrets (rotation keeps the old one for 24 h).
|
|
28
|
+
* Throws SignatureError; the timestamp must be within `toleranceSeconds` (default 5 minutes).
|
|
29
|
+
*/
|
|
30
|
+
export declare function verify(secrets: string | readonly string[], body: string, headers: HeaderSource, opts?: {
|
|
31
|
+
toleranceSeconds?: number;
|
|
32
|
+
now?: number;
|
|
33
|
+
}): Promise<void>;
|
|
34
|
+
export interface ConnectTicket {
|
|
35
|
+
userId: string;
|
|
36
|
+
installationId: string;
|
|
37
|
+
workspace: string;
|
|
38
|
+
/** A connection kind (`calendar`, `mailbox`, `drive`), or `setup` for the app's setup flow. */
|
|
39
|
+
kind: string;
|
|
40
|
+
/** Where the app sends the person back in Kennra when done (set by Kennra, signed). */
|
|
41
|
+
returnTo?: string;
|
|
42
|
+
/** Setup only: also connect the admin's own account of this kind (they opted in). */
|
|
43
|
+
connect?: string;
|
|
44
|
+
/**
|
|
45
|
+
* `document_pick` tickets (docs/15 §4.13): the record the member links documents to, and the
|
|
46
|
+
* purpose they work under. The app passes the ticket back with what was picked.
|
|
47
|
+
*/
|
|
48
|
+
entityId?: string;
|
|
49
|
+
purpose?: string;
|
|
50
|
+
/** The member's connection key in the app for documents, when Kennra knows one (e.g. `drive:<address>`). */
|
|
51
|
+
connectionKey?: string;
|
|
52
|
+
/** Unique ticket id: apps accept a ticket once (single use, review M5). Added when signing. */
|
|
53
|
+
jti?: string;
|
|
54
|
+
/**
|
|
55
|
+
* SHA-256 (hex) of the person's lowercased work email, when Kennra knows it: the app checks that
|
|
56
|
+
* the provider account it gets back is that person's (review M5). A hash keeps the email out of URLs.
|
|
57
|
+
*/
|
|
58
|
+
emailSha256?: string;
|
|
59
|
+
/** The domain of that email: apps enforce the match only for accounts on the workspace's own domains. */
|
|
60
|
+
emailDomain?: string;
|
|
61
|
+
}
|
|
62
|
+
export declare function signConnectTicket(secret: string, t: ConnectTicket, now?: number): Promise<string>;
|
|
63
|
+
/** How long a connect ticket is valid, in seconds. */
|
|
64
|
+
export declare const CONNECT_TICKET_TTL_SECONDS = 900;
|
|
65
|
+
/** Verifies a connect ticket (valid for 15 minutes). Throws SignatureError. Single use is the app's job (`jti`). */
|
|
66
|
+
export declare function verifyConnectTicket(secrets: string | readonly string[], ticket: string): Promise<ConnectTicket>;
|
|
67
|
+
/** The installation a ticket names, without verifying it (to find which secret to verify with). */
|
|
68
|
+
export declare function connectTicketInstallation(ticket: string): string | null;
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard Webhooks signatures (https://www.standardwebhooks.com/), used both ways between the
|
|
3
|
+
* Kennra core and apps (docs/15 §3.3): every request Kennra sends an app (lifecycle, webhooks,
|
|
4
|
+
* lookups, schedule ticks) carries `webhook-id`, `webhook-timestamp` and `webhook-signature`
|
|
5
|
+
* (`v1,<base64 HMAC-SHA256 of "id.timestamp.body">`) with the installation's signing secret
|
|
6
|
+
* (`whsec_<base64>`), plus `kennra-installation`. Web Crypto only: runs on Node, Bun, Deno and
|
|
7
|
+
* edge runtimes.
|
|
8
|
+
*/
|
|
9
|
+
const enc = new TextEncoder();
|
|
10
|
+
function b64(bytes) {
|
|
11
|
+
const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
12
|
+
let s = '';
|
|
13
|
+
for (const c of u)
|
|
14
|
+
s += String.fromCharCode(c);
|
|
15
|
+
return btoa(s);
|
|
16
|
+
}
|
|
17
|
+
function unb64(s) {
|
|
18
|
+
const bin = atob(s);
|
|
19
|
+
const out = new Uint8Array(bin.length);
|
|
20
|
+
for (let i = 0; i < bin.length; i++)
|
|
21
|
+
out[i] = bin.charCodeAt(i);
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/** A new signing secret: `whsec_` + 32 random bytes in base64. */
|
|
25
|
+
export function generateSigningSecret() {
|
|
26
|
+
return `whsec_${b64(crypto.getRandomValues(new Uint8Array(32)))}`;
|
|
27
|
+
}
|
|
28
|
+
async function hmac(secret, content) {
|
|
29
|
+
const key = await crypto.subtle.importKey('raw', unb64(secret.startsWith('whsec_') ? secret.slice(6) : secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
30
|
+
return b64(await crypto.subtle.sign('HMAC', key, enc.encode(content)));
|
|
31
|
+
}
|
|
32
|
+
/** Signs a body. `id` is unique per message (retries reuse it); `timestamp` in seconds. */
|
|
33
|
+
export async function sign(secret, body, opts = {}) {
|
|
34
|
+
const id = opts.id ?? `msg_${crypto.randomUUID()}`;
|
|
35
|
+
const ts = String(opts.timestamp ?? Math.floor(Date.now() / 1000));
|
|
36
|
+
return {
|
|
37
|
+
'webhook-id': id,
|
|
38
|
+
'webhook-timestamp': ts,
|
|
39
|
+
'webhook-signature': `v1,${await hmac(secret, `${id}.${ts}.${body}`)}`,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export class SignatureError extends Error {
|
|
43
|
+
code;
|
|
44
|
+
constructor(code, message) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.code = code;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function equal(a, b) {
|
|
50
|
+
if (a.length !== b.length)
|
|
51
|
+
return false;
|
|
52
|
+
let d = 0;
|
|
53
|
+
for (let i = 0; i < a.length; i++)
|
|
54
|
+
d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
55
|
+
return d === 0;
|
|
56
|
+
}
|
|
57
|
+
const header = (h, name) => h instanceof Headers ? (h.get(name) ?? undefined) : (h[name] ?? h[name.toLowerCase()]);
|
|
58
|
+
/**
|
|
59
|
+
* Verifies a signed body against one or more secrets (rotation keeps the old one for 24 h).
|
|
60
|
+
* Throws SignatureError; the timestamp must be within `toleranceSeconds` (default 5 minutes).
|
|
61
|
+
*/
|
|
62
|
+
export async function verify(secrets, body, headers, opts = {}) {
|
|
63
|
+
const id = header(headers, 'webhook-id');
|
|
64
|
+
const ts = header(headers, 'webhook-timestamp');
|
|
65
|
+
const sig = header(headers, 'webhook-signature');
|
|
66
|
+
if (!id || !ts || !sig)
|
|
67
|
+
throw new SignatureError('MISSING_HEADERS', 'Missing webhook-id, webhook-timestamp or webhook-signature');
|
|
68
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
69
|
+
if (Math.abs(now - Number(ts)) > (opts.toleranceSeconds ?? 300))
|
|
70
|
+
throw new SignatureError('TIMESTAMP_OUT_OF_TOLERANCE', 'The request is too old or from the future');
|
|
71
|
+
const given = sig.split(' ').flatMap((s) => (s.startsWith('v1,') ? [s.slice(3)] : []));
|
|
72
|
+
for (const secret of typeof secrets === 'string' ? [secrets] : secrets) {
|
|
73
|
+
const expected = await hmac(secret, `${id}.${ts}.${body}`);
|
|
74
|
+
if (given.some((g) => equal(g, expected)))
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
throw new SignatureError('INVALID_SIGNATURE', 'The signature does not match');
|
|
78
|
+
}
|
|
79
|
+
const b64url = (s) => btoa(unescape(encodeURIComponent(s)))
|
|
80
|
+
.replace(/\+/g, '-')
|
|
81
|
+
.replace(/\//g, '_')
|
|
82
|
+
.replace(/=+$/, '');
|
|
83
|
+
const unb64url = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));
|
|
84
|
+
export async function signConnectTicket(secret, t, now = Math.floor(Date.now() / 1000)) {
|
|
85
|
+
const payload = JSON.stringify({ ...t, jti: t.jti ?? crypto.randomUUID() });
|
|
86
|
+
const h = await sign(secret, payload, { id: 'connect', timestamp: now });
|
|
87
|
+
return `${b64url(payload)}.${now}.${h['webhook-signature'].slice(3)}`;
|
|
88
|
+
}
|
|
89
|
+
/** How long a connect ticket is valid, in seconds. */
|
|
90
|
+
export const CONNECT_TICKET_TTL_SECONDS = 900;
|
|
91
|
+
/** Verifies a connect ticket (valid for 15 minutes). Throws SignatureError. Single use is the app's job (`jti`). */
|
|
92
|
+
export async function verifyConnectTicket(secrets, ticket) {
|
|
93
|
+
const [p, ts, sig] = ticket.split('.');
|
|
94
|
+
if (!p || !ts || !sig)
|
|
95
|
+
throw new SignatureError('MISSING_HEADERS', 'Malformed connect ticket');
|
|
96
|
+
const payload = unb64url(p);
|
|
97
|
+
await verify(secrets, payload, { 'webhook-id': 'connect', 'webhook-timestamp': ts, 'webhook-signature': `v1,${sig}` }, { toleranceSeconds: CONNECT_TICKET_TTL_SECONDS });
|
|
98
|
+
return JSON.parse(payload);
|
|
99
|
+
}
|
|
100
|
+
/** The installation a ticket names, without verifying it (to find which secret to verify with). */
|
|
101
|
+
export function connectTicketInstallation(ticket) {
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(unb64url(ticket.split('.')[0] ?? '')).installationId ?? null;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@kennra/app-sdk/testing`: test an app without a Kennra server.
|
|
3
|
+
*
|
|
4
|
+
* - `FakeKennra`: an in-memory Kennra that issues installation tokens, serves the installation
|
|
5
|
+
* store, records ingest items, runs and connection reports, and sends signed requests to the app
|
|
6
|
+
* (lookups, schedule ticks, lifecycle, webhooks) exactly as the core does.
|
|
7
|
+
* - `recordedFetch`: replays recorded HTTP fixtures of a source API (no network in CI).
|
|
8
|
+
* - `conformance`: the checks a listed app must pass (signatures, idempotent replay, error mapping).
|
|
9
|
+
*/
|
|
10
|
+
import type { KennraApp } from './app.js';
|
|
11
|
+
import type { Fetch, IngestItem, IngestItemResult, LifecycleEvent, LookupRequest, SyncRunReport, UserConnectionReport } from './protocol.js';
|
|
12
|
+
export interface FakeInstallation {
|
|
13
|
+
installationId: string;
|
|
14
|
+
workspace: string;
|
|
15
|
+
settings?: Record<string, unknown>;
|
|
16
|
+
secrets?: Record<string, string>;
|
|
17
|
+
grant?: {
|
|
18
|
+
scope: string;
|
|
19
|
+
purposes: string[];
|
|
20
|
+
}[];
|
|
21
|
+
}
|
|
22
|
+
export declare class FakeKennra {
|
|
23
|
+
readonly app: KennraApp;
|
|
24
|
+
readonly baseUrl = "http://kennra.test";
|
|
25
|
+
readonly clientId: string;
|
|
26
|
+
readonly clientSecret = "kas_fake";
|
|
27
|
+
readonly ingested: (IngestItem & {
|
|
28
|
+
lane: string;
|
|
29
|
+
installationId: string;
|
|
30
|
+
})[];
|
|
31
|
+
/** Runs' outcomes (heartbeats, status `running`, are in `heartbeats`). */
|
|
32
|
+
readonly runs: SyncRunReport[];
|
|
33
|
+
readonly heartbeats: SyncRunReport[];
|
|
34
|
+
/** Runs Kennra gave up (their lease ran out): a heartbeat is answered `abandoned`. */
|
|
35
|
+
readonly abandoned: Set<string>;
|
|
36
|
+
readonly connections: UserConnectionReport[];
|
|
37
|
+
readonly state: Map<string, unknown>;
|
|
38
|
+
private readonly installs;
|
|
39
|
+
private readonly seenKeys;
|
|
40
|
+
/** Answer an ingest item yourself (default: ok, outcome `created`, replay on a repeated key). */
|
|
41
|
+
onIngest: (item: IngestItem) => Partial<IngestItemResult>;
|
|
42
|
+
constructor(app: KennraApp);
|
|
43
|
+
install(i: FakeInstallation): this;
|
|
44
|
+
/** The `fetch` the app's Kennra client uses (pass it as `kennra.fetch`). */
|
|
45
|
+
fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
46
|
+
private url;
|
|
47
|
+
/** Sends a signed request to the app, as the core does. `tamper` breaks the signature. */
|
|
48
|
+
send(installationId: string, path: string, body: unknown, opts?: {
|
|
49
|
+
tamper?: boolean;
|
|
50
|
+
}): Promise<Response>;
|
|
51
|
+
lookup(installationId: string, object: string, ref: string, extra?: Partial<LookupRequest>): Promise<Response>;
|
|
52
|
+
tick(installationId: string, scheduleId: string, opts?: {
|
|
53
|
+
runId?: string;
|
|
54
|
+
maxRunSeconds?: number;
|
|
55
|
+
wait?: boolean;
|
|
56
|
+
}): Promise<Response>;
|
|
57
|
+
lifecycle(installationId: string, type: LifecycleEvent['type']): Promise<Response>;
|
|
58
|
+
event(installationId: string, type: string, data: Record<string, unknown>): Promise<Response>;
|
|
59
|
+
}
|
|
60
|
+
/** A recorded HTTP exchange of a source API. */
|
|
61
|
+
export interface RecordedExchange {
|
|
62
|
+
method?: string;
|
|
63
|
+
/** Exact URL, or a prefix ending in `*`. */
|
|
64
|
+
url: string;
|
|
65
|
+
/** For POST bodies: a substring the request body must contain (e.g. a GraphQL operation name). */
|
|
66
|
+
bodyIncludes?: string;
|
|
67
|
+
status?: number;
|
|
68
|
+
body: unknown;
|
|
69
|
+
}
|
|
70
|
+
/** A fetch that answers from recorded exchanges and fails loudly on anything unrecorded. */
|
|
71
|
+
export declare function recordedFetch(exchanges: readonly RecordedExchange[]): Fetch & {
|
|
72
|
+
calls: string[];
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* The conformance checks a listed app must pass (docs/15 §6.1): requests without a valid
|
|
76
|
+
* signature are refused, lookups map not-found to 404, and health answers. Returns failures.
|
|
77
|
+
*/
|
|
78
|
+
export declare function conformance(fake: FakeKennra, installationId: string): Promise<string[]>;
|
|
79
|
+
export { createApp } from './app.js';
|
|
80
|
+
export { validateManifest } from './manifest.js';
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { generateSigningSecret, sign } from "./signature.js";
|
|
2
|
+
export class FakeKennra {
|
|
3
|
+
app;
|
|
4
|
+
baseUrl = 'http://kennra.test';
|
|
5
|
+
clientId;
|
|
6
|
+
clientSecret = 'kas_fake';
|
|
7
|
+
ingested = [];
|
|
8
|
+
/** Runs' outcomes (heartbeats, status `running`, are in `heartbeats`). */
|
|
9
|
+
runs = [];
|
|
10
|
+
heartbeats = [];
|
|
11
|
+
/** Runs Kennra gave up (their lease ran out): a heartbeat is answered `abandoned`. */
|
|
12
|
+
abandoned = new Set();
|
|
13
|
+
connections = [];
|
|
14
|
+
state = new Map();
|
|
15
|
+
installs = new Map();
|
|
16
|
+
seenKeys = new Map();
|
|
17
|
+
/** Answer an ingest item yourself (default: ok, outcome `created`, replay on a repeated key). */
|
|
18
|
+
onIngest = () => ({ outcome: 'created' });
|
|
19
|
+
constructor(app) {
|
|
20
|
+
this.app = app;
|
|
21
|
+
this.clientId = app.manifest.id;
|
|
22
|
+
}
|
|
23
|
+
install(i) {
|
|
24
|
+
this.installs.set(i.installationId, { ...i, signingSecret: generateSigningSecret() });
|
|
25
|
+
return this;
|
|
26
|
+
}
|
|
27
|
+
/** The `fetch` the app's Kennra client uses (pass it as `kennra.fetch`). */
|
|
28
|
+
fetch = async (input, init) => {
|
|
29
|
+
const req = new Request(input, init);
|
|
30
|
+
const url = new URL(req.url);
|
|
31
|
+
const body = req.method === 'GET' ? null : (await req.json().catch(() => null));
|
|
32
|
+
if (url.pathname === '/apps/token') {
|
|
33
|
+
const inst = this.installs.get(String(body?.['installation']));
|
|
34
|
+
if (!inst || body?.['client_secret'] !== this.clientSecret)
|
|
35
|
+
return Response.json({ error: 'invalid_client' }, { status: 401 });
|
|
36
|
+
return Response.json({
|
|
37
|
+
access_token: `tok:${inst.installationId}`,
|
|
38
|
+
token_type: 'Bearer',
|
|
39
|
+
expires_in: 900,
|
|
40
|
+
workspace: inst.workspace,
|
|
41
|
+
installation: inst.installationId,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const inst = this.installs.get((req.headers.get('authorization') ?? '').replace('Bearer tok:', ''));
|
|
45
|
+
if (!inst)
|
|
46
|
+
return Response.json({ error: 'unauthenticated' }, { status: 401 });
|
|
47
|
+
if (url.pathname === '/apps/installation')
|
|
48
|
+
return Response.json({
|
|
49
|
+
installationId: inst.installationId,
|
|
50
|
+
workspace: inst.workspace,
|
|
51
|
+
app: { id: this.app.manifest.id, version: this.app.manifest.version },
|
|
52
|
+
status: 'active',
|
|
53
|
+
settings: inst.settings ?? {},
|
|
54
|
+
secrets: inst.secrets ?? {},
|
|
55
|
+
signingSecrets: [inst.signingSecret],
|
|
56
|
+
grant: {
|
|
57
|
+
scopes: inst.grant ??
|
|
58
|
+
this.app.manifest.access.scopes.map((s) => ({ scope: s.scope, purposes: s.purposes })),
|
|
59
|
+
piiLevel: this.app.manifest.access.piiLevel,
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
const stateKey = url.pathname.match(/^\/apps\/installation\/state\/(.+)$/)?.[1];
|
|
63
|
+
if (stateKey) {
|
|
64
|
+
const k = `${inst.installationId}|${decodeURIComponent(stateKey)}`;
|
|
65
|
+
if (req.method === 'PUT')
|
|
66
|
+
this.state.set(k, body?.['value'] ?? null);
|
|
67
|
+
return Response.json({ key: stateKey, value: this.state.get(k) ?? null });
|
|
68
|
+
}
|
|
69
|
+
if (url.pathname === '/ingest') {
|
|
70
|
+
const lane = String(body?.['lane'] ?? 'live');
|
|
71
|
+
const results = (body?.['items'] ?? []).map((item) => {
|
|
72
|
+
const key = `${inst.installationId}|${item.idempotencyKey}`;
|
|
73
|
+
const prior = this.seenKeys.get(key);
|
|
74
|
+
if (prior)
|
|
75
|
+
return {
|
|
76
|
+
...prior,
|
|
77
|
+
replay: true,
|
|
78
|
+
outcome: item.command === 'recordMirroredFact' ? 'unchanged' : prior.outcome,
|
|
79
|
+
};
|
|
80
|
+
this.ingested.push({ ...item, lane, installationId: inst.installationId });
|
|
81
|
+
const r = { idempotencyKey: item.idempotencyKey, ok: true, ...this.onIngest(item) };
|
|
82
|
+
this.seenKeys.set(key, r);
|
|
83
|
+
return r;
|
|
84
|
+
});
|
|
85
|
+
return Response.json({ batchId: `batch_${this.ingested.length}`, lane, results });
|
|
86
|
+
}
|
|
87
|
+
if (url.pathname === '/apps/runs') {
|
|
88
|
+
const r = body;
|
|
89
|
+
if (r.status === 'running')
|
|
90
|
+
this.heartbeats.push(r);
|
|
91
|
+
else
|
|
92
|
+
this.runs.push(r);
|
|
93
|
+
const status = this.abandoned.has(r.runId) ? 'abandoned' : r.status;
|
|
94
|
+
return Response.json({ ok: true, runId: r.runId, status });
|
|
95
|
+
}
|
|
96
|
+
if (url.pathname === '/apps/user-connections') {
|
|
97
|
+
this.connections.push(body);
|
|
98
|
+
return Response.json({ ok: true });
|
|
99
|
+
}
|
|
100
|
+
return Response.json({ error: 'not_found' }, { status: 404 });
|
|
101
|
+
};
|
|
102
|
+
url(path) {
|
|
103
|
+
return /^https?:\/\//.test(path) ? path : `http://app.test${path.startsWith('/') ? path : `/${path}`}`;
|
|
104
|
+
}
|
|
105
|
+
/** Sends a signed request to the app, as the core does. `tamper` breaks the signature. */
|
|
106
|
+
async send(installationId, path, body, opts = {}) {
|
|
107
|
+
const inst = this.installs.get(installationId);
|
|
108
|
+
if (!inst)
|
|
109
|
+
throw new Error(`No fake installation ${installationId}`);
|
|
110
|
+
const text = JSON.stringify(body);
|
|
111
|
+
const headers = await sign(opts.tamper ? generateSigningSecret() : inst.signingSecret, text);
|
|
112
|
+
return this.app.fetch(new Request(this.url(path), {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
headers: { 'content-type': 'application/json', 'kennra-installation': installationId, ...headers },
|
|
115
|
+
body: text,
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
async lookup(installationId, object, ref, extra = {}) {
|
|
119
|
+
const decl = this.app.manifest.capabilities.lookups.find((l) => l.object === object);
|
|
120
|
+
if (!decl)
|
|
121
|
+
throw new Error(`No lookup ${object}`);
|
|
122
|
+
const inst = this.installs.get(installationId);
|
|
123
|
+
const req = {
|
|
124
|
+
type: 'lookup',
|
|
125
|
+
object,
|
|
126
|
+
ref,
|
|
127
|
+
installationId,
|
|
128
|
+
workspace: inst.workspace,
|
|
129
|
+
purposeClass: decl.purposes[0],
|
|
130
|
+
requestedBy: { type: 'human', pseudonym: 'u_test' },
|
|
131
|
+
deadline: new Date(Date.now() + decl.timeoutMs).toISOString(),
|
|
132
|
+
...extra,
|
|
133
|
+
};
|
|
134
|
+
return this.send(installationId, decl.url, req);
|
|
135
|
+
}
|
|
136
|
+
async tick(installationId, scheduleId, opts = {}) {
|
|
137
|
+
const s = this.app.manifest.capabilities.schedules.find((x) => x.id === scheduleId);
|
|
138
|
+
if (!s)
|
|
139
|
+
throw new Error(`No schedule ${scheduleId}`);
|
|
140
|
+
const tick = {
|
|
141
|
+
type: 'schedule.tick',
|
|
142
|
+
scheduleId,
|
|
143
|
+
runId: opts.runId ?? `run_${this.runs.length + 1}`,
|
|
144
|
+
lane: s.lane,
|
|
145
|
+
installationId,
|
|
146
|
+
workspace: this.installs.get(installationId).workspace,
|
|
147
|
+
...(opts.maxRunSeconds ? { maxRunSeconds: opts.maxRunSeconds } : {}),
|
|
148
|
+
};
|
|
149
|
+
const res = await this.send(installationId, s.url, tick);
|
|
150
|
+
if (opts.wait !== false)
|
|
151
|
+
await this.app.idle();
|
|
152
|
+
return res;
|
|
153
|
+
}
|
|
154
|
+
async lifecycle(installationId, type) {
|
|
155
|
+
const url = this.app.manifest.capabilities.lifecycle?.url;
|
|
156
|
+
if (!url)
|
|
157
|
+
throw new Error('No lifecycle URL');
|
|
158
|
+
return this.send(installationId, url, {
|
|
159
|
+
type,
|
|
160
|
+
installationId,
|
|
161
|
+
workspace: this.installs.get(installationId).workspace,
|
|
162
|
+
appId: this.app.manifest.id,
|
|
163
|
+
appVersion: this.app.manifest.version,
|
|
164
|
+
at: new Date().toISOString(),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async event(installationId, type, data) {
|
|
168
|
+
const url = this.app.manifest.capabilities.webhooks?.url;
|
|
169
|
+
if (!url)
|
|
170
|
+
throw new Error('No webhook URL');
|
|
171
|
+
const ws = this.installs.get(installationId).workspace;
|
|
172
|
+
return this.send(installationId, url, {
|
|
173
|
+
specversion: '1.0',
|
|
174
|
+
id: crypto.randomUUID(),
|
|
175
|
+
type,
|
|
176
|
+
source: `kennra:${ws}`,
|
|
177
|
+
time: new Date().toISOString(),
|
|
178
|
+
installationId,
|
|
179
|
+
workspace: ws,
|
|
180
|
+
data,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** A fetch that answers from recorded exchanges and fails loudly on anything unrecorded. */
|
|
185
|
+
export function recordedFetch(exchanges) {
|
|
186
|
+
const calls = [];
|
|
187
|
+
const f = (async (input, init) => {
|
|
188
|
+
const req = new Request(input, init);
|
|
189
|
+
const body = req.method === 'GET' ? '' : await req.text();
|
|
190
|
+
calls.push(`${req.method} ${req.url}`);
|
|
191
|
+
const hit = exchanges.find((x) => (x.method ?? 'GET') === req.method &&
|
|
192
|
+
(x.url.endsWith('*') ? req.url.startsWith(x.url.slice(0, -1)) : req.url === x.url) &&
|
|
193
|
+
(!x.bodyIncludes || body.includes(x.bodyIncludes)));
|
|
194
|
+
if (!hit)
|
|
195
|
+
throw new Error(`No recorded exchange for ${req.method} ${req.url}`);
|
|
196
|
+
return Response.json(hit.body, { status: hit.status ?? 200 });
|
|
197
|
+
});
|
|
198
|
+
f.calls = calls;
|
|
199
|
+
return f;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* The conformance checks a listed app must pass (docs/15 §6.1): requests without a valid
|
|
203
|
+
* signature are refused, lookups map not-found to 404, and health answers. Returns failures.
|
|
204
|
+
*/
|
|
205
|
+
export async function conformance(fake, installationId) {
|
|
206
|
+
const failures = [];
|
|
207
|
+
const m = fake.app.manifest;
|
|
208
|
+
for (const l of m.capabilities.lookups) {
|
|
209
|
+
const tampered = await fake.send(installationId, l.url, { type: 'lookup', object: l.object, ref: 'x' }, { tamper: true });
|
|
210
|
+
if (tampered.status !== 401)
|
|
211
|
+
failures.push(`lookup ${l.object} accepted a bad signature (${tampered.status})`);
|
|
212
|
+
}
|
|
213
|
+
for (const s of m.capabilities.schedules) {
|
|
214
|
+
const tampered = await fake.send(installationId, s.url, { type: 'schedule.tick', scheduleId: s.id }, { tamper: true });
|
|
215
|
+
if (tampered.status !== 401)
|
|
216
|
+
failures.push(`schedule ${s.id} accepted a bad signature (${tampered.status})`);
|
|
217
|
+
}
|
|
218
|
+
if (m.health) {
|
|
219
|
+
const res = await fake.app.fetch(new Request(`http://app.test${new URL(m.health.url, 'http://x').pathname}`));
|
|
220
|
+
if (!res.ok)
|
|
221
|
+
failures.push(`health answered ${res.status}`);
|
|
222
|
+
}
|
|
223
|
+
return failures;
|
|
224
|
+
}
|
|
225
|
+
export { createApp } from "./app.js";
|
|
226
|
+
export { validateManifest } from "./manifest.js";
|
package/package.json
CHANGED
|
@@ -1,16 +1,90 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kennra/app-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Build Kennra apps: manifest types and validation, installation tokens, ingest helpers, signed lookups, schedules and webhooks, and a test harness. Web-standard Request/Response.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"kennra",
|
|
7
|
+
"kennra-app",
|
|
8
|
+
"sdk",
|
|
9
|
+
"apps",
|
|
10
|
+
"crm",
|
|
11
|
+
"customer-memory",
|
|
12
|
+
"webhooks",
|
|
13
|
+
"integration"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://kennra.com/docs/apps",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://kennra.com/docs/apps",
|
|
18
|
+
"email": "support@kennra.com"
|
|
19
|
+
},
|
|
8
20
|
"repository": {
|
|
9
21
|
"type": "git",
|
|
10
|
-
"url": "git+https://github.com/CrystallizeAPI/kennra-monorepo.git"
|
|
22
|
+
"url": "git+https://github.com/CrystallizeAPI/kennra-monorepo.git",
|
|
23
|
+
"directory": "packages/app-sdk"
|
|
24
|
+
},
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"author": "Kennra AS",
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22",
|
|
31
|
+
"bun": ">=1.2"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"yaml": "^2.9.1",
|
|
35
|
+
"zod": "^4.1.0"
|
|
36
|
+
},
|
|
37
|
+
"main": "./dist/index.js",
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"exports": {
|
|
40
|
+
".": {
|
|
41
|
+
"types": "./dist/index.d.ts",
|
|
42
|
+
"default": "./dist/index.js"
|
|
43
|
+
},
|
|
44
|
+
"./manifest": {
|
|
45
|
+
"types": "./dist/manifest.d.ts",
|
|
46
|
+
"default": "./dist/manifest.js"
|
|
47
|
+
},
|
|
48
|
+
"./signature": {
|
|
49
|
+
"types": "./dist/signature.d.ts",
|
|
50
|
+
"default": "./dist/signature.js"
|
|
51
|
+
},
|
|
52
|
+
"./testing": {
|
|
53
|
+
"types": "./dist/testing.d.ts",
|
|
54
|
+
"default": "./dist/testing.js"
|
|
55
|
+
},
|
|
56
|
+
"./protocol": {
|
|
57
|
+
"types": "./dist/protocol.d.ts",
|
|
58
|
+
"default": "./dist/protocol.js"
|
|
59
|
+
},
|
|
60
|
+
"./operations": {
|
|
61
|
+
"types": "./dist/operations.d.ts",
|
|
62
|
+
"default": "./dist/operations.js"
|
|
63
|
+
},
|
|
64
|
+
"./hosting": {
|
|
65
|
+
"types": "./dist/hosting.d.ts",
|
|
66
|
+
"default": "./dist/hosting.js"
|
|
67
|
+
},
|
|
68
|
+
"./addresses": {
|
|
69
|
+
"types": "./dist/addresses.d.ts",
|
|
70
|
+
"default": "./dist/addresses.js"
|
|
71
|
+
},
|
|
72
|
+
"./admin-links": {
|
|
73
|
+
"types": "./dist/admin-links.d.ts",
|
|
74
|
+
"default": "./dist/admin-links.js"
|
|
75
|
+
},
|
|
76
|
+
"./capture": {
|
|
77
|
+
"types": "./dist/capture.d.ts",
|
|
78
|
+
"default": "./dist/capture.js"
|
|
79
|
+
},
|
|
80
|
+
"./capture-backfill": {
|
|
81
|
+
"types": "./dist/capture-backfill.d.ts",
|
|
82
|
+
"default": "./dist/capture-backfill.js"
|
|
83
|
+
},
|
|
84
|
+
"./package.json": "./package.json"
|
|
11
85
|
},
|
|
12
86
|
"files": [
|
|
13
|
-
"
|
|
87
|
+
"dist"
|
|
14
88
|
],
|
|
15
89
|
"publishConfig": {
|
|
16
90
|
"access": "public"
|