@niscorp/moss 0.3.3 → 0.5.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.
Files changed (175) hide show
  1. package/CHANGELOG.md +534 -0
  2. package/DESIGN.md +265 -49
  3. package/DOCS.md +1524 -341
  4. package/README.md +37 -20
  5. package/dist/app-BoVB0_0j.d.ts +143 -0
  6. package/dist/app-Cc8VnOz8.d.cts +143 -0
  7. package/dist/chunk-3RIWTXGI.cjs +174 -0
  8. package/dist/chunk-3RIWTXGI.cjs.map +1 -0
  9. package/dist/chunk-4ZGAFZGS.js +152 -0
  10. package/dist/chunk-4ZGAFZGS.js.map +1 -0
  11. package/dist/chunk-5U2ZZUI5.cjs +137 -0
  12. package/dist/chunk-5U2ZZUI5.cjs.map +1 -0
  13. package/dist/chunk-6QPTMKRE.cjs +53 -0
  14. package/dist/chunk-6QPTMKRE.cjs.map +1 -0
  15. package/dist/chunk-BQRPR2F7.js +2704 -0
  16. package/dist/chunk-BQRPR2F7.js.map +1 -0
  17. package/dist/chunk-BZK37HR3.cjs +2716 -0
  18. package/dist/chunk-BZK37HR3.cjs.map +1 -0
  19. package/dist/chunk-FTFME3HS.cjs +383 -0
  20. package/dist/chunk-FTFME3HS.cjs.map +1 -0
  21. package/dist/{chunk-NE2EXMTO.js → chunk-FTZ6NFKZ.js} +43 -16
  22. package/dist/chunk-FTZ6NFKZ.js.map +1 -0
  23. package/dist/chunk-IUJ2TRNB.cjs +57 -0
  24. package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
  25. package/dist/chunk-IW3A2YIC.js +49 -0
  26. package/dist/chunk-IW3A2YIC.js.map +1 -0
  27. package/dist/chunk-JYBHJDT7.cjs +30 -0
  28. package/dist/chunk-JYBHJDT7.cjs.map +1 -0
  29. package/dist/chunk-NRZ3Z2FF.js +61 -0
  30. package/dist/chunk-NRZ3Z2FF.js.map +1 -0
  31. package/dist/chunk-PCPQMC7A.js +26 -0
  32. package/dist/chunk-PCPQMC7A.js.map +1 -0
  33. package/dist/chunk-T5BRTFKP.js +53 -0
  34. package/dist/chunk-T5BRTFKP.js.map +1 -0
  35. package/dist/chunk-TGKDS2T7.cjs +330 -0
  36. package/dist/chunk-TGKDS2T7.cjs.map +1 -0
  37. package/dist/chunk-TLNRFAQ6.js +326 -0
  38. package/dist/chunk-TLNRFAQ6.js.map +1 -0
  39. package/dist/chunk-VKQPOZDJ.cjs +72 -0
  40. package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
  41. package/dist/chunk-ZWB6QDGF.js +374 -0
  42. package/dist/chunk-ZWB6QDGF.js.map +1 -0
  43. package/dist/client/node.cjs.map +1 -1
  44. package/dist/client/node.d.cts +3 -1
  45. package/dist/client/node.d.ts +3 -1
  46. package/dist/client/node.js.map +1 -1
  47. package/dist/client.cjs +14 -302
  48. package/dist/client.cjs.map +1 -1
  49. package/dist/client.d.cts +9 -33
  50. package/dist/client.d.ts +9 -33
  51. package/dist/client.js +2 -2
  52. package/dist/document-CU3muGbz.d.cts +169 -0
  53. package/dist/document-UFbAd-Ka.d.ts +169 -0
  54. package/dist/env-CY8EGWnD.d.cts +24 -0
  55. package/dist/env-DEPqqHEb.d.ts +24 -0
  56. package/dist/index-BuDuOSyx.d.cts +130 -0
  57. package/dist/index-BuDuOSyx.d.ts +130 -0
  58. package/dist/index.cjs +45 -3918
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +46 -100
  61. package/dist/index.d.ts +46 -100
  62. package/dist/index.js +4 -94
  63. package/dist/index.js.map +1 -1
  64. package/dist/integrations.cjs +975 -0
  65. package/dist/integrations.cjs.map +1 -0
  66. package/dist/integrations.d.cts +63 -0
  67. package/dist/integrations.d.ts +63 -0
  68. package/dist/integrations.js +972 -0
  69. package/dist/integrations.js.map +1 -0
  70. package/dist/messages-CSwCJgH3.d.cts +51 -0
  71. package/dist/messages-CSwCJgH3.d.ts +51 -0
  72. package/dist/node.cjs +17 -3457
  73. package/dist/node.cjs.map +1 -1
  74. package/dist/node.d.cts +13 -10
  75. package/dist/node.d.ts +13 -10
  76. package/dist/node.js +5 -3
  77. package/dist/protocol.cjs +24 -0
  78. package/dist/protocol.cjs.map +1 -0
  79. package/dist/protocol.d.cts +11 -0
  80. package/dist/protocol.d.ts +11 -0
  81. package/dist/protocol.js +3 -0
  82. package/dist/protocol.js.map +1 -0
  83. package/dist/slots-96gNc9uH.d.cts +12 -0
  84. package/dist/slots-BX5N0Juv.d.ts +14 -0
  85. package/dist/slots-CU-AbnJg.d.cts +14 -0
  86. package/dist/slots-sLXDrlbG.d.ts +12 -0
  87. package/dist/socket-D90h1xSV.d.cts +24 -0
  88. package/dist/socket-D90h1xSV.d.ts +24 -0
  89. package/dist/targets-DInbLzff.d.cts +9 -0
  90. package/dist/targets-DInbLzff.d.ts +9 -0
  91. package/dist/terminal/dom/index.cjs +8 -3
  92. package/dist/terminal/dom/index.cjs.map +1 -1
  93. package/dist/terminal/dom/index.d.cts +3 -0
  94. package/dist/terminal/dom/index.d.ts +3 -0
  95. package/dist/terminal/dom/index.js +8 -3
  96. package/dist/terminal/dom/index.js.map +1 -1
  97. package/dist/terminal/dom/server.cjs +2 -7
  98. package/dist/terminal/dom/server.cjs.map +1 -1
  99. package/dist/terminal/dom/server.d.cts +3 -5
  100. package/dist/terminal/dom/server.d.ts +3 -5
  101. package/dist/terminal/dom/server.js +2 -7
  102. package/dist/terminal/dom/server.js.map +1 -1
  103. package/dist/terminal/index.cjs +22 -300
  104. package/dist/terminal/index.cjs.map +1 -1
  105. package/dist/terminal/index.d.cts +7 -2
  106. package/dist/terminal/index.d.ts +7 -2
  107. package/dist/terminal/index.js +21 -22
  108. package/dist/terminal/index.js.map +1 -1
  109. package/dist/terminal/ink/index.d.ts +3 -2
  110. package/dist/terminal/ink/index.js +149 -106
  111. package/dist/terminal/ink/index.js.map +1 -1
  112. package/dist/terminal/react/index.cjs +21 -71
  113. package/dist/terminal/react/index.cjs.map +1 -1
  114. package/dist/terminal/react/index.d.cts +5 -2
  115. package/dist/terminal/react/index.d.ts +5 -2
  116. package/dist/terminal/react/index.js +17 -20
  117. package/dist/terminal/react/index.js.map +1 -1
  118. package/dist/terminal/react/server.cjs +4 -68
  119. package/dist/terminal/react/server.cjs.map +1 -1
  120. package/dist/terminal/react/server.d.cts +9 -6
  121. package/dist/terminal/react/server.d.ts +9 -6
  122. package/dist/terminal/react/server.js +3 -18
  123. package/dist/terminal/react/server.js.map +1 -1
  124. package/dist/terminal/tty/index.cjs +147 -130
  125. package/dist/terminal/tty/index.cjs.map +1 -1
  126. package/dist/terminal/tty/index.d.cts +4 -2
  127. package/dist/terminal/tty/index.d.ts +4 -2
  128. package/dist/terminal/tty/index.js +147 -130
  129. package/dist/terminal/tty/index.js.map +1 -1
  130. package/dist/terminal/vue/index.cjs +20 -72
  131. package/dist/terminal/vue/index.cjs.map +1 -1
  132. package/dist/terminal/vue/index.d.cts +8 -12
  133. package/dist/terminal/vue/index.d.ts +8 -12
  134. package/dist/terminal/vue/index.js +45 -1
  135. package/dist/terminal/vue/index.js.map +1 -1
  136. package/dist/terminal/vue/server.cjs +4 -76
  137. package/dist/terminal/vue/server.cjs.map +1 -1
  138. package/dist/terminal/vue/server.d.cts +7 -6
  139. package/dist/terminal/vue/server.d.ts +7 -6
  140. package/dist/terminal/vue/server.js +3 -10
  141. package/dist/terminal/vue/server.js.map +1 -1
  142. package/dist/tide.cjs +41 -0
  143. package/dist/tide.cjs.map +1 -0
  144. package/dist/tide.d.cts +25 -0
  145. package/dist/tide.d.ts +25 -0
  146. package/dist/tide.js +39 -0
  147. package/dist/tide.js.map +1 -0
  148. package/dist/unverified.cjs +12 -0
  149. package/dist/unverified.cjs.map +1 -0
  150. package/dist/unverified.d.cts +7 -0
  151. package/dist/unverified.d.ts +7 -0
  152. package/dist/unverified.js +10 -0
  153. package/dist/unverified.js.map +1 -0
  154. package/dist/vite.cjs +96 -232
  155. package/dist/vite.cjs.map +1 -1
  156. package/dist/vite.d.cts +6 -8
  157. package/dist/vite.d.ts +6 -8
  158. package/dist/vite.js +97 -71
  159. package/dist/vite.js.map +1 -1
  160. package/package.json +56 -13
  161. package/dist/chunk-4T6KAXBP.js +0 -256
  162. package/dist/chunk-4T6KAXBP.js.map +0 -1
  163. package/dist/chunk-AUZMT3GL.js +0 -3406
  164. package/dist/chunk-AUZMT3GL.js.map +0 -1
  165. package/dist/chunk-EMRDIZLY.js +0 -99
  166. package/dist/chunk-EMRDIZLY.js.map +0 -1
  167. package/dist/chunk-HOZID4EM.js +0 -366
  168. package/dist/chunk-HOZID4EM.js.map +0 -1
  169. package/dist/chunk-NE2EXMTO.js.map +0 -1
  170. package/dist/chunk-SK4PDGEE.js +0 -55
  171. package/dist/chunk-SK4PDGEE.js.map +0 -1
  172. package/dist/document-DhWxieUc.d.cts +0 -1024
  173. package/dist/document-DhWxieUc.d.ts +0 -1024
  174. package/dist/slots-Do9ScG7v.d.cts +0 -37
  175. package/dist/slots-Do9ScG7v.d.ts +0 -37
@@ -0,0 +1,975 @@
1
+ 'use strict';
2
+
3
+ var chunkJYBHJDT7_cjs = require('./chunk-JYBHJDT7.cjs');
4
+ var crypto = require('crypto');
5
+ var zod = require('zod');
6
+ var hono = require('hono');
7
+ var nova = require('@niscorp/nova');
8
+ var reflect = require('@niscorp/nova/reflect');
9
+ var strata = require('@niscorp/strata');
10
+
11
+ zod.z.looseObject({
12
+ integration: zod.z.string(),
13
+ principal: zod.z.string(),
14
+ scope: zod.z.record(zod.z.string(), zod.z.unknown()),
15
+ iat: zod.z.number(),
16
+ exp: zod.z.number()
17
+ });
18
+ var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ var SEED_BYTES = 32;
20
+ var seedRefusal = (bytes) => new Error(
21
+ `moss: the signing seed decodes to ${bytes} ${bytes === 1 ? "byte" : "bytes"}, and a signing key is ${SEED_BYTES}. Give ${SEED_BYTES} random bytes as base64 (\`signingSeed\` of \`createIntegrations\`), or give none: with no seed a key is made when the server starts and kept nowhere.`
22
+ );
23
+ var signerFromSeed = (seed) => {
24
+ const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, SEED_BYTES)]);
25
+ const privateKey = crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
26
+ return { privateKey, publicKey: crypto.createPublicKey(privateKey.export({ type: "pkcs8", format: "pem" })) };
27
+ };
28
+ var createAssertionSigner = (seedB64) => {
29
+ const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
30
+ if (seed !== void 0 && seed.length < SEED_BYTES) throw seedRefusal(seed.length);
31
+ const { publicKey, privateKey } = seed !== void 0 ? signerFromSeed(seed) : crypto.generateKeyPairSync("ed25519");
32
+ const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
33
+ return {
34
+ verifyKey,
35
+ mint: (claims, ttlMs = 3e4) => {
36
+ const iat = Date.now();
37
+ const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
38
+ return `${b64url(body)}.${b64url(crypto.sign(null, body, privateKey))}`;
39
+ }
40
+ };
41
+ };
42
+ var mintIntegrationKey = () => `ik_${crypto.randomBytes(32).toString("hex")}`;
43
+ var hashIntegrationKey = (key) => crypto.createHash("sha256").update(key).digest("hex");
44
+ var KEY_PREFIX = "ik_";
45
+ var NO_ACTOR = { refused: { status: 403, error: "no_actor", message: "This integration has no actor there." } };
46
+ var keyCredential = (deps) => async (token, request) => {
47
+ const integration = await deps.byKey(token);
48
+ if (integration === void 0) return { refused: { status: 401, error: "invalid_key", message: "The integration key did not resolve." } };
49
+ const actor = await deps.actor?.(integration, request.headers.get("x-nisc-acts-for") ?? "") ?? null;
50
+ if (actor === null) return NO_ACTOR;
51
+ const resolved = await deps.resolveIdentity(actor);
52
+ if (resolved.roles.length === 1 && resolved.roles[0] === "public") return NO_ACTOR;
53
+ return { principal: actor };
54
+ };
55
+
56
+ // src/integrations/entries.ts
57
+ var REGISTRY_TABLES = ["integrations", "integration_actions"];
58
+ var PAGE = 500;
59
+ var fromContext = (columns) => Object.fromEntries(columns.map((column) => [column, { $context: column }]));
60
+ var byId = { eq: ["integrations.id", { $context: "id" }] };
61
+ var approved = { eq: ["integrations.status", "approved"] };
62
+ var afterAction = {
63
+ or: [
64
+ { gt: ["integration_actions.integration_id", { $context: "after_integration" }] },
65
+ { and: [{ eq: ["integration_actions.integration_id", { $context: "after_integration" }] }, { gt: ["integration_actions.action_id", { $context: "after_action" }] }] }
66
+ ]
67
+ };
68
+ var byActionKey = [
69
+ { field: "integration_actions.integration_id", dir: "asc" },
70
+ { field: "integration_actions.action_id", dir: "asc" }
71
+ ];
72
+ var find = {
73
+ fingerprint: "integrations/find",
74
+ intent: "Where an integration is, whether it is approved, and what its proxy lets through",
75
+ dsl: { from: ["integrations"], fields: ["integrations.url", "integrations.status", "integrations.reach"], filter: byId, limit: 1 }
76
+ };
77
+ var registration = {
78
+ fingerprint: "integrations/registration",
79
+ intent: "Whether an integration is approved, and whether it was issued a key",
80
+ dsl: { from: ["integrations"], fields: ["integrations.status", "integrations.key_hash"], filter: byId, limit: 1 }
81
+ };
82
+ var requested = {
83
+ fingerprint: "integrations/requested",
84
+ intent: "What an integration asked to read and write",
85
+ dsl: { from: ["integrations"], fields: ["integrations.requested_data"], filter: byId, limit: 1 }
86
+ };
87
+ var byKey = {
88
+ fingerprint: "integrations/by-key",
89
+ intent: "The approved integration a key hash belongs to",
90
+ dsl: { from: ["integrations"], fields: ["integrations.id"], filter: { and: [{ eq: ["integrations.key_hash", { $context: "key_hash" }] }, approved] }, limit: 1 }
91
+ };
92
+ var recordFailedImport = {
93
+ fingerprint: "integrations/record-failed-import",
94
+ intent: "Keep why an import did not land on the row, and the address it was fetched from",
95
+ mutation: {
96
+ op: "insert",
97
+ table: "integrations",
98
+ values: fromContext(["id", "url", "last_error"]),
99
+ onConflict: { target: ["id"], set: fromContext(["url", "last_error"]) }
100
+ }
101
+ };
102
+ var importedColumns = {
103
+ ...fromContext(["url", "requested_actions", "requested_data", "reach", "phrasebook", "extension", "last_import_at"]),
104
+ last_error: null
105
+ };
106
+ var writeBundleStatements = [
107
+ { op: "insert", table: "integrations", values: { ...fromContext(["id"]), ...importedColumns }, onConflict: { target: ["id"], set: importedColumns } },
108
+ { op: "delete", table: "integration_actions", where: { eq: ["integration_actions.integration_id", { $context: "id" }] } },
109
+ {
110
+ op: "insertEach",
111
+ table: "integration_actions",
112
+ items: { $context: "actions" },
113
+ values: {
114
+ integration_id: { $context: "id" },
115
+ action_id: { $item: "action_id" },
116
+ definition: { $item: "definition" },
117
+ grammar: { $item: "grammar" }
118
+ }
119
+ }
120
+ ];
121
+ var writeBundle = {
122
+ fingerprint: "integrations/write-bundle",
123
+ intent: "Land a bundle: the row of its integration as the bundle says it is now, and its actions in place of the ones before",
124
+ mutation: writeBundleStatements
125
+ };
126
+ var writeBundleAndKeepKey = {
127
+ fingerprint: "integrations/write-bundle-and-keep-key",
128
+ intent: "Land a bundle, and keep the hash of the key its integration is issued with it, where it holds none",
129
+ mutation: [...writeBundleStatements, { op: "update", table: "integrations", set: fromContext(["key_hash"]), where: { and: [byId, { isNull: "integrations.key_hash" }] } }]
130
+ };
131
+ var approve = {
132
+ fingerprint: "integrations/approve",
133
+ intent: "Approve an integration: what it asked to read and write becomes what it is granted",
134
+ mutation: { op: "update", table: "integrations", set: { status: "approved", ...fromContext(["approved_data"]) }, where: byId }
135
+ };
136
+ var setBackToPending = {
137
+ fingerprint: "integrations/set-back-to-pending",
138
+ intent: "Take an approval back, and keep why on the row",
139
+ mutation: { op: "update", table: "integrations", set: { status: "pending", ...fromContext(["last_error"]) }, where: byId }
140
+ };
141
+ var remove = {
142
+ fingerprint: "integrations/remove",
143
+ intent: "Remove an integration; its actions go with the row",
144
+ mutation: { op: "delete", table: "integrations", where: byId }
145
+ };
146
+ var list = {
147
+ fingerprint: "integrations/list",
148
+ intent: "Every integration, with what its row keeps of the host app\u2019s own vocabulary, a page at a time",
149
+ dsl: {
150
+ from: ["integrations"],
151
+ fields: [
152
+ "integrations.id",
153
+ "integrations.url",
154
+ "integrations.status",
155
+ "integrations.requested_actions",
156
+ "integrations.requested_data",
157
+ "integrations.approved_data",
158
+ "integrations.extension",
159
+ "integrations.last_import_at",
160
+ "integrations.last_error"
161
+ ],
162
+ filter: { gt: ["integrations.id", { $context: "after" }] },
163
+ sort: [{ field: "integrations.id", dir: "asc" }],
164
+ limit: PAGE
165
+ }
166
+ };
167
+ var actionCounts = {
168
+ fingerprint: "integrations/action-counts",
169
+ intent: "How many actions each integration ships, a page at a time",
170
+ dsl: {
171
+ from: ["integration_actions"],
172
+ fields: ["integration_actions.integration_id"],
173
+ aggregate: { action_count: { count: "*" } },
174
+ groupBy: ["integration_actions.integration_id"],
175
+ filter: { gt: ["integration_actions.integration_id", { $context: "after" }] },
176
+ sort: [{ field: "integration_actions.integration_id", dir: "asc" }],
177
+ limit: PAGE
178
+ }
179
+ };
180
+ var storedActions = {
181
+ fingerprint: "integrations/stored-actions",
182
+ intent: "The stored actions of every approved integration, a page at a time",
183
+ dsl: {
184
+ from: ["integration_actions", "integrations"],
185
+ fields: ["integration_actions.integration_id", "integration_actions.action_id", "integration_actions.definition", "integration_actions.grammar"],
186
+ filter: { and: [approved, afterAction] },
187
+ sort: byActionKey,
188
+ limit: PAGE
189
+ }
190
+ };
191
+ var actionsOf = {
192
+ fingerprint: "integrations/actions-of",
193
+ intent: "The stored actions of one integration, whether or not it is approved, a page at a time",
194
+ dsl: {
195
+ from: ["integration_actions"],
196
+ fields: ["integration_actions.integration_id", "integration_actions.action_id", "integration_actions.definition", "integration_actions.grammar"],
197
+ filter: { and: [{ eq: ["integration_actions.integration_id", { $context: "id" }] }, afterAction] },
198
+ sort: byActionKey,
199
+ limit: PAGE
200
+ }
201
+ };
202
+ var REGISTRY_ENTRIES = [
203
+ find,
204
+ registration,
205
+ requested,
206
+ byKey,
207
+ recordFailedImport,
208
+ writeBundle,
209
+ writeBundleAndKeepKey,
210
+ approve,
211
+ setBackToPending,
212
+ remove,
213
+ list,
214
+ actionCounts,
215
+ storedActions,
216
+ actionsOf
217
+ ];
218
+
219
+ // src/integrations/reach.ts
220
+ var normalizePath = (path) => (path.split("?")[0] ?? "").replace(/\/+$/, "");
221
+ var reachOf = (bundle, integrationId) => {
222
+ const own = `/integrations/${integrationId}/`;
223
+ const reach = {};
224
+ const admit = (url, actionId) => {
225
+ if (!url.startsWith(own)) return;
226
+ const key = normalizePath(url);
227
+ const held = reach[key] ??= [];
228
+ if (!held.includes(actionId)) held.push(actionId);
229
+ };
230
+ for (const [actionId, action] of Object.entries(bundle.actions)) {
231
+ for (const endpoint of Object.values(action.endpoints ?? {})) {
232
+ admit("url" in endpoint ? endpoint.url : "", actionId);
233
+ }
234
+ }
235
+ return Object.fromEntries(Object.entries(reach).sort(([a], [b]) => a.localeCompare(b)));
236
+ };
237
+ var reachAdmits = (reach, path, held) => (reach[normalizePath(path)] ?? []).some((actionId) => held.has(actionId));
238
+ var reachDeclares = (reach, path) => reach[normalizePath(path)] !== void 0;
239
+
240
+ // src/integrations/forward.ts
241
+ var createForwarder = (deps) => {
242
+ const send = deps.fetch ?? fetch;
243
+ const sent = async (url, request) => {
244
+ try {
245
+ const init = await request();
246
+ return { kind: "answered", response: await send(url, { ...init, signal: AbortSignal.timeout(deps.timeoutMs) }) };
247
+ } catch (error) {
248
+ return { kind: "unreachable", error };
249
+ }
250
+ };
251
+ return async (call) => {
252
+ const found = await deps.find(call.integration);
253
+ if (found === void 0) return { kind: "refused", why: "unknown" };
254
+ if (found.status !== "approved") return { kind: "refused", why: "unapproved", status: found.status };
255
+ const url = `${found.url.replace(/\/$/, "")}/${call.path}`;
256
+ if (call.principal === void 0) {
257
+ if (call.admits !== void 0 && !call.admits(found)) return { kind: "refused", why: "inadmissible" };
258
+ return sent(url, call.request);
259
+ }
260
+ const principal = call.principal;
261
+ const caller = await deps.resolveIdentity(principal);
262
+ if (caller.installed !== void 0 && !caller.installed.includes(call.integration)) return { kind: "refused", why: "uninstalled" };
263
+ if (call.admits !== void 0 && !call.admits(found, caller)) return { kind: "refused", why: "inadmissible" };
264
+ const assertion = deps.mint({ integration: call.integration, principal, scope: { ...await deps.scopeOf(principal), ...call.scope ?? {} } });
265
+ return sent(url, () => call.request(assertion));
266
+ };
267
+ };
268
+ var relayed = (response, otherwise, more = {}) => new Response(response.body, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? otherwise, ...more } });
269
+ var HOOK_LIMIT = 240;
270
+ var HOOK_WINDOW_MS = 6e4;
271
+ var createHookLimit = () => {
272
+ const hits = /* @__PURE__ */ new Map();
273
+ return (id, now) => {
274
+ const seen = hits.get(id);
275
+ if (seen === void 0 || now >= seen.resets) {
276
+ hits.set(id, { count: 1, resets: now + HOOK_WINDOW_MS });
277
+ return true;
278
+ }
279
+ seen.count += 1;
280
+ return seen.count <= HOOK_LIMIT;
281
+ };
282
+ };
283
+ var webhook = (deps, routes) => {
284
+ const hookAllows = createHookLimit();
285
+ routes.post("/integrations/:id/hook/*", async (c) => {
286
+ const id = c.req.param("id");
287
+ const here = new URL(c.req.url);
288
+ const headers = new Headers(c.req.raw.headers);
289
+ headers.delete("authorization");
290
+ headers.delete("host");
291
+ const ended = await deps.forward({
292
+ integration: id,
293
+ admits: () => hookAllows(id, Date.now()),
294
+ path: `${here.pathname.split("/").slice(3).join("/")}${here.search}`,
295
+ // The body goes on as the bytes that arrived: the vendor's signature is over exactly those.
296
+ request: async () => ({ method: "POST", headers, body: await c.req.arrayBuffer() })
297
+ });
298
+ if (ended.kind === "refused") {
299
+ return ended.why === "inadmissible" ? c.json({ message: "Too many." }, 429) : c.json({ message: "Not found." }, 404);
300
+ }
301
+ if (ended.kind === "unreachable") return c.json({ message: "The integration is unreachable." }, 502);
302
+ return relayed(ended.response, "application/json");
303
+ });
304
+ };
305
+ var proxy = (deps, routes) => {
306
+ routes.all("/integrations/:id/*", async (c) => {
307
+ const principal = c.get("principal");
308
+ if (principal === null) return c.json({ message: "Sign in first." }, 401);
309
+ const id = c.req.param("id");
310
+ const here = new URL(c.req.url);
311
+ const ended = await deps.forward({
312
+ integration: id,
313
+ principal,
314
+ admits: (found, caller) => reachAdmits(found.reach, c.req.path, new Set(deps.grantedActionIds(caller.roles, caller.installed))),
315
+ path: `${here.pathname.split("/").slice(3).join("/")}${here.search}`,
316
+ request: async (assertion) => ({
317
+ method: c.req.method,
318
+ headers: { "content-type": "application/json", authorization: `Bearer ${assertion}` },
319
+ ...c.req.method === "GET" ? {} : { body: await c.req.text() }
320
+ })
321
+ });
322
+ if (ended.kind === "refused") return c.json({ message: ended.why === "uninstalled" ? "Not installed here." : "No such integration." }, 404);
323
+ if (ended.kind === "unreachable") return c.json({ message: "The integration is unreachable." }, 502);
324
+ return relayed(ended.response, "application/json");
325
+ });
326
+ };
327
+ var proxyRoutes = (deps) => {
328
+ const routes = new hono.Hono();
329
+ webhook(deps, routes);
330
+ proxy(deps, routes);
331
+ return routes;
332
+ };
333
+ var callIntegrationWith = (deps) => {
334
+ const emit = chunkJYBHJDT7_cjs.emitterOf(deps.telemetry);
335
+ return async (id, path, init) => {
336
+ const clock = emit === void 0 ? void 0 : chunkJYBHJDT7_cjs.spanClock();
337
+ const done = (status, httpStatus) => {
338
+ if (emit === void 0 || clock === void 0) return;
339
+ emit({
340
+ name: "integration.call",
341
+ startUnixNano: clock.startUnixNano,
342
+ endUnixNano: clock.endUnixNano(),
343
+ status,
344
+ attributes: { integration: id, path, ...httpStatus !== void 0 ? { httpStatus } : {} }
345
+ });
346
+ };
347
+ const ended = await deps.forward({
348
+ integration: id,
349
+ principal: init.principal,
350
+ ...init.scope === void 0 ? {} : { scope: init.scope },
351
+ path: path.replace(/^\/+/, ""),
352
+ request: (assertion) => ({
353
+ method: init.method ?? "POST",
354
+ headers: { "content-type": "application/json", authorization: `Bearer ${assertion}` },
355
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) }
356
+ })
357
+ });
358
+ if (ended.kind === "unreachable") {
359
+ done("error");
360
+ throw ended.error;
361
+ }
362
+ if (ended.kind === "refused") {
363
+ done("refused");
364
+ const why = ended.why === "unapproved" ? `not approved (status "${ended.status}").` : ended.why === "uninstalled" ? `not installed for "${init.principal}".` : "no such integration.";
365
+ throw new Error(`moss: callIntegration("${id}"): ${why}`);
366
+ }
367
+ done(ended.response.ok ? "ok" : "error", ended.response.status);
368
+ return ended.response;
369
+ };
370
+ };
371
+ var INTEGRATION_PATH = /^\/integrations\/([a-z][a-z0-9-]*)\//;
372
+ var SaidSchema = zod.z.looseObject({ message: zod.z.string() });
373
+ var withFallbackMessage = (inner) => async (url, init) => {
374
+ const integration = INTEGRATION_PATH.exec(url)?.[1];
375
+ if (integration === void 0) return inner(url, init);
376
+ const fallback = (status) => {
377
+ const body = { message: `The ${integration} integration is not answering right now. The rest of the app is unaffected.` };
378
+ return { ok: false, status, json: async () => body, text: async () => JSON.stringify(body) };
379
+ };
380
+ let reply;
381
+ try {
382
+ reply = await inner(url, init);
383
+ } catch {
384
+ return fallback(502);
385
+ }
386
+ if (reply.ok) return reply;
387
+ try {
388
+ const body = await reply.json();
389
+ const said = SaidSchema.safeParse(body);
390
+ if (said.success && said.data.message !== "The integration is unreachable.") {
391
+ return { ok: false, status: reply.status, json: async () => body, text: async () => JSON.stringify(body) };
392
+ }
393
+ } catch {
394
+ }
395
+ return fallback(reply.status);
396
+ };
397
+ var INTEGRATION_ID = /^[a-z][a-z0-9-]*$/;
398
+ var INTEGRATION_ID_RULE = "An integration id is lower-case letters, digits and hyphens, and starts with a letter.";
399
+ var BundleSchema = zod.z.object({
400
+ integration: zod.z.string().regex(INTEGRATION_ID, INTEGRATION_ID_RULE),
401
+ grants: zod.z.object({
402
+ actions: zod.z.array(zod.z.string()).default([]),
403
+ data: zod.z.array(zod.z.string()).default([])
404
+ }).default({ actions: [], data: [] }),
405
+ grammar: zod.z.record(zod.z.string(), zod.z.number().int().nonnegative()).optional(),
406
+ actions: zod.z.record(zod.z.string(), nova.ActionDefinitionSchema),
407
+ phrasebook: zod.z.record(zod.z.string().regex(/^[a-z]{2}$/, "a phrasebook is keyed by LANGUAGE (`de`), never by locale (`de-AT`)"), zod.z.record(zod.z.string(), zod.z.string())).default({}),
408
+ extension: zod.z.unknown().optional()
409
+ }).strict();
410
+ var AUDIENCE = /^[a-z][a-z0-9-]*$/;
411
+ var upgradeBundle = (payload, upgrader) => {
412
+ if (upgrader === void 0 || !reflect.isRecord(payload) || !reflect.isRecord(payload["actions"])) return { ok: true, payload };
413
+ const declared = payload["grammar"];
414
+ const stamp = reflect.isRecord(declared) ? Object.fromEntries(Object.entries(declared).map(([k, v]) => [k, Number(v)])) : {};
415
+ try {
416
+ const actions = Object.fromEntries(
417
+ Object.entries(payload["actions"]).map(([id, definition]) => [id, upgrader.upgrade(definition, { kind: "nisc.nova/action", stamp }).document])
418
+ );
419
+ return { ok: true, payload: { ...payload, actions, grammar: upgrader.stamp } };
420
+ } catch (error) {
421
+ if (!(error instanceof strata.StrataError)) throw error;
422
+ return {
423
+ ok: false,
424
+ reasons: error.code === "TOO_NEW" ? ["This integration was built on newer nisc grammars than this host runs \u2014 the host must be updated first.", ...error.details] : [error.message.split("\n")[0] ?? error.code, ...error.details]
425
+ };
426
+ }
427
+ };
428
+ var endpointReasons = (id, action, ctx) => {
429
+ const reasons = [];
430
+ for (const [name, endpoint] of Object.entries(action.endpoints ?? {})) {
431
+ if ("fn" in endpoint) {
432
+ reasons.push(`action ${id}: endpoint "${name}" uses fn:, which runs in this app's process`);
433
+ continue;
434
+ }
435
+ const url = endpoint.url;
436
+ const own = `/integrations/${ctx.integrationId}/`;
437
+ if (url.startsWith(own)) {
438
+ if (url.startsWith(`${own}hook/`)) {
439
+ reasons.push(`action ${id}: endpoint "${name}" is under /hook/, which is the unauthenticated webhook path`);
440
+ }
441
+ continue;
442
+ }
443
+ if (!url.startsWith("/api/")) {
444
+ reasons.push(`action ${id}: endpoint "${name}" calls "${url}" \u2014 only ${own}* or /api/*/vex`);
445
+ continue;
446
+ }
447
+ const fingerprint = reflect.isRecord(endpoint.request) ? endpoint.request["fingerprint"] : void 0;
448
+ if (typeof fingerprint !== "string") {
449
+ reasons.push(`action ${id}: endpoint "${name}" calls the app without naming a fingerprint`);
450
+ } else if (!ctx.fingerprints.has(fingerprint)) {
451
+ reasons.push(`action ${id}: endpoint "${name}" calls "${fingerprint}", which this app does not serve`);
452
+ }
453
+ }
454
+ return reasons;
455
+ };
456
+ var actionReasons = (bundle, ctx) => {
457
+ const reasons = [];
458
+ for (const [id, action] of Object.entries(bundle.actions)) {
459
+ const parts = id.split(".");
460
+ if (parts[0] !== "ext" || parts.length < 4 || !AUDIENCE.test(parts[1] ?? "")) {
461
+ reasons.push(`action ${id}: not namespaced ext.<audience>.<integration>.<name>`);
462
+ } else if (parts[2] !== ctx.integrationId) {
463
+ reasons.push(`action ${id}: claims the "${parts[2]}" namespace, which belongs to somebody else`);
464
+ }
465
+ if (action.id !== id) reasons.push(`action ${id}: its own id says "${action.id}"`);
466
+ reasons.push(...ctx.layoutMisfits(action.layout).map((misfit) => `action ${id}: ${misfit}`));
467
+ reasons.push(...endpointReasons(id, action, ctx));
468
+ }
469
+ return reasons;
470
+ };
471
+ var chainReasons = (bundle, ctx) => ctx.endlessChains({ ...ctx.hostActions ?? {}, ...bundle.actions }).filter((chain) => chain.through.some((actionId) => bundle.actions[actionId] !== void 0)).map((chain) => `a chain of steps that never ends: ${chain.path}`);
472
+ var extensionContextOf = (bundle, ctx) => ({
473
+ integration: ctx.integrationId,
474
+ url: ctx.url,
475
+ actions: bundle.actions,
476
+ fingerprints: ctx.fingerprints,
477
+ layoutMisfits: ctx.layoutMisfits
478
+ });
479
+ var extensionOf = (bundle, ctx) => {
480
+ const config = ctx.extension;
481
+ if (config === void 0) return { reasons: bundle.extension === void 0 ? [] : ["extension: this app takes no extension, and the bundle carries one."] };
482
+ const parsed = config.schema.safeParse(bundle.extension);
483
+ if (!parsed.success) return { reasons: parsed.error.issues.map((issue) => `${["extension", ...issue.path].join(".")}: ${issue.message}`) };
484
+ return { reasons: config.check?.(parsed.data, extensionContextOf(bundle, ctx)) ?? [], extension: parsed.data };
485
+ };
486
+ var schemaReasons = (error) => error.issues.flatMap(
487
+ (issue) => issue.code === "unrecognized_keys" && issue.path.length === 0 ? issue.keys.map((key) => `"${key}" is not a field of a bundle. What belongs to the host app\u2019s own vocabulary goes under \`extension\`.`) : [`${issue.path.join(".") || "(root)"}: ${issue.message}`]
488
+ );
489
+ var runIntake = (payload, ctx) => {
490
+ if (strata.exceedsDepth(payload)) return { ok: false, reasons: [strata.depthRefusal()] };
491
+ const upgraded = upgradeBundle(payload, ctx.upgrader);
492
+ if (!upgraded.ok) return upgraded;
493
+ const parsed = BundleSchema.safeParse(upgraded.payload);
494
+ if (!parsed.success) return { ok: false, reasons: schemaReasons(parsed.error) };
495
+ const bundle = parsed.data;
496
+ const extension = extensionOf(bundle, ctx);
497
+ const reasons = [
498
+ ...bundle.integration === ctx.integrationId ? [] : [`bundle says it is "${bundle.integration}" but was fetched as "${ctx.integrationId}"`],
499
+ ...actionReasons(bundle, ctx),
500
+ ...chainReasons(bundle, ctx),
501
+ ...extension.reasons
502
+ ];
503
+ return reasons.length > 0 ? { ok: false, reasons } : { ok: true, bundle, extension: extension.extension };
504
+ };
505
+ var rowsOf = (answered) => zod.z.array(zod.z.unknown()).parse(answered);
506
+ var everyRow = async (row, page, after) => {
507
+ const rows = rowsOf(await page(after)).map((answered) => row.parse(answered));
508
+ const last = rows.at(-1);
509
+ return rows.length < PAGE || last === void 0 ? rows : [...rows, ...await everyRow(row, page, last)];
510
+ };
511
+ var strings = zod.z.array(zod.z.string()).catch([]);
512
+ var ReachSchema = zod.z.record(zod.z.string(), zod.z.array(zod.z.string())).catch({});
513
+ var FoundRowSchema = zod.z.object({ url: zod.z.string(), status: zod.z.string(), reach: ReachSchema });
514
+ var RegistrationRowSchema = zod.z.object({ status: zod.z.string(), key_hash: zod.z.string().nullish() });
515
+ var WrittenRowSchema = zod.z.looseObject({ key_hash: zod.z.string().nullish() });
516
+ var WrittenSchema = zod.z.union([zod.z.array(WrittenRowSchema), WrittenRowSchema.transform((row) => [row]), zod.z.undefined().transform(() => [])]);
517
+ var RequestedRowSchema = zod.z.object({ requested_data: strings });
518
+ var KeyHolderRowSchema = zod.z.object({ id: zod.z.string() });
519
+ var actionKey = { integration_id: zod.z.string(), action_id: zod.z.string() };
520
+ var afterAction2 = (last) => ({
521
+ after_integration: last?.integration_id ?? "",
522
+ after_action: last?.action_id ?? ""
523
+ });
524
+ var StoredActionRowSchema = zod.z.object({ ...actionKey, definition: zod.z.unknown(), grammar: zod.z.unknown() });
525
+ var ActionCountRowSchema = zod.z.object({ integration_id: zod.z.string(), action_count: zod.z.union([zod.z.number(), zod.z.string(), zod.z.bigint()]).transform((count) => Number(count)) });
526
+ var ListedRowSchema = zod.z.object({
527
+ id: zod.z.string(),
528
+ url: zod.z.string(),
529
+ status: zod.z.string(),
530
+ requested_actions: strings,
531
+ requested_data: strings,
532
+ approved_data: strings,
533
+ extension: zod.z.unknown(),
534
+ // Drivers hand back a Date, an ISO string or a number for the same column.
535
+ last_import_at: zod.z.unknown().transform((at) => at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : null),
536
+ last_error: zod.z.string().nullish()
537
+ }).transform((row) => ({
538
+ id: row.id,
539
+ url: row.url,
540
+ status: row.status,
541
+ requestedActions: row.requested_actions,
542
+ requestedData: row.requested_data,
543
+ approvedData: row.approved_data,
544
+ extension: row.extension ?? null,
545
+ lastImportAt: row.last_import_at,
546
+ lastError: row.last_error ?? null
547
+ }));
548
+ var findIntegration = async (replay, id) => FoundRowSchema.optional().parse(rowsOf(await replay("integrations/find", { id }))[0]);
549
+ var recordFailedImport2 = async (replay, id, url, error) => {
550
+ await replay("integrations/record-failed-import", { id, url, last_error: error });
551
+ };
552
+ var registrationOf = async (replay, id) => {
553
+ const row = RegistrationRowSchema.optional().parse(rowsOf(await replay("integrations/registration", { id }))[0]);
554
+ return { approved: row?.status === "approved", holdsKey: typeof row?.key_hash === "string" && row.key_hash !== "" };
555
+ };
556
+ var importedRow = ({ id, url, bundle, extension }) => ({
557
+ id,
558
+ url,
559
+ requested_actions: bundle.grants.actions,
560
+ requested_data: bundle.grants.data,
561
+ reach: reachOf(bundle, id),
562
+ phrasebook: bundle.phrasebook,
563
+ // As JSON text: an extension that is itself a string would be read as JSON, and refused.
564
+ extension: extension === void 0 ? null : JSON.stringify(extension),
565
+ last_import_at: (/* @__PURE__ */ new Date()).toISOString()
566
+ });
567
+ var writeBundle2 = async (replay, imported) => {
568
+ const { bundle } = imported;
569
+ const actions = Object.entries(bundle.actions).map(([actionId, definition]) => ({ action_id: actionId, definition, grammar: imported.stamp }));
570
+ const said = { ...importedRow(imported), actions };
571
+ if (imported.keyHash === void 0) {
572
+ await replay("integrations/write-bundle", said);
573
+ return { keptKey: false };
574
+ }
575
+ const written = WrittenSchema.parse(await replay("integrations/write-bundle-and-keep-key", { ...said, key_hash: imported.keyHash }));
576
+ return { keptKey: written.some((row) => row.key_hash === imported.keyHash) };
577
+ };
578
+ var approveIntegration = async (replay, id) => {
579
+ const asked = RequestedRowSchema.optional().parse(rowsOf(await replay("integrations/requested", { id }))[0]);
580
+ if (asked === void 0) return void 0;
581
+ await replay("integrations/approve", { id, approved_data: asked.requested_data });
582
+ return asked.requested_data;
583
+ };
584
+ var setBackToPending2 = async (replay, id, why) => {
585
+ await replay("integrations/set-back-to-pending", { id, last_error: why });
586
+ };
587
+ var removeIntegration = async (replay, id) => {
588
+ await replay("integrations/remove", { id });
589
+ };
590
+ var integrationByKey = async (replay, key) => KeyHolderRowSchema.optional().parse(rowsOf(await replay("integrations/by-key", { key_hash: hashIntegrationKey(key) }))[0])?.id;
591
+ var listIntegrations = async (replay) => {
592
+ const listed = await everyRow(ListedRowSchema, (after) => replay("integrations/list", { after: after?.id ?? "" }));
593
+ const counted = await everyRow(ActionCountRowSchema, (after) => replay("integrations/action-counts", { after: after?.integration_id ?? "" }));
594
+ const counts = new Map(counted.map((row) => [row.integration_id, row.action_count]));
595
+ return listed.map((row) => ({ ...row, actionCount: counts.get(row.id) ?? 0 }));
596
+ };
597
+ var RegisteredRowSchema = zod.z.object({ id: zod.z.string(), url: zod.z.string(), status: zod.z.string(), extension: zod.z.unknown() });
598
+ var storedExtension = (id, stored, schema) => {
599
+ if (schema === void 0 || stored === null || stored === void 0) return void 0;
600
+ const parsed = schema.safeParse(stored);
601
+ if (parsed.success) return parsed.data;
602
+ const first = parsed.error.issues[0];
603
+ console.error(`[moss] the stored extension of integration "${id}" is not read: ${first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}`}`);
604
+ return void 0;
605
+ };
606
+ var registeredIntegrations = async (replay, schema) => {
607
+ const rows = await everyRow(RegisteredRowSchema, (after) => replay("integrations/list", { after: after?.id ?? "" }));
608
+ return rows.map((row) => ({ id: row.id, status: row.status, url: row.url, extension: storedExtension(row.id, row.extension, schema) }));
609
+ };
610
+ var storedAction = (id, definition) => {
611
+ if (strata.exceedsDepth(definition)) {
612
+ console.error(`[moss] integration action "${id}" is not served: ${strata.depthRefusal()}`);
613
+ return void 0;
614
+ }
615
+ const parsed = nova.ActionDefinitionSchema.safeParse(definition);
616
+ if (parsed.success) return parsed.data;
617
+ const first = parsed.error.issues[0];
618
+ console.error(
619
+ `[moss] integration action "${id}" is not served: it is not an action nova reads (${first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}`})`
620
+ );
621
+ return void 0;
622
+ };
623
+ var actionsIn = (rows, upgrader) => {
624
+ const out = {};
625
+ const keep = (id, definition) => {
626
+ const action = storedAction(id, definition);
627
+ if (action !== void 0) out[id] = action;
628
+ };
629
+ for (const row of rows) {
630
+ const id = row.action_id;
631
+ if (upgrader === void 0) {
632
+ keep(id, row.definition);
633
+ continue;
634
+ }
635
+ const stamp = reflect.isRecord(row.grammar) ? Object.fromEntries(Object.entries(row.grammar).map(([k, v]) => [k, Number(v)])) : {};
636
+ try {
637
+ keep(id, upgrader.upgrade(row.definition, { kind: "nisc.nova/action", stamp }).document);
638
+ } catch (error) {
639
+ if (!(error instanceof strata.StrataError)) throw error;
640
+ console.error(`[moss] integration action "${id}" is not served: ${error.message.split("\n")[0] ?? error.code}`);
641
+ }
642
+ }
643
+ return out;
644
+ };
645
+ var loadIntegrationActions = async (replay, upgrader) => actionsIn(await everyRow(StoredActionRowSchema, (after) => replay("integrations/stored-actions", afterAction2(after))), upgrader);
646
+ var storedActionsOf = async (replay, id, upgrader) => actionsIn(await everyRow(StoredActionRowSchema, (after) => replay("integrations/actions-of", { id, ...afterAction2(after) })), upgrader);
647
+ var STORED_ACTIONS = {
648
+ table: "integration_actions",
649
+ column: "definition",
650
+ stamp: "grammar",
651
+ kind: "nisc.nova/action",
652
+ key: ["integration_id", "action_id"]
653
+ };
654
+ var integrationOfAction = (id) => id.startsWith("ext.") ? id.split(".")[2] : void 0;
655
+ var filterInstalled = (ids, installed) => {
656
+ if (installed === void 0) return ids;
657
+ return ids.filter((id) => {
658
+ const owner = integrationOfAction(id);
659
+ return owner === void 0 || installed.has(owner);
660
+ });
661
+ };
662
+
663
+ // src/integrations/operator.ts
664
+ var RegisterBodySchema = zod.z.looseObject({ id: zod.z.string().catch(""), url: zod.z.string().catch("") }).catch({ id: "", url: "" });
665
+ var ProbeBodySchema = zod.z.looseObject({ path: zod.z.string().optional().catch(void 0) }).catch({});
666
+ var refused = (reasons) => ({ ok: false, error: reasons.join("; "), status: 422, answer: { message: "Refused.", reasons } });
667
+ var takeIn = async (deps, id, url) => {
668
+ let payload;
669
+ try {
670
+ const response = await fetch(`${url.replace(/\/$/, "")}/bundle`, { signal: AbortSignal.timeout(deps.timeoutMs) });
671
+ if (!response.ok) throw new Error(String(response.status));
672
+ payload = await response.json();
673
+ } catch {
674
+ return { ok: false, error: "the service did not answer with a bundle", status: 502, answer: { message: "The integration did not answer with a bundle." } };
675
+ }
676
+ const context = {
677
+ integrationId: id,
678
+ url,
679
+ layoutMisfits: deps.layoutMisfits,
680
+ endlessChains: deps.endlessChains,
681
+ fingerprints: new Set(await deps.fingerprints()),
682
+ upgrader: deps.grammars,
683
+ hostActions: deps.actions()
684
+ };
685
+ const result = runIntake(payload, { ...context, ...deps.extension === void 0 ? {} : { extension: deps.extension } });
686
+ if (!result.ok) return refused(result.reasons);
687
+ const prepare = deps.extension?.prepare;
688
+ if (prepare === void 0 || result.extension === void 0) return { ok: true, bundle: result.bundle, extension: result.extension };
689
+ try {
690
+ return { ok: true, bundle: result.bundle, extension: await prepare(result.extension, extensionContextOf(result.bundle, context)) };
691
+ } catch (error) {
692
+ return refused([`extension: ${String(error)}`]);
693
+ }
694
+ };
695
+ var register = (deps, routes) => {
696
+ routes.post("/integrations", async (c) => {
697
+ const sent = await c.req.json().catch(() => ({}));
698
+ const { id, url } = RegisterBodySchema.parse(sent);
699
+ if (id === "" || url === "") return c.json({ message: "Give an id and a url." }, 400);
700
+ if (!INTEGRATION_ID.test(id)) return c.json({ message: INTEGRATION_ID_RULE }, 400);
701
+ const taken = await takeIn(deps, id, url);
702
+ if (!taken.ok) {
703
+ await recordFailedImport2(deps.replay, id, url, taken.error);
704
+ return c.json(taken.answer, taken.status);
705
+ }
706
+ const { approved: wasApproved, holdsKey } = await registrationOf(deps.replay, id);
707
+ if (wasApproved) {
708
+ const refusal = deps.refusalOf({ ...deps.actions(), ...taken.bundle.actions });
709
+ if (refusal !== void 0) return c.json({ message: "Refused \u2014 the app would not serve this.", reasons: [`Error: ${refusal}`] }, 422);
710
+ }
711
+ const key = holdsKey ? void 0 : mintIntegrationKey();
712
+ const { keptKey } = await writeBundle2(deps.replay, {
713
+ id,
714
+ url,
715
+ bundle: taken.bundle,
716
+ extension: taken.extension,
717
+ stamp: deps.grammars.stamp,
718
+ ...key === void 0 ? {} : { keyHash: hashIntegrationKey(key) }
719
+ });
720
+ await deps.reload();
721
+ const status = wasApproved ? "approved" : "pending";
722
+ return c.json({ id, status, actions: Object.keys(taken.bundle.actions).length, ...key !== void 0 && keptKey ? { key } : {} });
723
+ });
724
+ };
725
+ var approve2 = (deps, routes) => {
726
+ routes.post("/integrations/:id/approve", async (c) => {
727
+ const id = c.req.param("id");
728
+ const refusal = deps.refusalOf({ ...deps.actions(), ...await storedActionsOf(deps.replay, id, deps.grammars) });
729
+ if (refusal !== void 0) return c.json({ message: "Refused \u2014 the app would not serve this.", reasons: [`Error: ${refusal}`] }, 422);
730
+ const requested2 = await approveIntegration(deps.replay, id);
731
+ if (requested2 === void 0) return c.json({ message: "No such integration." }, 404);
732
+ try {
733
+ await deps.reload();
734
+ } catch (error) {
735
+ const why = String(error);
736
+ await setBackToPending2(deps.replay, id, why);
737
+ await deps.reload();
738
+ return c.json({ message: "Refused \u2014 the app would not serve this.", reasons: [why] }, 422);
739
+ }
740
+ return c.json({ id, status: "approved", granted: requested2 });
741
+ });
742
+ };
743
+ var probe = (deps, routes) => {
744
+ routes.post("/integrations/:id/probe", async (c) => {
745
+ const id = c.req.param("id");
746
+ const found = await findIntegration(deps.replay, id);
747
+ if (found === void 0) return c.json({ message: "No such integration." }, 404);
748
+ const sent = await c.req.json().catch(() => ({}));
749
+ const path = ProbeBodySchema.parse(sent).path ?? "bundle";
750
+ if (path !== "bundle" && !reachDeclares(found.reach, `/integrations/${id}/${path}`)) {
751
+ return c.json({ message: "That path is not one this integration declared." }, 404);
752
+ }
753
+ const started = Date.now();
754
+ try {
755
+ const response = await fetch(`${found.url.replace(/\/$/, "")}/${path}`, { signal: AbortSignal.timeout(deps.timeoutMs) });
756
+ const text = await response.text();
757
+ return c.json({ status: response.status, ms: Date.now() - started, body: text.slice(0, 2e3) });
758
+ } catch (err) {
759
+ return c.json({ status: 0, ms: Date.now() - started, body: String(err) });
760
+ }
761
+ });
762
+ };
763
+ var operatorRoutes = (deps) => {
764
+ const routes = new hono.Hono();
765
+ routes.get("/integrations", async (c) => c.json({ integrations: await listIntegrations(deps.replay) }));
766
+ register(deps, routes);
767
+ approve2(deps, routes);
768
+ routes.delete("/integrations/:id", async (c) => {
769
+ const id = c.req.param("id");
770
+ await removeIntegration(deps.replay, id);
771
+ await deps.reload();
772
+ return c.json({ id, removed: true });
773
+ });
774
+ probe(deps, routes);
775
+ return routes;
776
+ };
777
+ var convertsItself = (value) => {
778
+ if (typeof value !== "object" || value === null) return false;
779
+ const standard = Reflect.get(value, "~standard");
780
+ const converter = reflect.isRecord(standard) ? standard["jsonSchema"] : void 0;
781
+ return reflect.isRecord(converter) && typeof converter["output"] === "function";
782
+ };
783
+ var ComponentMetaSchema = zod.z.object({
784
+ description: zod.z.string().optional().catch(void 0),
785
+ propsSchema: zod.z.custom(convertsItself).optional().catch(void 0)
786
+ });
787
+ var componentMetaOf = (meta) => {
788
+ const parsed = ComponentMetaSchema.safeParse(meta ?? {});
789
+ return parsed.success ? parsed.data : {};
790
+ };
791
+ var buildContract = (host, integrationId) => {
792
+ const registered = host.components;
793
+ const components = Object.keys(registered).sort().map((name) => nova.paletteEntryOf(name, componentMetaOf(registered[name]?.meta)));
794
+ const audiences = /* @__PURE__ */ new Set();
795
+ for (const def of Object.values(host.charter)) {
796
+ if (def === void 0 || Array.isArray(def)) continue;
797
+ const selection = def.actions;
798
+ const list2 = Array.isArray(selection) ? selection : selection?.allow ?? [];
799
+ for (const entry of list2) {
800
+ const parts = entry.split(".");
801
+ if (parts[0] === "ext" && parts[1] !== void 0 && parts[1] !== "*") audiences.add(parts[1]);
802
+ }
803
+ }
804
+ return {
805
+ components,
806
+ audiences: [...audiences].sort(),
807
+ namespace: `ext.<audience>.${integrationId}.<name>`,
808
+ actionSchema: "nova ActionDefinition",
809
+ ...host.extension === void 0 ? {} : { extension: host.extension }
810
+ };
811
+ };
812
+ var describeProp = (schema) => {
813
+ const enumValues = schema["enum"];
814
+ if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(", ")}`;
815
+ const anyOf = schema["anyOf"];
816
+ if (Array.isArray(anyOf)) {
817
+ const consts = anyOf.map((option) => reflect.isRecord(option) ? option["const"] : void 0).filter((v) => v !== void 0);
818
+ if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(", ")}`;
819
+ }
820
+ const type = schema["type"];
821
+ const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
822
+ const min = schema["minimum"];
823
+ const max = schema["maximum"];
824
+ if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
825
+ return base;
826
+ };
827
+ var PropsTableSchema = zod.z.looseObject({
828
+ properties: zod.z.record(zod.z.string(), zod.z.record(zod.z.string(), zod.z.unknown())).optional(),
829
+ required: zod.z.array(zod.z.string()).optional()
830
+ });
831
+ var componentAsMarkdown = (component) => {
832
+ const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
833
+ const table = PropsTableSchema.safeParse(component.propsSchema);
834
+ const properties = table.success ? table.data.properties : void 0;
835
+ if (properties === void 0 || Object.keys(properties).length === 0) return head;
836
+ const required = new Set(table.success ? table.data.required ?? [] : []);
837
+ const rows = Object.entries(properties).map(
838
+ ([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
839
+ );
840
+ return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
841
+ };
842
+ var contractAsMarkdown = (contract, fingerprints) => [
843
+ `# What you can build against`,
844
+ ``,
845
+ `## Your namespace`,
846
+ ``,
847
+ ` ${contract.namespace}`,
848
+ ``,
849
+ `Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
850
+ ``,
851
+ `## Components your layouts may use`,
852
+ ``,
853
+ contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
854
+ ``,
855
+ `## Fingerprints you may call`,
856
+ ``,
857
+ `Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
858
+ `\`/integrations/<your id>/\`. Nothing else.`,
859
+ ``,
860
+ fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
861
+ ``,
862
+ ...contract.extension === void 0 ? [] : [
863
+ `## What this app adds: \`extension\``,
864
+ ``,
865
+ `A bundle says what belongs to this app's own vocabulary under \`extension\`. What the app tells you of it:`,
866
+ ``,
867
+ "```json",
868
+ JSON.stringify(contract.extension, null, 2),
869
+ "```",
870
+ ``
871
+ ],
872
+ `## What you cannot ship`,
873
+ ``,
874
+ `- vex entries or mutations. Call what is listed above; if you need a read that`,
875
+ ` does not exist, it is a change to the app.`,
876
+ `- \`fn:\` endpoints. Those run in the app's process.`,
877
+ `- components. Layouts compose what is listed above.`,
878
+ `- tables. Bring your own storage; we hand you identifiers.`,
879
+ ``
880
+ ].join("\n");
881
+ var contractRoutes = (deps) => {
882
+ const routes = new hono.Hono();
883
+ routes.get("/api/integrations/contract", async (c) => {
884
+ const id = c.req.query("id") ?? "<your id>";
885
+ const contract = buildContract(deps.host, id);
886
+ const fingerprints = await deps.fingerprintsFor(c.get("principal"));
887
+ if (c.req.query("format") === "md") {
888
+ return new Response(contractAsMarkdown(contract, fingerprints), {
889
+ headers: { "content-type": "text/markdown; charset=utf-8" }
890
+ });
891
+ }
892
+ return c.json({ ...contract, fingerprints, verifyKey: deps.verifyKey });
893
+ });
894
+ routes.get("/api/integrations/verify-key", (c) => c.json({ alg: "ed25519", key: deps.verifyKey }));
895
+ return routes;
896
+ };
897
+
898
+ // src/integrations/feature.ts
899
+ var DEFAULT_OUTBOUND_TIMEOUT_MS = 3e4;
900
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
901
+ var outboundTimeoutOf = (asked) => {
902
+ if (asked === void 0) return DEFAULT_OUTBOUND_TIMEOUT_MS;
903
+ if (!Number.isInteger(asked) || asked < 1 || asked > MAX_TIMEOUT_MS) {
904
+ throw new Error(
905
+ `moss: the \`outboundTimeoutMs\` of \`createIntegrations\` is ${String(asked)}. It is how long a call out to an integration may take: a whole number of milliseconds from 1 to ${String(MAX_TIMEOUT_MS)}. No call out waits for ever.`
906
+ );
907
+ }
908
+ return asked;
909
+ };
910
+ var start = async (config, timeoutMs, seams) => {
911
+ const replay = await seams.ownEntries(REGISTRY_ENTRIES);
912
+ await seams.upgradeStore(STORED_ACTIONS);
913
+ const find2 = (id) => findIntegration(replay, id);
914
+ const signer = createAssertionSigner(config.signingSeed);
915
+ const forward = createForwarder({ find: find2, resolveIdentity: seams.resolveIdentity, scopeOf: seams.scopeOf, mint: signer.mint, timeoutMs });
916
+ const stored = () => loadIntegrationActions(replay, seams.grammars);
917
+ const reload = async () => seams.replaceActions(await stored());
918
+ seams.addCatalogFilter(filterInstalled);
919
+ seams.setActionsLoader(stored);
920
+ seams.registerCredential(KEY_PREFIX, keyCredential({ byKey: (key) => integrationByKey(replay, key), actor: config.integrationActor, resolveIdentity: seams.resolveIdentity }));
921
+ seams.wrapWire(withFallbackMessage);
922
+ seams.mountRoutes(
923
+ contractRoutes({
924
+ host: { components: seams.components, charter: seams.charter, extension: config.extension?.contract },
925
+ fingerprintsFor: seams.fingerprintsFor,
926
+ verifyKey: signer.verifyKey
927
+ })
928
+ );
929
+ seams.mountOperatorRoutes(
930
+ operatorRoutes({
931
+ replay,
932
+ extension: config.extension,
933
+ grammars: seams.grammars,
934
+ fingerprints: seams.fingerprints,
935
+ layoutMisfits: seams.layoutMisfits,
936
+ endlessChains: seams.endlessChains,
937
+ actions: seams.actions,
938
+ refusalOf: seams.refusalOf,
939
+ reload,
940
+ timeoutMs
941
+ })
942
+ );
943
+ seams.mountRoutes(proxyRoutes({ grantedActionIds: seams.grantedActionIds, forward }));
944
+ const approved2 = await stored();
945
+ if (Object.keys(approved2).length > 0) seams.replaceActions(approved2);
946
+ return { replay, call: callIntegrationWith({ forward, ...seams.telemetry === void 0 ? {} : { telemetry: seams.telemetry } }) };
947
+ };
948
+ var createIntegrations = (config = {}) => {
949
+ const timeoutMs = outboundTimeoutOf(config.outboundTimeoutMs);
950
+ let started;
951
+ const running = (call) => {
952
+ if (started === void 0) {
953
+ throw new Error(
954
+ `moss: integrations.${call} was called before a server started the feature. Put what createIntegrations returned in the manifest's \`features\`, and call it once createServer has answered.`
955
+ );
956
+ }
957
+ return started;
958
+ };
959
+ return {
960
+ name: "integrations",
961
+ tables: { names: REGISTRY_TABLES },
962
+ start: async (seams) => {
963
+ started = await start(config, timeoutMs, seams);
964
+ },
965
+ callIntegration: async (id, path, init) => running("callIntegration").call(id, path, init),
966
+ listIntegrations: async () => registeredIntegrations(running("listIntegrations").replay, config.extension?.schema),
967
+ integrationByKey: async (key) => integrationByKey(running("integrationByKey").replay, key),
968
+ integrationOfAction
969
+ };
970
+ };
971
+
972
+ exports.createAssertionSigner = createAssertionSigner;
973
+ exports.createIntegrations = createIntegrations;
974
+ //# sourceMappingURL=integrations.cjs.map
975
+ //# sourceMappingURL=integrations.cjs.map