node-app-build 6.4.1

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Minimal blocking HTTP client wrapping the daemon's auth endpoints.
//!
//! Mirrors the four calls in `tests/e2e/src/harness/auth.ts`:
//!   POST /api/auth/onboarding-challenge
//!   POST /api/auth/complete-onboarding
//!   POST /api/auth/challenge
//!   POST /api/auth/verify
//! plus the two helpers `tests/e2e/src/harness/test-harness.ts` calls:
//!   GET  /api/node/info                     (populate node_id)
//!   POST /api/v2/internal/test/seed-peer    (cross-seed peer IP)
//!
//! All daemon responses are wrapped in an `ApiResponse { success, data,
//! error }` envelope on most routes, but the v2 hexagonal routes return
//! domain objects directly. `extract_data` accepts both shapes — same
//! tolerance the e2e `unwrapResponseOrThrow` helper uses.

use anyhow::{anyhow, bail, Context, Result};
use serde_json::{json, Value};

const AUTH_TIMEOUT_SECS: u64 = 30;

pub struct AgentHttpClient {
    base_url: String,
    agent: ureq::Agent,
}

pub struct OnboardingChallenge {
    pub challenge_id: String,
    pub challenge: String,
}

pub struct AuthSession {
    pub token: String,
    pub refresh_token: String,
}

impl AgentHttpClient {
    pub fn new(base_url: impl Into<String>) -> Self {
        let agent = ureq::AgentBuilder::new()
            .timeout(std::time::Duration::from_secs(AUTH_TIMEOUT_SECS))
            .build();
        Self {
            base_url: base_url.into(),
            agent,
        }
    }

    /// Returns true iff the node has not yet been onboarded by anyone.
    /// Tolerates schema drift: any non-200 is treated as "unknown — try
    /// onboarding and let the server reject" so we don't lock the agent
    /// out on an unrelated upstream change.
    pub fn is_unowned(&self) -> Result<bool> {
        let response = self
            .agent
            .get(&format!("{}/api/auth/onboarding-status", self.base_url))
            .call();
        match response {
            Ok(r) => {
                let value: Value = r.into_json().context("parse onboarding-status JSON")?;
                let data = extract_data(value);
                // Field name is `is_onboarded` on the OnboardingStatusResponse
                // shape; missing == treat as fresh.
                let onboarded = data
                    .get("is_onboarded")
                    .and_then(Value::as_bool)
                    .unwrap_or(false);
                Ok(!onboarded)
            }
            Err(ureq::Error::Status(_, _)) => Ok(false),
            Err(e) => Err(anyhow!("onboarding-status request failed: {e}")),
        }
    }

    pub fn create_onboarding_challenge(&self) -> Result<OnboardingChallenge> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/auth/onboarding-challenge", self.base_url),
            None,
            &json!({}),
        )?;
        let data = extract_data(value);
        Ok(OnboardingChallenge {
            challenge_id: string_field(&data, "challenge_id")?,
            challenge: string_field(&data, "challenge")?,
        })
    }

    pub fn complete_onboarding(
        &self,
        public_key_hex: &str,
        challenge_id: &str,
        signature_hex: &str,
        username: &str,
    ) -> Result<AuthSession> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/auth/complete-onboarding", self.base_url),
            None,
            &json!({
                "public_key": public_key_hex,
                "challenge_id": challenge_id,
                "signature": signature_hex,
                "username": username,
                "first_name": "Agent",
                "last_name": "Dev",
            }),
        )?;
        let data = extract_data(value);
        Ok(AuthSession {
            token: string_field(&data, "token")?,
            refresh_token: string_field(&data, "refresh_token")?,
        })
    }

    pub fn create_login_challenge(&self, public_key_hex: &str) -> Result<OnboardingChallenge> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/auth/challenge", self.base_url),
            None,
            &json!({ "public_key": public_key_hex }),
        )?;
        let data = extract_data(value);
        Ok(OnboardingChallenge {
            challenge_id: string_field(&data, "challenge_id")?,
            challenge: string_field(&data, "challenge")?,
        })
    }

    pub fn verify_login(
        &self,
        public_key_hex: &str,
        challenge_id: &str,
        signature_hex: &str,
    ) -> Result<AuthSession> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/auth/verify", self.base_url),
            None,
            &json!({
                "public_key": public_key_hex,
                "challenge_id": challenge_id,
                "signature": signature_hex,
            }),
        )?;
        let data = extract_data(value);
        Ok(AuthSession {
            token: string_field(&data, "token")?,
            refresh_token: string_field(&data, "refresh_token")?,
        })
    }

    pub fn get_node_id(&self, token: &str) -> Result<String> {
        let response = self
            .agent
            .get(&format!("{}/api/node/info", self.base_url))
            .set("Authorization", &format!("Bearer {token}"))
            .call()
            .map_err(|e| anyhow!("GET /api/node/info failed: {e}"))?;
        let value: Value = response.into_json().context("parse node info JSON")?;
        let data = extract_data(value);
        string_field(&data, "node_id")
    }

    /// Seed `peer_node_id` at `ip:port` into this node's IP pool so future
    /// L402 / proxy calls can resolve the peer. Idempotent server-side
    /// (the test seed endpoint upserts). Any 4xx/5xx is bubbled up.
    pub fn seed_peer_endpoint(
        &self,
        token: &str,
        peer_node_id: &str,
        ip: &str,
        port: u16,
    ) -> Result<()> {
        let _: Value = post_json(
            &self.agent,
            &format!("{}/api/v2/internal/test/seed-peer", self.base_url),
            Some(token),
            &json!({
                "node_id": peer_node_id,
                "ip_address": ip,
                "port": port,
            }),
        )?;
        Ok(())
    }

    // ── Lightning / capability probe methods ─────────────────────────────────

    /// GET /api/balance — wallet balance summary.
    pub fn get_balance(&self, token: &str) -> Result<Value> {
        let response = self
            .agent
            .get(&format!("{}/api/balance", self.base_url))
            .set("Authorization", &format!("Bearer {token}"))
            .call()
            .map_err(|e| anyhow!("GET /api/balance failed: {e}"))?;
        let value: Value = response.into_json().context("parse balance JSON")?;
        Ok(extract_data(value))
    }

    /// GET /api/channels — list open Lightning channels.
    pub fn list_channels(&self, token: &str) -> Result<Value> {
        let response = self
            .agent
            .get(&format!("{}/api/channels", self.base_url))
            .set("Authorization", &format!("Bearer {token}"))
            .call()
            .map_err(|e| anyhow!("GET /api/channels failed: {e}"))?;
        let value: Value = response.into_json().context("parse channels JSON")?;
        Ok(extract_data(value))
    }

    /// GET /api/peers — list connected Lightning peers.
    pub fn list_peers(&self, token: &str) -> Result<Value> {
        let response = self
            .agent
            .get(&format!("{}/api/peers", self.base_url))
            .set("Authorization", &format!("Bearer {token}"))
            .call()
            .map_err(|e| anyhow!("GET /api/peers failed: {e}"))?;
        let value: Value = response.into_json().context("parse peers JSON")?;
        Ok(extract_data(value))
    }

    /// GET /api/onchain/address/new — generate a fresh on-chain Bitcoin address.
    ///
    /// Returns the `address` string from the response.
    pub fn new_onchain_address(&self, token: &str) -> Result<String> {
        let response = self
            .agent
            .get(&format!("{}/api/onchain/address/new", self.base_url))
            .set("Authorization", &format!("Bearer {token}"))
            .call()
            .map_err(|e| anyhow!("GET /api/onchain/address/new failed: {e}"))?;
        let value: Value = response.into_json().context("parse onchain address JSON")?;
        let data = extract_data(value);
        string_field(&data, "address")
    }

    /// POST /api/peers/connect — connect to a Lightning peer.
    ///
    /// `peer` must be in `pubkey@host:port` format (the server parses it).
    pub fn connect_peer(&self, token: &str, peer: &str) -> Result<Value> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/peers/connect", self.base_url),
            Some(token),
            &json!({ "peer_info": peer }),
        )?;
        Ok(extract_data(value))
    }

    /// Build the JSON body for `POST /api/channels/open`.
    ///
    /// Extracted so the body shape can be unit-tested without a live daemon.
    /// The `peer_pubkey_and_address` field carries the `pubkey@host:port`
    /// string and the server splits it internally.
    pub(crate) fn open_channel_body(peer: &str, sats: u64, push_msat: u64) -> Value {
        json!({
            "peer_pubkey_and_address": peer,
            "channel_amount_sats": sats,
            "push_to_counterparty_msat": push_msat,
        })
    }

    /// POST /api/channels/open — open a Lightning channel with a peer.
    ///
    /// `peer` must be in `pubkey@host:port` format.
    pub fn open_channel(
        &self,
        token: &str,
        peer: &str,
        sats: u64,
        push_msat: u64,
    ) -> Result<Value> {
        let body = Self::open_channel_body(peer, sats, push_msat);
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/channels/open", self.base_url),
            Some(token),
            &body,
        )?;
        Ok(extract_data(value))
    }

    /// POST /api/payments/invoices/create — create a BOLT11 invoice.
    ///
    /// Returns the bolt11 string from the `invoice` field of the response.
    pub fn create_invoice(
        &self,
        token: &str,
        amount_msat: u64,
        memo: &str,
    ) -> Result<String> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/payments/invoices/create", self.base_url),
            Some(token),
            &json!({
                "amount_msat": amount_msat,
                "description": memo,
                "expiry_secs": 3600u32,
            }),
        )?;
        let data = extract_data(value);
        string_field(&data, "invoice")
    }

    /// POST /api/payments/send/invoice — pay a BOLT11 invoice.
    ///
    /// The `invoice` field carries the bolt11 string.
    pub fn pay_invoice(&self, token: &str, bolt11: &str) -> Result<Value> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/payments/send/invoice", self.base_url),
            Some(token),
            &json!({ "invoice": bolt11 }),
        )?;
        Ok(extract_data(value))
    }

    /// POST /api/v2/system/capabilities/invoke — invoke a registered capability.
    ///
    /// Routes through the platform capability router; works for both core and
    /// builtin-app capabilities.
    pub fn invoke_capability(
        &self,
        token: &str,
        capability: &str,
        payload: Value,
    ) -> Result<Value> {
        let value: Value = post_json(
            &self.agent,
            &format!("{}/api/v2/system/capabilities/invoke", self.base_url),
            Some(token),
            &json!({
                "capability": capability,
                "payload": payload,
            }),
        )?;
        Ok(extract_data(value))
    }

    /// POST `{base_url}{route}` with an arbitrary JSON body — used for the L402
    /// cross-node probe, where `from`'s daemon receives the call and its
    /// L402HttpClient proxies it to `to`.
    ///
    /// Returns `(http_status_code, response_body_as_value)`.
    /// Unlike `post_json`, a 402 response is NOT treated as an error — it is
    /// returned to the caller as a soft outcome so the probe can report it.
    pub fn post_raw_with_status(
        &self,
        token: &str,
        route: &str,
        body: &Value,
    ) -> Result<(u16, Value)> {
        let url = format!("{}{}", self.base_url, route);
        let request = self
            .agent
            .post(&url)
            .set("Content-Type", "application/json")
            .set("Authorization", &format!("Bearer {token}"));
        match request.send_json(body.clone()) {
            Ok(r) => {
                let status = r.status();
                let value: Value = r
                    .into_json()
                    .unwrap_or_else(|_| json!({}));
                Ok((status, value))
            }
            Err(ureq::Error::Status(code, r)) => {
                // 402 is a soft outcome for the L402 probe; return it rather
                // than bailing so callers can inspect the WWW-Authenticate
                // challenge or print a structured hint.
                let body_str = r.into_string().unwrap_or_default();
                let value: Value = serde_json::from_str(&body_str)
                    .unwrap_or_else(|_| json!({ "raw": body_str }));
                Ok((code, value))
            }
            Err(e) => anyhow::bail!("POST {url} transport error: {e}"),
        }
    }
}

fn post_json(
    agent: &ureq::Agent,
    url: &str,
    bearer: Option<&str>,
    body: &Value,
) -> Result<Value> {
    let mut request = agent.post(url).set("Content-Type", "application/json");
    if let Some(token) = bearer {
        request = request.set("Authorization", &format!("Bearer {token}"));
    }
    let response = match request.send_json(body.clone()) {
        Ok(r) => r,
        Err(ureq::Error::Status(code, r)) => {
            let body = r.into_string().unwrap_or_default();
            bail!("POST {url} returned HTTP {code}: {body}");
        }
        Err(e) => bail!("POST {url} transport error: {e}"),
    };
    response
        .into_json::<Value>()
        .with_context(|| format!("parse JSON response from POST {url}"))
}

/// Accept both shapes the daemon returns:
///   { "success": true, "data": {...} }       (legacy v1 envelope)
///   {...}                                    (v2 hexagonal direct return)
fn extract_data(value: Value) -> Value {
    match value {
        Value::Object(ref obj) if obj.contains_key("success") && obj.contains_key("data") => {
            obj.get("data").cloned().unwrap_or(Value::Null)
        }
        other => other,
    }
}

fn string_field(value: &Value, key: &str) -> Result<String> {
    value
        .get(key)
        .and_then(Value::as_str)
        .map(str::to_owned)
        .ok_or_else(|| anyhow!("response missing '{key}' string field; got: {value}"))
}

#[cfg(test)]
mod probe_tests {
    use super::*;

    #[test]
    fn open_channel_body_has_expected_fields() {
        let body = AgentHttpClient::open_channel_body("03aa@127.0.0.1:9536", 100_000, 10_000_000);
        assert_eq!(body["peer_pubkey_and_address"], "03aa@127.0.0.1:9536");
        assert_eq!(body["channel_amount_sats"], 100_000u64);
        assert_eq!(body["push_to_counterparty_msat"], 10_000_000u64);
    }
}