@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,461 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createPrivateKey,
5
+ createPublicKey,
6
+ diffieHellman,
7
+ generateKeyPairSync,
8
+ hkdfSync,
9
+ randomBytes,
10
+ } from "node:crypto";
11
+ import { ed25519, x25519 } from "@noble/curves/ed25519.js";
12
+ import {
13
+ importPrivateKeyPkcs8,
14
+ importPublicKeyRaw,
15
+ signEd25519,
16
+ verifyEd25519,
17
+ } from "@ipab/bundle/pointer/crypto";
18
+ import {
19
+ parseScopeCertificate,
20
+ type ScopeCertificate,
21
+ } from "@ipab/bundle/pointer/scope";
22
+ import { HostError, object } from "./errors.js";
23
+ import type { Identity } from "./identity.js";
24
+
25
+ export type MemberRole = "ordinary" | "pivot";
26
+ export interface ApprovalContext {
27
+ configUrl: string;
28
+ owner: string;
29
+ member: string;
30
+ role: MemberRole;
31
+ profileId: string;
32
+ headId: string;
33
+ epoch: number;
34
+ }
35
+ export interface ApprovalEnvelopeV2 {
36
+ v: 2;
37
+ ciphertext: string;
38
+ }
39
+ export function ed25519PublicToX25519(publicKey: string): Uint8Array {
40
+ if (!/^[A-Za-z0-9_-]{43}$/.test(publicKey))
41
+ throw new HostError("Invalid Ed25519 public key.");
42
+ const raw = Buffer.from(publicKey, "base64url");
43
+ if (raw.length !== 32) throw new HostError("Invalid Ed25519 public key.");
44
+ try {
45
+ return ed25519.utils.toMontgomery(raw);
46
+ } catch {
47
+ throw new HostError("Invalid Ed25519 public key.");
48
+ }
49
+ }
50
+ export function ed25519PrivateToX25519(identity: Identity): Uint8Array {
51
+ let privateKey;
52
+ try {
53
+ privateKey = createPrivateKey({
54
+ key: Buffer.from(identity.privateKey, "base64url"),
55
+ type: "pkcs8",
56
+ format: "der",
57
+ });
58
+ } catch {
59
+ throw new HostError("Approval requires an Ed25519 account identity.");
60
+ }
61
+ if (privateKey.asymmetricKeyType !== "ed25519")
62
+ throw new HostError("Approval requires an Ed25519 account identity.");
63
+ const rawPub = createPublicKey(privateKey)
64
+ .export({ format: "der", type: "spki" })
65
+ .subarray(-32);
66
+ if (
67
+ rawPub.length !== 32 ||
68
+ rawPub.toString("base64url") !== identity.publicKey
69
+ )
70
+ throw new HostError("Stored account identity is inconsistent.");
71
+ const seed = privateKey
72
+ .export({ format: "der", type: "pkcs8" })
73
+ .subarray(-32);
74
+ if (seed.length !== 32)
75
+ throw new HostError("Invalid Ed25519 private key encoding.");
76
+ return ed25519.utils.toMontgomerySecret(seed);
77
+ }
78
+ export function parseApprovalV2(value: unknown): ApprovalEnvelopeV2 {
79
+ const envelope = object(value, "approval envelope");
80
+ if (
81
+ Object.keys(envelope).sort().join() !== "ciphertext,v" ||
82
+ envelope.v !== 2 ||
83
+ typeof envelope.ciphertext !== "string" ||
84
+ !/^[A-Za-z0-9_-]+$/.test(envelope.ciphertext)
85
+ )
86
+ throw new HostError("Invalid approval envelope encoding.");
87
+ const raw = Buffer.from(envelope.ciphertext, "base64url");
88
+ if (raw.length < 61 || raw.length > 8192)
89
+ throw new HostError("Invalid approval envelope encoding.");
90
+ return { v: 2, ciphertext: envelope.ciphertext };
91
+ }
92
+ const approvalBindingV2 = (ctx: ApprovalContext) =>
93
+ JSON.stringify([
94
+ "IPAB-APPROVAL/2",
95
+ ctx.configUrl,
96
+ ctx.owner,
97
+ ctx.member,
98
+ ctx.role,
99
+ ctx.profileId,
100
+ ctx.headId,
101
+ ctx.epoch,
102
+ ]);
103
+ export function sealApprovalV2(
104
+ context: ApprovalContext,
105
+ secret: MembershipSecret,
106
+ owner: Identity,
107
+ ): ApprovalEnvelopeV2 {
108
+ if (owner.publicKey !== context.owner)
109
+ throw new HostError("Owner identity does not match approval context.");
110
+ const ephemeral = x25519.keygen();
111
+ const memberX25519Pub = ed25519PublicToX25519(context.member);
112
+ const ownerX25519Priv = ed25519PrivateToX25519(owner);
113
+ const ikm = Buffer.concat([
114
+ x25519.getSharedSecret(ephemeral.secretKey, memberX25519Pub),
115
+ x25519.getSharedSecret(ownerX25519Priv, memberX25519Pub),
116
+ ]);
117
+ const info = Buffer.from(approvalBindingV2(context));
118
+ const key = Buffer.from(
119
+ hkdfSync("sha256", ikm, ephemeral.publicKey, info, 32),
120
+ );
121
+ const iv = randomBytes(12);
122
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
123
+ cipher.setAAD(info);
124
+ const encrypted = Buffer.concat([
125
+ cipher.update(JSON.stringify(secret), "utf8"),
126
+ cipher.final(),
127
+ ]);
128
+ const packed = Buffer.concat([
129
+ ephemeral.publicKey,
130
+ iv,
131
+ cipher.getAuthTag(),
132
+ encrypted,
133
+ ]);
134
+ return {
135
+ v: 2,
136
+ ciphertext: packed.toString("base64url"),
137
+ };
138
+ }
139
+ export function openApprovalV2(
140
+ value: unknown,
141
+ context: ApprovalContext,
142
+ memberIdentity: Identity,
143
+ ): MembershipSecret {
144
+ const envelope = parseApprovalV2(value);
145
+ if (memberIdentity.publicKey !== context.member)
146
+ throw new HostError(
147
+ "Approval signature or exact request/resource/identity binding is invalid.",
148
+ );
149
+ try {
150
+ const packed = Buffer.from(envelope.ciphertext, "base64url");
151
+ const ephemeralPub = packed.subarray(0, 32);
152
+ const iv = packed.subarray(32, 44);
153
+ const tag = packed.subarray(44, 60);
154
+ const encrypted = packed.subarray(60);
155
+ const memberX25519Priv = ed25519PrivateToX25519(memberIdentity);
156
+ const ownerX25519Pub = ed25519PublicToX25519(context.owner);
157
+ const ikm = Buffer.concat([
158
+ x25519.getSharedSecret(memberX25519Priv, ephemeralPub),
159
+ x25519.getSharedSecret(memberX25519Priv, ownerX25519Pub),
160
+ ]);
161
+ const info = Buffer.from(approvalBindingV2(context));
162
+ const key = Buffer.from(hkdfSync("sha256", ikm, ephemeralPub, info, 32));
163
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
164
+ decipher.setAAD(info);
165
+ decipher.setAuthTag(tag);
166
+ const secret = object(
167
+ JSON.parse(
168
+ Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
169
+ "utf8",
170
+ ),
171
+ ) as unknown,
172
+ "membership secret",
173
+ );
174
+ if (
175
+ Object.keys(secret).sort().join() !== "certificate,swarmKey" ||
176
+ typeof secret.swarmKey !== "string" ||
177
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey)
178
+ )
179
+ throw new HostError("Invalid membership secret.");
180
+ return {
181
+ certificate: parseScopeCertificate(secret.certificate),
182
+ swarmKey: secret.swarmKey,
183
+ };
184
+ } catch {
185
+ throw new HostError(
186
+ "Could not decrypt or authenticate the approved package; verify the Owner, binding, and HOME Ed25519 identity.",
187
+ );
188
+ }
189
+ }
190
+
191
+ export interface EncryptionIdentity {
192
+ publicKey: string;
193
+ privateKey: string;
194
+ }
195
+ export function validateEncryptionIdentity(value: EncryptionIdentity): void {
196
+ const privateKey = createPrivateKey({
197
+ key: Buffer.from(value.privateKey, "base64url"),
198
+ type: "pkcs8",
199
+ format: "der",
200
+ });
201
+ if (
202
+ privateKey.asymmetricKeyType !== "x25519" ||
203
+ createPublicKey(privateKey)
204
+ .export({ type: "spki", format: "der" })
205
+ .toString("base64url") !== value.publicKey
206
+ )
207
+ throw new HostError("Stored encryption identity is inconsistent.");
208
+ }
209
+ export function encryptionIdentity(): EncryptionIdentity {
210
+ const keys = generateKeyPairSync("x25519");
211
+ return {
212
+ publicKey: keys.publicKey
213
+ .export({ format: "der", type: "spki" })
214
+ .toString("base64url"),
215
+ privateKey: keys.privateKey
216
+ .export({ format: "der", type: "pkcs8" })
217
+ .toString("base64url"),
218
+ };
219
+ }
220
+ export interface EnvelopeBinding {
221
+ configUrl: string;
222
+ scopeId: string;
223
+ owner: string;
224
+ member: string;
225
+ requestId: string;
226
+ peerId: string;
227
+ profileId: string;
228
+ headId: string;
229
+ epoch: number;
230
+ encryptionKey: string;
231
+ }
232
+ export interface MembershipSecret {
233
+ certificate: ScopeCertificate;
234
+ swarmKey: string;
235
+ }
236
+ export interface Envelope {
237
+ binding: EnvelopeBinding;
238
+ ephemeral: string;
239
+ salt: string;
240
+ iv: string;
241
+ ciphertext: string;
242
+ tag: string;
243
+ signature: string;
244
+ }
245
+ export function parseEnvelope(value: unknown): Envelope {
246
+ const envelope = object(value, "approval envelope");
247
+ if (
248
+ Object.keys(envelope).sort().join() !==
249
+ "binding,ciphertext,ephemeral,iv,salt,signature,tag"
250
+ )
251
+ throw new HostError("Invalid approval envelope encoding.");
252
+ const fields = object(envelope.binding, "approval binding");
253
+ if (
254
+ Object.keys(fields).sort().join() !==
255
+ "configUrl,encryptionKey,epoch,headId,member,owner,peerId,profileId,requestId,scopeId"
256
+ )
257
+ throw new HostError("Invalid approval binding.");
258
+ const text = (record: Record<string, unknown>, key: string): string => {
259
+ const field = record[key];
260
+ if (typeof field !== "string")
261
+ throw new HostError("Invalid approval field.");
262
+ return field;
263
+ };
264
+ const epoch = fields.epoch;
265
+ if (typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 1)
266
+ throw new HostError("Invalid approval epoch.");
267
+ const binding: EnvelopeBinding = {
268
+ configUrl: text(fields, "configUrl"),
269
+ scopeId: text(fields, "scopeId"),
270
+ owner: text(fields, "owner"),
271
+ member: text(fields, "member"),
272
+ requestId: text(fields, "requestId"),
273
+ peerId: text(fields, "peerId"),
274
+ profileId: text(fields, "profileId"),
275
+ headId: text(fields, "headId"),
276
+ epoch,
277
+ encryptionKey: text(fields, "encryptionKey"),
278
+ };
279
+ const result: Envelope = {
280
+ binding,
281
+ ephemeral: text(envelope, "ephemeral"),
282
+ salt: text(envelope, "salt"),
283
+ iv: text(envelope, "iv"),
284
+ ciphertext: text(envelope, "ciphertext"),
285
+ tag: text(envelope, "tag"),
286
+ signature: text(envelope, "signature"),
287
+ };
288
+ if (
289
+ ![
290
+ result.ephemeral,
291
+ result.salt,
292
+ result.iv,
293
+ result.ciphertext,
294
+ result.tag,
295
+ result.signature,
296
+ ].every((field) => /^[A-Za-z0-9_-]+$/.test(field)) ||
297
+ result.salt.length !== 43 ||
298
+ result.iv.length !== 16 ||
299
+ result.tag.length !== 22 ||
300
+ result.signature.length !== 86 ||
301
+ result.ciphertext.length > 8192
302
+ )
303
+ throw new HostError("Invalid approval envelope encoding.");
304
+ return result;
305
+ }
306
+ const message = (e: Omit<Envelope, "signature">) =>
307
+ JSON.stringify([
308
+ "IPAB-APPROVAL/1",
309
+ e.binding,
310
+ e.ephemeral,
311
+ e.salt,
312
+ e.iv,
313
+ e.ciphertext,
314
+ e.tag,
315
+ ]);
316
+ function encryptionKey(
317
+ privateKey: string,
318
+ publicKey: string,
319
+ salt: Buffer,
320
+ binding: EnvelopeBinding,
321
+ ): Buffer {
322
+ const privateObject = createPrivateKey({
323
+ key: Buffer.from(privateKey, "base64url"),
324
+ type: "pkcs8",
325
+ format: "der",
326
+ });
327
+ const publicObject = createPublicKey({
328
+ key: Buffer.from(publicKey, "base64url"),
329
+ type: "spki",
330
+ format: "der",
331
+ });
332
+ if (
333
+ privateObject.asymmetricKeyType !== "x25519" ||
334
+ publicObject.asymmetricKeyType !== "x25519"
335
+ )
336
+ throw new HostError("Approval requires X25519 encryption keys.");
337
+ return Buffer.from(
338
+ hkdfSync(
339
+ "sha256",
340
+ diffieHellman({ privateKey: privateObject, publicKey: publicObject }),
341
+ salt,
342
+ Buffer.from(JSON.stringify(["IPAB-ENVELOPE/1", binding])),
343
+ 32,
344
+ ),
345
+ );
346
+ }
347
+ export async function sealApproval(
348
+ binding: EnvelopeBinding,
349
+ secret: MembershipSecret,
350
+ owner: Identity,
351
+ ): Promise<Envelope> {
352
+ const ephemeral = encryptionIdentity();
353
+ const salt = randomBytes(32),
354
+ iv = randomBytes(12);
355
+ const cipher = createCipheriv(
356
+ "aes-256-gcm",
357
+ encryptionKey(ephemeral.privateKey, binding.encryptionKey, salt, binding),
358
+ iv,
359
+ );
360
+ cipher.setAAD(Buffer.from(JSON.stringify(binding)));
361
+ const ciphertext = Buffer.concat([
362
+ cipher.update(JSON.stringify(secret), "utf8"),
363
+ cipher.final(),
364
+ ]);
365
+ const envelope = {
366
+ binding,
367
+ ephemeral: ephemeral.publicKey,
368
+ salt: salt.toString("base64url"),
369
+ iv: iv.toString("base64url"),
370
+ ciphertext: ciphertext.toString("base64url"),
371
+ tag: cipher.getAuthTag().toString("base64url"),
372
+ };
373
+ return {
374
+ ...envelope,
375
+ signature: await signEd25519(
376
+ await importPrivateKeyPkcs8(owner.privateKey),
377
+ message(envelope),
378
+ ),
379
+ };
380
+ }
381
+ export async function verifyApprovalEnvelope(
382
+ value: unknown,
383
+ expected: Omit<EnvelopeBinding, "encryptionKey" | "requestId">,
384
+ ): Promise<Envelope> {
385
+ const envelope = parseEnvelope(value);
386
+ if (
387
+ envelope.binding.configUrl !== expected.configUrl ||
388
+ envelope.binding.scopeId !== expected.scopeId ||
389
+ envelope.binding.owner !== expected.owner ||
390
+ envelope.binding.member !== expected.member ||
391
+ envelope.binding.peerId !== expected.peerId ||
392
+ envelope.binding.profileId !== expected.profileId ||
393
+ envelope.binding.headId !== expected.headId ||
394
+ envelope.binding.epoch !== expected.epoch ||
395
+ !(await verifyEd25519(
396
+ await importPublicKeyRaw(expected.owner),
397
+ envelope.signature,
398
+ message(envelope),
399
+ ))
400
+ )
401
+ throw new HostError(
402
+ "Approval signature or exact request/resource/identity binding is invalid.",
403
+ );
404
+ return envelope;
405
+ }
406
+ export async function openApproval(
407
+ value: unknown,
408
+ expected: EnvelopeBinding,
409
+ identity: EncryptionIdentity,
410
+ ): Promise<MembershipSecret> {
411
+ const envelope = parseEnvelope(value);
412
+ if (
413
+ JSON.stringify(envelope.binding) !== JSON.stringify(expected) ||
414
+ expected.encryptionKey !== identity.publicKey ||
415
+ !(await verifyEd25519(
416
+ await importPublicKeyRaw(expected.owner),
417
+ envelope.signature,
418
+ message(envelope),
419
+ ))
420
+ )
421
+ throw new HostError(
422
+ "Approval signature or exact request/resource/identity binding is invalid.",
423
+ );
424
+ try {
425
+ const decipher = createDecipheriv(
426
+ "aes-256-gcm",
427
+ encryptionKey(
428
+ identity.privateKey,
429
+ envelope.ephemeral,
430
+ Buffer.from(envelope.salt, "base64url"),
431
+ expected,
432
+ ),
433
+ Buffer.from(envelope.iv, "base64url"),
434
+ );
435
+ decipher.setAAD(Buffer.from(JSON.stringify(expected)));
436
+ decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
437
+ const secret = object(
438
+ JSON.parse(
439
+ Buffer.concat([
440
+ decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
441
+ decipher.final(),
442
+ ]).toString("utf8"),
443
+ ) as unknown,
444
+ "membership secret",
445
+ );
446
+ if (
447
+ Object.keys(secret).sort().join() !== "certificate,swarmKey" ||
448
+ typeof secret.swarmKey !== "string" ||
449
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey)
450
+ )
451
+ throw new HostError("Invalid membership secret.");
452
+ return {
453
+ certificate: parseScopeCertificate(secret.certificate),
454
+ swarmKey: secret.swarmKey,
455
+ };
456
+ } catch {
457
+ throw new HostError(
458
+ "Could not decrypt the approved package; preserve the original local Request identity.",
459
+ );
460
+ }
461
+ }
@@ -0,0 +1,126 @@
1
+ import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import {
6
+ protectedPath,
7
+ protectedPaths,
8
+ secureNew,
9
+ type ProtectedPath,
10
+ } from "./identity.js";
11
+ import { nodeError } from "./authoring.js";
12
+ import { HostError } from "./errors.js";
13
+
14
+ export async function privateDirectory(
15
+ parent: string,
16
+ name: string,
17
+ ): Promise<string> {
18
+ const path = join(parent, name);
19
+ try {
20
+ await lstat(path);
21
+ } catch (cause) {
22
+ if (!nodeError(cause, "ENOENT")) throw cause;
23
+ try {
24
+ await mkdir(path, { mode: 0o700 });
25
+ await secureNew(path, true);
26
+ } catch (error) {
27
+ if (!nodeError(error, "EEXIST")) throw error;
28
+ }
29
+ }
30
+ await protectedPath(path, true);
31
+ return path;
32
+ }
33
+ export async function readPrivate<T>(
34
+ directory: string,
35
+ name: string,
36
+ additionalPaths: readonly ProtectedPath[] = [],
37
+ maximumBytes = 2 * 1024 * 1024,
38
+ ): Promise<T | undefined> {
39
+ const path = join(directory, name);
40
+ if (additionalPaths.length) {
41
+ try {
42
+ await lstat(path);
43
+ } catch (cause) {
44
+ if (nodeError(cause, "ENOENT")) return undefined;
45
+ throw cause;
46
+ }
47
+ await protectedPaths([{ path }, ...additionalPaths]);
48
+ } else {
49
+ try {
50
+ await protectedPath(path);
51
+ } catch (cause) {
52
+ if (nodeError(cause, "ENOENT")) return undefined;
53
+ throw cause;
54
+ }
55
+ }
56
+ if ((await lstat(path)).size > maximumBytes)
57
+ throw new HostError("Protected state is oversized.");
58
+ return JSON.parse(await readFile(path, "utf8")) as T;
59
+ }
60
+ export async function writePrivate(
61
+ directory: string,
62
+ name: string,
63
+ value: unknown,
64
+ ): Promise<void> {
65
+ const target = join(directory, name);
66
+ const temporary = join(directory, `.write-${randomUUID()}`);
67
+ const file = await open(temporary, "wx", 0o600);
68
+ try {
69
+ await secureNew(temporary, false, { inherit: true });
70
+ await file.writeFile(JSON.stringify(value));
71
+ await file.sync();
72
+ await file.close();
73
+ await rename(temporary, target);
74
+ } finally {
75
+ await file.close();
76
+ await unlink(temporary).catch((cause: unknown) => {
77
+ if (!nodeError(cause, "ENOENT")) throw cause;
78
+ });
79
+ }
80
+ }
81
+ export async function withPrivateLock<T>(
82
+ directory: string,
83
+ operation: () => Promise<T>,
84
+ signal?: AbortSignal,
85
+ attempts = 300,
86
+ ): Promise<T> {
87
+ signal?.throwIfAborted();
88
+ const path = join(directory, "operation.sqlite");
89
+ try {
90
+ const handle = await open(path, "wx", 0o600);
91
+ await handle.close();
92
+ await secureNew(path, false, { inherit: true });
93
+ } catch (cause) {
94
+ if (!nodeError(cause, "EEXIST")) throw cause;
95
+ }
96
+ await protectedPath(path);
97
+ const db = new DatabaseSync(path);
98
+ let locked = false;
99
+ try {
100
+ db.exec("PRAGMA busy_timeout=0");
101
+ for (let attempt = 0; attempt < attempts; attempt++) {
102
+ signal?.throwIfAborted();
103
+ try {
104
+ db.exec("BEGIN IMMEDIATE");
105
+ locked = true;
106
+ break;
107
+ } catch (cause) {
108
+ if (
109
+ !(cause instanceof Error) ||
110
+ !cause.message.includes("database is locked")
111
+ )
112
+ throw cause;
113
+ await new Promise((resolve) => setTimeout(resolve, 100));
114
+ }
115
+ }
116
+ if (!locked)
117
+ throw new HostError(
118
+ "Another local Swarm operation is still running; retry later.",
119
+ );
120
+ signal?.throwIfAborted();
121
+ return await operation();
122
+ } finally {
123
+ if (locked) db.exec("ROLLBACK");
124
+ db.close();
125
+ }
126
+ }
@@ -0,0 +1,98 @@
1
+ import { encodeSchema, type BundleType } from "@ipab/bundle";
2
+ import { HostError, object } from "./errors.js";
3
+ import { relativePath } from "./space.js";
4
+ import {
5
+ swarmRootSchema,
6
+ swarmStateSchema,
7
+ previousSwarmStateSchema,
8
+ legacySwarmStateSchema,
9
+ } from "@ipab/bundle/swarm-state";
10
+ export {
11
+ swarmRootType,
12
+ swarmRootSchema,
13
+ parseSwarmRootState,
14
+ type SwarmRootState,
15
+ swarmStateType,
16
+ swarmStateSchema,
17
+ previousSwarmStateType,
18
+ previousSwarmStateSchema,
19
+ legacySwarmStateType,
20
+ legacySwarmStateSchema,
21
+ parseSwarmState,
22
+ } from "@ipab/bundle/swarm-state";
23
+
24
+ export const legacySwarmMetaType: BundleType = {
25
+ contentType: "application/json",
26
+ schema: {
27
+ type: "object",
28
+ required: ["templatePath", "registryPath"],
29
+ properties: {
30
+ templatePath: { type: "string", minLength: 1, maxLength: 196 },
31
+ registryPath: { type: "string", minLength: 1, maxLength: 196 },
32
+ },
33
+ additionalProperties: false,
34
+ },
35
+ };
36
+ export const swarmMetaType: BundleType = {
37
+ contentType: "application/json",
38
+ schema: {
39
+ type: "object",
40
+ additionalProperties: false,
41
+ required: ["templatePath", "registryPath", "skillPath"],
42
+ properties: {
43
+ templatePath: { type: "string", minLength: 1, maxLength: 196 },
44
+ registryPath: { type: "string", minLength: 1, maxLength: 196 },
45
+ skillPath: { type: "string", minLength: 1, maxLength: 196 },
46
+ },
47
+ },
48
+ };
49
+ export const swarmMetaSchema = await encodeSchema(swarmMetaType);
50
+ export const legacySwarmMetaSchema = await encodeSchema(legacySwarmMetaType);
51
+ export interface SwarmMeta {
52
+ templatePath: string;
53
+ registryPath: string;
54
+ skillPath?: string;
55
+ }
56
+ export function isSwarmStateSchema(cid: string): boolean {
57
+ return (
58
+ cid === swarmStateSchema.cid.toString() ||
59
+ cid === previousSwarmStateSchema.cid.toString() ||
60
+ cid === legacySwarmStateSchema.cid.toString()
61
+ );
62
+ }
63
+ export function isSwarmRootSchema(cid: string): boolean {
64
+ return cid === swarmRootSchema.cid.toString();
65
+ }
66
+ export function parseSwarmMeta(value: unknown): SwarmMeta {
67
+ const data = object(value, "Swarm Meta");
68
+ if (
69
+ ![
70
+ "registryPath,templatePath",
71
+ "registryPath,skillPath,templatePath",
72
+ ].includes(Object.keys(data).sort().join()) ||
73
+ typeof data.templatePath !== "string" ||
74
+ typeof data.registryPath !== "string" ||
75
+ ("skillPath" in data && typeof data.skillPath !== "string")
76
+ )
77
+ throw new HostError(
78
+ "Swarm Meta requires templatePath, registryPath and (for the new exact type) skillPath.",
79
+ );
80
+ for (const path of [
81
+ data.templatePath,
82
+ data.registryPath,
83
+ ...(typeof data.skillPath === "string" ? [data.skillPath] : []),
84
+ ]) {
85
+ relativePath(path);
86
+ if (path.length > 196 || path.includes(":"))
87
+ throw new HostError(
88
+ "Swarm Meta paths must be current-Swarm ordinary Name prefixes of at most 196 characters, not URIs.",
89
+ );
90
+ }
91
+ return {
92
+ templatePath: data.templatePath,
93
+ registryPath: data.registryPath,
94
+ ...(typeof data.skillPath === "string"
95
+ ? { skillPath: data.skillPath }
96
+ : {}),
97
+ };
98
+ }