@ipab/cli 0.1.0-rc.0 → 0.1.0-rc.10

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 (285) hide show
  1. package/README.md +230 -7
  2. package/dist/app-authoring.d.ts +16 -2
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +151 -66
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -63
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -44
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +15 -45
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +8 -21
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +35 -54
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +5 -32
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +2009 -308
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +9 -4
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +164 -23
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -0
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +56 -2
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +684 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -1
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +125 -4
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +18 -20
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +146 -126
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -9
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -13
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +128 -16
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +506 -94
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +469 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4708 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +45 -67
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +35 -49
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +18 -11
  230. package/src/app-authoring.ts +254 -88
  231. package/src/app-definition.ts +33 -45
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +28 -71
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +63 -72
  236. package/src/builtins.ts +7 -38
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2500 -376
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +215 -26
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +100 -2
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1082 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +90 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +161 -4
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +190 -142
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -3
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -14
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +782 -116
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7051 -0
  280. package/src/template-definition.ts +35 -49
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
@@ -0,0 +1,601 @@
1
+ import {
2
+ createServer,
3
+ type IncomingMessage,
4
+ type ServerResponse,
5
+ } from "node:http";
6
+ import { createServer as createTcpServer } from "node:net";
7
+ import { CID } from "multiformats/cid";
8
+ import {
9
+ canonicalService,
10
+ isCanonicalPublicKey,
11
+ ServiceError,
12
+ } from "@ipab/bundle/pointer/protocol";
13
+ import {
14
+ importPrivateKeyPkcs8,
15
+ importPublicKeyRaw,
16
+ randomBytes,
17
+ signEd25519,
18
+ toBase64Url,
19
+ verifyEd25519,
20
+ } from "@ipab/bundle/pointer/crypto";
21
+ import {
22
+ boundedText,
23
+ parseScopeWriteReceipt,
24
+ RESOURCE_ID_PATTERN,
25
+ type ScopeWriteReceipt,
26
+ } from "@ipab/bundle/pointer/scope";
27
+ import { HostError, message, object } from "./errors.js";
28
+ import {
29
+ probePeer,
30
+ validateAddress,
31
+ type KuboNode,
32
+ type p2pForward,
33
+ } from "./kubo.js";
34
+ import {
35
+ validateSearchParams,
36
+ type SearchApiResponse,
37
+ type ValidatedSearchParams,
38
+ } from "./search-index.js";
39
+
40
+ export const PIVOT_PROTOCOL = "/x/ipab-pivot/1.0.0";
41
+ export const PIVOT_RECEIPT_PROTOCOL = PIVOT_PROTOCOL;
42
+ export const MAX_PIVOT_RPC_BYTES = 64 * 1024;
43
+ const MAX_REQUEST_URL_BYTES = 4096;
44
+
45
+ export interface PivotReceiptRequest {
46
+ v: 1;
47
+ service: string;
48
+ scopeId: string;
49
+ headId: string;
50
+ epoch: number;
51
+ root: string;
52
+ ifCid: string;
53
+ idempotencyKey: string;
54
+ member: string;
55
+ timestamp: number;
56
+ nonce: string;
57
+ addresses: string[];
58
+ signature: string;
59
+ }
60
+
61
+ export interface PivotReceiptResponse {
62
+ v: 1;
63
+ receipt: ScopeWriteReceipt;
64
+ }
65
+
66
+ export function pivotReceiptSigningMessage(
67
+ request: Omit<PivotReceiptRequest, "signature">,
68
+ ): string {
69
+ return JSON.stringify([
70
+ "IPAB-PIVOT-RECEIPT/1",
71
+ request.service,
72
+ request.scopeId,
73
+ request.headId,
74
+ request.epoch,
75
+ request.root,
76
+ request.ifCid,
77
+ request.idempotencyKey,
78
+ request.member,
79
+ request.timestamp,
80
+ request.nonce,
81
+ request.addresses,
82
+ ]);
83
+ }
84
+
85
+ export function parsePivotReceiptRequest(input: unknown): PivotReceiptRequest {
86
+ const data = object(input, "Pivot receipt request");
87
+ if (
88
+ Object.keys(data).sort().join() !==
89
+ "addresses,epoch,headId,idempotencyKey,ifCid,member,nonce,root,scopeId,service,signature,timestamp,v" ||
90
+ data.v !== 1 ||
91
+ typeof data.service !== "string" ||
92
+ typeof data.scopeId !== "string" ||
93
+ !RESOURCE_ID_PATTERN.test(data.scopeId) ||
94
+ typeof data.headId !== "string" ||
95
+ !RESOURCE_ID_PATTERN.test(data.headId) ||
96
+ typeof data.epoch !== "number" ||
97
+ !Number.isSafeInteger(data.epoch) ||
98
+ data.epoch < 1 ||
99
+ typeof data.root !== "string" ||
100
+ typeof data.ifCid !== "string" ||
101
+ typeof data.idempotencyKey !== "string" ||
102
+ !/^[A-Za-z0-9._-]{16,128}$/.test(data.idempotencyKey) ||
103
+ !isCanonicalPublicKey(data.member) ||
104
+ typeof data.timestamp !== "number" ||
105
+ !Number.isSafeInteger(data.timestamp) ||
106
+ data.timestamp < 0 ||
107
+ typeof data.nonce !== "string" ||
108
+ !/^[A-Za-z0-9_-]{22,128}$/.test(data.nonce) ||
109
+ !Array.isArray(data.addresses) ||
110
+ data.addresses.length > 16 ||
111
+ !data.addresses.every((address) => typeof address === "string") ||
112
+ typeof data.signature !== "string" ||
113
+ !/^[A-Za-z0-9_-]{86}$/.test(data.signature)
114
+ )
115
+ throw new HostError("Invalid Pivot receipt request.");
116
+ let service: string;
117
+ try {
118
+ service = canonicalService(data.service);
119
+ if (service !== data.service)
120
+ throw new HostError("Noncanonical Pivot receipt service URL.");
121
+ if (CID.parse(data.root).toV1().toString() !== data.root)
122
+ throw new HostError("Invalid Pivot receipt root CID.");
123
+ if (CID.parse(data.ifCid).toString() !== data.ifCid)
124
+ throw new HostError("Invalid Pivot receipt ifCid.");
125
+ } catch (cause) {
126
+ if (cause instanceof HostError) throw cause;
127
+ throw new HostError("Invalid Pivot receipt request.");
128
+ }
129
+ return {
130
+ v: 1,
131
+ service,
132
+ scopeId: data.scopeId,
133
+ headId: data.headId,
134
+ epoch: data.epoch,
135
+ root: data.root,
136
+ ifCid: data.ifCid,
137
+ idempotencyKey: data.idempotencyKey,
138
+ member: data.member,
139
+ timestamp: data.timestamp,
140
+ nonce: data.nonce,
141
+ addresses: data.addresses,
142
+ signature: data.signature,
143
+ };
144
+ }
145
+
146
+ export async function signPivotReceiptRequest(
147
+ input: Omit<
148
+ PivotReceiptRequest,
149
+ "v" | "signature" | "timestamp" | "nonce"
150
+ > & {
151
+ timestamp?: number;
152
+ nonce?: string;
153
+ },
154
+ privateKey: string,
155
+ ): Promise<PivotReceiptRequest> {
156
+ const body: Omit<PivotReceiptRequest, "signature"> = {
157
+ v: 1,
158
+ service: canonicalService(input.service),
159
+ scopeId: input.scopeId,
160
+ headId: input.headId,
161
+ epoch: input.epoch,
162
+ root: input.root,
163
+ ifCid: input.ifCid,
164
+ idempotencyKey: input.idempotencyKey,
165
+ member: input.member,
166
+ timestamp: input.timestamp ?? Math.floor(Date.now() / 1000),
167
+ nonce: input.nonce ?? toBase64Url(randomBytes(24)),
168
+ addresses: input.addresses.slice(0, 16),
169
+ };
170
+ const signature = await signEd25519(
171
+ await importPrivateKeyPkcs8(privateKey),
172
+ pivotReceiptSigningMessage(body),
173
+ );
174
+ return parsePivotReceiptRequest({ ...body, signature });
175
+ }
176
+
177
+ export async function verifyPivotReceiptRequest(
178
+ request: PivotReceiptRequest,
179
+ expectedPeerId: string,
180
+ nowSec = Math.floor(Date.now() / 1000),
181
+ ): Promise<void> {
182
+ if (Math.abs(request.timestamp - nowSec) > 60)
183
+ throw new HostError("Receipt request timestamp must be within 60 seconds.");
184
+ for (const address of request.addresses)
185
+ validateAddress(address, expectedPeerId);
186
+ const { signature, ...body } = request;
187
+ const ok = await verifyEd25519(
188
+ await importPublicKeyRaw(request.member),
189
+ signature,
190
+ pivotReceiptSigningMessage(body),
191
+ );
192
+ if (!ok)
193
+ throw new HostError("Invalid member signature on Pivot receipt request.");
194
+ }
195
+
196
+ export function parsePivotReceiptResponse(
197
+ input: unknown,
198
+ ): PivotReceiptResponse {
199
+ const data = object(input, "Pivot receipt response");
200
+ if (Object.keys(data).sort().join() !== "receipt,v" || data.v !== 1)
201
+ throw new HostError("Invalid Pivot receipt response.");
202
+ return {
203
+ v: 1,
204
+ receipt: parseScopeWriteReceipt(data.receipt),
205
+ };
206
+ }
207
+
208
+ async function readBoundedBody(request: IncomingMessage): Promise<string> {
209
+ const chunks: Buffer[] = [];
210
+ let total = 0;
211
+ for await (const chunk of request) {
212
+ const buffer = Buffer.isBuffer(chunk)
213
+ ? chunk
214
+ : typeof chunk === "string"
215
+ ? Buffer.from(chunk)
216
+ : Buffer.from(chunk as Uint8Array);
217
+ total += buffer.length;
218
+ if (total > MAX_PIVOT_RPC_BYTES)
219
+ throw new ServiceError(413, "too_large", "request body too large");
220
+ chunks.push(buffer);
221
+ }
222
+ return Buffer.concat(chunks).toString("utf8");
223
+ }
224
+
225
+ export interface PivotServer {
226
+ port: number;
227
+ address: string;
228
+ close: () => Promise<void>;
229
+ }
230
+
231
+ export type PivotReceiptServer = PivotServer;
232
+
233
+ export type PivotReceiptHandler = (
234
+ request: PivotReceiptRequest,
235
+ signal: AbortSignal,
236
+ ) => Promise<ScopeWriteReceipt>;
237
+
238
+ export interface PivotServiceHandlers {
239
+ receipt?: PivotReceiptHandler;
240
+ search?: (params: ValidatedSearchParams) => SearchApiResponse | null;
241
+ diagnostic?: (text: string) => void;
242
+ }
243
+
244
+ function sendJson(
245
+ response: ServerResponse,
246
+ status: number,
247
+ body: unknown,
248
+ ): void {
249
+ const payload = JSON.stringify(body);
250
+ response.writeHead(status, {
251
+ "content-type": "application/json; charset=utf-8",
252
+ "content-length": Buffer.byteLength(payload),
253
+ "cache-control": "no-store",
254
+ });
255
+ response.end(payload);
256
+ }
257
+
258
+ export async function startPivotHttpServer(
259
+ handlers: PivotServiceHandlers,
260
+ ): Promise<PivotServer> {
261
+ const server = createServer((request, response) => {
262
+ const controller = new AbortController();
263
+ response.once("close", () => {
264
+ if (!response.writableEnded) controller.abort();
265
+ });
266
+ void (async () => {
267
+ const rawUrl = request.url ?? "";
268
+ if (Buffer.byteLength(rawUrl) > MAX_REQUEST_URL_BYTES) {
269
+ sendJson(response, 414, { error: "Request URI too long." });
270
+ return;
271
+ }
272
+ const parsedUrl = new URL(rawUrl, "http://127.0.0.1");
273
+
274
+ if (parsedUrl.pathname === "/v1/search") {
275
+ try {
276
+ if (request.method !== "GET") {
277
+ sendJson(response, 405, { error: "Method not allowed." });
278
+ return;
279
+ }
280
+ let validated: ValidatedSearchParams;
281
+ try {
282
+ validated = validateSearchParams({
283
+ q: parsedUrl.searchParams.get("q"),
284
+ prefix: parsedUrl.searchParams.get("prefix"),
285
+ kind: parsedUrl.searchParams.get("kind"),
286
+ schemaCid: parsedUrl.searchParams.get("schemaCid"),
287
+ limit: parsedUrl.searchParams.get("limit"),
288
+ offset: parsedUrl.searchParams.get("offset"),
289
+ });
290
+ } catch (cause) {
291
+ sendJson(response, 400, {
292
+ error: cause instanceof Error ? cause.message : String(cause),
293
+ });
294
+ return;
295
+ }
296
+ const result = handlers.search?.(validated) ?? null;
297
+ if (!result) {
298
+ sendJson(response, 503, {
299
+ error: "Search index is not ready yet.",
300
+ });
301
+ return;
302
+ }
303
+ sendJson(response, 200, result);
304
+ } catch (cause) {
305
+ handlers.diagnostic?.(
306
+ `Pivot search server error: ${cause instanceof Error ? cause.message : String(cause)}`,
307
+ );
308
+ if (!response.headersSent)
309
+ sendJson(response, 500, { error: "Internal search error." });
310
+ }
311
+ return;
312
+ }
313
+
314
+ if (parsedUrl.pathname === "/v1/receipt" && handlers.receipt) {
315
+ try {
316
+ if (request.method !== "POST") {
317
+ response.writeHead(405, { "content-type": "application/json" });
318
+ response.end(
319
+ JSON.stringify({ error: { message: "method not allowed" } }),
320
+ );
321
+ return;
322
+ }
323
+ const raw = await readBoundedBody(request);
324
+ let parsed: unknown;
325
+ try {
326
+ parsed = JSON.parse(raw) as unknown;
327
+ } catch {
328
+ response.writeHead(400, { "content-type": "application/json" });
329
+ response.end(
330
+ JSON.stringify({ error: { message: "invalid JSON" } }),
331
+ );
332
+ return;
333
+ }
334
+ const receiptRequest = parsePivotReceiptRequest(parsed);
335
+ const receipt = await handlers.receipt(
336
+ receiptRequest,
337
+ controller.signal,
338
+ );
339
+ const payload: PivotReceiptResponse = { v: 1, receipt };
340
+ response.writeHead(200, { "content-type": "application/json" });
341
+ response.end(JSON.stringify(payload));
342
+ } catch (cause) {
343
+ const status =
344
+ cause instanceof ServiceError
345
+ ? cause.status
346
+ : cause instanceof HostError &&
347
+ cause.code === "PIVOT_UNAUTHORIZED"
348
+ ? 403
349
+ : cause instanceof HostError
350
+ ? 400
351
+ : 500;
352
+ const text =
353
+ cause instanceof ServiceError || cause instanceof HostError
354
+ ? message(cause)
355
+ : "Pivot receipt request failed.";
356
+ if (status === 500) {
357
+ handlers.diagnostic?.(
358
+ `Pivot receipt server error: ${cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)}`,
359
+ );
360
+ }
361
+ if (!response.headersSent) {
362
+ response.writeHead(status, { "content-type": "application/json" });
363
+ response.end(
364
+ JSON.stringify({ error: { message: text.slice(0, 512) } }),
365
+ );
366
+ }
367
+ }
368
+ return;
369
+ }
370
+
371
+ response.writeHead(404, { "content-type": "application/json" });
372
+ response.end(JSON.stringify({ error: { message: "not found" } }));
373
+ })();
374
+ });
375
+ server.requestTimeout = 90_000;
376
+ server.headersTimeout = 10_000;
377
+ server.maxConnections = 64;
378
+ const close = () =>
379
+ new Promise<void>((accept, reject) => {
380
+ server.close((error) => {
381
+ if (error) reject(error);
382
+ else accept();
383
+ });
384
+ server.closeAllConnections();
385
+ });
386
+ await new Promise<void>((accept, reject) => {
387
+ server.once("error", reject);
388
+ server.listen(0, "127.0.0.1", () => {
389
+ server.removeListener("error", reject);
390
+ accept();
391
+ });
392
+ });
393
+ const address = server.address();
394
+ if (!address || typeof address === "string") {
395
+ await close();
396
+ throw new HostError("Pivot HTTP server did not bind loopback.");
397
+ }
398
+ return {
399
+ port: address.port,
400
+ address: `/ip4/127.0.0.1/tcp/${address.port}`,
401
+ close,
402
+ };
403
+ }
404
+
405
+ export async function startPivotReceiptHttpServer(
406
+ handler: PivotReceiptHandler,
407
+ ): Promise<PivotReceiptServer> {
408
+ return startPivotHttpServer({ receipt: handler });
409
+ }
410
+
411
+ async function freeLoopbackPort(): Promise<number> {
412
+ const server = createTcpServer();
413
+ return new Promise((resolve, reject) => {
414
+ server.once("error", reject);
415
+ server.listen(0, "127.0.0.1", () => {
416
+ const address = server.address();
417
+ if (!address || typeof address === "string") {
418
+ server.close();
419
+ reject(new HostError("No free loopback port."));
420
+ return;
421
+ }
422
+ server.close((error) => {
423
+ if (error) reject(error);
424
+ else resolve(address.port);
425
+ });
426
+ });
427
+ });
428
+ }
429
+
430
+ async function kuboP2pRpc(
431
+ node: KuboNode,
432
+ endpoint: string,
433
+ fetcher: typeof fetch,
434
+ signal?: AbortSignal,
435
+ ): Promise<void> {
436
+ const response = await fetcher(`${node.api}/api/v0/${endpoint}`, {
437
+ method: "POST",
438
+ headers: { authorization: `Bearer ${node.auth}` },
439
+ redirect: "error",
440
+ signal: signal ?? AbortSignal.timeout(15_000),
441
+ });
442
+ const text = await boundedText(response);
443
+ if (!response.ok)
444
+ throw new HostError(
445
+ `Kubo ${endpoint.split("?")[0]} failed (HTTP ${response.status}): ${text.slice(0, 256)}`,
446
+ );
447
+ }
448
+
449
+ export async function mountPivotServer(
450
+ node: KuboNode,
451
+ handlers: PivotServiceHandlers,
452
+ fetcher: typeof fetch = fetch,
453
+ ): Promise<PivotServer> {
454
+ const httpServer = await startPivotHttpServer(handlers);
455
+ const target = httpServer.address;
456
+ try {
457
+ // Clear any stale listener for this protocol on the same Swarm node first.
458
+ await kuboP2pRpc(
459
+ node,
460
+ `p2p/close?protocol=${encodeURIComponent(PIVOT_PROTOCOL)}`,
461
+ fetcher,
462
+ ).catch(() => {});
463
+ await kuboP2pRpc(
464
+ node,
465
+ `p2p/listen?arg=${encodeURIComponent(PIVOT_PROTOCOL)}&arg=${encodeURIComponent(target)}`,
466
+ fetcher,
467
+ );
468
+ } catch (cause) {
469
+ await httpServer.close();
470
+ throw cause;
471
+ }
472
+ return {
473
+ port: httpServer.port,
474
+ address: target,
475
+ close: async () => {
476
+ try {
477
+ await kuboP2pRpc(
478
+ node,
479
+ `p2p/close?protocol=${encodeURIComponent(PIVOT_PROTOCOL)}&target-address=${encodeURIComponent(target)}`,
480
+ fetcher,
481
+ ).catch(() => {});
482
+ } finally {
483
+ await httpServer.close();
484
+ }
485
+ },
486
+ };
487
+ }
488
+
489
+ export async function mountPivotReceiptServer(
490
+ node: KuboNode,
491
+ handler: PivotReceiptHandler,
492
+ fetcher: typeof fetch = fetch,
493
+ ): Promise<PivotReceiptServer> {
494
+ return mountPivotServer(node, { receipt: handler }, fetcher);
495
+ }
496
+
497
+ export async function withPivotP2pForward<T>(
498
+ options: {
499
+ node: KuboNode;
500
+ pivotPeerId: string;
501
+ pivotAddresses?: readonly string[];
502
+ signal?: AbortSignal;
503
+ fetcher?: typeof fetch;
504
+ p2pForwardFn?: typeof p2pForward;
505
+ },
506
+ run: (endpoint: { host: string; port: number }) => Promise<T>,
507
+ ): Promise<T> {
508
+ options.signal?.throwIfAborted();
509
+ if (options.pivotAddresses?.length)
510
+ await probePeer(
511
+ options.node,
512
+ options.pivotPeerId,
513
+ options.pivotAddresses,
514
+ options.signal,
515
+ ).catch(() => false);
516
+ if (options.p2pForwardFn) {
517
+ const forward = await options.p2pForwardFn(
518
+ options.node,
519
+ PIVOT_PROTOCOL,
520
+ options.pivotPeerId,
521
+ options.signal,
522
+ );
523
+ try {
524
+ return await run({ host: forward.host, port: forward.port });
525
+ } finally {
526
+ await forward.close().catch(() => {});
527
+ }
528
+ }
529
+ const fetcher = options.fetcher ?? fetch;
530
+ const port = await freeLoopbackPort();
531
+ const listenAddress = `/ip4/127.0.0.1/tcp/${port}`;
532
+ const targetAddress = `/p2p/${options.pivotPeerId}`;
533
+ await kuboP2pRpc(
534
+ options.node,
535
+ `p2p/forward?arg=${encodeURIComponent(PIVOT_PROTOCOL)}&arg=${encodeURIComponent(listenAddress)}&arg=${encodeURIComponent(targetAddress)}`,
536
+ fetcher,
537
+ options.signal,
538
+ );
539
+ try {
540
+ return await run({ host: "127.0.0.1", port });
541
+ } finally {
542
+ await kuboP2pRpc(
543
+ options.node,
544
+ `p2p/close?protocol=${encodeURIComponent(PIVOT_PROTOCOL)}&listen-address=${encodeURIComponent(listenAddress)}`,
545
+ fetcher,
546
+ ).catch(() => {});
547
+ }
548
+ }
549
+
550
+ export async function requestPivotReceiptOverP2p(
551
+ node: KuboNode,
552
+ pivotPeerId: string,
553
+ pivotAddresses: readonly string[],
554
+ request: PivotReceiptRequest,
555
+ signal: AbortSignal,
556
+ fetcher: typeof fetch = fetch,
557
+ ): Promise<ScopeWriteReceipt> {
558
+ return withPivotP2pForward(
559
+ { node, pivotPeerId, pivotAddresses, signal, fetcher },
560
+ async ({ host, port }) => {
561
+ const response = await fetcher(`http://${host}:${port}/v1/receipt`, {
562
+ method: "POST",
563
+ headers: {
564
+ accept: "application/json",
565
+ "content-type": "application/json",
566
+ },
567
+ body: JSON.stringify(request),
568
+ redirect: "error",
569
+ cache: "no-store",
570
+ signal,
571
+ });
572
+ const text = await boundedText(response);
573
+ let parsed: unknown;
574
+ try {
575
+ parsed = JSON.parse(text) as unknown;
576
+ } catch {
577
+ throw new HostError(
578
+ `Pivot receipt RPC returned non-JSON (HTTP ${response.status}).`,
579
+ );
580
+ }
581
+ if (!response.ok) {
582
+ const detail =
583
+ parsed &&
584
+ typeof parsed === "object" &&
585
+ "error" in parsed &&
586
+ parsed.error &&
587
+ typeof parsed.error === "object" &&
588
+ "message" in parsed.error &&
589
+ typeof parsed.error.message === "string"
590
+ ? parsed.error.message
591
+ : `HTTP ${response.status}`;
592
+ throw new HostError(
593
+ detail,
594
+ 1,
595
+ response.status === 403 ? "PIVOT_UNAUTHORIZED" : undefined,
596
+ );
597
+ }
598
+ return parsePivotReceiptResponse(parsed).receipt;
599
+ },
600
+ );
601
+ }
@@ -0,0 +1,87 @@
1
+ import * as dagPb from "@ipld/dag-pb";
2
+ import { CID } from "multiformats/cid";
3
+ import type { IpfsStore } from "@ipab/ipfs-store";
4
+ import { provideContent } from "./content-provider.js";
5
+ import { HostError, object } from "./errors.js";
6
+ import { pinAdd, type KuboNode } from "./kubo.js";
7
+
8
+ export interface PublicationPin {
9
+ root: string;
10
+ epoch: number;
11
+ }
12
+ export interface PublicationPinRequest extends PublicationPin {
13
+ addresses: string[];
14
+ }
15
+ export interface PublicationPins {
16
+ publicationPin?: PublicationPinRequest;
17
+ publicationPins?: Record<string, PublicationPin>;
18
+ }
19
+
20
+ function pin(value: unknown): PublicationPin {
21
+ const data = object(value, "publication pin");
22
+ if (
23
+ typeof data.root !== "string" ||
24
+ CID.parse(data.root).toV1().toString() !== data.root ||
25
+ !Number.isSafeInteger(data.epoch) ||
26
+ typeof data.epoch !== "number" ||
27
+ data.epoch < 1
28
+ )
29
+ throw new HostError("Invalid publication pin.");
30
+ return { root: data.root, epoch: data.epoch };
31
+ }
32
+
33
+ export function parsePublicationPins(
34
+ value: Record<string, unknown>,
35
+ ): PublicationPins {
36
+ const result: PublicationPins = {};
37
+ if (value.publicationPin !== undefined) {
38
+ const request = object(value.publicationPin, "publication pin request");
39
+ if (
40
+ Object.keys(request).sort().join() !== "addresses,epoch,root" ||
41
+ !Array.isArray(request.addresses) ||
42
+ request.addresses.length > 16 ||
43
+ !request.addresses.every((address) => typeof address === "string")
44
+ )
45
+ throw new HostError("Invalid publication pin request.");
46
+ result.publicationPin = { ...pin(request), addresses: request.addresses };
47
+ }
48
+ if (value.publicationPins !== undefined) {
49
+ const pins = object(value.publicationPins, "publication pin confirmations");
50
+ if (Object.keys(pins).length > 256)
51
+ throw new HostError("Too many publication pin confirmations.");
52
+ result.publicationPins = Object.fromEntries(
53
+ Object.entries(pins).map(([key, value]) => {
54
+ if (!/^[A-Za-z0-9_-]{43}$/.test(key))
55
+ throw new HostError("Invalid publication pin member.");
56
+ const data = object(value, "publication pin confirmation");
57
+ if (Object.keys(data).sort().join() !== "epoch,root")
58
+ throw new HostError("Invalid publication pin confirmation.");
59
+ return [key, pin(data)];
60
+ }),
61
+ );
62
+ }
63
+ return result;
64
+ }
65
+
66
+ export async function pinPublication(
67
+ store: IpfsStore,
68
+ roots: readonly string[],
69
+ node: KuboNode,
70
+ signal: AbortSignal,
71
+ fetcher: typeof fetch = fetch,
72
+ ): Promise<void> {
73
+ signal.throwIfAborted();
74
+ if (roots.length === 1 && CID.parse(roots[0]!).code === dagPb.code) {
75
+ await pinAdd(node, roots[0]!, true, signal, 120_000, fetcher);
76
+ return;
77
+ }
78
+ await provideContent(
79
+ store,
80
+ roots,
81
+ node.api,
82
+ fetcher,
83
+ node.auth,
84
+ roots,
85
+ signal,
86
+ );
87
+ }