@karpoland/sdk 0.0.0-stage → 1.0.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 +202 -0
- package/README.ja.md +542 -0
- package/README.md +541 -2
- package/README.zh-CN.md +542 -0
- package/dist/app-B7n0h9Pk.d.cts +450 -0
- package/dist/app-DLU_Aj53.d.ts +450 -0
- package/dist/chunk-EZJ5H5WT.js +87 -0
- package/dist/chunk-EZJ5H5WT.js.map +1 -0
- package/dist/chunk-TRJPD7KM.js +378 -0
- package/dist/chunk-TRJPD7KM.js.map +1 -0
- package/dist/cli.js +875 -0
- package/dist/index.cjs +1448 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +562 -0
- package/dist/index.d.ts +562 -0
- package/dist/index.js +1004 -0
- package/dist/index.js.map +1 -0
- package/dist/page.cjs +311 -0
- package/dist/page.cjs.map +1 -0
- package/dist/page.d.cts +116 -0
- package/dist/page.d.ts +116 -0
- package/dist/page.global.js +1 -0
- package/dist/page.js +135 -0
- package/dist/page.js.map +1 -0
- package/dist/testing.cjs +238 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +123 -0
- package/dist/testing.d.ts +123 -0
- package/dist/testing.js +146 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-VExoR9cc.d.cts +1189 -0
- package/dist/types-VExoR9cc.d.ts +1189 -0
- package/package.json +70 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1004 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ALREADY_DONE,
|
|
3
|
+
APP_REASONS,
|
|
4
|
+
AppError,
|
|
5
|
+
MAX_IDEMPOTENCY_KEY,
|
|
6
|
+
PlatformError,
|
|
7
|
+
Reasons,
|
|
8
|
+
STATUSES,
|
|
9
|
+
createTransport,
|
|
10
|
+
enc,
|
|
11
|
+
idempotencyHeader,
|
|
12
|
+
isPlatformError,
|
|
13
|
+
isReason,
|
|
14
|
+
rfc3339,
|
|
15
|
+
shouldRetry,
|
|
16
|
+
statusOfHttp
|
|
17
|
+
} from "./chunk-TRJPD7KM.js";
|
|
18
|
+
import {
|
|
19
|
+
MAX_SKEW_SECONDS,
|
|
20
|
+
SIGNATURE_HEADER,
|
|
21
|
+
TIMESTAMP_HEADER,
|
|
22
|
+
sign,
|
|
23
|
+
signedHeaders,
|
|
24
|
+
verifySignature
|
|
25
|
+
} from "./chunk-EZJ5H5WT.js";
|
|
26
|
+
|
|
27
|
+
// src/version.ts
|
|
28
|
+
var SDK_VERSION = "1.0.0";
|
|
29
|
+
var USER_AGENT = `karpoland-sdk-ts/${SDK_VERSION}`;
|
|
30
|
+
|
|
31
|
+
// src/client.ts
|
|
32
|
+
var MAX_RESIDENT_IDS = 100;
|
|
33
|
+
function createClient(opts) {
|
|
34
|
+
if (!opts.platform) throw new TypeError("createClient: platform (the API origin) is required");
|
|
35
|
+
const context = { callId: opts.callId, deliveryId: opts.deliveryId };
|
|
36
|
+
const t = createTransport({
|
|
37
|
+
base: opts.platform.replace(/\/+$/, "") + "/v1/app-service",
|
|
38
|
+
fetch: opts.fetch,
|
|
39
|
+
retry: opts.retry,
|
|
40
|
+
userAgent: USER_AGENT,
|
|
41
|
+
headers: () => {
|
|
42
|
+
if (!opts.appKey) throw new TypeError("karpoland client: no appKey (kap_\u2026) yet; issue one and configure the app");
|
|
43
|
+
const h = { Authorization: `Bearer ${opts.appKey}`, ...opts.headers };
|
|
44
|
+
if (context.callId) h["MP-Karpo-Call"] = String(context.callId);
|
|
45
|
+
if (context.deliveryId) h["MP-Karpo-Delivery"] = String(context.deliveryId);
|
|
46
|
+
return h;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const req = (method, path, o) => t.request(method, path, o);
|
|
50
|
+
const post = (path, body = {}) => req("POST", path, { body });
|
|
51
|
+
const once = async (method, path, body, o) => req(method, path, { body, headers: idempotencyHeader(o?.idempotencyKey), idempotent: true });
|
|
52
|
+
const s = (id) => `/sessions/${enc(id)}`;
|
|
53
|
+
async function residentsGet(ids) {
|
|
54
|
+
const want = [...new Set(ids.filter(Boolean).map(String))];
|
|
55
|
+
const out = [];
|
|
56
|
+
for (let i = 0; i < want.length; i += MAX_RESIDENT_IDS) {
|
|
57
|
+
const r = await req("GET", "/residents", { query: { ids: want.slice(i, i + MAX_RESIDENT_IDS).join(",") } });
|
|
58
|
+
out.push(...r.residents ?? []);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
const relations = (path, query = {}) => req("GET", `/relations/${path}`, { query });
|
|
63
|
+
const finish = async (id, body) => {
|
|
64
|
+
const r = await req("POST", `/calls/${enc(id)}/result`, { body, idempotent: true, doneOnRetry: "app.ALREADY_DONE" });
|
|
65
|
+
return r === ALREADY_DONE ? getCall(id) : r.call;
|
|
66
|
+
};
|
|
67
|
+
const one = async (key, p) => (await p)?.[key];
|
|
68
|
+
const list = async (key, p) => (await p)?.[key] ?? [];
|
|
69
|
+
const getCall = (id) => one("call", req("GET", `/calls/${enc(id)}`));
|
|
70
|
+
const session = (p) => one("session", p);
|
|
71
|
+
const participant = (p) => one("participant", p);
|
|
72
|
+
const board = (p) => one("board", p);
|
|
73
|
+
return {
|
|
74
|
+
context,
|
|
75
|
+
withContext: (ctx) => createClient({ ...opts, callId: ctx.callId, deliveryId: ctx.deliveryId }),
|
|
76
|
+
request: (method, path, o) => req(method, path, o),
|
|
77
|
+
me: () => req("GET", "/me"),
|
|
78
|
+
installs: { get: (id) => one("install", req("GET", `/installs/${enc(id)}`)) },
|
|
79
|
+
calls: {
|
|
80
|
+
get: getCall,
|
|
81
|
+
complete: (id, result, o = {}) => finish(id, { result: result === void 0 ? null : result, ...o.text ? { text: o.text } : {} }),
|
|
82
|
+
fail: (id, error) => finish(id, { error })
|
|
83
|
+
},
|
|
84
|
+
sessions: {
|
|
85
|
+
create: (input, o) => session(once("POST", "/sessions", input, o)),
|
|
86
|
+
get: (id) => session(req("GET", s(id))),
|
|
87
|
+
list: (query = {}) => {
|
|
88
|
+
const { status, ...rest } = query;
|
|
89
|
+
return list("sessions", req("GET", "/sessions", { query: { ...rest, status: Array.isArray(status) ? status.join(",") : status } }));
|
|
90
|
+
},
|
|
91
|
+
update: (id, input) => session(req("PATCH", s(id), { body: input })),
|
|
92
|
+
start: (id) => session(post(`${s(id)}/start`)),
|
|
93
|
+
pause: (id, reason) => session(post(`${s(id)}/pause`, { reason })),
|
|
94
|
+
resume: (id) => session(post(`${s(id)}/resume`)),
|
|
95
|
+
cancel: (id, reason) => session(post(`${s(id)}/cancel`, { reason })),
|
|
96
|
+
end: (id, summary = {}, o) => session(once("POST", `${s(id)}/end`, summary, o)),
|
|
97
|
+
invite: (id, residentIds) => list("invited", post(`${s(id)}/invite`, { resident_ids: residentIds })),
|
|
98
|
+
rematch: (id, o) => once("POST", `${s(id)}/rematch`, {}, o),
|
|
99
|
+
share: (id, visibility) => post(`${s(id)}/share`, visibility ? { visibility } : {}),
|
|
100
|
+
decide: (id, resident, action) => participant(post(`${s(id)}/participants/${enc(resident)}/${action}`)),
|
|
101
|
+
participants: {
|
|
102
|
+
list: (id) => list("participants", req("GET", `${s(id)}/participants`)),
|
|
103
|
+
add: (id, resident, role = "player") => post(`${s(id)}/participants`, { resident_id: resident, role }),
|
|
104
|
+
set: (id, resident, input) => participant(req("PUT", `${s(id)}/participants/${enc(resident)}`, { body: input })),
|
|
105
|
+
remove: (id, resident) => participant(req("DELETE", `${s(id)}/participants/${enc(resident)}`))
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
boards: {
|
|
109
|
+
// Full identifiers carry "/" and go in the body or ?ref=.
|
|
110
|
+
submit: (b, rows, where = {}, o) => one("ref", once("POST", "/scores", { board: b, rows, ...where }, o)),
|
|
111
|
+
publishTop: (b, rows, where = {}, o) => one("ref", once("PUT", "/top", { board: b, rows, ...where }, o)),
|
|
112
|
+
open: (b, input = {}) => board(post("/periods", { board: b, op: "open", ...input })),
|
|
113
|
+
close: (b, where = {}) => board(post("/periods", { board: b, op: "close", ...where })),
|
|
114
|
+
reveal: (b, where = {}) => board(post("/periods", { board: b, op: "reveal", ...where })),
|
|
115
|
+
get: (ref, query = {}) => board(req("GET", "/boards", { query: { ref, ...query } })),
|
|
116
|
+
list: (query = {}) => list("boards", req("GET", "/boards", { query }))
|
|
117
|
+
},
|
|
118
|
+
messages: {
|
|
119
|
+
send: (input, o) => once("POST", "/messages", { ...input, due_at: rfc3339(input.due_at) }, o)
|
|
120
|
+
},
|
|
121
|
+
timers: {
|
|
122
|
+
set: (key, input) => one("timer", req("PUT", `/timers/${enc(key)}`, { body: { ...input, at: rfc3339(input.at) } })),
|
|
123
|
+
cancel: async (key, where = {}) => void await req("DELETE", `/timers/${enc(key)}`, { query: where }),
|
|
124
|
+
list: (where = {}) => list("timers", req("GET", "/timers", { query: where }))
|
|
125
|
+
},
|
|
126
|
+
posts: { create: (input, o) => one("message_id", once("POST", "/posts", input, o)) },
|
|
127
|
+
relations: {
|
|
128
|
+
sameOwner: async (otherId) => (await relations("same-owner", { other_id: otherId })).same_owner === true,
|
|
129
|
+
members: async (installId) => (await relations("members", { install_id: installId })).residents ?? [],
|
|
130
|
+
contacts: async () => (await relations("contacts")).residents ?? [],
|
|
131
|
+
quota: (key, n) => post("/relations/quota", { key, n })
|
|
132
|
+
},
|
|
133
|
+
residents: { get: residentsGet },
|
|
134
|
+
joinRequests: {
|
|
135
|
+
decide: (id, d) => post(`/join-requests/${enc(id)}/${d.approve ? "approve" : "reject"}`, { reason: d.reason ?? "" })
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/app.ts
|
|
141
|
+
var MAX_BODY_BYTES = 1 << 20;
|
|
142
|
+
var DEDUPE_TTL_SECONDS = 24 * 3600;
|
|
143
|
+
function memoryDedupe(opts = {}) {
|
|
144
|
+
const max = opts.max ?? 1e4;
|
|
145
|
+
const ttl = (opts.ttlSeconds ?? DEDUPE_TTL_SECONDS) * 1e3;
|
|
146
|
+
const done = /* @__PURE__ */ new Map();
|
|
147
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
148
|
+
return {
|
|
149
|
+
begin(key) {
|
|
150
|
+
const hit = done.get(key);
|
|
151
|
+
if (hit) {
|
|
152
|
+
if (Date.now() - hit.at <= ttl) return { state: "done", answer: hit.answer };
|
|
153
|
+
done.delete(key);
|
|
154
|
+
}
|
|
155
|
+
if (inFlight.has(key)) return { state: "in_flight" };
|
|
156
|
+
inFlight.add(key);
|
|
157
|
+
return { state: "new" };
|
|
158
|
+
},
|
|
159
|
+
end(key, answer) {
|
|
160
|
+
inFlight.delete(key);
|
|
161
|
+
if (!answer) return;
|
|
162
|
+
done.delete(key);
|
|
163
|
+
done.set(key, { at: Date.now(), answer });
|
|
164
|
+
while (done.size > max) done.delete(done.keys().next().value);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
var SIGNING_REREAD_SECONDS = 60;
|
|
169
|
+
var JOIN_EVENTS = /* @__PURE__ */ new Set(["member.join", "join.requested"]);
|
|
170
|
+
var eventKey = (e) => JOIN_EVENTS.has(e) ? "member.join" : e;
|
|
171
|
+
var ACCEPTED = /* @__PURE__ */ Symbol.for("karpoland.accepted");
|
|
172
|
+
var GATE_DECISIONS = /* @__PURE__ */ new Set(["approve", "reject", "pending"]);
|
|
173
|
+
function checkHandlers(manifest, registered) {
|
|
174
|
+
const tools = new Set(registered.tools);
|
|
175
|
+
const hooks = new Set(registered.hooks);
|
|
176
|
+
const isGate = (h) => !!h.gate && h.verify == null;
|
|
177
|
+
const declaredTools = new Set((manifest.tools ?? []).map((t) => t.name));
|
|
178
|
+
const declaredHooks = new Set((manifest.hooks ?? []).filter((h) => h.handler && !isGate(h)).map((h) => eventKey(h.on)));
|
|
179
|
+
const gated = (manifest.hooks ?? []).some(isGate);
|
|
180
|
+
for (const h of [...hooks]) if (JOIN_EVENTS.has(h)) hooks.delete(h), hooks.add("member.join");
|
|
181
|
+
const missing = [];
|
|
182
|
+
const extra = [];
|
|
183
|
+
for (const t of declaredTools) if (!tools.has(t)) missing.push(`tool ${t}`);
|
|
184
|
+
for (const t of tools) if (!declaredTools.has(t)) extra.push(`tool ${t}`);
|
|
185
|
+
for (const h of declaredHooks) if (!hooks.has(h)) missing.push(`hook ${h}`);
|
|
186
|
+
for (const h of hooks) if (!declaredHooks.has(h)) extra.push(`hook ${h}`);
|
|
187
|
+
if (gated && !registered.gate) missing.push("gate member.join");
|
|
188
|
+
if (registered.gate && !gated) extra.push("gate member.join");
|
|
189
|
+
const problems = [];
|
|
190
|
+
if (missing.length) problems.push("no handler for " + missing.sort().join(", "));
|
|
191
|
+
if (extra.length) problems.push("not in the manifest: " + extra.sort().join(", "));
|
|
192
|
+
return problems;
|
|
193
|
+
}
|
|
194
|
+
var json = (status, body) => ({
|
|
195
|
+
status,
|
|
196
|
+
headers: body === void 0 ? {} : { "Content-Type": "application/json; charset=utf-8" },
|
|
197
|
+
body: body === void 0 ? "" : JSON.stringify(body)
|
|
198
|
+
});
|
|
199
|
+
var REPLY_KEYS = /* @__PURE__ */ new Set(["result", "text"]);
|
|
200
|
+
function toReply(out) {
|
|
201
|
+
if (out === void 0) return { result: null };
|
|
202
|
+
if (out && typeof out === "object" && !Array.isArray(out) && Object.getPrototypeOf(out) === Object.prototype) {
|
|
203
|
+
const keys = Object.keys(out);
|
|
204
|
+
if (keys.length > 0 && keys.every((k) => REPLY_KEYS.has(k))) {
|
|
205
|
+
const r = out;
|
|
206
|
+
return { result: r.result === void 0 ? null : r.result, ...r.text !== void 0 ? { text: r.text } : {} };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return { result: out };
|
|
210
|
+
}
|
|
211
|
+
function errorResponse(e, kind, log) {
|
|
212
|
+
if (e instanceof AppError) return json(e.httpStatus, e.toJSON());
|
|
213
|
+
if (e instanceof PlatformError) {
|
|
214
|
+
if (e.httpStatus === 401) {
|
|
215
|
+
log?.error(isReason(e, "key.INVALID") ? "karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app" : "karpoland: the platform refused the app key", e);
|
|
216
|
+
return json(503, { status: "UNAVAILABLE", reason: e.reason, message: e.message });
|
|
217
|
+
}
|
|
218
|
+
if (kind === "hook" && shouldRetry(e)) return json(503, { status: e.status, reason: e.reason, message: e.message });
|
|
219
|
+
if (e.httpStatus >= 400 && e.httpStatus < 500) {
|
|
220
|
+
return json(e.httpStatus, { status: e.status, reason: e.reason, message: e.message, action: e.action });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
log?.error("karpoland: handler failed", e);
|
|
224
|
+
return json(500, { error: "app error" });
|
|
225
|
+
}
|
|
226
|
+
function createApp(options = {}) {
|
|
227
|
+
const opts = { ...options };
|
|
228
|
+
const tools = /* @__PURE__ */ new Map();
|
|
229
|
+
const hooks = /* @__PURE__ */ new Map();
|
|
230
|
+
let gate;
|
|
231
|
+
let dedupe = opts.dedupe === void 0 ? memoryDedupe() : opts.dedupe;
|
|
232
|
+
const log = opts.logger ?? console;
|
|
233
|
+
const client = (ctx = {}) => {
|
|
234
|
+
if (!opts.appKey || !opts.platform) {
|
|
235
|
+
return new Proxy({}, {
|
|
236
|
+
get(_, prop) {
|
|
237
|
+
if (prop === "then") return void 0;
|
|
238
|
+
throw new Error(`karpoland: set appKey and platform in createApp() to use the platform client (karpo.${String(prop)})`);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
const c = { appKey: opts.appKey, platform: opts.platform, retry: opts.retry, fetch: opts.fetch, ...ctx };
|
|
243
|
+
return createClient(c);
|
|
244
|
+
};
|
|
245
|
+
let signing = null;
|
|
246
|
+
let signingReadAt = 0;
|
|
247
|
+
let signingRead = null;
|
|
248
|
+
const canReadSigning = () => !opts.signingSecret && !!opts.platform && !!opts.appKey;
|
|
249
|
+
const readSigning = () => {
|
|
250
|
+
if (!canReadSigning()) return Promise.resolve();
|
|
251
|
+
if (signingRead) return signingRead;
|
|
252
|
+
if (signingReadAt && Date.now() - signingReadAt < SIGNING_REREAD_SECONDS * 1e3) return Promise.resolve();
|
|
253
|
+
signingReadAt = Date.now();
|
|
254
|
+
signingRead = (async () => {
|
|
255
|
+
try {
|
|
256
|
+
const r = await client().request("GET", "/signing");
|
|
257
|
+
const b = r && typeof r.signing === "object" && r.signing ? r.signing : r;
|
|
258
|
+
if (typeof b.signing_secret === "string" && b.signing_secret) {
|
|
259
|
+
signing = { secret: b.signing_secret, domainToken: typeof b.domain_token === "string" ? b.domain_token : "" };
|
|
260
|
+
} else log.error("karpoland: GET /v1/app-service/signing answered without signing_secret");
|
|
261
|
+
} catch (e) {
|
|
262
|
+
if (e instanceof PlatformError && isReason(e, "key.INVALID")) log.error("karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app");
|
|
263
|
+
else log.error("karpoland: could not read the signing secret (GET /v1/app-service/signing); deliveries are answered 503 until it can. On a platform without that route, set signingSecret", e);
|
|
264
|
+
} finally {
|
|
265
|
+
signingRead = null;
|
|
266
|
+
}
|
|
267
|
+
})();
|
|
268
|
+
return signingRead;
|
|
269
|
+
};
|
|
270
|
+
const secret = async () => {
|
|
271
|
+
if (opts.signingSecret) return opts.signingSecret;
|
|
272
|
+
if (!signing) await readSigning();
|
|
273
|
+
return signing?.secret;
|
|
274
|
+
};
|
|
275
|
+
const stripBase = (path) => {
|
|
276
|
+
const base = (opts.basePath ?? "").replace(/\/+$/, "");
|
|
277
|
+
if (!base) return path;
|
|
278
|
+
if (path === base) return "/";
|
|
279
|
+
return path.startsWith(base + "/") ? path.slice(base.length) : null;
|
|
280
|
+
};
|
|
281
|
+
const signedPath = (path) => (opts.signaturePathPrefix ?? "").replace(/\/+$/, "") + path;
|
|
282
|
+
async function once(key, run) {
|
|
283
|
+
const store = dedupe || null;
|
|
284
|
+
if (!store) return run();
|
|
285
|
+
let claim;
|
|
286
|
+
try {
|
|
287
|
+
claim = await store.begin(key);
|
|
288
|
+
} catch (e) {
|
|
289
|
+
log.error("karpoland: dedupe store failed", e);
|
|
290
|
+
return json(503, { error: "dedupe unavailable" });
|
|
291
|
+
}
|
|
292
|
+
if (claim.state === "done") {
|
|
293
|
+
const a = claim.answer;
|
|
294
|
+
return { status: a.status, headers: a.body ? { "Content-Type": "application/json; charset=utf-8" } : {}, body: a.body };
|
|
295
|
+
}
|
|
296
|
+
if (claim.state === "in_flight") return json(503, { error: "delivery in progress" });
|
|
297
|
+
let res;
|
|
298
|
+
try {
|
|
299
|
+
res = await run();
|
|
300
|
+
} catch (e) {
|
|
301
|
+
log.error("karpoland: handler failed", e);
|
|
302
|
+
res = json(500, { error: "app error" });
|
|
303
|
+
}
|
|
304
|
+
try {
|
|
305
|
+
await store.end(key, res.status < 500 ? { status: res.status, body: res.body } : null);
|
|
306
|
+
} catch (e) {
|
|
307
|
+
log.error("karpoland: dedupe store failed", e);
|
|
308
|
+
}
|
|
309
|
+
return res;
|
|
310
|
+
}
|
|
311
|
+
async function handle(req, waitUntil) {
|
|
312
|
+
const method = req.method.toUpperCase();
|
|
313
|
+
if (method === "GET" && (req.path === "/.well-known/karpo-app.txt" || stripBase(req.path) === "/.well-known/karpo-app.txt")) {
|
|
314
|
+
if (!signing) await readSigning();
|
|
315
|
+
if (!signing?.domainToken || opts.signingSecret) return { status: 404, headers: { "Content-Type": "text/plain" }, body: "" };
|
|
316
|
+
return { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8" }, body: signing.domainToken };
|
|
317
|
+
}
|
|
318
|
+
const path = stripBase(req.path);
|
|
319
|
+
if (path === null) return json(404, { error: "not found" });
|
|
320
|
+
if (method === "GET" && path === "/healthz") return json(200, { ok: true });
|
|
321
|
+
const route = path === "/.karpo/handshake" ? "handshake" : path.startsWith("/tools/") ? "tool" : path.startsWith("/hooks/") ? "hook" : null;
|
|
322
|
+
if (!route) return json(404, { error: "not found" });
|
|
323
|
+
if (method !== "POST") return json(405, { error: "use POST" });
|
|
324
|
+
if (req.body.length > (opts.maxBodyBytes ?? MAX_BODY_BYTES)) return json(413, { error: "body too large" });
|
|
325
|
+
const signature = req.headers.get(SIGNATURE_HEADER);
|
|
326
|
+
const headerId = String(req.headers.get("mp-karpo-call") || req.headers.get("mp-karpo-delivery") || "");
|
|
327
|
+
const signed = { method, path: req.signedPath ?? signedPath(req.path), id: headerId };
|
|
328
|
+
const verify = (key2) => verifySignature(key2 ?? "", req.headers.get(TIMESTAMP_HEADER), signed, req.body, signature, { maxSkewSeconds: opts.maxSkewSeconds });
|
|
329
|
+
let key = await secret();
|
|
330
|
+
if (!key && canReadSigning()) return json(503, { error: "signing secret unavailable" });
|
|
331
|
+
let why = await verify(key);
|
|
332
|
+
if (why === "mismatch" && canReadSigning()) {
|
|
333
|
+
await readSigning();
|
|
334
|
+
if (signing && signing.secret !== key) {
|
|
335
|
+
key = signing.secret;
|
|
336
|
+
why = await verify(key);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (why) {
|
|
340
|
+
if (!key) log.warn?.("karpoland: no signing secret (set platform and appKey); refusing deliveries");
|
|
341
|
+
return json(401, { status: "UNAUTHENTICATED", reason: "auth.TOKEN_INVALID", message: why === "skew" ? "stale timestamp" : "bad signature" });
|
|
342
|
+
}
|
|
343
|
+
let msg;
|
|
344
|
+
try {
|
|
345
|
+
msg = JSON.parse(new TextDecoder().decode(req.body));
|
|
346
|
+
} catch {
|
|
347
|
+
return json(400, { status: "INVALID_ARGUMENT", reason: "request.BAD_TYPE", message: "body is not JSON" });
|
|
348
|
+
}
|
|
349
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg)) return json(400, { status: "INVALID_ARGUMENT", reason: "request.BAD_TYPE", message: "body is not an object" });
|
|
350
|
+
const keepAlive = (p) => {
|
|
351
|
+
const guarded = p.catch((e) => log.error("karpoland: background work failed", e));
|
|
352
|
+
waitUntil?.(guarded);
|
|
353
|
+
};
|
|
354
|
+
const bodyId = route === "tool" ? String(msg.call?.id ?? "") : route === "hook" ? String(msg.delivery_id ?? "") : "";
|
|
355
|
+
if (headerId !== bodyId) {
|
|
356
|
+
return json(401, { status: "UNAUTHENTICATED", reason: "auth.TOKEN_INVALID", message: "signed id differs from the body's" });
|
|
357
|
+
}
|
|
358
|
+
if (route === "handshake") return handshake(msg);
|
|
359
|
+
if (route === "tool") {
|
|
360
|
+
const name = decodeURIComponent(path.slice("/tools/".length));
|
|
361
|
+
const run2 = () => runTool(name, msg, bodyId, keepAlive);
|
|
362
|
+
return bodyId ? once("call:" + bodyId, run2) : run2();
|
|
363
|
+
}
|
|
364
|
+
const event = decodeURIComponent(path.slice("/hooks/".length));
|
|
365
|
+
const run = () => JOIN_EVENTS.has(event) && msg.gate === true ? runGate(event, msg, bodyId, keepAlive) : runHook(event, msg, bodyId, keepAlive);
|
|
366
|
+
return bodyId ? once("delivery:" + bodyId, run) : run();
|
|
367
|
+
}
|
|
368
|
+
function handshake(msg) {
|
|
369
|
+
const missing = [];
|
|
370
|
+
if (Array.isArray(msg.tools)) {
|
|
371
|
+
for (const t of msg.tools) if (!tools.has(t)) missing.push(`tool ${t}`);
|
|
372
|
+
}
|
|
373
|
+
if (Array.isArray(msg.hooks)) {
|
|
374
|
+
for (const h of msg.hooks) {
|
|
375
|
+
const k = eventKey(h);
|
|
376
|
+
if (k === "member.join" ? !gate && !hooks.has("member.join") && !hooks.has("join.requested") : !hooks.has(h)) missing.push(`hook ${h}`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (missing.length) {
|
|
380
|
+
missing.sort();
|
|
381
|
+
return json(422, { status: "FAILED_PRECONDITION", reason: "app.HANDSHAKE_FAILED", message: "no handler for " + missing.join(", "), detail: { items: missing } });
|
|
382
|
+
}
|
|
383
|
+
return json(200, { challenge: msg.challenge });
|
|
384
|
+
}
|
|
385
|
+
async function runTool(name, msg, callId, keepAlive) {
|
|
386
|
+
const fn = tools.get(name);
|
|
387
|
+
if (!fn) return json(404, { status: "NOT_FOUND", reason: "request.UNKNOWN_TOOL", message: `no tool ${name} here` });
|
|
388
|
+
const args = msg.call?.args ?? {};
|
|
389
|
+
let accepted = false;
|
|
390
|
+
const base = () => client();
|
|
391
|
+
const ctx = {
|
|
392
|
+
app: msg.app,
|
|
393
|
+
call: { id: callId, tool: name, args, idempotencyKey: msg.call?.idempotency_key || void 0, firstSeen: !!msg.call?.first_seen },
|
|
394
|
+
args,
|
|
395
|
+
caller: msg.caller ?? null,
|
|
396
|
+
install: msg.install ?? null,
|
|
397
|
+
session: msg.session ?? null,
|
|
398
|
+
event: msg.event ?? null,
|
|
399
|
+
commandMessageId: msg.command_message_id ?? null,
|
|
400
|
+
karpo: client({ callId }),
|
|
401
|
+
accepted() {
|
|
402
|
+
accepted = true;
|
|
403
|
+
return ACCEPTED;
|
|
404
|
+
},
|
|
405
|
+
async complete(result, opts2) {
|
|
406
|
+
await base().calls.complete(callId, result, opts2);
|
|
407
|
+
},
|
|
408
|
+
async fail(status, reason, message = "") {
|
|
409
|
+
await base().calls.fail(callId, { status, reason, message });
|
|
410
|
+
},
|
|
411
|
+
defer(work) {
|
|
412
|
+
accepted = true;
|
|
413
|
+
keepAlive(
|
|
414
|
+
(async () => {
|
|
415
|
+
let out;
|
|
416
|
+
try {
|
|
417
|
+
out = await work();
|
|
418
|
+
} catch (e) {
|
|
419
|
+
if (e instanceof AppError) return base().calls.fail(callId, e.toJSON());
|
|
420
|
+
log.error(`karpoland: deferred work for ${name} failed`, e);
|
|
421
|
+
return base().calls.fail(callId, { status: "FAILED_PRECONDITION", reason: "app.RULE_VIOLATION", message: "the app could not finish this call" });
|
|
422
|
+
}
|
|
423
|
+
const r = toReply(out);
|
|
424
|
+
return base().calls.complete(callId, r.result, r.text ? { text: r.text } : void 0);
|
|
425
|
+
})()
|
|
426
|
+
);
|
|
427
|
+
return ACCEPTED;
|
|
428
|
+
},
|
|
429
|
+
waitUntil: keepAlive,
|
|
430
|
+
raw: msg
|
|
431
|
+
};
|
|
432
|
+
try {
|
|
433
|
+
const out = await fn(ctx, args);
|
|
434
|
+
if (out === ACCEPTED || accepted) return json(202, { accepted: true });
|
|
435
|
+
return json(200, toReply(out));
|
|
436
|
+
} catch (e) {
|
|
437
|
+
return errorResponse(e, "tool", log);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const hookContext = (event, id, msg, keepAlive) => ({
|
|
441
|
+
app: msg.app,
|
|
442
|
+
event,
|
|
443
|
+
deliveryId: id,
|
|
444
|
+
attempt: msg.attempt ?? 1,
|
|
445
|
+
install: msg.install ?? null,
|
|
446
|
+
sessionId: msg.session_id ?? null,
|
|
447
|
+
residentId: msg.resident_id ?? null,
|
|
448
|
+
data: msg.data ?? {},
|
|
449
|
+
karpo: client({ deliveryId: id }),
|
|
450
|
+
waitUntil: keepAlive,
|
|
451
|
+
raw: msg
|
|
452
|
+
});
|
|
453
|
+
async function runGate(event, msg, id, keepAlive) {
|
|
454
|
+
if (!gate) {
|
|
455
|
+
log.warn?.("karpoland: a join request gate delivery came but no app.gate handler is registered; the room's admins decide");
|
|
456
|
+
return json(204);
|
|
457
|
+
}
|
|
458
|
+
const ctx = hookContext(event, id, msg, keepAlive);
|
|
459
|
+
let out;
|
|
460
|
+
try {
|
|
461
|
+
out = await gate(ctx, ctx.data);
|
|
462
|
+
} catch (e) {
|
|
463
|
+
return errorResponse(e, "hook", log);
|
|
464
|
+
}
|
|
465
|
+
if (out === void 0 || out === null) {
|
|
466
|
+
log.warn?.("karpoland: the gate gave no decision; the room's admins decide");
|
|
467
|
+
return json(204);
|
|
468
|
+
}
|
|
469
|
+
const answer = typeof out === "string" ? { decision: out } : out;
|
|
470
|
+
if (!GATE_DECISIONS.has(answer.decision)) {
|
|
471
|
+
log.error(`karpoland: the gate answered ${JSON.stringify(answer.decision)}; use "approve", "reject" or "pending"`);
|
|
472
|
+
return json(500, { error: "app error" });
|
|
473
|
+
}
|
|
474
|
+
return json(200, answer.reason ? { decision: answer.decision, reason: answer.reason } : { decision: answer.decision });
|
|
475
|
+
}
|
|
476
|
+
async function runHook(event, msg, id, keepAlive) {
|
|
477
|
+
const fn = hooks.get(event) ?? (JOIN_EVENTS.has(event) ? hooks.get("member.join") ?? hooks.get("join.requested") : void 0);
|
|
478
|
+
try {
|
|
479
|
+
if (fn) {
|
|
480
|
+
const ctx = hookContext(event, id, msg, keepAlive);
|
|
481
|
+
await fn(ctx, ctx.data);
|
|
482
|
+
}
|
|
483
|
+
return json(204);
|
|
484
|
+
} catch (e) {
|
|
485
|
+
return errorResponse(e, "hook", log);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const app = {
|
|
489
|
+
tool(name, handler) {
|
|
490
|
+
tools.set(name, handler);
|
|
491
|
+
return app;
|
|
492
|
+
},
|
|
493
|
+
hook(event, handler) {
|
|
494
|
+
hooks.set(event, handler);
|
|
495
|
+
return app;
|
|
496
|
+
},
|
|
497
|
+
gate(handler) {
|
|
498
|
+
gate = handler;
|
|
499
|
+
return app;
|
|
500
|
+
},
|
|
501
|
+
handle,
|
|
502
|
+
client,
|
|
503
|
+
configure(o) {
|
|
504
|
+
const rekey = "appKey" in o && o.appKey !== opts.appKey || "platform" in o && o.platform !== opts.platform;
|
|
505
|
+
Object.assign(opts, o);
|
|
506
|
+
if (o.dedupe !== void 0) dedupe = o.dedupe;
|
|
507
|
+
if (rekey) {
|
|
508
|
+
signing = null;
|
|
509
|
+
signingReadAt = 0;
|
|
510
|
+
void readSigning();
|
|
511
|
+
}
|
|
512
|
+
return app;
|
|
513
|
+
},
|
|
514
|
+
async fetch(request, ...rest) {
|
|
515
|
+
const wu = rest.find((x) => !!x && typeof x.waitUntil === "function");
|
|
516
|
+
const url = new URL(request.url);
|
|
517
|
+
const body = request.method === "GET" || request.method === "HEAD" ? new Uint8Array() : new Uint8Array(await request.arrayBuffer());
|
|
518
|
+
const out = await handle({ method: request.method, path: url.pathname, headers: request.headers, body }, wu ? (p) => wu.waitUntil(p) : void 0);
|
|
519
|
+
return new Response(out.status === 204 || out.body === "" ? null : out.body, { status: out.status, headers: out.headers });
|
|
520
|
+
},
|
|
521
|
+
async handler(req, res, next) {
|
|
522
|
+
try {
|
|
523
|
+
const url = new URL(req.url ?? "/", "http://app");
|
|
524
|
+
const orig = req.originalUrl;
|
|
525
|
+
const signed = orig ? new URL(orig, "http://app").pathname : void 0;
|
|
526
|
+
const body = await readNodeBody(req, opts.maxBodyBytes ?? MAX_BODY_BYTES);
|
|
527
|
+
const headers = {
|
|
528
|
+
get(name) {
|
|
529
|
+
const v = req.headers[name.toLowerCase()];
|
|
530
|
+
return Array.isArray(v) ? v[0] : v ?? null;
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
const out = await handle({ method: req.method ?? "GET", path: url.pathname, signedPath: signed, headers, body });
|
|
534
|
+
if (out.status === 404 && next) return next();
|
|
535
|
+
res.writeHead(out.status, out.headers);
|
|
536
|
+
res.end(out.body);
|
|
537
|
+
} catch (e) {
|
|
538
|
+
if (e.code === "TOO_LARGE") {
|
|
539
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
540
|
+
return void res.end(JSON.stringify({ error: "body too large" }));
|
|
541
|
+
}
|
|
542
|
+
log.error("karpoland: request failed", e);
|
|
543
|
+
if (!res.headersSent) res.writeHead(500, { "Content-Type": "application/json" });
|
|
544
|
+
res.end(JSON.stringify({ error: "app error" }));
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
async listen(port = 0, host) {
|
|
548
|
+
const http = await import("http");
|
|
549
|
+
const server = http.createServer((req, res) => void app.handler(req, res));
|
|
550
|
+
await new Promise((resolve, reject) => {
|
|
551
|
+
server.once("error", reject);
|
|
552
|
+
server.listen(port, host, () => resolve());
|
|
553
|
+
});
|
|
554
|
+
const addr = server.address();
|
|
555
|
+
const p = typeof addr === "object" && addr ? addr.port : port;
|
|
556
|
+
const closed = new Promise((resolve) => server.once("close", () => resolve()));
|
|
557
|
+
return {
|
|
558
|
+
port: p,
|
|
559
|
+
url: `http://${host && host !== "0.0.0.0" ? host : "127.0.0.1"}:${p}`,
|
|
560
|
+
close: () => new Promise((resolve) => server.close(() => resolve())),
|
|
561
|
+
wait: () => closed
|
|
562
|
+
};
|
|
563
|
+
},
|
|
564
|
+
check(manifest) {
|
|
565
|
+
const problems = checkHandlers(manifest, { tools: tools.keys(), hooks: hooks.keys(), gate: !!gate });
|
|
566
|
+
if (problems.length) throw new Error("karpoland: " + problems.join("; "));
|
|
567
|
+
},
|
|
568
|
+
get tools() {
|
|
569
|
+
return [...tools.keys()];
|
|
570
|
+
},
|
|
571
|
+
get hooks() {
|
|
572
|
+
return [...hooks.keys()];
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
void readSigning();
|
|
576
|
+
return app;
|
|
577
|
+
}
|
|
578
|
+
function readNodeBody(req, max) {
|
|
579
|
+
if (req.rawBody !== void 0) {
|
|
580
|
+
return Promise.resolve(typeof req.rawBody === "string" ? new TextEncoder().encode(req.rawBody) : req.rawBody);
|
|
581
|
+
}
|
|
582
|
+
if (req.method === "GET" || req.method === "HEAD") return Promise.resolve(new Uint8Array());
|
|
583
|
+
return new Promise((resolve, reject) => {
|
|
584
|
+
const chunks = [];
|
|
585
|
+
let n = 0;
|
|
586
|
+
req.on("data", (c) => {
|
|
587
|
+
n += c.length;
|
|
588
|
+
if (n > max) {
|
|
589
|
+
reject(Object.assign(new Error("body too large"), { code: "TOO_LARGE" }));
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
chunks.push(c);
|
|
593
|
+
});
|
|
594
|
+
req.on("end", () => {
|
|
595
|
+
const out = new Uint8Array(n);
|
|
596
|
+
let o = 0;
|
|
597
|
+
for (const c of chunks) {
|
|
598
|
+
out.set(c, o);
|
|
599
|
+
o += c.length;
|
|
600
|
+
}
|
|
601
|
+
resolve(out);
|
|
602
|
+
});
|
|
603
|
+
req.on("error", reject);
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// src/developer.ts
|
|
608
|
+
var bundleSha = (uri) => uri.slice(uri.lastIndexOf("/") + 1);
|
|
609
|
+
function createDeveloperClient(opts) {
|
|
610
|
+
if (!opts.token) throw new TypeError("createDeveloperClient: token (kat_\u2026) is required");
|
|
611
|
+
const t = createTransport({
|
|
612
|
+
base: opts.platform.replace(/\/+$/, "") + "/v1",
|
|
613
|
+
fetch: opts.fetch,
|
|
614
|
+
retry: opts.retry,
|
|
615
|
+
userAgent: USER_AGENT,
|
|
616
|
+
headers: () => ({ Authorization: `Bearer ${opts.token}` })
|
|
617
|
+
});
|
|
618
|
+
const a = (app) => {
|
|
619
|
+
if (!/^\d+$/.test(String(app))) throw new TypeError(`app is the app's numeric id (KARPO_APP_ID), not ${JSON.stringify(app)}; apps.ensureBySlug gives it`);
|
|
620
|
+
return `/apps/${enc(app)}`;
|
|
621
|
+
};
|
|
622
|
+
const tr = (id) => `/app-transfers/${enc(id)}`;
|
|
623
|
+
const one = async (key, p) => (await p)?.[key];
|
|
624
|
+
const list = async (key, p) => (await p)?.[key] ?? [];
|
|
625
|
+
return {
|
|
626
|
+
request: (method, path, body, query) => t.request(method, path, { body, query }),
|
|
627
|
+
apps: {
|
|
628
|
+
ensureBySlug: async (slug, input = {}) => {
|
|
629
|
+
const r = await t.request("PUT", `/apps/by-slug/${enc(slug)}`, { body: input });
|
|
630
|
+
return r?.app ?? { id: String(r?.app_id ?? "") };
|
|
631
|
+
},
|
|
632
|
+
get: (app) => t.request("GET", a(app)),
|
|
633
|
+
list: (query = {}) => list("apps", t.request("GET", "/apps", { query })),
|
|
634
|
+
update: (app, input) => one("app", t.request("PUT", a(app), { body: input })),
|
|
635
|
+
verifyDomain: (app, serviceUrl) => one("app", t.request("POST", `${a(app)}/domain/verify`, { body: { service_url: serviceUrl }, retry: false }))
|
|
636
|
+
},
|
|
637
|
+
keys: {
|
|
638
|
+
issue: (app, label = "") => t.request("POST", `${a(app)}/keys`, { body: { label } }),
|
|
639
|
+
list: (app) => list("keys", t.request("GET", `${a(app)}/keys`)),
|
|
640
|
+
revoke: async (app, keyId) => void await t.request("DELETE", `${a(app)}/keys/${enc(keyId)}`)
|
|
641
|
+
},
|
|
642
|
+
signing: {
|
|
643
|
+
rotate: (app, o = {}) => t.request("POST", `${a(app)}/signing-rotations`, { body: { revoke_all_keys: !!o.revokeAllKeys }, retry: false })
|
|
644
|
+
},
|
|
645
|
+
members: {
|
|
646
|
+
list: (app) => list("members", t.request("GET", `${a(app)}/members`)),
|
|
647
|
+
set: (app, resident, o = {}) => one("member", t.request("PUT", `${a(app)}/members/${enc(resident)}`, { body: o.bootstrap === void 0 ? {} : { bootstrap: o.bootstrap } })),
|
|
648
|
+
remove: async (app, resident) => void await t.request("DELETE", `${a(app)}/members/${enc(resident)}`)
|
|
649
|
+
},
|
|
650
|
+
transfers: {
|
|
651
|
+
create: (app, input) => one("transfer", t.request("POST", `${a(app)}/transfers`, { body: input, retry: false })),
|
|
652
|
+
list: (app, query = {}) => t.request("GET", `${a(app)}/transfers`, { query }),
|
|
653
|
+
mine: (query = {}) => t.request("GET", "/me/app-transfers", { query }),
|
|
654
|
+
accept: (id, o = {}) => one("transfer", t.request("POST", `${tr(id)}/accept`, { body: o.cutOff ? { cut_off: true } : {}, retry: false })),
|
|
655
|
+
decline: (id) => one("transfer", t.request("POST", `${tr(id)}/decline`, { body: {} })),
|
|
656
|
+
cancel: (id) => one("transfer", t.request("POST", `${tr(id)}/cancel`, { body: {} }))
|
|
657
|
+
},
|
|
658
|
+
bundles: {
|
|
659
|
+
upload: (app, zip) => t.request("POST", `${a(app)}/bundles`, { body: zip, headers: { "Content-Type": "application/zip" }, retry: false })
|
|
660
|
+
},
|
|
661
|
+
versions: {
|
|
662
|
+
list: (app) => list("versions", t.request("GET", `${a(app)}/versions`)),
|
|
663
|
+
publish: (app, input) => {
|
|
664
|
+
const m = input.manifest;
|
|
665
|
+
const body = { manifest: m, version: m.version };
|
|
666
|
+
if (input.bundle_uri) Object.assign(body, { bundle_uri: input.bundle_uri, bundle_sha256: bundleSha(input.bundle_uri) });
|
|
667
|
+
return t.request("POST", `${a(app)}/versions`, { body, retry: false });
|
|
668
|
+
}
|
|
669
|
+
},
|
|
670
|
+
installs: {
|
|
671
|
+
list: (app, query = {}) => t.request("GET", `${a(app)}/installs`, { query })
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// src/manifest.ts
|
|
677
|
+
var SCOPES = ["room:post", "session:rw", "board:rw", "message:send", "relation:read", "contacts:read", "timer:rw", "room:read", "room:gate"];
|
|
678
|
+
var HOOK_EVENTS = [
|
|
679
|
+
"app.installed",
|
|
680
|
+
"app.uninstalled",
|
|
681
|
+
"resident.first_seen",
|
|
682
|
+
"message.created",
|
|
683
|
+
"member.joined",
|
|
684
|
+
"member.left",
|
|
685
|
+
"member.join",
|
|
686
|
+
"session.created",
|
|
687
|
+
"session.started",
|
|
688
|
+
"session.paused",
|
|
689
|
+
"session.resumed",
|
|
690
|
+
"session.ended",
|
|
691
|
+
"session.cancelled",
|
|
692
|
+
"participant.changed",
|
|
693
|
+
"timer.fired",
|
|
694
|
+
"app.message.replied",
|
|
695
|
+
"app.upgraded"
|
|
696
|
+
];
|
|
697
|
+
var BASE_OUTCOMES = ["none", "won", "lost", "tied", "ranked", "quit", "timed_out", "disqualified"];
|
|
698
|
+
var LISTING_CATEGORIES = ["game", "social", "tool", "fun", "work"];
|
|
699
|
+
var CARD_SIZES = ["standard", "tall"];
|
|
700
|
+
var MAX_SESSION_BOARDS = 4;
|
|
701
|
+
var MANIFEST_IGNORED = ["summary", "icon", "color", "default_locale", "service_url", "hooks[].timeout", "hooks[].default"];
|
|
702
|
+
var ManifestError = class extends Error {
|
|
703
|
+
constructor(issues) {
|
|
704
|
+
super("invalid manifest:\n" + issues.map((i) => ` ${i.field}: ${i.message}`).join("\n"));
|
|
705
|
+
this.issues = issues;
|
|
706
|
+
}
|
|
707
|
+
issues;
|
|
708
|
+
name = "ManifestError";
|
|
709
|
+
};
|
|
710
|
+
var MAX_RELEASE_NOTES = 500;
|
|
711
|
+
var reName = /^[a-z][a-z0-9_]{0,63}$/;
|
|
712
|
+
var reKey = /^[a-z][a-z0-9_]{0,31}$/;
|
|
713
|
+
var reVersion = /^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;
|
|
714
|
+
var runes = (s) => typeof s === "string" ? [...s].length : 0;
|
|
715
|
+
var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
716
|
+
function validZone(tz) {
|
|
717
|
+
try {
|
|
718
|
+
new Intl.DateTimeFormat("en", { timeZone: tz });
|
|
719
|
+
return true;
|
|
720
|
+
} catch {
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
function intChoice(c, def) {
|
|
725
|
+
if (c === void 0) return def;
|
|
726
|
+
if (typeof c === "number") return { default: c, min: c, max: c };
|
|
727
|
+
let { default: d, min = 0, max = 0 } = c;
|
|
728
|
+
if (min === 0 && max === 0) min = d, max = d;
|
|
729
|
+
return { default: d, min, max };
|
|
730
|
+
}
|
|
731
|
+
var MAX_CONNECT = 10;
|
|
732
|
+
var TOP_KEYS = ["name", "version", "pages", "connect", "scopes", "install_policy", "sessions", "boards", "tools", "commands", "hooks", "install_config", "listing", "release_notes", "labels"];
|
|
733
|
+
var TOOL_KEYS = ["name", "description", "parameters", "visibility", "example"];
|
|
734
|
+
var HOOK_KEYS = ["on", "filter", "handler", "say", "verify", "gate"];
|
|
735
|
+
var KIND_KEYS = ["kind", "title", "scopes", "create", "open_create", "join_modes", "default_join_mode", "listed", "capacity", "max_open", "open_ttl", "auto_start", "auto_end", "keep_seat_on_left_room", "invite_by", "boards", "outcomes", "labels", "serial", "card"];
|
|
736
|
+
var REFUSED = {
|
|
737
|
+
points: "points are not open to apps yet; remove manifest.points",
|
|
738
|
+
achievements: "app-defined achievements are not open yet; remove manifest.achievements",
|
|
739
|
+
"hooks[].call": "declarative call hooks are gone: use handler: true and call the tool's logic in the handler",
|
|
740
|
+
"sessions[].board": "a session kind's boards are a list: write boards: [ \u2026 ]"
|
|
741
|
+
};
|
|
742
|
+
var reCommandLiteral = /^[^{\s]+$/;
|
|
743
|
+
var rePagePath = /^(\/[A-Za-z0-9._~-]+)*\/?$/;
|
|
744
|
+
var reConnectHost = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
745
|
+
var LAND_DOMAINS = ["karpo.land", "karpo.ai"];
|
|
746
|
+
function oneEdit(a, b) {
|
|
747
|
+
if (Math.abs(a.length - b.length) > 1 || a === b) return false;
|
|
748
|
+
let i = 0;
|
|
749
|
+
let j = 0;
|
|
750
|
+
let edits = 0;
|
|
751
|
+
while (i < a.length && j < b.length) {
|
|
752
|
+
if (a[i] === b[j]) i++, j++;
|
|
753
|
+
else {
|
|
754
|
+
if (++edits > 1) return false;
|
|
755
|
+
if (a.length > b.length) i++;
|
|
756
|
+
else if (b.length > a.length) j++;
|
|
757
|
+
else i++, j++;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
return edits + (a.length - i) + (b.length - j) <= 1;
|
|
761
|
+
}
|
|
762
|
+
function unknownKey(key, known) {
|
|
763
|
+
const near = known.find((k) => k === key + "s" || oneEdit(key, k));
|
|
764
|
+
return `unknown field "${key}"` + (near ? `; did you mean "${near}"?` : "");
|
|
765
|
+
}
|
|
766
|
+
function checkKeys(obj, known, at, ignored, refusedAt, bad) {
|
|
767
|
+
for (const k of Object.keys(obj)) {
|
|
768
|
+
if (known.includes(k) || ignored.includes(k)) continue;
|
|
769
|
+
const field = at ? `${at}.${k}` : k;
|
|
770
|
+
bad(field, REFUSED[refusedAt ? `${refusedAt}.${k}` : k] ?? unknownKey(k, known));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
function checkConnectOrigin(s, allowHttp = false) {
|
|
774
|
+
const want = "an origin is https:// or wss:// and a host, e.g. https://api.example.com or https://*.example.com";
|
|
775
|
+
if (typeof s !== "string") return want;
|
|
776
|
+
const m = s.toLowerCase().replace(/\/$/, "").match(/^([a-z]+):\/\/([^/?#@]+)$/);
|
|
777
|
+
if (!m) return want;
|
|
778
|
+
const [, scheme, hostport] = m;
|
|
779
|
+
if (scheme !== "https" && scheme !== "wss" && !(allowHttp && (scheme === "http" || scheme === "ws"))) return want;
|
|
780
|
+
const host = hostport.replace(/:\d+$/, "").replace(/^\*\./, "");
|
|
781
|
+
if (!reConnectHost.test(host)) return want;
|
|
782
|
+
if (LAND_DOMAINS.some((d) => host === d || host.endsWith("." + d))) return `${s} is Karpo Land's own host: pages reach Land without connect`;
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
function validateManifest(m, opts = {}) {
|
|
786
|
+
const issues = [];
|
|
787
|
+
const bad = (field, message) => issues.push({ field: "manifest" + (field ? "." + field : ""), message });
|
|
788
|
+
if (!isObj(m)) {
|
|
789
|
+
bad("", "manifest is a JSON object");
|
|
790
|
+
return issues;
|
|
791
|
+
}
|
|
792
|
+
const man = m;
|
|
793
|
+
checkKeys(m, TOP_KEYS, "", ["summary", "icon", "color", "default_locale", "service_url"], "", bad);
|
|
794
|
+
if (runes(man.name) === 0 || runes(man.name) > 40) bad("name", "name must be 1 to 40 characters (the platform still requires it in the manifest)");
|
|
795
|
+
if (typeof man.version !== "string" || !reVersion.test(man.version)) bad("version", "version must be MAJOR.MINOR.PATCH, e.g. 1.2.0");
|
|
796
|
+
if (man.install_policy !== void 0 && man.install_policy !== "anyone" && man.install_policy !== "developer") bad("install_policy", "install_policy is anyone or developer");
|
|
797
|
+
if (man.connect !== void 0) {
|
|
798
|
+
if (!Array.isArray(man.connect)) bad("connect", "connect is a list of origins");
|
|
799
|
+
else {
|
|
800
|
+
if (man.connect.length > MAX_CONNECT) bad("connect", `connect lists at most ${MAX_CONNECT} origins`);
|
|
801
|
+
man.connect.forEach((o, i) => {
|
|
802
|
+
const e = checkConnectOrigin(o, !!opts.allowHttp);
|
|
803
|
+
if (e) bad(`connect[${i}]`, e);
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
(man.pages ?? []).forEach((p, i) => {
|
|
808
|
+
if (!p?.name || typeof p.path !== "string" || !p.path.startsWith("/")) return bad(`pages[${i}]`, "a page needs a name and a path starting with /");
|
|
809
|
+
const segs = p.path.split("/");
|
|
810
|
+
if (!rePagePath.test(p.path) || segs.includes(".") || segs.includes("..")) bad(`pages[${i}]`, "a page path is plain segments of A-Z a-z 0-9 . _ ~ - (no . or .. segments, no %, \\, ? or #)");
|
|
811
|
+
});
|
|
812
|
+
(man.scopes ?? []).forEach((s, i) => {
|
|
813
|
+
if (!SCOPES.includes(s)) bad(`scopes[${i}]`, `unknown scope "${s}"`);
|
|
814
|
+
});
|
|
815
|
+
const tools = /* @__PURE__ */ new Set();
|
|
816
|
+
if ((man.tools ?? []).length > 100) bad("tools", "at most 100 tools");
|
|
817
|
+
(man.tools ?? []).forEach((t, i) => {
|
|
818
|
+
const f = `tools[${i}]`;
|
|
819
|
+
if (isObj(t)) checkKeys(t, TOOL_KEYS, f, [], "tools[]", bad);
|
|
820
|
+
if (typeof t?.name !== "string" || !reName.test(t.name)) bad(f + ".name", "tool names are a-z, 0-9 and _, starting with a letter");
|
|
821
|
+
else if (tools.has(t.name)) bad(f + ".name", `tool "${t.name}" is declared twice`);
|
|
822
|
+
else tools.add(t.name);
|
|
823
|
+
if (t?.visibility !== void 0 && t.visibility !== "room" && t.visibility !== "caller") bad(f + ".visibility", "visibility is room or caller");
|
|
824
|
+
if (t?.parameters !== void 0) {
|
|
825
|
+
if (!isObj(t.parameters)) bad(f + ".parameters", "parameters is not a valid JSON Schema: must be an object");
|
|
826
|
+
else if (t.parameters.type !== void 0 && t.parameters.type !== "object") bad(f + ".parameters", 'arguments are a JSON object: parameters.type must be "object"');
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
const boards = /* @__PURE__ */ new Set();
|
|
830
|
+
const addBoard = (b, field, sessionBoard) => {
|
|
831
|
+
if (!isObj(b)) return bad(field, "a board is an object");
|
|
832
|
+
if (typeof b.key !== "string" || !reKey.test(b.key)) return bad(field, "board keys are a-z, 0-9 and _, starting with a letter, at most 32");
|
|
833
|
+
if (boards.has(b.key)) return bad(field, `board "${b.key}" is declared twice`);
|
|
834
|
+
if (runes(b.name) === 0 || runes(b.name) > 20) return bad(field, "board name is 1 to 20 characters");
|
|
835
|
+
const owner = sessionBoard ? "session" : b.owner ?? "install";
|
|
836
|
+
if (!["session", "install", "app"].includes(owner)) return bad(field, "an app's board belongs to a session, an install or the app");
|
|
837
|
+
const period = b.period ?? "none";
|
|
838
|
+
if (!["none", "day", "week", "month", "manual"].includes(period)) return bad(field, "period is none, day, week, month or manual");
|
|
839
|
+
if (owner === "session" && period !== "none") return bad(field, "a session board has one period");
|
|
840
|
+
if (b.order !== void 0 && b.order !== "asc" && b.order !== "desc") return bad(field, "order is asc or desc");
|
|
841
|
+
const detail = b.detail ?? "full";
|
|
842
|
+
if (detail !== "full" && detail !== "top") return bad(field, "detail is full or top");
|
|
843
|
+
if (owner === "session" && detail !== "full") return bad(field, "a session board keeps every score");
|
|
844
|
+
if (b.visibility !== void 0 && !["app_only", "self", "participants", "room_members", "public"].includes(b.visibility)) return bad(field, `unknown visibility "${b.visibility}"`);
|
|
845
|
+
if (b.tz && !validZone(b.tz)) return bad(field, `unknown time zone "${b.tz}"`);
|
|
846
|
+
if (b.square !== void 0 && b.square !== null && typeof b.square !== "boolean") return bad(field, "square is true or false");
|
|
847
|
+
if (b.square && (owner !== "app" || (b.visibility ?? "public") !== "public")) return bad(field, "only a public app board shows on the square");
|
|
848
|
+
boards.add(b.key);
|
|
849
|
+
};
|
|
850
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
851
|
+
(man.sessions ?? []).forEach((k, i) => {
|
|
852
|
+
const f = `sessions[${i}]`;
|
|
853
|
+
if (isObj(k)) checkKeys(k, KIND_KEYS, f, [], "sessions[]", bad);
|
|
854
|
+
const err = sessionKindError(k);
|
|
855
|
+
if (err) return bad(f, err);
|
|
856
|
+
if (kinds.has(k.kind)) return bad(f + ".kind", `session kind "${k.kind}" is declared twice`);
|
|
857
|
+
if (k.card !== void 0 && k.card !== null) {
|
|
858
|
+
if (!isObj(k.card)) return bad(f + ".card", "card is an object");
|
|
859
|
+
if (k.card.size !== void 0 && !CARD_SIZES.includes(k.card.size)) return bad(f + ".card.size", "card.size is standard or tall");
|
|
860
|
+
}
|
|
861
|
+
kinds.add(k.kind);
|
|
862
|
+
if (k.boards !== void 0) {
|
|
863
|
+
if (!Array.isArray(k.boards)) return bad(f + ".boards", "boards is a list");
|
|
864
|
+
if (k.boards.length > MAX_SESSION_BOARDS) return bad(f + ".boards", `at most ${MAX_SESSION_BOARDS} boards per session kind`);
|
|
865
|
+
k.boards.forEach((b, j) => addBoard({ ...b, owner: "session" }, `${f}.boards[${j}]`, true));
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
(man.boards ?? []).forEach((b, i) => addBoard(b, `boards[${i}]`, false));
|
|
869
|
+
(man.commands ?? []).forEach((c, i) => {
|
|
870
|
+
const f = `commands[${i}]`;
|
|
871
|
+
if (!tools.has(c?.tool)) return bad(f + ".tool", `command calls unknown tool "${c?.tool}"`);
|
|
872
|
+
if (c.reply_to !== void 0 && c.reply_to !== "app_post" && c.reply_to !== "session_post") return bad(f + ".reply_to", "reply_to is app_post or session_post");
|
|
873
|
+
const p = typeof c.pattern === "string" ? c.pattern.trim() : "";
|
|
874
|
+
if (p === "" || runes(p) > 100) return bad(f + ".pattern", "a command pattern is 1 to 100 characters");
|
|
875
|
+
if (c.reply_to === void 0 && !reCommandLiteral.test(p.split(/\s+/)[0] ?? "")) bad(f + ".pattern", "a command without reply_to starts with a literal word (no {variable}); for any text use reply_to or a message.created hook with room:read");
|
|
876
|
+
});
|
|
877
|
+
(man.hooks ?? []).forEach((h, i) => {
|
|
878
|
+
const f = `hooks[${i}]`;
|
|
879
|
+
if (isObj(h)) checkKeys(h, HOOK_KEYS, f, ["timeout", "default"], "hooks[]", bad);
|
|
880
|
+
if (!HOOK_EVENTS.includes(h?.on)) return bad(f + ".on", `unknown event "${h?.on}"`);
|
|
881
|
+
let forms = [!!h.handler, h.say != null, h.verify != null].filter(Boolean).length;
|
|
882
|
+
if (h.gate && forms === 0) forms = 1;
|
|
883
|
+
if (forms !== 1 && h.call == null) return bad(f, "a hook has exactly one of handler, say and verify");
|
|
884
|
+
if (h.verify) {
|
|
885
|
+
if (h.on !== "member.join") return bad(f + ".verify", "verify answers member.join only");
|
|
886
|
+
if (!h.verify.questions?.length) return bad(f + ".verify.questions", "verify needs at least one question");
|
|
887
|
+
}
|
|
888
|
+
if (h.say && (!h.say.text || runes(h.say.text) > 500)) return bad(f + ".say.text", "say text is 1 to 500 characters");
|
|
889
|
+
if (h.gate && h.on !== "member.join") return bad(f + ".gate", "only member.join hooks gate");
|
|
890
|
+
if (h.filter?.pattern) {
|
|
891
|
+
try {
|
|
892
|
+
new RegExp(h.filter.pattern);
|
|
893
|
+
} catch (e) {
|
|
894
|
+
return bad(f + ".filter.pattern", e.message);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (h.on === "message.created" && !h.filter?.reply_to && !(man.scopes ?? []).includes("room:read"))
|
|
898
|
+
return bad(f, "a message.created hook without filter.reply_to receives every room message: declare the room:read scope");
|
|
899
|
+
if (h.on === "member.join" && !(man.scopes ?? []).includes("room:gate")) return bad(f, "member.join hooks see join requests: declare the room:gate scope");
|
|
900
|
+
});
|
|
901
|
+
if (man.listing !== void 0 && man.listing !== null) {
|
|
902
|
+
const l = man.listing;
|
|
903
|
+
if (!isObj(l)) bad("listing", "listing is an object");
|
|
904
|
+
else {
|
|
905
|
+
if (l.square !== void 0 && typeof l.square !== "boolean") bad("listing.square", "square is true or false");
|
|
906
|
+
if (!LISTING_CATEGORIES.includes(l.category)) bad("listing.category", "category is game, social, tool, fun or work");
|
|
907
|
+
if (l.tagline !== void 0 && (typeof l.tagline !== "string" || runes(l.tagline) > 30)) bad("listing.tagline", "tagline is at most 30 characters");
|
|
908
|
+
if (l.cover_color !== void 0 && typeof l.cover_color !== "string") bad("listing.cover_color", "cover_color is a string");
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
if (man.install_policy === "developer") {
|
|
912
|
+
if (isObj(man.listing) && man.listing.square === true) bad("install_policy", "install_policy developer keeps the app in its developers' rooms: it cannot list on the square (listing.square)");
|
|
913
|
+
else if ((man.sessions ?? []).some((k) => isObj(k) && Array.isArray(k.scopes) && k.scopes.includes("open")))
|
|
914
|
+
bad("install_policy", "install_policy developer keeps the app in its developers' rooms: it cannot declare an open-scope session kind");
|
|
915
|
+
}
|
|
916
|
+
if (man.release_notes !== void 0 && man.release_notes !== null) {
|
|
917
|
+
if (typeof man.release_notes !== "string") bad("release_notes", "release_notes is text");
|
|
918
|
+
else if (runes(man.release_notes) > MAX_RELEASE_NOTES) bad("release_notes", `release_notes is at most ${MAX_RELEASE_NOTES} characters`);
|
|
919
|
+
}
|
|
920
|
+
if (man.install_config !== void 0 && man.install_config !== null && !isObj(man.install_config)) bad("install_config", "install_config is not a valid JSON Schema: must be an object");
|
|
921
|
+
return issues;
|
|
922
|
+
}
|
|
923
|
+
function sessionKindError(k) {
|
|
924
|
+
if (!isObj(k) || typeof k.kind !== "string" || !reKey.test(k.kind)) return "kind is a-z, 0-9 and _, starting with a letter";
|
|
925
|
+
for (const s of k.scopes ?? []) if (!["room", "multi_room", "open"].includes(s)) return "scopes are room, multi_room and open";
|
|
926
|
+
if (k.create !== void 0 && !["owner", "admin", "member"].includes(k.create)) return "create is owner, admin or member";
|
|
927
|
+
if (k.open_create !== void 0 && !["anyone", "app"].includes(k.open_create)) return "open_create is anyone or app";
|
|
928
|
+
const modes = k.join_modes?.length ? k.join_modes : ["open", "approval", "invite"];
|
|
929
|
+
for (const j of modes) if (!["open", "approval", "invite"].includes(j)) return "join modes are open, approval and invite";
|
|
930
|
+
if (k.default_join_mode !== void 0 && !modes.includes(k.default_join_mode)) return "default_join_mode must be one of join_modes";
|
|
931
|
+
if (k.invite_by !== void 0 && !["host", "participants"].includes(k.invite_by)) return "invite_by is host or participants";
|
|
932
|
+
const c = k.capacity ?? {};
|
|
933
|
+
const ranges = [
|
|
934
|
+
intChoice(c.min_players, { default: 1, min: 1, max: 1e3 }),
|
|
935
|
+
intChoice(c.max_players, { default: 0, min: 0, max: 1e3 }),
|
|
936
|
+
intChoice(c.max_observers, { default: 0, min: 0, max: 1e3 })
|
|
937
|
+
];
|
|
938
|
+
for (const r of ranges) {
|
|
939
|
+
if (r.min > r.default || r.max > 0 && r.default > r.max || r.max > 1e3 || r.min < 0) return "capacity defaults must lie within their ranges, at most 1000";
|
|
940
|
+
}
|
|
941
|
+
if (k.auto_end !== void 0 && (k.auto_end < 0 || k.auto_end > 30 * 24 * 3600)) return "auto_end is at most 30 days";
|
|
942
|
+
if (k.serial !== void 0 && typeof k.serial !== "boolean") return "serial is true or false";
|
|
943
|
+
if ((k.outcomes ?? []).length > 10) return "at most 10 custom outcomes";
|
|
944
|
+
for (const o of k.outcomes ?? []) {
|
|
945
|
+
if (!BASE_OUTCOMES.includes(o?.base) || !reKey.test(o?.code ?? "")) return "a custom outcome has a code and a base outcome";
|
|
946
|
+
}
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
function defineManifest(manifest, opts) {
|
|
950
|
+
const issues = validateManifest(manifest, opts);
|
|
951
|
+
if (issues.length) throw new ManifestError(issues);
|
|
952
|
+
return manifest;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// src/index.ts
|
|
956
|
+
function boardRef(p) {
|
|
957
|
+
const ns = p.platform ? "platform" : p.room ? `room:${p.room}` : `app:${p.app}`;
|
|
958
|
+
const part = p.session ? `/ss_${p.session}` : p.install ? `/in_${p.install}` : "";
|
|
959
|
+
return `${ns}/${p.key}${part}${p.seq ? `@${p.seq}` : ""}`;
|
|
960
|
+
}
|
|
961
|
+
export {
|
|
962
|
+
ACCEPTED,
|
|
963
|
+
APP_REASONS,
|
|
964
|
+
AppError,
|
|
965
|
+
BASE_OUTCOMES,
|
|
966
|
+
CARD_SIZES,
|
|
967
|
+
DEDUPE_TTL_SECONDS,
|
|
968
|
+
HOOK_EVENTS,
|
|
969
|
+
LISTING_CATEGORIES,
|
|
970
|
+
MANIFEST_IGNORED,
|
|
971
|
+
MAX_BODY_BYTES,
|
|
972
|
+
MAX_CONNECT,
|
|
973
|
+
MAX_IDEMPOTENCY_KEY,
|
|
974
|
+
MAX_RELEASE_NOTES,
|
|
975
|
+
MAX_RESIDENT_IDS,
|
|
976
|
+
MAX_SESSION_BOARDS,
|
|
977
|
+
MAX_SKEW_SECONDS,
|
|
978
|
+
ManifestError,
|
|
979
|
+
PlatformError,
|
|
980
|
+
Reasons,
|
|
981
|
+
SCOPES,
|
|
982
|
+
SDK_VERSION,
|
|
983
|
+
SIGNATURE_HEADER,
|
|
984
|
+
SIGNING_REREAD_SECONDS,
|
|
985
|
+
STATUSES,
|
|
986
|
+
TIMESTAMP_HEADER,
|
|
987
|
+
USER_AGENT,
|
|
988
|
+
boardRef,
|
|
989
|
+
checkConnectOrigin,
|
|
990
|
+
createApp,
|
|
991
|
+
createClient,
|
|
992
|
+
createDeveloperClient,
|
|
993
|
+
defineManifest,
|
|
994
|
+
isPlatformError,
|
|
995
|
+
isReason,
|
|
996
|
+
memoryDedupe,
|
|
997
|
+
shouldRetry,
|
|
998
|
+
sign,
|
|
999
|
+
signedHeaders,
|
|
1000
|
+
statusOfHttp,
|
|
1001
|
+
validateManifest,
|
|
1002
|
+
verifySignature
|
|
1003
|
+
};
|
|
1004
|
+
//# sourceMappingURL=index.js.map
|