@midsummer-ai/sdk 0.1.0-staging.3335 → 0.1.0-staging.3338
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/apps.d.mts +63 -0
- package/apps.mjs +101 -0
- package/package.json +8 -1
package/apps.d.mts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
//#region src/apps.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* For an app teams install on Midsummer: check that an event or a runner job Midsummer posted is
|
|
4
|
+
* genuine, and act in an installation with a token that is renewed before it ends.
|
|
5
|
+
*
|
|
6
|
+
* import { InstalledApp, verifyEvent } from "@midsummer-ai/sdk/apps"
|
|
7
|
+
*
|
|
8
|
+
* // In your events handler, with the body exactly as it arrived:
|
|
9
|
+
* if (!(await verifyEvent(request.headers, body, process.env.MIDSUMMER_SIGNING_SECRET!))) return new Response(null, { status: 401 })
|
|
10
|
+
* const event = JSON.parse(body) as AppEvent
|
|
11
|
+
*
|
|
12
|
+
* const app = new InstalledApp({ id: "oapp_…", secret: process.env.MIDSUMMER_APP_SECRET! })
|
|
13
|
+
* await app.request(event.data.installation.id, "/v1/mr/acme/web/mr-12/checks/style", { method: "PUT", body: JSON.stringify({ candidateId, state: "running" }) })
|
|
14
|
+
*
|
|
15
|
+
* Events are signed as Standard Webhooks says, so any of its libraries checks them too.
|
|
16
|
+
*/
|
|
17
|
+
/** What Midsummer posts to an app: its `type`, when, and `data` with the installation it is for. */
|
|
18
|
+
interface AppEvent<Data extends Record<string, unknown> = Record<string, unknown>> {
|
|
19
|
+
readonly type: string;
|
|
20
|
+
readonly timestamp: string;
|
|
21
|
+
readonly data: Data & {
|
|
22
|
+
readonly installation: {
|
|
23
|
+
readonly id: string;
|
|
24
|
+
readonly team: string;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Whether a request Midsummer posted is genuine: signed with `secret` (`whsec_…`, shown when the
|
|
30
|
+
* app was registered) over its `webhook-id`, its `webhook-timestamp` and the body exactly as it
|
|
31
|
+
* arrived, and no older than five minutes. A rotated secret signs beside the one before for a day,
|
|
32
|
+
* so a request carries a signature from each, and either one passing is enough.
|
|
33
|
+
*/
|
|
34
|
+
declare function verifyEvent(headers: Headers | Readonly<Record<string, string | undefined>>, body: string, secret: string, now?: number): Promise<boolean>;
|
|
35
|
+
/**
|
|
36
|
+
* An app acting in the teams that installed it. Each installation's token is asked for with the
|
|
37
|
+
* app's id and secret, kept until a minute before it ends, and asked for again after; a team that
|
|
38
|
+
* removes the app ends its tokens at once, and its calls answer 401.
|
|
39
|
+
*/
|
|
40
|
+
declare class InstalledApp {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(options: {
|
|
43
|
+
readonly id: string;
|
|
44
|
+
readonly secret: string;
|
|
45
|
+
readonly origin?: string;
|
|
46
|
+
readonly fetch?: typeof fetch;
|
|
47
|
+
});
|
|
48
|
+
/** An installation's token (`msinst_…`), from the one kept while it has over a minute left. Throws when Midsummer refuses the app's secret or the installation. */
|
|
49
|
+
token(installationId: string, now?: number): Promise<string>;
|
|
50
|
+
/** A call to Midsummer's API as the app in one installation, such as `/v1/mr/acme/web/mr-12/comments`; JSON unless the body says otherwise. */
|
|
51
|
+
request(installationId: string, path: string, init?: RequestInit): Promise<Response>;
|
|
52
|
+
/** Trades the one-time code a manifest's app was made with for its id, secret and signing secret, shown this once. */
|
|
53
|
+
static fromManifestCode(code: string, options?: {
|
|
54
|
+
readonly origin?: string;
|
|
55
|
+
readonly fetch?: typeof fetch;
|
|
56
|
+
}): Promise<{
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly secret: string;
|
|
59
|
+
readonly signingSecret?: string;
|
|
60
|
+
}>;
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { AppEvent, InstalledApp, verifyEvent };
|
package/apps.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
//#region src/apps.ts
|
|
2
|
+
/** How old a signed event may be, and how far ahead of the clock: five minutes, as Standard Webhooks says. */
|
|
3
|
+
const TOLERANCE_SECONDS = 300;
|
|
4
|
+
/**
|
|
5
|
+
* Whether a request Midsummer posted is genuine: signed with `secret` (`whsec_…`, shown when the
|
|
6
|
+
* app was registered) over its `webhook-id`, its `webhook-timestamp` and the body exactly as it
|
|
7
|
+
* arrived, and no older than five minutes. A rotated secret signs beside the one before for a day,
|
|
8
|
+
* so a request carries a signature from each, and either one passing is enough.
|
|
9
|
+
*/
|
|
10
|
+
async function verifyEvent(headers, body, secret, now = Date.now()) {
|
|
11
|
+
const read = (name) => (headers instanceof Headers ? headers.get(name) : headers[name]) ?? void 0;
|
|
12
|
+
const id = read("webhook-id"), timestamp = read("webhook-timestamp"), signatures = read("webhook-signature");
|
|
13
|
+
if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
|
|
14
|
+
if (Math.abs(now / 1e3 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
|
|
15
|
+
const key = await crypto.subtle.importKey("raw", fromBase64(secret.replace(/^whsec_/, "")), {
|
|
16
|
+
name: "HMAC",
|
|
17
|
+
hash: "SHA-256"
|
|
18
|
+
}, false, ["sign"]);
|
|
19
|
+
const expected = toBase64(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`))));
|
|
20
|
+
return signatures.split(" ").some((entry) => {
|
|
21
|
+
const [version, signature] = entry.split(",");
|
|
22
|
+
return version === "v1" && signature !== void 0 && same(signature, expected);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* An app acting in the teams that installed it. Each installation's token is asked for with the
|
|
27
|
+
* app's id and secret, kept until a minute before it ends, and asked for again after; a team that
|
|
28
|
+
* removes the app ends its tokens at once, and its calls answer 401.
|
|
29
|
+
*/
|
|
30
|
+
var InstalledApp = class {
|
|
31
|
+
#id;
|
|
32
|
+
#secret;
|
|
33
|
+
#origin;
|
|
34
|
+
#fetch;
|
|
35
|
+
#tokens = /* @__PURE__ */ new Map();
|
|
36
|
+
constructor(options) {
|
|
37
|
+
this.#id = options.id;
|
|
38
|
+
this.#secret = options.secret;
|
|
39
|
+
this.#origin = (options.origin ?? "https://api.midsummer.new").replace(/\/+$/, "");
|
|
40
|
+
this.#fetch = options.fetch ?? fetch;
|
|
41
|
+
}
|
|
42
|
+
/** An installation's token (`msinst_…`), from the one kept while it has over a minute left. Throws when Midsummer refuses the app's secret or the installation. */
|
|
43
|
+
async token(installationId, now = Date.now()) {
|
|
44
|
+
const kept = this.#tokens.get(installationId);
|
|
45
|
+
if (kept && kept.until - 6e4 > now) return kept.token;
|
|
46
|
+
const response = await this.#fetch(`${this.#origin}/v1/oauth/token`, {
|
|
47
|
+
method: "POST",
|
|
48
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
49
|
+
body: new URLSearchParams({
|
|
50
|
+
grant_type: "client_credentials",
|
|
51
|
+
client_id: this.#id,
|
|
52
|
+
client_secret: this.#secret,
|
|
53
|
+
installation_id: installationId
|
|
54
|
+
}).toString()
|
|
55
|
+
});
|
|
56
|
+
if (!response.ok) throw new Error(`Midsummer gave no token for ${installationId}: HTTP ${response.status} ${await response.text()}`);
|
|
57
|
+
const { access_token: token, expires_in: seconds } = await response.json();
|
|
58
|
+
this.#tokens.set(installationId, {
|
|
59
|
+
token,
|
|
60
|
+
until: now + seconds * 1e3
|
|
61
|
+
});
|
|
62
|
+
return token;
|
|
63
|
+
}
|
|
64
|
+
/** A call to Midsummer's API as the app in one installation, such as `/v1/mr/acme/web/mr-12/comments`; JSON unless the body says otherwise. */
|
|
65
|
+
async request(installationId, path, init = {}) {
|
|
66
|
+
const headers = new Headers(init.headers);
|
|
67
|
+
headers.set("Authorization", `Bearer ${await this.token(installationId)}`);
|
|
68
|
+
if (init.body !== void 0 && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
69
|
+
return this.#fetch(`${this.#origin}${path.startsWith("/") ? path : `/${path}`}`, {
|
|
70
|
+
...init,
|
|
71
|
+
headers
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** Trades the one-time code a manifest's app was made with for its id, secret and signing secret, shown this once. */
|
|
75
|
+
static async fromManifestCode(code, options = {}) {
|
|
76
|
+
const origin = (options.origin ?? "https://api.midsummer.new").replace(/\/+$/, "");
|
|
77
|
+
const response = await (options.fetch ?? fetch)(`${origin}/v1/apps/conversions/${encodeURIComponent(code)}`, { method: "POST" });
|
|
78
|
+
if (!response.ok) throw new Error(`Midsummer refused the code: HTTP ${response.status} ${await response.text()}`);
|
|
79
|
+
return await response.json();
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
function fromBase64(text) {
|
|
83
|
+
const bytes = atob(text);
|
|
84
|
+
const out = new Uint8Array(bytes.length);
|
|
85
|
+
for (let index = 0; index < bytes.length; index += 1) out[index] = bytes.charCodeAt(index);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
function toBase64(bytes) {
|
|
89
|
+
let text = "";
|
|
90
|
+
for (const byte of bytes) text += String.fromCharCode(byte);
|
|
91
|
+
return btoa(text);
|
|
92
|
+
}
|
|
93
|
+
/** Whether two signatures are the same, compared in time that does not depend on where they differ. */
|
|
94
|
+
function same(a, b) {
|
|
95
|
+
if (a.length !== b.length) return false;
|
|
96
|
+
let differ = 0;
|
|
97
|
+
for (let index = 0; index < a.length; index += 1) differ |= a.charCodeAt(index) ^ b.charCodeAt(index);
|
|
98
|
+
return differ === 0;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
export { InstalledApp, verifyEvent };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midsummer-ai/sdk",
|
|
3
|
-
"version": "0.1.0-staging.
|
|
3
|
+
"version": "0.1.0-staging.3338",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
|
|
@@ -119,6 +119,10 @@
|
|
|
119
119
|
"types": "./email/contract.d.mts",
|
|
120
120
|
"import": "./email/contract.mjs"
|
|
121
121
|
},
|
|
122
|
+
"./apps": {
|
|
123
|
+
"types": "./apps.d.mts",
|
|
124
|
+
"import": "./apps.mjs"
|
|
125
|
+
},
|
|
122
126
|
"./email/client": {
|
|
123
127
|
"types": "./email/client.d.mts",
|
|
124
128
|
"import": "./email/client.mjs"
|
|
@@ -225,6 +229,9 @@
|
|
|
225
229
|
"email/contract": [
|
|
226
230
|
"./email/contract.d.mts"
|
|
227
231
|
],
|
|
232
|
+
"apps": [
|
|
233
|
+
"./apps.d.mts"
|
|
234
|
+
],
|
|
228
235
|
"email/client": [
|
|
229
236
|
"./email/client.d.mts"
|
|
230
237
|
],
|