pinnace 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +164 -0
  3. package/dist/car/car-build.d.ts +26 -0
  4. package/dist/car/car-build.d.ts.map +1 -0
  5. package/dist/car/car-build.js +113 -0
  6. package/dist/car/car-build.js.map +1 -0
  7. package/dist/ci/ci-emit.d.ts +116 -0
  8. package/dist/ci/ci-emit.d.ts.map +1 -0
  9. package/dist/ci/ci-emit.js +190 -0
  10. package/dist/ci/ci-emit.js.map +1 -0
  11. package/dist/cli/bin.d.ts +3 -0
  12. package/dist/cli/bin.d.ts.map +1 -0
  13. package/dist/cli/bin.js +17 -0
  14. package/dist/cli/bin.js.map +1 -0
  15. package/dist/cli/run.d.ts +94 -0
  16. package/dist/cli/run.d.ts.map +1 -0
  17. package/dist/cli/run.js +731 -0
  18. package/dist/cli/run.js.map +1 -0
  19. package/dist/config/config-resolution.d.ts +186 -0
  20. package/dist/config/config-resolution.d.ts.map +1 -0
  21. package/dist/config/config-resolution.js +137 -0
  22. package/dist/config/config-resolution.js.map +1 -0
  23. package/dist/deploy/deploy.d.ts +121 -0
  24. package/dist/deploy/deploy.d.ts.map +1 -0
  25. package/dist/deploy/deploy.js +150 -0
  26. package/dist/deploy/deploy.js.map +1 -0
  27. package/dist/derive/ipns-key-derivation.d.ts +37 -0
  28. package/dist/derive/ipns-key-derivation.d.ts.map +1 -0
  29. package/dist/derive/ipns-key-derivation.js +130 -0
  30. package/dist/derive/ipns-key-derivation.js.map +1 -0
  31. package/dist/index.d.ts +27 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +29 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/node/node-commands.d.ts +115 -0
  36. package/dist/node/node-commands.d.ts.map +1 -0
  37. package/dist/node/node-commands.js +231 -0
  38. package/dist/node/node-commands.js.map +1 -0
  39. package/dist/provision/cloud-init.d.ts +162 -0
  40. package/dist/provision/cloud-init.d.ts.map +1 -0
  41. package/dist/provision/cloud-init.js +460 -0
  42. package/dist/provision/cloud-init.js.map +1 -0
  43. package/dist/publisher/key-import.d.ts +105 -0
  44. package/dist/publisher/key-import.d.ts.map +1 -0
  45. package/dist/publisher/key-import.js +76 -0
  46. package/dist/publisher/key-import.js.map +1 -0
  47. package/dist/publisher/record-sequence.d.ts +90 -0
  48. package/dist/publisher/record-sequence.d.ts.map +1 -0
  49. package/dist/publisher/record-sequence.js +250 -0
  50. package/dist/publisher/record-sequence.js.map +1 -0
  51. package/dist/rpc/kubo-rpc-client.d.ts +154 -0
  52. package/dist/rpc/kubo-rpc-client.d.ts.map +1 -0
  53. package/dist/rpc/kubo-rpc-client.js +207 -0
  54. package/dist/rpc/kubo-rpc-client.js.map +1 -0
  55. package/dist/rpc/mock-kubo.d.ts +87 -0
  56. package/dist/rpc/mock-kubo.d.ts.map +1 -0
  57. package/dist/rpc/mock-kubo.js +129 -0
  58. package/dist/rpc/mock-kubo.js.map +1 -0
  59. package/dist/site/site-management.d.ts +126 -0
  60. package/dist/site/site-management.d.ts.map +1 -0
  61. package/dist/site/site-management.js +123 -0
  62. package/dist/site/site-management.js.map +1 -0
  63. package/dist/status/status-report.d.ts +145 -0
  64. package/dist/status/status-report.d.ts.map +1 -0
  65. package/dist/status/status-report.js +192 -0
  66. package/dist/status/status-report.js.map +1 -0
  67. package/package.json +45 -2
  68. package/src/car/car-build.ts +135 -0
  69. package/src/ci/ci-emit.ts +284 -0
  70. package/src/cli/bin.ts +20 -0
  71. package/src/cli/run.ts +970 -0
  72. package/src/config/config-resolution.ts +264 -0
  73. package/src/deploy/deploy.ts +250 -0
  74. package/src/derive/ipns-key-derivation.ts +173 -0
  75. package/src/index.ts +146 -0
  76. package/src/node/node-commands.ts +395 -0
  77. package/src/provision/cloud-init.ts +646 -0
  78. package/src/publisher/key-import.ts +141 -0
  79. package/src/publisher/record-sequence.ts +336 -0
  80. package/src/rpc/kubo-rpc-client.ts +281 -0
  81. package/src/rpc/mock-kubo.ts +194 -0
  82. package/src/site/site-management.ts +241 -0
  83. package/src/status/status-report.ts +291 -0
package/src/index.ts ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * pinnace library core — the public TypeScript API.
3
+ *
4
+ * All logic lives in the core (see CONTEXT.md `core vs cli`); the `pinnace`
5
+ * CLI bin (src/cli/bin.ts) is a thin wrapper that imports from here, so every
6
+ * operation is equally usable as a TypeScript API. Subsequent tracer-bullet
7
+ * tasks (Kubo RPC client, CAR build, key derivation, cloud-init, CI emitter,
8
+ * status, config, deploy, site management, CLI) hang off this entrypoint.
9
+ */
10
+
11
+ /** The package name, exposed so the CLI and API can report a consistent identity. */
12
+ export const PINNACE = 'pinnace';
13
+
14
+ /** Returns the pinnace package name (a trivial seam proving the toolchain is wired). */
15
+ export function name(): string {
16
+ return PINNACE;
17
+ }
18
+
19
+ export {
20
+ KuboRpcClient,
21
+ KuboRpcError,
22
+ type KuboRpcClientOptions,
23
+ type FetchLike,
24
+ type FilesMkdirOptions,
25
+ type FilesRmOptions,
26
+ type NamePublishOptions,
27
+ } from './rpc/kubo-rpc-client.js';
28
+ export {
29
+ MockKuboApi,
30
+ type RecordedRequest,
31
+ type MockResponseSpec,
32
+ } from './rpc/mock-kubo.js';
33
+ export {buildCar, writeCar, type BuiltCar} from './car/car-build.js';
34
+ export {
35
+ deriveIpnsKey,
36
+ deriveIpnsId,
37
+ IPNS_INFO_PREFIX,
38
+ type Master,
39
+ type DeriveIpnsInput,
40
+ type DerivedIpnsKey,
41
+ } from './derive/ipns-key-derivation.js';
42
+ export {
43
+ resolveConfig,
44
+ resolveMasterSecret,
45
+ resolveHostToken,
46
+ hostTokenEnvVar,
47
+ MissingHostTokenError,
48
+ type PinnaceConfigFile,
49
+ type ResolvedConfig,
50
+ type HostConfig,
51
+ type SiteConfig,
52
+ type HostRole,
53
+ type SiteMode,
54
+ type EnvRecord,
55
+ type CliOverrides,
56
+ type ResolveConfigInput,
57
+ type ResolveMasterInput,
58
+ type ResolveHostTokenInput,
59
+ } from './config/config-resolution.js';
60
+ export {
61
+ emitCi,
62
+ githubCiProvider,
63
+ CI_SYSTEMS,
64
+ type CiSystem,
65
+ type CIProvider,
66
+ type EmitCiInput,
67
+ type EmittedCi,
68
+ type EmittedFile,
69
+ type RequiredCiSetting,
70
+ } from './ci/ci-emit.js';
71
+ export {
72
+ provision,
73
+ hetznerHostProvider,
74
+ HOST_PROVIDERS,
75
+ type HostName,
76
+ type HostProvider,
77
+ type ProvisionInput,
78
+ type ProvisionResult,
79
+ } from './provision/cloud-init.js';
80
+ export {
81
+ serializeIpnsKeyForImport,
82
+ importIpnsKeyIntoPublisher,
83
+ KeyImportRoleError,
84
+ LIBP2P_ED25519_PRIVATE_KEY_PREFIX,
85
+ type ImportIpnsKeyInput,
86
+ type KeyImportResult,
87
+ } from './publisher/key-import.js';
88
+ export {
89
+ republishAndExport,
90
+ mirrorAndReannounce,
91
+ makeRepublishOp,
92
+ makeMirrorOp,
93
+ promoteReplicaToPublisher,
94
+ RECORD_LIFETIME,
95
+ RECORD_TTL,
96
+ type PromoteReplicaInput,
97
+ type PromoteReplicaResult,
98
+ } from './publisher/record-sequence.js';
99
+ export {
100
+ runNodeCommand,
101
+ discoverSites,
102
+ NODE_VERBS,
103
+ type NodeVerb,
104
+ type NodeCommandContext,
105
+ type NodeCommandOps,
106
+ type NodeCommandResult,
107
+ type NodeOpResult,
108
+ type DiscoveredSite,
109
+ type SiteOutcome,
110
+ type PublisherFetch,
111
+ type GatewayFetch,
112
+ } from './node/node-commands.js';
113
+ export {
114
+ listSites,
115
+ removeSite,
116
+ addSite,
117
+ placeInMfs,
118
+ SITE_VERBS,
119
+ type SiteVerb,
120
+ type SiteListing,
121
+ type ListSitesInput,
122
+ type RemoveSiteInput,
123
+ type RemoveSiteResult,
124
+ type AddSiteInput,
125
+ type AddSiteResult,
126
+ } from './site/site-management.js';
127
+ export {
128
+ deploy,
129
+ type DeployInput,
130
+ type DeployTarget,
131
+ type DeployResult,
132
+ type DeployNodeOk,
133
+ type DeployNodeFailure,
134
+ } from './deploy/deploy.js';
135
+ export {
136
+ statusReport,
137
+ makeStatusOp,
138
+ defaultProvidersLookup,
139
+ defaultGatewayProbe,
140
+ type StatusReport,
141
+ type SiteStatus,
142
+ type StatusReportInput,
143
+ type ProvidersLookup,
144
+ type ProvidersResponse,
145
+ type GatewayProbe,
146
+ } from './status/status-report.js';
@@ -0,0 +1,395 @@
1
+ /**
2
+ * The **on-box** command surface of `pinnace` — the `node` namespace.
3
+ *
4
+ * The SAME `pinnace` binary the operator runs as a client also runs the
5
+ * recurring loop ON a Kubo node (invoked by the cloud-init systemd timers).
6
+ * This module is that loop's command surface: `pinnace node <verb>` with
7
+ * `verb` in {`republish`, `mirror`, `warm`, `status`}. Each verb is a THIN
8
+ * wrapper that discovers sites from the LOCAL Kubo RPC and dispatches to a
9
+ * core operation, exactly like the client CLI wraps core operations
10
+ * (CONTEXT.md `core vs cli`). One codebase, two invocation contexts, so the
11
+ * record/warm/mirror/status logic has a single implementation — no bash/TS
12
+ * behaviour drift like the reference prototype had.
13
+ *
14
+ * BOUNDARY (see docs/adr/0002-*): Kubo owns pinning (`dag/import --pin-roots`)
15
+ * and provider-record freshness (`Reprovider.Interval`); this recurring loop
16
+ * owns ONLY IPNS republish/export, replica mirror/fallback, gateway warm, and
17
+ * status. It does nothing recurring for pinning or reprovide.
18
+ *
19
+ * Behaviour ported (not copied as bash) from the reference cloud-init scripts
20
+ * `ipfs-ipns-publish.sh`, `ipfs-ipns-mirror.sh`, `ipfs-warm.sh`,
21
+ * `ipfs-status.sh` (`~/searches/ipfs-hetzner/cloud-init.yaml`).
22
+ *
23
+ * SEAM NOTE: the publisher/replica record SEQUENCE (export -> fetch ->
24
+ * routing/put -> fallback) is OWNED and tested by the `publisher-replica-model`
25
+ * task, and `status`'s per-site checks by the `status-report` task. Both land
26
+ * in parallel with this task. So the four core operations are injectable via
27
+ * {@link NodeCommandOps}: this module's default `republish`/`mirror` DELEGATE to
28
+ * the owned record-sequence core (`../publisher/record-sequence.ts`) so there is
29
+ * a SINGLE implementation (no bash/TS drift, per ADR-0002), and `status`
30
+ * delegates to the `status-report` core injected via `ctx.ops`. This task owns
31
+ * the command surface + role-gating + `warm` + the boundary ADR.
32
+ */
33
+ import {mkdir, writeFile} from 'node:fs/promises';
34
+ import {join} from 'node:path';
35
+ import type {HostRole} from '../config/config-resolution.js';
36
+ import type {KuboRpcClient} from '../rpc/kubo-rpc-client.js';
37
+ import {
38
+ republishAndExport,
39
+ mirrorAndReannounce,
40
+ } from '../publisher/record-sequence.js';
41
+
42
+ /** The four on-box verbs, under the `node` namespace. */
43
+ export type NodeVerb = 'republish' | 'mirror' | 'warm' | 'status';
44
+
45
+ /** The verbs, in a stable order (for help text / iteration). */
46
+ export const NODE_VERBS: readonly NodeVerb[] = [
47
+ 'republish',
48
+ 'mirror',
49
+ 'warm',
50
+ 'status',
51
+ ];
52
+
53
+ /** Which role each role-gated verb requires; role-agnostic verbs are absent. */
54
+ const VERB_ROLE_GATE: Partial<Record<NodeVerb, HostRole>> = {
55
+ republish: 'publisher',
56
+ mirror: 'replica',
57
+ };
58
+
59
+ /** One site as auto-discovered from MFS `/sites/*`: its `id` and current CID. */
60
+ export interface DiscoveredSite {
61
+ /** The MFS entry `id` under `/sites/` (the site's single identifier). */
62
+ id: string;
63
+ /** The current content root CID (`files/stat --hash`). */
64
+ cid: string;
65
+ }
66
+
67
+ /** Per-site outcome line a verb reports (shape is verb-specific but uniform). */
68
+ export interface SiteOutcome {
69
+ /** The site's single `id` (its MFS entry / KDF input). */
70
+ id: string;
71
+ cid?: string;
72
+ ipns?: string;
73
+ /** A short machine-readable status token (e.g. `re-announced`, `no-record`). */
74
+ status?: string;
75
+ /**
76
+ * `status`-verb only: whether the network announces this node for the CID
77
+ * (the delegated-routing providers list contains our PeerID). Owned + filled
78
+ * by the `status-report` core op; absent for other verbs.
79
+ */
80
+ announced?: boolean;
81
+ /** `status`-verb only: whether a cold public gateway served the CID (2xx/206). */
82
+ gatewayServes?: boolean;
83
+ /** `status`-verb only: the raw HTTP status the cold-gateway probe returned. */
84
+ gatewayHttp?: number;
85
+ }
86
+
87
+ /** The uniform result an op returns: the per-site outcomes it produced. */
88
+ export interface NodeOpResult {
89
+ sites: SiteOutcome[];
90
+ }
91
+
92
+ /** The full result {@link runNodeCommand} returns for one verb invocation. */
93
+ export interface NodeCommandResult extends NodeOpResult {
94
+ /** The verb that ran. */
95
+ verb: NodeVerb;
96
+ /** True when role-gating (or a missing precondition) skipped the op. */
97
+ skipped?: boolean;
98
+ /** Why it was skipped (e.g. `role publisher required, this box is replica`). */
99
+ skippedReason?: string;
100
+ }
101
+
102
+ /**
103
+ * An injectable HTTP fetch for a single URL, returning the body text. Used for
104
+ * fetching the publisher's exported record on a replica. Tests inject a fake;
105
+ * production passes a `fetch`-backed implementation. Throwing signals the
106
+ * endpoint is unreachable (the replica then falls back to its cache).
107
+ */
108
+ export type PublisherFetch = (url: string) => Promise<string>;
109
+
110
+ /**
111
+ * An injectable HTTP fetch for gateway WARMING: fetch the URL (a small range is
112
+ * enough to seat the cache) and return the HTTP status. Tests inject a fake so
113
+ * no live gateway is hit.
114
+ */
115
+ export type GatewayFetch = (url: string) => Promise<number>;
116
+
117
+ /**
118
+ * The four core operations, injectable so the parallel `publisher-replica-model`
119
+ * (republish/mirror) and `status-report` (status) tasks can supply the owned,
120
+ * fully-tested implementations behind this SAME seam. Any op left unset uses
121
+ * this module's thin default (the direct Kubo wiring the reference describes).
122
+ */
123
+ export interface NodeCommandOps {
124
+ republish: (
125
+ ctx: NodeCommandContext,
126
+ sites: DiscoveredSite[],
127
+ ) => Promise<NodeOpResult>;
128
+ mirror: (
129
+ ctx: NodeCommandContext,
130
+ sites: DiscoveredSite[],
131
+ ) => Promise<NodeOpResult>;
132
+ warm: (
133
+ ctx: NodeCommandContext,
134
+ sites: DiscoveredSite[],
135
+ ) => Promise<NodeOpResult>;
136
+ status: (
137
+ ctx: NodeCommandContext,
138
+ sites: DiscoveredSite[],
139
+ ) => Promise<NodeOpResult>;
140
+ }
141
+
142
+ /**
143
+ * Everything a verb needs to run on the box. On-box PATHS (records/cache/
144
+ * dashboard) are explicit fields so tests isolate them to temp fixtures and
145
+ * production points them at the real box locations (`/var/www/ipfs-dash/...`,
146
+ * `/var/lib/ipfs/records`) — no global default location is baked into the
147
+ * logic.
148
+ */
149
+ export interface NodeCommandContext {
150
+ /** The LOCAL Kubo RPC client (this box's daemon). */
151
+ client: KuboRpcClient;
152
+ /** This box's role; gates `republish` (publisher) and `mirror` (replica). */
153
+ role: HostRole;
154
+ /** The MFS directory sites live under (default `/sites`). */
155
+ sitesDir?: string;
156
+ /** Gateway URL templates with a `{cid}` placeholder to warm through. */
157
+ gateways?: string[];
158
+ /** For replicas: base URL to fetch the publisher's exported records from. */
159
+ publisherEndpoint?: string;
160
+ /** Where the publisher EXPORTS signed records (replicas fetch these). */
161
+ recordsDir?: string;
162
+ /** Where a replica CACHES the last good record for fallback. */
163
+ cacheDir?: string;
164
+ /** Where `status` writes its dashboard JSON. */
165
+ dashboardDir?: string;
166
+ /** Injected publisher-record fetch (replica); defaults to a `fetch` call. */
167
+ publisherFetch?: PublisherFetch;
168
+ /** Injected gateway warm fetch; defaults to a `fetch` range request. */
169
+ gatewayFetch?: GatewayFetch;
170
+ /** Override any of the four core ops (parallel tasks supply the owned impl). */
171
+ ops?: Partial<NodeCommandOps>;
172
+ }
173
+
174
+ /**
175
+ * Auto-discover sites from MFS `/sites/*`: list the directory, then stat each
176
+ * entry for its current CID. Entries without a resolvable CID are skipped.
177
+ * Shared by every verb (the reference scripts all begin with this same walk).
178
+ */
179
+ export async function discoverSites(
180
+ client: KuboRpcClient,
181
+ sitesDir = '/sites',
182
+ ): Promise<DiscoveredSite[]> {
183
+ let listing: {Entries?: Array<{Name?: string}> | null};
184
+ try {
185
+ listing = await client.filesLs<{Entries?: Array<{Name?: string}> | null}>(
186
+ sitesDir,
187
+ );
188
+ } catch {
189
+ // No /sites dir yet (fresh box) — nothing to do, not an error.
190
+ return [];
191
+ }
192
+ const entries = listing.Entries ?? [];
193
+ const sites: DiscoveredSite[] = [];
194
+ for (const entry of entries) {
195
+ const id = entry?.Name;
196
+ if (!id) continue;
197
+ try {
198
+ const stat = await client.filesStat<{Hash?: string}>(`${sitesDir}/${id}`);
199
+ if (stat?.Hash) sites.push({id, cid: stat.Hash});
200
+ } catch {
201
+ // A site whose stat fails is skipped, not fatal for the others.
202
+ }
203
+ }
204
+ return sites;
205
+ }
206
+
207
+ /**
208
+ * Run one on-box verb. Resolves the role gate first (a wrong-role verb is a
209
+ * SKIP — a clean no-op that touches no Kubo RPC, so scheduling all timers on
210
+ * every box is safe), then discovers sites and dispatches to the (possibly
211
+ * injected) core op. Throws on an unknown verb (loud, never a silent no-op).
212
+ */
213
+ export async function runNodeCommand(
214
+ verb: NodeVerb,
215
+ ctx: NodeCommandContext,
216
+ ): Promise<NodeCommandResult> {
217
+ if (!NODE_VERBS.includes(verb)) {
218
+ throw new Error(
219
+ `unknown node verb '${verb}'; expected one of ${NODE_VERBS.join(', ')}`,
220
+ );
221
+ }
222
+
223
+ const requiredRole = VERB_ROLE_GATE[verb];
224
+ if (requiredRole && ctx.role !== requiredRole) {
225
+ return {
226
+ verb,
227
+ sites: [],
228
+ skipped: true,
229
+ skippedReason: `role ${requiredRole} required, this box is ${ctx.role}`,
230
+ };
231
+ }
232
+
233
+ const sites = await discoverSites(ctx.client, ctx.sitesDir ?? '/sites');
234
+ const op = ctx.ops?.[verb] ?? DEFAULT_OPS[verb];
235
+ const result = await op(ctx, sites);
236
+
237
+ // The dashboard PERSISTENCE is on-box wiring owned by this command layer, so
238
+ // it happens whether `status` used the default op or the injected
239
+ // `status-report` core op — the reused core produces the report, this
240
+ // wrapper writes it where the dashboard reads (and ONLY there).
241
+ if (verb === 'status') {
242
+ await writeStatusReport(ctx, result);
243
+ }
244
+
245
+ return {verb, ...result};
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Default (thin) core-op implementations.
250
+ //
251
+ // The `warm` and `status` defaults are the direct Kubo wiring the reference
252
+ // cloud-init scripts describe. The `republish`/`mirror` defaults DELEGATE to the
253
+ // owned record-sequence core (`../publisher/record-sequence.ts`) so the record
254
+ // SEQUENCE (export -> fetch -> routing/put -> fallback) has a SINGLE
255
+ // implementation shared by client and box (ADR-0002); `status` reuses the
256
+ // `status-report` core injected via `ctx.ops`.
257
+ // ---------------------------------------------------------------------------
258
+
259
+ /**
260
+ * Default `republish` (publisher): DELEGATE to the owned record-sequence core
261
+ * ({@link republishAndExport}). It refreshes the signed record (`name/publish`,
262
+ * ~72h/1h) and EXPORTS it (`routing/get`) to {@link NodeCommandContext.recordsDir}
263
+ * where replicas fetch it. One implementation, no bash/TS drift (ADR-0002).
264
+ */
265
+ async function defaultRepublish(
266
+ ctx: NodeCommandContext,
267
+ sites: DiscoveredSite[],
268
+ ): Promise<NodeOpResult> {
269
+ return republishAndExport(ctx, sites);
270
+ }
271
+
272
+ /**
273
+ * Default `mirror` (replica): DELEGATE to the owned record-sequence core
274
+ * ({@link mirrorAndReannounce}). It fetches the publisher's exported record,
275
+ * re-announces it (`routing/put`), and FALLS BACK to the last cached record
276
+ * when the publisher endpoint is unreachable — NEVER signing.
277
+ */
278
+ async function defaultMirror(
279
+ ctx: NodeCommandContext,
280
+ sites: DiscoveredSite[],
281
+ ): Promise<NodeOpResult> {
282
+ return mirrorAndReannounce(ctx, sites);
283
+ }
284
+
285
+ /**
286
+ * Default `warm`. Re-fetch each site's current CID through every configured
287
+ * gateway template (`{cid}` substituted); `.eth` names are ALSO warmed via
288
+ * eth.limo. Warming failures are recorded, never thrown (a cold gateway must
289
+ * not fail the whole run).
290
+ */
291
+ async function defaultWarm(
292
+ ctx: NodeCommandContext,
293
+ sites: DiscoveredSite[],
294
+ ): Promise<NodeOpResult> {
295
+ const warm = ctx.gatewayFetch ?? httpFetchStatus;
296
+ const gateways = ctx.gateways ?? [];
297
+ const outcomes: SiteOutcome[] = [];
298
+ for (const site of sites) {
299
+ for (const template of gateways) {
300
+ const url = template.replaceAll('{cid}', site.cid);
301
+ await safeWarm(warm, url);
302
+ }
303
+ // eth.limo warming heuristic: an `id` ending `.eth` is ALSO warmed via
304
+ // eth.limo (keyed off the MFS entry `id`, the value that flows through
305
+ // here). Making this an explicit `ensName` hint is the sibling ENS-demotion
306
+ // idea's job, out of scope for this config-model change.
307
+ if (site.id.endsWith('.eth')) {
308
+ await safeWarm(warm, `https://${site.id}.limo/`);
309
+ }
310
+ outcomes.push({id: site.id, cid: site.cid, status: 'warmed'});
311
+ }
312
+ return {sites: outcomes};
313
+ }
314
+
315
+ /**
316
+ * Default `status` — a thin stand-in used ONLY when no `status` op is injected.
317
+ * The PRODUCTION on-box path (`pinnace node status`, wired in cli/run.ts's
318
+ * `runNodeCli`) injects the OWNED `status` op ({@link makeStatusOp} from
319
+ * status-report) via {@link NodeCommandContext.ops}.status, which is the real
320
+ * per-site CID/IPNS/announce/gateway report. This default remains as the
321
+ * seam's safe fallback (e.g. a direct `runNodeCommand` call that does not want
322
+ * the live external checks / a hermetic test that injects its own op), so a
323
+ * bare call still reports current CID + IPNS id without reaching the network.
324
+ * The dashboard write is done by the command layer ({@link runNodeCommand}).
325
+ */
326
+ async function defaultStatus(
327
+ ctx: NodeCommandContext,
328
+ sites: DiscoveredSite[],
329
+ ): Promise<NodeOpResult> {
330
+ // Thin stand-in report until `status-report` supplies the owned op: current
331
+ // CID from discovery + IPNS id from the keystore. The external announce /
332
+ // gateway-serves checks are that task's concern (injected here). The
333
+ // dashboard write is done by the command layer ({@link runNodeCommand}), not
334
+ // here, so an injected op gets persisted the same way.
335
+ const keys = await listKeys(ctx.client);
336
+ const outcomes: SiteOutcome[] = sites.map((s) => ({
337
+ id: s.id,
338
+ cid: s.cid,
339
+ ipns: keys.get(s.id) ?? '',
340
+ }));
341
+ return {sites: outcomes};
342
+ }
343
+
344
+ /** Serialise a status result to `status.json` under the dashboard dir only. */
345
+ async function writeStatusReport(
346
+ ctx: NodeCommandContext,
347
+ result: NodeOpResult,
348
+ ): Promise<void> {
349
+ if (!ctx.dashboardDir) return;
350
+ await mkdir(ctx.dashboardDir, {recursive: true});
351
+ const payload = {generated: new Date().toISOString(), sites: result.sites};
352
+ await writeFile(
353
+ join(ctx.dashboardDir, 'status.json'),
354
+ JSON.stringify(payload, null, 2),
355
+ );
356
+ }
357
+
358
+ /** The default op table (verb -> thin Kubo wiring). */
359
+ const DEFAULT_OPS: NodeCommandOps = {
360
+ republish: defaultRepublish,
361
+ mirror: defaultMirror,
362
+ warm: defaultWarm,
363
+ status: defaultStatus,
364
+ };
365
+
366
+ // ---------------------------------------------------------------------------
367
+ // Small shared helpers.
368
+ // ---------------------------------------------------------------------------
369
+
370
+ /** Map site/key name -> IPNS id from `key/list -l`. */
371
+ async function listKeys(client: KuboRpcClient): Promise<Map<string, string>> {
372
+ const res = await client.keyList<{
373
+ Keys?: Array<{Name?: string; Id?: string}> | null;
374
+ }>();
375
+ const map = new Map<string, string>();
376
+ for (const k of res.Keys ?? []) {
377
+ if (k?.Name && k?.Id) map.set(k.Name, k.Id);
378
+ }
379
+ return map;
380
+ }
381
+
382
+ /** Warm one URL, swallowing any error (a cold gateway must not fail the run). */
383
+ async function safeWarm(warm: GatewayFetch, url: string): Promise<void> {
384
+ try {
385
+ await warm(url);
386
+ } catch {
387
+ // Intentionally ignored: warming is best-effort.
388
+ }
389
+ }
390
+
391
+ /** Production gateway warm: range-request the URL and return the HTTP status. */
392
+ async function httpFetchStatus(url: string): Promise<number> {
393
+ const res = await fetch(url, {headers: {range: 'bytes=0-0'}});
394
+ return res.status;
395
+ }