@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.
- package/README.md +230 -7
- package/dist/app-authoring.d.ts +16 -2
- package/dist/app-authoring.d.ts.map +1 -1
- package/dist/app-authoring.js +151 -66
- package/dist/app-authoring.js.map +1 -1
- package/dist/app-definition.d.ts +52 -63
- package/dist/app-definition.d.ts.map +1 -1
- package/dist/app-definition.js +33 -44
- package/dist/app-definition.js.map +1 -1
- package/dist/app-prebuild.d.ts +18 -0
- package/dist/app-prebuild.d.ts.map +1 -1
- package/dist/app-prebuild.js +46 -0
- package/dist/app-prebuild.js.map +1 -1
- package/dist/app-templates.d.ts +0 -1
- package/dist/app-templates.d.ts.map +1 -1
- package/dist/app-templates.js +15 -45
- package/dist/app-templates.js.map +1 -1
- package/dist/assembly.d.ts +7 -0
- package/dist/assembly.d.ts.map +1 -0
- package/dist/assembly.js +130 -0
- package/dist/assembly.js.map +1 -0
- package/dist/authoring.d.ts +8 -21
- package/dist/authoring.d.ts.map +1 -1
- package/dist/authoring.js +35 -54
- package/dist/authoring.js.map +1 -1
- package/dist/builtins/skill.ipab.car +0 -0
- package/dist/builtins/template.bundle-viewer.car +0 -0
- package/dist/builtins/template.check.car +0 -0
- package/dist/builtins/template.node.car +0 -0
- package/dist/builtins/template.web-app.car +0 -0
- package/dist/builtins.d.ts.map +1 -1
- package/dist/builtins.js +5 -32
- package/dist/builtins.js.map +1 -1
- package/dist/bundled-skills.d.ts +14 -0
- package/dist/bundled-skills.d.ts.map +1 -0
- package/dist/bundled-skills.js +34 -0
- package/dist/bundled-skills.js.map +1 -0
- package/dist/cli.d.ts +8 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2009 -308
- package/dist/cli.js.map +1 -1
- package/dist/config-secret.d.ts +3 -0
- package/dist/config-secret.d.ts.map +1 -0
- package/dist/config-secret.js +12 -0
- package/dist/config-secret.js.map +1 -0
- package/dist/config.d.ts +9 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +164 -23
- package/dist/config.js.map +1 -1
- package/dist/content-provider.d.ts +32 -0
- package/dist/content-provider.d.ts.map +1 -0
- package/dist/content-provider.js +222 -0
- package/dist/content-provider.js.map +1 -0
- package/dist/context-types.d.ts +12 -0
- package/dist/context-types.d.ts.map +1 -0
- package/dist/context-types.js +2 -0
- package/dist/context-types.js.map +1 -0
- package/dist/context.d.ts +26 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +56 -2
- package/dist/context.js.map +1 -1
- package/dist/daemon-ui.d.ts +93 -0
- package/dist/daemon-ui.d.ts.map +1 -0
- package/dist/daemon-ui.js +713 -0
- package/dist/daemon-ui.js.map +1 -0
- package/dist/daemon.d.ts +21 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/daemon.js +317 -0
- package/dist/daemon.js.map +1 -0
- package/dist/doctor.d.ts +32 -0
- package/dist/doctor.d.ts.map +1 -0
- package/dist/doctor.js +684 -0
- package/dist/doctor.js.map +1 -0
- package/dist/errors.d.ts +1 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -20
- package/dist/errors.js.map +1 -1
- package/dist/get.d.ts +3 -0
- package/dist/get.d.ts.map +1 -0
- package/dist/get.js +80 -0
- package/dist/get.js.map +1 -0
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +6 -14
- package/dist/history.js.map +1 -1
- package/dist/host-error.d.ts +9 -0
- package/dist/host-error.d.ts.map +1 -0
- package/dist/host-error.js +21 -0
- package/dist/host-error.js.map +1 -0
- package/dist/identity.d.ts +16 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +119 -0
- package/dist/identity.js.map +1 -0
- package/dist/ipc.d.ts +5 -1
- package/dist/ipc.d.ts.map +1 -1
- package/dist/ipc.js +125 -4
- package/dist/ipc.js.map +1 -1
- package/dist/kubo-install.d.ts +26 -0
- package/dist/kubo-install.d.ts.map +1 -0
- package/dist/kubo-install.js +724 -0
- package/dist/kubo-install.js.map +1 -0
- package/dist/kubo-peering.d.ts +11 -0
- package/dist/kubo-peering.d.ts.map +1 -0
- package/dist/kubo-peering.js +93 -0
- package/dist/kubo-peering.js.map +1 -0
- package/dist/kubo-peers.d.ts +12 -0
- package/dist/kubo-peers.d.ts.map +1 -0
- package/dist/kubo-peers.js +119 -0
- package/dist/kubo-peers.js.map +1 -0
- package/dist/kubo-release.d.ts +22 -0
- package/dist/kubo-release.d.ts.map +1 -0
- package/dist/kubo-release.js +176 -0
- package/dist/kubo-release.js.map +1 -0
- package/dist/kubo-topology.d.ts +19 -0
- package/dist/kubo-topology.d.ts.map +1 -0
- package/dist/kubo-topology.js +113 -0
- package/dist/kubo-topology.js.map +1 -0
- package/dist/kubo.d.ts +85 -0
- package/dist/kubo.d.ts.map +1 -0
- package/dist/kubo.js +755 -0
- package/dist/kubo.js.map +1 -0
- package/dist/pins.d.ts +18 -20
- package/dist/pins.d.ts.map +1 -1
- package/dist/pins.js +146 -126
- package/dist/pins.js.map +1 -1
- package/dist/pivot-rpc.d.ts +62 -0
- package/dist/pivot-rpc.d.ts.map +1 -0
- package/dist/pivot-rpc.js +407 -0
- package/dist/pivot-rpc.js.map +1 -0
- package/dist/pivot-service.d.ts +16 -0
- package/dist/pivot-service.d.ts.map +1 -0
- package/dist/pivot-service.js +50 -0
- package/dist/pivot-service.js.map +1 -0
- package/dist/publish-source.d.ts +3 -0
- package/dist/publish-source.d.ts.map +1 -0
- package/dist/publish-source.js +85 -0
- package/dist/publish-source.js.map +1 -0
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +9 -4
- package/dist/runtime.js.map +1 -1
- package/dist/search-index.d.ts +64 -0
- package/dist/search-index.d.ts.map +1 -0
- package/dist/search-index.js +409 -0
- package/dist/search-index.js.map +1 -0
- package/dist/search-service.d.ts +23 -0
- package/dist/search-service.d.ts.map +1 -0
- package/dist/search-service.js +116 -0
- package/dist/search-service.js.map +1 -0
- package/dist/skill-definition.d.ts +6 -0
- package/dist/skill-definition.d.ts.map +1 -0
- package/dist/skill-definition.js +38 -0
- package/dist/skill-definition.js.map +1 -0
- package/dist/skill-source.d.ts +9 -0
- package/dist/skill-source.d.ts.map +1 -0
- package/dist/skill-source.js +24 -0
- package/dist/skill-source.js.map +1 -0
- package/dist/skills.d.ts +104 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +894 -0
- package/dist/skills.js.map +1 -0
- package/dist/source-bundle.d.ts +3 -9
- package/dist/source-bundle.d.ts.map +1 -1
- package/dist/source-bundle.js +17 -13
- package/dist/source-bundle.js.map +1 -1
- package/dist/space-path.d.ts +3 -0
- package/dist/space-path.d.ts.map +1 -0
- package/dist/space-path.js +17 -0
- package/dist/space-path.js.map +1 -0
- package/dist/space.d.ts +16 -4
- package/dist/space.d.ts.map +1 -1
- package/dist/space.js +170 -24
- package/dist/space.js.map +1 -1
- package/dist/state-storage-windows.d.ts +2 -0
- package/dist/state-storage-windows.d.ts.map +1 -0
- package/dist/state-storage-windows.js +114 -0
- package/dist/state-storage-windows.js.map +1 -0
- package/dist/state-storage.d.ts +5 -0
- package/dist/state-storage.d.ts.map +1 -0
- package/dist/state-storage.js +333 -0
- package/dist/state-storage.js.map +1 -0
- package/dist/state.d.ts +128 -16
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +506 -94
- package/dist/state.js.map +1 -1
- package/dist/swarm-envelope.d.ts +57 -0
- package/dist/swarm-envelope.d.ts.map +1 -0
- package/dist/swarm-envelope.js +299 -0
- package/dist/swarm-envelope.js.map +1 -0
- package/dist/swarm-files.d.ts +6 -0
- package/dist/swarm-files.d.ts.map +1 -0
- package/dist/swarm-files.js +116 -0
- package/dist/swarm-files.js.map +1 -0
- package/dist/swarm-meta.d.ts +15 -0
- package/dist/swarm-meta.d.ts.map +1 -0
- package/dist/swarm-meta.js +68 -0
- package/dist/swarm-meta.js.map +1 -0
- package/dist/swarm-observations.d.ts +40 -0
- package/dist/swarm-observations.d.ts.map +1 -0
- package/dist/swarm-observations.js +271 -0
- package/dist/swarm-observations.js.map +1 -0
- package/dist/swarm.d.ts +469 -0
- package/dist/swarm.d.ts.map +1 -0
- package/dist/swarm.js +4708 -0
- package/dist/swarm.js.map +1 -0
- package/dist/template-definition.d.ts +45 -67
- package/dist/template-definition.d.ts.map +1 -1
- package/dist/template-definition.js +35 -49
- package/dist/template-definition.js.map +1 -1
- package/dist/template-paths.d.ts +7 -0
- package/dist/template-paths.d.ts.map +1 -0
- package/dist/template-paths.js +23 -0
- package/dist/template-paths.js.map +1 -0
- package/dist/template-presentation.d.ts +20 -0
- package/dist/template-presentation.d.ts.map +1 -0
- package/dist/template-presentation.js +133 -0
- package/dist/template-presentation.js.map +1 -0
- package/dist/template-source.d.ts +4 -1
- package/dist/template-source.d.ts.map +1 -1
- package/dist/template-source.js +11 -4
- package/dist/template-source.js.map +1 -1
- package/dist/templates.d.ts +11 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +53 -0
- package/dist/templates.js.map +1 -0
- package/dist/unixfs-tree.d.ts +67 -0
- package/dist/unixfs-tree.d.ts.map +1 -0
- package/dist/unixfs-tree.js +329 -0
- package/dist/unixfs-tree.js.map +1 -0
- package/package.json +18 -11
- package/src/app-authoring.ts +254 -88
- package/src/app-definition.ts +33 -45
- package/src/app-prebuild.ts +61 -0
- package/src/app-templates.ts +28 -71
- package/src/assembly.ts +185 -0
- package/src/authoring.ts +63 -72
- package/src/builtins.ts +7 -38
- package/src/bundled-skills.ts +60 -0
- package/src/cli.ts +2500 -376
- package/src/config-secret.ts +14 -0
- package/src/config.ts +215 -26
- package/src/content-provider.ts +299 -0
- package/src/context-types.ts +11 -0
- package/src/context.ts +100 -2
- package/src/daemon-ui.ts +812 -0
- package/src/daemon.ts +386 -0
- package/src/doctor.ts +1082 -0
- package/src/errors.ts +1 -25
- package/src/get.ts +90 -0
- package/src/history.ts +5 -15
- package/src/host-error.ts +26 -0
- package/src/identity.ts +175 -0
- package/src/ipc.ts +161 -4
- package/src/kubo-install.ts +936 -0
- package/src/kubo-peering.ts +126 -0
- package/src/kubo-peers.ts +144 -0
- package/src/kubo-release.ts +230 -0
- package/src/kubo-topology.ts +148 -0
- package/src/kubo.ts +1088 -0
- package/src/pins.ts +190 -142
- package/src/pivot-rpc.ts +601 -0
- package/src/pivot-service.ts +87 -0
- package/src/publish-source.ts +103 -0
- package/src/runtime.ts +16 -3
- package/src/search-index.ts +560 -0
- package/src/search-service.ts +152 -0
- package/src/skill-definition.ts +53 -0
- package/src/skill-source.ts +29 -0
- package/src/skills.ts +1236 -0
- package/src/source-bundle.ts +26 -14
- package/src/space-path.ts +30 -0
- package/src/space.ts +230 -42
- package/src/state-storage-windows.ts +134 -0
- package/src/state-storage.ts +378 -0
- package/src/state.ts +782 -116
- package/src/swarm-envelope.ts +461 -0
- package/src/swarm-files.ts +126 -0
- package/src/swarm-meta.ts +98 -0
- package/src/swarm-observations.ts +393 -0
- package/src/swarm.ts +7051 -0
- package/src/template-definition.ts +35 -49
- package/src/template-paths.ts +43 -0
- package/src/template-presentation.ts +151 -0
- package/src/template-source.ts +19 -5
- package/src/templates.ts +77 -0
- package/src/unixfs-tree.ts +401 -0
package/src/kubo.ts
ADDED
|
@@ -0,0 +1,1088 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { isDeepStrictEqual, promisify } from "node:util";
|
|
3
|
+
import {
|
|
4
|
+
createHash,
|
|
5
|
+
createPrivateKey,
|
|
6
|
+
createPublicKey,
|
|
7
|
+
sign,
|
|
8
|
+
} from "node:crypto";
|
|
9
|
+
import { lstat, open, readFile, writeFile } from "node:fs/promises";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { createServer } from "node:net";
|
|
12
|
+
import {
|
|
13
|
+
advertisedIps,
|
|
14
|
+
BlockUnavailable,
|
|
15
|
+
readWithPeers,
|
|
16
|
+
} from "./kubo-peers.js";
|
|
17
|
+
import { base58btc } from "multiformats/bases/base58";
|
|
18
|
+
import { boundedText, uniqueId } from "@ipab/bundle/pointer/scope";
|
|
19
|
+
import {
|
|
20
|
+
protectedPath,
|
|
21
|
+
protectedPaths,
|
|
22
|
+
secureNew,
|
|
23
|
+
type Identity,
|
|
24
|
+
} from "./identity.js";
|
|
25
|
+
import {
|
|
26
|
+
privateDirectory,
|
|
27
|
+
readPrivate,
|
|
28
|
+
withPrivateLock,
|
|
29
|
+
writePrivate,
|
|
30
|
+
} from "./swarm-files.js";
|
|
31
|
+
import { HostError, object } from "./errors.js";
|
|
32
|
+
import { nodeError } from "./authoring.js";
|
|
33
|
+
import { peerArguments, type PeeringPeer } from "./kubo-peering.js";
|
|
34
|
+
import { topologyConfig } from "./kubo-topology.js";
|
|
35
|
+
|
|
36
|
+
import { kuboBinary, withKuboProgram } from "./kubo-install.js";
|
|
37
|
+
export { kuboBinary };
|
|
38
|
+
export { KUBO_VERSION } from "./kubo-release.js";
|
|
39
|
+
// Windows Firewall creates an inbound rule for every program that listens on a
|
|
40
|
+
// non-loopback address, so each new managed binary location prompts for
|
|
41
|
+
// authorization. Binding only 127.0.0.1 creates no rule at all, which keeps
|
|
42
|
+
// same-host private networks (and automated tests) unattended. A LAN swarms
|
|
43
|
+
// still advertises private IPv4 addresses as peers dial *in* to that listener.
|
|
44
|
+
export type ListenMode = "lan" | "loopback";
|
|
45
|
+
function swarmAddress(listen: ListenMode, port: number): string {
|
|
46
|
+
return `/ip4/${listen === "loopback" ? "127.0.0.1" : "0.0.0.0"}/tcp/${port}`;
|
|
47
|
+
}
|
|
48
|
+
const run = promisify(execFile);
|
|
49
|
+
export interface NodeRecord {
|
|
50
|
+
scope: string;
|
|
51
|
+
peerId: string;
|
|
52
|
+
api: number;
|
|
53
|
+
gateway: number;
|
|
54
|
+
swarm: number;
|
|
55
|
+
auth: string;
|
|
56
|
+
epoch?: number;
|
|
57
|
+
pid?: number;
|
|
58
|
+
listen?: ListenMode;
|
|
59
|
+
topology?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface KuboNode {
|
|
62
|
+
repo: string;
|
|
63
|
+
peerId: string;
|
|
64
|
+
api: string;
|
|
65
|
+
gateway: string;
|
|
66
|
+
addresses: string[];
|
|
67
|
+
auth: string;
|
|
68
|
+
pid?: number;
|
|
69
|
+
topology?: string;
|
|
70
|
+
}
|
|
71
|
+
export function nodeRecord(value: unknown, scope: string): NodeRecord {
|
|
72
|
+
const record = object(value, "protected managed-node record");
|
|
73
|
+
const { peerId, api, gateway, swarm, auth, pid, epoch, listen, topology } =
|
|
74
|
+
record;
|
|
75
|
+
if (
|
|
76
|
+
Object.keys(record).some(
|
|
77
|
+
(key) =>
|
|
78
|
+
![
|
|
79
|
+
"scope",
|
|
80
|
+
"peerId",
|
|
81
|
+
"api",
|
|
82
|
+
"gateway",
|
|
83
|
+
"swarm",
|
|
84
|
+
"auth",
|
|
85
|
+
"pid",
|
|
86
|
+
"epoch",
|
|
87
|
+
"listen",
|
|
88
|
+
"topology",
|
|
89
|
+
].includes(key),
|
|
90
|
+
) ||
|
|
91
|
+
record.scope !== scope ||
|
|
92
|
+
typeof peerId !== "string" ||
|
|
93
|
+
!/^[A-Za-z0-9]{32,128}$/.test(peerId) ||
|
|
94
|
+
typeof api !== "number" ||
|
|
95
|
+
typeof gateway !== "number" ||
|
|
96
|
+
typeof swarm !== "number" ||
|
|
97
|
+
![api, gateway, swarm].every(
|
|
98
|
+
(port) => Number.isSafeInteger(port) && port > 0 && port <= 65535,
|
|
99
|
+
) ||
|
|
100
|
+
new Set([record.api, record.gateway, record.swarm]).size !== 3 ||
|
|
101
|
+
typeof auth !== "string" ||
|
|
102
|
+
!/^[A-Za-z0-9_-]{43}$/.test(auth) ||
|
|
103
|
+
(pid !== undefined &&
|
|
104
|
+
(typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)) ||
|
|
105
|
+
(epoch !== undefined &&
|
|
106
|
+
(typeof epoch !== "number" ||
|
|
107
|
+
!Number.isSafeInteger(epoch) ||
|
|
108
|
+
epoch < 1)) ||
|
|
109
|
+
(listen !== undefined && listen !== "lan" && listen !== "loopback") ||
|
|
110
|
+
(topology !== undefined &&
|
|
111
|
+
(typeof topology !== "string" || !/^[a-f0-9]{64}$/.test(topology)))
|
|
112
|
+
)
|
|
113
|
+
throw new HostError(
|
|
114
|
+
"Invalid protected managed-node record; old node formats are unsupported.",
|
|
115
|
+
);
|
|
116
|
+
return {
|
|
117
|
+
scope,
|
|
118
|
+
peerId,
|
|
119
|
+
api,
|
|
120
|
+
gateway,
|
|
121
|
+
swarm,
|
|
122
|
+
auth,
|
|
123
|
+
...(pid !== undefined ? { pid } : {}),
|
|
124
|
+
...(epoch !== undefined ? { epoch } : {}),
|
|
125
|
+
...(listen !== undefined ? { listen } : {}),
|
|
126
|
+
...(topology !== undefined ? { topology } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
async function freePort(): Promise<number> {
|
|
130
|
+
const server = createServer();
|
|
131
|
+
return new Promise((resolve, reject) => {
|
|
132
|
+
server.once("error", reject);
|
|
133
|
+
server.listen(0, "127.0.0.1", () => {
|
|
134
|
+
const address = server.address();
|
|
135
|
+
if (!address || typeof address === "string") {
|
|
136
|
+
server.close();
|
|
137
|
+
reject(new HostError("No free port."));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
server.close((error) => {
|
|
141
|
+
if (error) reject(error);
|
|
142
|
+
else resolve(address.port);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
export function kuboEd25519Identity(identity: Identity): {
|
|
148
|
+
peerId: string;
|
|
149
|
+
privKey: string;
|
|
150
|
+
} {
|
|
151
|
+
const privateKey = createPrivateKey({
|
|
152
|
+
key: Buffer.from(identity.privateKey, "base64url"),
|
|
153
|
+
type: "pkcs8",
|
|
154
|
+
format: "der",
|
|
155
|
+
});
|
|
156
|
+
if (privateKey.asymmetricKeyType !== "ed25519")
|
|
157
|
+
throw new HostError("Managed Kubo node requires an Ed25519 account key.");
|
|
158
|
+
const rawPub = createPublicKey(privateKey)
|
|
159
|
+
.export({ format: "der", type: "spki" })
|
|
160
|
+
.subarray(-32);
|
|
161
|
+
if (
|
|
162
|
+
rawPub.length !== 32 ||
|
|
163
|
+
rawPub.toString("base64url") !== identity.publicKey
|
|
164
|
+
)
|
|
165
|
+
throw new HostError("Stored account identity is inconsistent.");
|
|
166
|
+
const pkcs8 = privateKey.export({ format: "der", type: "pkcs8" });
|
|
167
|
+
const seed = pkcs8.subarray(-32);
|
|
168
|
+
if (seed.length !== 32)
|
|
169
|
+
throw new HostError("Invalid Ed25519 private key encoding.");
|
|
170
|
+
return {
|
|
171
|
+
peerId: peerId(identity.publicKey),
|
|
172
|
+
privKey: Buffer.concat([
|
|
173
|
+
Buffer.from([8, 1, 18, 64]),
|
|
174
|
+
seed,
|
|
175
|
+
rawPub,
|
|
176
|
+
]).toString("base64"),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export async function prepareNode(
|
|
180
|
+
stateDir: string,
|
|
181
|
+
scope: string,
|
|
182
|
+
listen: ListenMode = "lan",
|
|
183
|
+
identity?: Identity,
|
|
184
|
+
): Promise<KuboNode> {
|
|
185
|
+
if (!/^[a-f0-9]{64}$/.test(scope))
|
|
186
|
+
throw new HostError("Invalid service-bound local Scope identity.");
|
|
187
|
+
return withKuboProgram(stateDir, (binary) =>
|
|
188
|
+
prepareWithBinary(stateDir, scope, binary, listen, undefined, identity),
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
export async function checkCachedNode(
|
|
192
|
+
stateDir: string,
|
|
193
|
+
scope: string,
|
|
194
|
+
epoch: number,
|
|
195
|
+
peer: string,
|
|
196
|
+
) {
|
|
197
|
+
if (!/^[a-f0-9]{64}$/.test(scope))
|
|
198
|
+
throw new HostError("Invalid service-bound local Scope identity.");
|
|
199
|
+
const saved = await readPrivate<unknown>(
|
|
200
|
+
join(stateDir, "swarm-nodes", scope),
|
|
201
|
+
"node.json",
|
|
202
|
+
);
|
|
203
|
+
if (saved === undefined) return;
|
|
204
|
+
const node = nodeRecord(saved, scope);
|
|
205
|
+
if (node.peerId !== peer || (node.epoch !== undefined && node.epoch > epoch))
|
|
206
|
+
throw new HostError(
|
|
207
|
+
"Cached membership does not match the recorded node identity or epoch; retry with --refresh.",
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
async function prepareWithBinary(
|
|
211
|
+
stateDir: string,
|
|
212
|
+
scope: string,
|
|
213
|
+
binary: string,
|
|
214
|
+
listen: ListenMode,
|
|
215
|
+
signal?: AbortSignal,
|
|
216
|
+
identity?: Identity,
|
|
217
|
+
): Promise<KuboNode> {
|
|
218
|
+
const parent = join(stateDir, "swarm-nodes");
|
|
219
|
+
const directory = join(parent, scope);
|
|
220
|
+
const repo = join(directory, "repo");
|
|
221
|
+
try {
|
|
222
|
+
await protectedPaths(
|
|
223
|
+
[parent, directory, repo].map((path) => ({ path, directory: true })),
|
|
224
|
+
);
|
|
225
|
+
} catch (cause) {
|
|
226
|
+
if (!nodeError(cause, "ENOENT")) throw cause;
|
|
227
|
+
await privateDirectory(stateDir, "swarm-nodes");
|
|
228
|
+
await privateDirectory(parent, scope);
|
|
229
|
+
await privateDirectory(directory, "repo");
|
|
230
|
+
}
|
|
231
|
+
const prepare = async () => {
|
|
232
|
+
let record = await readPrivate<NodeRecord>(directory, "node.json", [
|
|
233
|
+
{ path: join(repo, "config") },
|
|
234
|
+
]);
|
|
235
|
+
if (record === undefined) {
|
|
236
|
+
try {
|
|
237
|
+
await lstat(join(repo, "swarm.key"));
|
|
238
|
+
throw new HostError(
|
|
239
|
+
"Managed node record is missing; restore it before using the existing protected repo.",
|
|
240
|
+
);
|
|
241
|
+
} catch (cause) {
|
|
242
|
+
if (!nodeError(cause, "ENOENT")) throw cause;
|
|
243
|
+
}
|
|
244
|
+
const env = { ...process.env, IPFS_PATH: repo, LIBP2P_FORCE_PNET: "1" };
|
|
245
|
+
try {
|
|
246
|
+
await lstat(join(repo, "config"));
|
|
247
|
+
} catch (cause) {
|
|
248
|
+
if (!nodeError(cause, "ENOENT")) throw cause;
|
|
249
|
+
await run(binary, ["init", "--profile=server"], {
|
|
250
|
+
env,
|
|
251
|
+
signal,
|
|
252
|
+
timeout: 30_000,
|
|
253
|
+
windowsHide: true,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
const config = JSON.parse(
|
|
257
|
+
await readFile(join(repo, "config"), "utf8"),
|
|
258
|
+
) as {
|
|
259
|
+
Identity: { PeerID: string; PrivKey: string };
|
|
260
|
+
Addresses: Record<string, unknown>;
|
|
261
|
+
Bootstrap: string[];
|
|
262
|
+
Discovery: { MDNS: { Enabled: boolean } };
|
|
263
|
+
Routing: { Type: string };
|
|
264
|
+
AutoTLS?: { Enabled: boolean };
|
|
265
|
+
AutoConf?: { Enabled: boolean };
|
|
266
|
+
API?: {
|
|
267
|
+
Authorizations?: Record<
|
|
268
|
+
string,
|
|
269
|
+
{ AuthSecret: string; AllowedPaths: string[] }
|
|
270
|
+
>;
|
|
271
|
+
};
|
|
272
|
+
AutoNAT?: { ServiceMode: string };
|
|
273
|
+
Swarm: {
|
|
274
|
+
AddrFilters: string[];
|
|
275
|
+
DisableNatPortMap: boolean;
|
|
276
|
+
EnableHolePunching: boolean;
|
|
277
|
+
RelayClient: { Enabled: boolean };
|
|
278
|
+
RelayService: { Enabled: boolean };
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
if (identity) {
|
|
282
|
+
const kuboId = kuboEd25519Identity(identity);
|
|
283
|
+
config.Identity.PeerID = kuboId.peerId;
|
|
284
|
+
config.Identity.PrivKey = kuboId.privKey;
|
|
285
|
+
}
|
|
286
|
+
record = {
|
|
287
|
+
scope,
|
|
288
|
+
peerId: config.Identity.PeerID,
|
|
289
|
+
api: await freePort(),
|
|
290
|
+
gateway: await freePort(),
|
|
291
|
+
swarm: await freePort(),
|
|
292
|
+
auth: uniqueId(),
|
|
293
|
+
listen,
|
|
294
|
+
};
|
|
295
|
+
config.Addresses = {
|
|
296
|
+
API: `/ip4/127.0.0.1/tcp/${record.api}`,
|
|
297
|
+
Gateway: `/ip4/127.0.0.1/tcp/${record.gateway}`,
|
|
298
|
+
Swarm: [swarmAddress(listen, record.swarm)],
|
|
299
|
+
};
|
|
300
|
+
config.Bootstrap = [];
|
|
301
|
+
config.Swarm.AddrFilters = [];
|
|
302
|
+
config.Swarm.DisableNatPortMap = true;
|
|
303
|
+
config.Swarm.EnableHolePunching = false;
|
|
304
|
+
config.Swarm.RelayClient.Enabled = false;
|
|
305
|
+
config.Swarm.RelayService.Enabled = false;
|
|
306
|
+
config.API = {
|
|
307
|
+
...config.API,
|
|
308
|
+
Authorizations: {
|
|
309
|
+
IPAB: {
|
|
310
|
+
AuthSecret: `bearer:${record.auth}`,
|
|
311
|
+
AllowedPaths: ["/api/v0"],
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
if (config.AutoNAT) config.AutoNAT.ServiceMode = "disabled";
|
|
316
|
+
config.Discovery.MDNS.Enabled = false;
|
|
317
|
+
config.Routing.Type = "none";
|
|
318
|
+
if (config.AutoTLS) config.AutoTLS.Enabled = false;
|
|
319
|
+
if (config.AutoConf) config.AutoConf.Enabled = false;
|
|
320
|
+
await writeFile(join(repo, "config"), JSON.stringify(config), {
|
|
321
|
+
mode: 0o600,
|
|
322
|
+
});
|
|
323
|
+
await secureNew(join(repo, "config"));
|
|
324
|
+
await writePrivate(directory, "node.json", record);
|
|
325
|
+
await protectedPath(join(repo, "config"));
|
|
326
|
+
}
|
|
327
|
+
record = nodeRecord(record, scope);
|
|
328
|
+
// A repo created before listen modes existed binds 0.0.0.0, so it is LAN.
|
|
329
|
+
record.listen ??= "lan";
|
|
330
|
+
if (record.listen !== listen)
|
|
331
|
+
throw new HostError(
|
|
332
|
+
"Managed node already listens in a different mode; existing repos are not rebound.",
|
|
333
|
+
);
|
|
334
|
+
return {
|
|
335
|
+
repo,
|
|
336
|
+
peerId: record.peerId,
|
|
337
|
+
api: `http://127.0.0.1:${record.api}`,
|
|
338
|
+
gateway: `http://127.0.0.1:${record.gateway}`,
|
|
339
|
+
auth: record.auth,
|
|
340
|
+
...(record.pid !== undefined ? { pid: record.pid } : {}),
|
|
341
|
+
addresses: advertisedIps(record.listen).map(
|
|
342
|
+
(ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`,
|
|
343
|
+
),
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
return withPrivateLock(directory, prepare, signal);
|
|
347
|
+
}
|
|
348
|
+
export async function peerProof(
|
|
349
|
+
node: KuboNode,
|
|
350
|
+
message: string,
|
|
351
|
+
): Promise<{ publicKey: string; signature: string }> {
|
|
352
|
+
await protectedPath(join(node.repo, "config"));
|
|
353
|
+
const config = JSON.parse(
|
|
354
|
+
await readFile(join(node.repo, "config"), "utf8"),
|
|
355
|
+
) as { Identity: { PrivKey: string } };
|
|
356
|
+
const protobuf = Buffer.from(config.Identity.PrivKey, "base64");
|
|
357
|
+
if (
|
|
358
|
+
protobuf.length !== 68 ||
|
|
359
|
+
!protobuf.subarray(0, 4).equals(Buffer.from([8, 1, 18, 64]))
|
|
360
|
+
)
|
|
361
|
+
throw new HostError("Only new Ed25519 Kubo identities are supported.");
|
|
362
|
+
const privateKey = createPrivateKey({
|
|
363
|
+
key: Buffer.concat([
|
|
364
|
+
Buffer.from("302e020100300506032b657004220420", "hex"),
|
|
365
|
+
protobuf.subarray(4, 36),
|
|
366
|
+
]),
|
|
367
|
+
type: "pkcs8",
|
|
368
|
+
format: "der",
|
|
369
|
+
});
|
|
370
|
+
const raw = createPublicKey(privateKey)
|
|
371
|
+
.export({ format: "der", type: "spki" })
|
|
372
|
+
.subarray(-32);
|
|
373
|
+
if (peerId(raw.toString("base64url")) !== node.peerId)
|
|
374
|
+
throw new HostError("Kubo identity mismatch.");
|
|
375
|
+
return {
|
|
376
|
+
publicKey: raw.toString("base64url"),
|
|
377
|
+
signature: sign(null, Buffer.from(message), privateKey).toString(
|
|
378
|
+
"base64url",
|
|
379
|
+
),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
export function peerId(raw: string): string {
|
|
383
|
+
return base58btc
|
|
384
|
+
.encode(
|
|
385
|
+
Buffer.concat([
|
|
386
|
+
Buffer.from([0, 36, 8, 1, 18, 32]),
|
|
387
|
+
Buffer.from(raw, "base64url"),
|
|
388
|
+
]),
|
|
389
|
+
)
|
|
390
|
+
.slice(1);
|
|
391
|
+
}
|
|
392
|
+
async function rpc(
|
|
393
|
+
node: KuboNode,
|
|
394
|
+
command: string,
|
|
395
|
+
signal?: AbortSignal,
|
|
396
|
+
timeout = 5000,
|
|
397
|
+
fetcher: typeof fetch = fetch,
|
|
398
|
+
): Promise<Response> {
|
|
399
|
+
return fetcher(`${node.api}/api/v0/${command}`, {
|
|
400
|
+
method: "POST",
|
|
401
|
+
headers: { authorization: `Bearer ${node.auth}` },
|
|
402
|
+
redirect: "error",
|
|
403
|
+
signal: signal
|
|
404
|
+
? AbortSignal.any([signal, AbortSignal.timeout(timeout)])
|
|
405
|
+
: AbortSignal.timeout(timeout),
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
async function ready(node: KuboNode, signal?: AbortSignal): Promise<boolean> {
|
|
409
|
+
try {
|
|
410
|
+
const response = await rpc(node, "id", signal);
|
|
411
|
+
if (response.status === 401 || response.status === 403) {
|
|
412
|
+
await response.body?.cancel();
|
|
413
|
+
throw new HostError(
|
|
414
|
+
"Owned Kubo API authorization failed; refusing control.",
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
if (!response.ok) {
|
|
418
|
+
await response.body?.cancel();
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
const identity = JSON.parse(await boundedText(response)) as { ID: string };
|
|
422
|
+
if (identity.ID !== node.peerId)
|
|
423
|
+
throw new HostError(
|
|
424
|
+
"Selected Kubo port belongs to another node; refusing control.",
|
|
425
|
+
);
|
|
426
|
+
return true;
|
|
427
|
+
} catch (cause) {
|
|
428
|
+
signal?.throwIfAborted();
|
|
429
|
+
if (cause instanceof HostError) throw cause;
|
|
430
|
+
return false;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
export async function stopNode(node: KuboNode): Promise<void> {
|
|
434
|
+
if (!(await ready(node))) return;
|
|
435
|
+
await (await rpc(node, "shutdown")).body?.cancel();
|
|
436
|
+
for (let i = 0; i < 100; i++) {
|
|
437
|
+
const responsive = await ready(node);
|
|
438
|
+
let alive = false;
|
|
439
|
+
if (node.pid !== undefined) {
|
|
440
|
+
try {
|
|
441
|
+
process.kill(node.pid, 0);
|
|
442
|
+
alive = true;
|
|
443
|
+
} catch (cause) {
|
|
444
|
+
if (!nodeError(cause, "ESRCH")) throw cause;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (!responsive && !alive) return;
|
|
448
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
449
|
+
}
|
|
450
|
+
throw new HostError("Owned Kubo node did not stop.");
|
|
451
|
+
}
|
|
452
|
+
export async function startNode(
|
|
453
|
+
stateDir: string,
|
|
454
|
+
scope: string,
|
|
455
|
+
key: string,
|
|
456
|
+
epoch: number,
|
|
457
|
+
listen: ListenMode = "lan",
|
|
458
|
+
membership?: {
|
|
459
|
+
self: string;
|
|
460
|
+
peers: readonly PeeringPeer[];
|
|
461
|
+
pivot?: boolean;
|
|
462
|
+
signal?: AbortSignal;
|
|
463
|
+
identity?: Identity;
|
|
464
|
+
},
|
|
465
|
+
): Promise<KuboNode> {
|
|
466
|
+
if (!/^[a-f0-9]{64}$/.test(scope))
|
|
467
|
+
throw new HostError("Invalid service-bound local Scope identity.");
|
|
468
|
+
if (!/^[a-f0-9]{64}$/.test(key)) throw new HostError("Invalid Swarm key.");
|
|
469
|
+
const signal = membership?.signal;
|
|
470
|
+
signal?.throwIfAborted();
|
|
471
|
+
return withKuboProgram(
|
|
472
|
+
stateDir,
|
|
473
|
+
async (binary) => {
|
|
474
|
+
signal?.throwIfAborted();
|
|
475
|
+
const node = await prepareWithBinary(
|
|
476
|
+
stateDir,
|
|
477
|
+
scope,
|
|
478
|
+
binary,
|
|
479
|
+
listen,
|
|
480
|
+
signal,
|
|
481
|
+
membership?.identity,
|
|
482
|
+
);
|
|
483
|
+
if (membership && node.peerId !== membership.self)
|
|
484
|
+
throw new HostError(
|
|
485
|
+
"Approved PeerID differs from this local Request's Kubo identity.",
|
|
486
|
+
);
|
|
487
|
+
const directory = join(stateDir, "swarm-nodes", scope);
|
|
488
|
+
const start = async () => {
|
|
489
|
+
signal?.throwIfAborted();
|
|
490
|
+
const record = (await readPrivate<NodeRecord>(directory, "node.json"))!;
|
|
491
|
+
if (record.epoch !== undefined && record.epoch > epoch)
|
|
492
|
+
throw new HostError(
|
|
493
|
+
"Refusing to restore an older Swarm epoch; refresh membership.",
|
|
494
|
+
);
|
|
495
|
+
const invalidateTopology = async () => {
|
|
496
|
+
if (record.topology !== undefined) {
|
|
497
|
+
delete record.topology;
|
|
498
|
+
await writePrivate(directory, "node.json", record);
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
if (record.epoch !== undefined && record.epoch !== epoch) {
|
|
502
|
+
await invalidateTopology();
|
|
503
|
+
await stopNode(node);
|
|
504
|
+
}
|
|
505
|
+
let online = await ready(node, signal);
|
|
506
|
+
if (!online && record.pid !== undefined) {
|
|
507
|
+
try {
|
|
508
|
+
process.kill(record.pid, 0);
|
|
509
|
+
throw new HostError(
|
|
510
|
+
"Owned node process is still running but not ready; retry before changing its configuration.",
|
|
511
|
+
);
|
|
512
|
+
} catch (cause) {
|
|
513
|
+
if (!nodeError(cause, "ESRCH")) throw cause;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
const desired = membership?.peers ?? [];
|
|
517
|
+
const config = await readPrivate<Record<string, unknown>>(
|
|
518
|
+
node.repo,
|
|
519
|
+
"config",
|
|
520
|
+
);
|
|
521
|
+
if (!config)
|
|
522
|
+
throw new HostError("Missing protected Kubo configuration.");
|
|
523
|
+
const nextConfig = topologyConfig(
|
|
524
|
+
config,
|
|
525
|
+
membership?.pivot ?? false,
|
|
526
|
+
desired,
|
|
527
|
+
listen === "loopback",
|
|
528
|
+
);
|
|
529
|
+
if (!isDeepStrictEqual(config, nextConfig)) {
|
|
530
|
+
await invalidateTopology();
|
|
531
|
+
if (online) {
|
|
532
|
+
await stopNode(node);
|
|
533
|
+
online = false;
|
|
534
|
+
}
|
|
535
|
+
await writePrivate(node.repo, "config", nextConfig);
|
|
536
|
+
}
|
|
537
|
+
const keyPath = join(node.repo, "swarm.key");
|
|
538
|
+
if (record.epoch === epoch) {
|
|
539
|
+
await protectedPath(keyPath);
|
|
540
|
+
if (
|
|
541
|
+
(await readFile(keyPath, "utf8")) !==
|
|
542
|
+
`/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`
|
|
543
|
+
)
|
|
544
|
+
throw new HostError(
|
|
545
|
+
"Swarm key file does not match approved epoch.",
|
|
546
|
+
);
|
|
547
|
+
} else {
|
|
548
|
+
await writeFile(
|
|
549
|
+
keyPath,
|
|
550
|
+
`/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`,
|
|
551
|
+
{
|
|
552
|
+
mode: 0o600,
|
|
553
|
+
},
|
|
554
|
+
);
|
|
555
|
+
await secureNew(keyPath);
|
|
556
|
+
}
|
|
557
|
+
if (!online) {
|
|
558
|
+
signal?.throwIfAborted();
|
|
559
|
+
// Kubo's bootstrap fallback is persisted independently of config.
|
|
560
|
+
// Clear only its version-pinned backup key while the owned repo is
|
|
561
|
+
// offline, so removed candidates cannot reappear after a restart.
|
|
562
|
+
await run(
|
|
563
|
+
binary,
|
|
564
|
+
["diag", "datastore", "put", "/local/temp_bootstrap_peers", "[]"],
|
|
565
|
+
{
|
|
566
|
+
env: {
|
|
567
|
+
...process.env,
|
|
568
|
+
IPFS_PATH: node.repo,
|
|
569
|
+
LIBP2P_FORCE_PNET: "1",
|
|
570
|
+
},
|
|
571
|
+
signal,
|
|
572
|
+
timeout: 30_000,
|
|
573
|
+
windowsHide: true,
|
|
574
|
+
},
|
|
575
|
+
);
|
|
576
|
+
const logfile = join(directory, "daemon.log");
|
|
577
|
+
const log = await open(logfile, "a", 0o600);
|
|
578
|
+
await secureNew(logfile);
|
|
579
|
+
const child = spawn(
|
|
580
|
+
binary,
|
|
581
|
+
["daemon", "--enable-gc=false", "--migrate=false"],
|
|
582
|
+
{
|
|
583
|
+
env: {
|
|
584
|
+
...process.env,
|
|
585
|
+
IPFS_PATH: node.repo,
|
|
586
|
+
LIBP2P_FORCE_PNET: "1",
|
|
587
|
+
},
|
|
588
|
+
detached: true,
|
|
589
|
+
windowsHide: true,
|
|
590
|
+
stdio: ["ignore", log.fd, log.fd],
|
|
591
|
+
},
|
|
592
|
+
);
|
|
593
|
+
let failure: Error | undefined;
|
|
594
|
+
child.once("error", (error) => {
|
|
595
|
+
failure = error;
|
|
596
|
+
});
|
|
597
|
+
const closed = new Promise<void>((resolve) => {
|
|
598
|
+
child.once("close", () => {
|
|
599
|
+
resolve();
|
|
600
|
+
});
|
|
601
|
+
});
|
|
602
|
+
child.unref();
|
|
603
|
+
await log.close();
|
|
604
|
+
try {
|
|
605
|
+
if (child.pid !== undefined) {
|
|
606
|
+
record.pid = child.pid;
|
|
607
|
+
node.pid = child.pid;
|
|
608
|
+
record.epoch = epoch;
|
|
609
|
+
await writePrivate(directory, "node.json", record);
|
|
610
|
+
}
|
|
611
|
+
for (let i = 0; ; i++) {
|
|
612
|
+
signal?.throwIfAborted();
|
|
613
|
+
if (failure) throw failure;
|
|
614
|
+
if (await ready(node, signal)) break;
|
|
615
|
+
if (i >= 150 || child.exitCode !== null)
|
|
616
|
+
throw new HostError(
|
|
617
|
+
"Owned Kubo startup failed; inspect protected daemon.log.",
|
|
618
|
+
);
|
|
619
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
620
|
+
}
|
|
621
|
+
} catch (cause) {
|
|
622
|
+
child.kill();
|
|
623
|
+
await Promise.race([
|
|
624
|
+
closed,
|
|
625
|
+
new Promise<void>((resolve) => setTimeout(resolve, 5000)),
|
|
626
|
+
]);
|
|
627
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
628
|
+
child.kill("SIGKILL");
|
|
629
|
+
await closed;
|
|
630
|
+
throw cause;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const topology = membership
|
|
634
|
+
? createHash("sha256")
|
|
635
|
+
.update(
|
|
636
|
+
JSON.stringify({
|
|
637
|
+
self: membership.self,
|
|
638
|
+
pivot: membership.pivot ?? false,
|
|
639
|
+
peers: membership.peers,
|
|
640
|
+
}),
|
|
641
|
+
)
|
|
642
|
+
.digest("hex")
|
|
643
|
+
: undefined;
|
|
644
|
+
if (record.epoch !== epoch || record.topology !== topology) {
|
|
645
|
+
record.epoch = epoch;
|
|
646
|
+
if (topology) record.topology = topology;
|
|
647
|
+
else delete record.topology;
|
|
648
|
+
await writePrivate(directory, "node.json", record);
|
|
649
|
+
}
|
|
650
|
+
if (topology) node.topology = topology;
|
|
651
|
+
return node;
|
|
652
|
+
};
|
|
653
|
+
return withPrivateLock(directory, start, signal);
|
|
654
|
+
},
|
|
655
|
+
signal,
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
export function validateAddress(address: string, expectedPeer?: string): void {
|
|
659
|
+
const match =
|
|
660
|
+
/^\/ip4\/(\d+\.\d+\.\d+\.\d+)\/tcp\/([1-9]\d{0,4})\/p2p\/([A-Za-z0-9]+)$/.exec(
|
|
661
|
+
address,
|
|
662
|
+
);
|
|
663
|
+
if (
|
|
664
|
+
!match ||
|
|
665
|
+
Number(match[2]) > 65535 ||
|
|
666
|
+
match[1]!.split(".").some((n) => Number(n) > 255) ||
|
|
667
|
+
(expectedPeer && match[3] !== expectedPeer)
|
|
668
|
+
)
|
|
669
|
+
throw new HostError(
|
|
670
|
+
"Pivot profile requires IPv4 TCP multiaddr bound to its PeerID.",
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
export async function probePeer(
|
|
674
|
+
node: KuboNode,
|
|
675
|
+
id: string,
|
|
676
|
+
addresses: readonly string[],
|
|
677
|
+
signal?: AbortSignal,
|
|
678
|
+
): Promise<boolean> {
|
|
679
|
+
for (const address of addresses) validateAddress(address, id);
|
|
680
|
+
if (!addresses.length) return false;
|
|
681
|
+
const response = await rpc(
|
|
682
|
+
node,
|
|
683
|
+
`swarm/connect?${addresses.map((address) => `arg=${encodeURIComponent(address)}`).join("&")}`,
|
|
684
|
+
signal,
|
|
685
|
+
8_000,
|
|
686
|
+
);
|
|
687
|
+
const body = await boundedText(response);
|
|
688
|
+
return response.ok && !body.includes('"Error"');
|
|
689
|
+
}
|
|
690
|
+
export interface PeerConnection {
|
|
691
|
+
peerId: string;
|
|
692
|
+
address: string;
|
|
693
|
+
transport: "direct" | "relay";
|
|
694
|
+
}
|
|
695
|
+
export async function nodeConnections(
|
|
696
|
+
node: KuboNode,
|
|
697
|
+
signal?: AbortSignal,
|
|
698
|
+
): Promise<PeerConnection[]> {
|
|
699
|
+
if (!(await ready(node, signal)))
|
|
700
|
+
throw new HostError("Owned Kubo API is unavailable.");
|
|
701
|
+
const response = await rpc(node, "swarm/peers", signal);
|
|
702
|
+
if (!response.ok) {
|
|
703
|
+
await response.body?.cancel();
|
|
704
|
+
throw new HostError(`Owned Kubo connections: HTTP ${response.status}`);
|
|
705
|
+
}
|
|
706
|
+
const data = object(
|
|
707
|
+
JSON.parse(await boundedText(response)) as unknown,
|
|
708
|
+
"owned Kubo connections",
|
|
709
|
+
);
|
|
710
|
+
if (data.Peers === null) return [];
|
|
711
|
+
if (!Array.isArray(data.Peers) || data.Peers.length > 4096)
|
|
712
|
+
throw new HostError("Invalid owned Kubo connections.");
|
|
713
|
+
return data.Peers.map((entry: unknown) => {
|
|
714
|
+
const { Peer, Addr } = object(entry, "owned Kubo connection");
|
|
715
|
+
if (typeof Peer !== "string" || typeof Addr !== "string")
|
|
716
|
+
throw new HostError("Invalid owned Kubo connection.");
|
|
717
|
+
return {
|
|
718
|
+
peerId: Peer,
|
|
719
|
+
address: Addr,
|
|
720
|
+
transport: Addr.includes("/p2p-circuit") ? "relay" : "direct",
|
|
721
|
+
};
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
export function kuboSource(
|
|
725
|
+
node: KuboNode,
|
|
726
|
+
addresses: readonly string[] = [],
|
|
727
|
+
diagnostic?: (line: string) => void,
|
|
728
|
+
detailed = false,
|
|
729
|
+
) {
|
|
730
|
+
const groups = new Map<string, string[]>();
|
|
731
|
+
for (const address of new Set(addresses)) {
|
|
732
|
+
validateAddress(address);
|
|
733
|
+
const target = address.split("/").at(-1)!;
|
|
734
|
+
if (target === node.peerId) continue;
|
|
735
|
+
const group = groups.get(target) ?? [];
|
|
736
|
+
if (group.length < 16)
|
|
737
|
+
group.push(address.slice(0, -`/p2p/${target}`.length));
|
|
738
|
+
groups.set(target, group);
|
|
739
|
+
}
|
|
740
|
+
let fallbackUsed = false;
|
|
741
|
+
const connected = async (signal: AbortSignal) => {
|
|
742
|
+
const response = await rpc(node, "swarm/peers", signal);
|
|
743
|
+
if (!response.ok) {
|
|
744
|
+
await response.body?.cancel();
|
|
745
|
+
throw new HostError(`HTTP ${response.status}`);
|
|
746
|
+
}
|
|
747
|
+
const data = object(
|
|
748
|
+
JSON.parse(await boundedText(response)) as unknown,
|
|
749
|
+
"owned Kubo connections",
|
|
750
|
+
);
|
|
751
|
+
if (data.Peers === null) return new Set<string>();
|
|
752
|
+
if (!Array.isArray(data.Peers))
|
|
753
|
+
throw new HostError("Invalid owned Kubo connections.");
|
|
754
|
+
return new Set(
|
|
755
|
+
data.Peers.map((entry: unknown) => {
|
|
756
|
+
const { Peer } = object(entry, "owned Kubo connection");
|
|
757
|
+
if (typeof Peer !== "string")
|
|
758
|
+
throw new HostError("Invalid owned Kubo connection.");
|
|
759
|
+
return Peer;
|
|
760
|
+
}),
|
|
761
|
+
);
|
|
762
|
+
};
|
|
763
|
+
const connect = async (
|
|
764
|
+
id: string,
|
|
765
|
+
addrs: readonly string[],
|
|
766
|
+
signal: AbortSignal,
|
|
767
|
+
) => {
|
|
768
|
+
const response = await rpc(
|
|
769
|
+
node,
|
|
770
|
+
`swarm/connect?${peerArguments(id, addrs)}`,
|
|
771
|
+
signal,
|
|
772
|
+
);
|
|
773
|
+
try {
|
|
774
|
+
if (!response.ok) throw new HostError(`HTTP ${response.status}`);
|
|
775
|
+
// swarm/connect may stream the result. Do not treat headers alone as success.
|
|
776
|
+
await boundedText(response);
|
|
777
|
+
} finally {
|
|
778
|
+
await response.body?.cancel();
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
return {
|
|
782
|
+
block: {
|
|
783
|
+
async get(
|
|
784
|
+
cid: string,
|
|
785
|
+
options: { signal?: AbortSignal } = {},
|
|
786
|
+
): Promise<Uint8Array> {
|
|
787
|
+
return readWithPeers(
|
|
788
|
+
groups,
|
|
789
|
+
async (signal, offline) => {
|
|
790
|
+
const response = await rpc(
|
|
791
|
+
node,
|
|
792
|
+
`block/get?arg=${encodeURIComponent(cid)}${offline ? "&offline=true" : ""}`,
|
|
793
|
+
signal,
|
|
794
|
+
30_000,
|
|
795
|
+
);
|
|
796
|
+
if (!response.ok || !response.body) {
|
|
797
|
+
const error = `Swarm block unavailable (HTTP ${response.status}).`;
|
|
798
|
+
if (offline && [404, 500].includes(response.status)) {
|
|
799
|
+
const detail = object(
|
|
800
|
+
JSON.parse(await boundedText(response)) as unknown,
|
|
801
|
+
"owned Kubo block error",
|
|
802
|
+
).Message;
|
|
803
|
+
if (
|
|
804
|
+
typeof detail === "string" &&
|
|
805
|
+
detail.startsWith("block was not found locally (offline):")
|
|
806
|
+
)
|
|
807
|
+
throw new BlockUnavailable(error);
|
|
808
|
+
}
|
|
809
|
+
await response.body?.cancel();
|
|
810
|
+
if (!offline && [404, 500].includes(response.status))
|
|
811
|
+
throw new BlockUnavailable(error);
|
|
812
|
+
throw new HostError(error);
|
|
813
|
+
}
|
|
814
|
+
const stream: ReadableStream<Uint8Array> = response.body;
|
|
815
|
+
const reader = stream.getReader();
|
|
816
|
+
const chunks: Uint8Array[] = [];
|
|
817
|
+
let size = 0;
|
|
818
|
+
try {
|
|
819
|
+
for (;;) {
|
|
820
|
+
const part = await reader.read();
|
|
821
|
+
if (part.done) break;
|
|
822
|
+
size += part.value.length;
|
|
823
|
+
if (size > 2 * 1024 * 1024) {
|
|
824
|
+
await reader.cancel();
|
|
825
|
+
throw new HostError("Kubo block exceeds limit.");
|
|
826
|
+
}
|
|
827
|
+
chunks.push(part.value);
|
|
828
|
+
}
|
|
829
|
+
} finally {
|
|
830
|
+
reader.releaseLock();
|
|
831
|
+
}
|
|
832
|
+
const bytes = new Uint8Array(size);
|
|
833
|
+
let offset = 0;
|
|
834
|
+
for (const chunk of chunks) {
|
|
835
|
+
bytes.set(chunk, offset);
|
|
836
|
+
offset += chunk.length;
|
|
837
|
+
}
|
|
838
|
+
return bytes;
|
|
839
|
+
},
|
|
840
|
+
connected,
|
|
841
|
+
connect,
|
|
842
|
+
() => {
|
|
843
|
+
if (fallbackUsed) return false;
|
|
844
|
+
fallbackUsed = true;
|
|
845
|
+
return true;
|
|
846
|
+
},
|
|
847
|
+
options.signal,
|
|
848
|
+
diagnostic,
|
|
849
|
+
detailed,
|
|
850
|
+
);
|
|
851
|
+
},
|
|
852
|
+
},
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
export interface KuboP2pListener {
|
|
857
|
+
protocol: string;
|
|
858
|
+
listenAddress: string;
|
|
859
|
+
targetAddress: string;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
export async function p2pList(
|
|
863
|
+
node: KuboNode,
|
|
864
|
+
signal?: AbortSignal,
|
|
865
|
+
): Promise<KuboP2pListener[]> {
|
|
866
|
+
const response = await rpc(node, "p2p/ls", signal, 10_000);
|
|
867
|
+
if (!response.ok) {
|
|
868
|
+
await response.body?.cancel();
|
|
869
|
+
throw new HostError(`Owned Kubo p2p/ls failed (HTTP ${response.status}).`);
|
|
870
|
+
}
|
|
871
|
+
const data = object(
|
|
872
|
+
JSON.parse(await boundedText(response)) as unknown,
|
|
873
|
+
"owned Kubo p2p/ls response",
|
|
874
|
+
);
|
|
875
|
+
if (data.Listeners === null || data.Listeners === undefined) return [];
|
|
876
|
+
if (!Array.isArray(data.Listeners) || data.Listeners.length > 4096)
|
|
877
|
+
throw new HostError("Invalid owned Kubo p2p/ls response.");
|
|
878
|
+
return data.Listeners.map((entry: unknown) => {
|
|
879
|
+
const item = object(entry, "owned Kubo p2p listener");
|
|
880
|
+
if (
|
|
881
|
+
typeof item.Protocol !== "string" ||
|
|
882
|
+
typeof item.ListenAddress !== "string" ||
|
|
883
|
+
typeof item.TargetAddress !== "string"
|
|
884
|
+
)
|
|
885
|
+
throw new HostError("Invalid owned Kubo p2p listener entry.");
|
|
886
|
+
return {
|
|
887
|
+
protocol: item.Protocol,
|
|
888
|
+
listenAddress: item.ListenAddress,
|
|
889
|
+
targetAddress: item.TargetAddress,
|
|
890
|
+
};
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
export async function p2pClose(
|
|
895
|
+
node: KuboNode,
|
|
896
|
+
options: {
|
|
897
|
+
protocol?: string;
|
|
898
|
+
listenAddress?: string;
|
|
899
|
+
targetAddress?: string;
|
|
900
|
+
},
|
|
901
|
+
signal?: AbortSignal,
|
|
902
|
+
): Promise<void> {
|
|
903
|
+
const query = new URLSearchParams();
|
|
904
|
+
if (options.protocol !== undefined) query.set("protocol", options.protocol);
|
|
905
|
+
if (options.listenAddress !== undefined)
|
|
906
|
+
query.set("listen-address", options.listenAddress);
|
|
907
|
+
if (options.targetAddress !== undefined)
|
|
908
|
+
query.set("target-address", options.targetAddress);
|
|
909
|
+
const qs = query.toString();
|
|
910
|
+
const response = await rpc(
|
|
911
|
+
node,
|
|
912
|
+
qs ? `p2p/close?${qs}` : "p2p/close",
|
|
913
|
+
signal,
|
|
914
|
+
10_000,
|
|
915
|
+
);
|
|
916
|
+
if (!response.ok) {
|
|
917
|
+
await response.body?.cancel();
|
|
918
|
+
throw new HostError(
|
|
919
|
+
`Owned Kubo p2p/close failed (HTTP ${response.status}).`,
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
await response.body?.cancel();
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
export async function p2pListen(
|
|
926
|
+
node: KuboNode,
|
|
927
|
+
protocol: string,
|
|
928
|
+
targetAddress: string,
|
|
929
|
+
signal?: AbortSignal,
|
|
930
|
+
): Promise<void> {
|
|
931
|
+
const selfListen = `/p2p/${node.peerId}`;
|
|
932
|
+
const existing = await p2pList(node, signal);
|
|
933
|
+
const matching = existing.filter(
|
|
934
|
+
(entry) =>
|
|
935
|
+
entry.protocol === protocol && entry.listenAddress === selfListen,
|
|
936
|
+
);
|
|
937
|
+
if (matching.length === 1 && matching[0]!.targetAddress === targetAddress)
|
|
938
|
+
return;
|
|
939
|
+
if (matching.length > 0) {
|
|
940
|
+
await p2pClose(node, { protocol, listenAddress: selfListen }, signal);
|
|
941
|
+
}
|
|
942
|
+
const response = await rpc(
|
|
943
|
+
node,
|
|
944
|
+
`p2p/listen?arg=${encodeURIComponent(protocol)}&arg=${encodeURIComponent(targetAddress)}`,
|
|
945
|
+
signal,
|
|
946
|
+
10_000,
|
|
947
|
+
);
|
|
948
|
+
if (!response.ok) {
|
|
949
|
+
const detail = await boundedText(response).catch(() => "");
|
|
950
|
+
throw new HostError(
|
|
951
|
+
`Owned Kubo p2p/listen failed (HTTP ${response.status})${detail ? `: ${detail.slice(0, 256)}` : ""}.`,
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
await response.body?.cancel();
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function parseLoopbackMultiaddr(address: string): {
|
|
958
|
+
host: string;
|
|
959
|
+
port: number;
|
|
960
|
+
} {
|
|
961
|
+
const match = /^\/ip4\/127\.0\.0\.1\/tcp\/([1-9]\d{0,4})$/.exec(address);
|
|
962
|
+
if (!match)
|
|
963
|
+
throw new HostError(
|
|
964
|
+
`Unexpected Kubo p2p/forward listen address: ${address}`,
|
|
965
|
+
);
|
|
966
|
+
const port = Number(match[1]);
|
|
967
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
|
|
968
|
+
throw new HostError(`Invalid Kubo p2p/forward port in ${address}`);
|
|
969
|
+
return { host: "127.0.0.1", port };
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
export interface KuboP2pForward {
|
|
973
|
+
listenAddress: string;
|
|
974
|
+
host: string;
|
|
975
|
+
port: number;
|
|
976
|
+
close: () => Promise<void>;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
export async function p2pForward(
|
|
980
|
+
node: KuboNode,
|
|
981
|
+
protocol: string,
|
|
982
|
+
targetPeerId: string,
|
|
983
|
+
signal?: AbortSignal,
|
|
984
|
+
): Promise<KuboP2pForward> {
|
|
985
|
+
const targetAddress = `/p2p/${targetPeerId}`;
|
|
986
|
+
const before = new Set(
|
|
987
|
+
(await p2pList(node, signal))
|
|
988
|
+
.filter(
|
|
989
|
+
(entry) =>
|
|
990
|
+
entry.protocol === protocol && entry.targetAddress === targetAddress,
|
|
991
|
+
)
|
|
992
|
+
.map((entry) => entry.listenAddress),
|
|
993
|
+
);
|
|
994
|
+
const response = await rpc(
|
|
995
|
+
node,
|
|
996
|
+
`p2p/forward?arg=${encodeURIComponent(protocol)}&arg=${encodeURIComponent("/ip4/127.0.0.1/tcp/0")}&arg=${encodeURIComponent(targetAddress)}`,
|
|
997
|
+
signal,
|
|
998
|
+
10_000,
|
|
999
|
+
);
|
|
1000
|
+
if (!response.ok) {
|
|
1001
|
+
const detail = await boundedText(response).catch(() => "");
|
|
1002
|
+
throw new HostError(
|
|
1003
|
+
`Owned Kubo p2p/forward failed (HTTP ${response.status})${detail ? `: ${detail.slice(0, 256)}` : ""}.`,
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
const body = (await boundedText(response)).trim();
|
|
1007
|
+
let listenAddress: string | undefined;
|
|
1008
|
+
if (body) {
|
|
1009
|
+
try {
|
|
1010
|
+
const parsed = JSON.parse(body) as Record<string, unknown>;
|
|
1011
|
+
if (typeof parsed.ListenAddress === "string")
|
|
1012
|
+
listenAddress = parsed.ListenAddress;
|
|
1013
|
+
} catch {
|
|
1014
|
+
// Kubo p2p/forward normally returns an empty body.
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
if (!listenAddress) {
|
|
1018
|
+
const after = (await p2pList(node, signal)).filter(
|
|
1019
|
+
(entry) =>
|
|
1020
|
+
entry.protocol === protocol && entry.targetAddress === targetAddress,
|
|
1021
|
+
);
|
|
1022
|
+
const created = after.find((entry) => !before.has(entry.listenAddress));
|
|
1023
|
+
listenAddress = created?.listenAddress ?? after.at(-1)?.listenAddress;
|
|
1024
|
+
}
|
|
1025
|
+
if (!listenAddress)
|
|
1026
|
+
throw new HostError(
|
|
1027
|
+
`Owned Kubo p2p/forward did not report a local listener for ${protocol} -> ${targetAddress}.`,
|
|
1028
|
+
);
|
|
1029
|
+
const { host, port } = parseLoopbackMultiaddr(listenAddress);
|
|
1030
|
+
let closed = false;
|
|
1031
|
+
return {
|
|
1032
|
+
listenAddress,
|
|
1033
|
+
host,
|
|
1034
|
+
port,
|
|
1035
|
+
close: async () => {
|
|
1036
|
+
if (closed) return;
|
|
1037
|
+
closed = true;
|
|
1038
|
+
await p2pClose(node, {
|
|
1039
|
+
protocol,
|
|
1040
|
+
listenAddress,
|
|
1041
|
+
targetAddress,
|
|
1042
|
+
});
|
|
1043
|
+
},
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
export async function pinAdd(
|
|
1048
|
+
node: KuboNode,
|
|
1049
|
+
cid: string,
|
|
1050
|
+
recursive: boolean,
|
|
1051
|
+
signal?: AbortSignal,
|
|
1052
|
+
timeout = 120_000,
|
|
1053
|
+
fetcher: typeof fetch = fetch,
|
|
1054
|
+
): Promise<void> {
|
|
1055
|
+
const response = await rpc(
|
|
1056
|
+
node,
|
|
1057
|
+
`pin/add?arg=${encodeURIComponent(cid)}&recursive=${recursive ? "true" : "false"}`,
|
|
1058
|
+
signal,
|
|
1059
|
+
timeout,
|
|
1060
|
+
fetcher,
|
|
1061
|
+
);
|
|
1062
|
+
if (!response.ok) {
|
|
1063
|
+
const detail = await boundedText(response).catch(() => "");
|
|
1064
|
+
throw new HostError(
|
|
1065
|
+
`Owned Kubo pin/add failed for ${cid} (HTTP ${response.status})${detail ? `: ${detail.slice(0, 256)}` : ""}.`,
|
|
1066
|
+
);
|
|
1067
|
+
}
|
|
1068
|
+
await boundedText(response);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
export async function pinRm(
|
|
1072
|
+
node: KuboNode,
|
|
1073
|
+
cid: string,
|
|
1074
|
+
recursive: boolean,
|
|
1075
|
+
signal?: AbortSignal,
|
|
1076
|
+
): Promise<void> {
|
|
1077
|
+
const response = await rpc(
|
|
1078
|
+
node,
|
|
1079
|
+
`pin/rm?arg=${encodeURIComponent(cid)}&recursive=${recursive ? "true" : "false"}`,
|
|
1080
|
+
signal,
|
|
1081
|
+
30_000,
|
|
1082
|
+
);
|
|
1083
|
+
if (!response.ok) {
|
|
1084
|
+
await response.body?.cancel();
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
await boundedText(response);
|
|
1088
|
+
}
|