microsoft-webui-desktop 3.0.3

Configurable native desktop SDK for WebUI applications
Documentation
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Bounded control parsing and native document bookkeeping, without COM.

use crate::ipc::{DocumentActivation, Hello, IpcError, IpcErrorCode};
use serde::Deserialize;

pub(super) use super::protocol::app_url;

pub(super) const MAX_CONTROL_UNITS: usize = 4096;
pub(super) const MAX_TASKS: usize = 128;

pub(super) fn reserved_path(uri: &str) -> Option<&str> {
    if !app_url(uri) {
        return None;
    }
    let path = uri.strip_prefix(super::APP_ORIGIN)?;
    let route = path.split(['?', '#']).next()?;
    // These are immutable SDK assets, not authenticated binary endpoints.
    if matches!(route, "/_webui/ipc/bootstrap.js" | "/_webui/ipc/runtime.js") {
        return None;
    }
    (route == "/_webui/ipc" || route.starts_with("/_webui/ipc/")).then_some(path)
}

pub(super) fn decimal(value: &str) -> Option<u64> {
    if value.is_empty()
        || value.len() > 20
        || value.starts_with('0')
        || !value.bytes().all(|c| c.is_ascii_digit())
    {
        return None;
    }
    value.parse().ok()
}

pub(super) fn nonce(value: &str) -> Option<[u8; 16]> {
    if value.len() != 32 {
        return None;
    }
    let mut out = [0; 16];
    for (byte, pair) in out.iter_mut().zip(value.as_bytes().as_chunks::<2>().0) {
        let digit = |c| match c {
            b'0'..=b'9' => Some(c - b'0'),
            b'a'..=b'f' => Some(c - b'a' + 10),
            _ => None,
        };
        *byte = digit(pair[0])? * 16 + digit(pair[1])?;
    }
    Some(out)
}

#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
pub(super) enum Control {
    #[serde(rename_all = "camelCase")]
    Hello {
        call_id: String,
        navigation: String,
        document_nonce: String,
        challenge: String,
        wire_version: u32,
        contract_name: String,
        contract_major: u32,
        schema_hash: String,
        #[serde(default)]
        native_carrier_version: Option<u8>,
    },
    Disconnect {
        generation: String,
        token: String,
    },
}

pub(super) use crate::native_ipc::NativeHello as HelloCall;

impl Control {
    pub fn into_hello(self, carrier: bool) -> Option<HelloCall> {
        let Self::Hello {
            call_id,
            navigation,
            document_nonce,
            challenge,
            wire_version,
            contract_name,
            contract_major,
            schema_hash,
            native_carrier_version,
        } = self
        else {
            return None;
        };
        if native_carrier_version != carrier.then_some(1)
            || call_id.is_empty()
            || call_id.len() > 32
            || contract_name.len() > 256
            || schema_hash.len() != 64
        {
            return None;
        }
        Some(HelloCall {
            call_id,
            proof: DocumentActivation {
                navigation: decimal(&navigation)?,
                document_nonce: nonce(&document_nonce)?,
                challenge: nonce(&challenge)?,
            },
            hello: Hello {
                wire_version,
                contract_name,
                contract_major,
                schema_hash,
            },
        })
    }
}

#[derive(Default)]
pub(super) struct Document {
    pub epoch: crate::document::DocumentEpoch,
    pub native_id: Option<u64>,
    pub hello_pending: bool,
    pub generation: Option<u64>,
    pub token: Option<String>,
    pub max_frame_bytes: Option<usize>,
    pub limits: Option<crate::ipc::IpcLimits>,
    pub proof: Option<DocumentActivation>,
    pub unavailable_code: Option<IpcErrorCode>,
}

impl Document {
    /// NavigationStarting excludes same-document changes; redirects retain ID.
    pub fn start(&mut self, native_id: u64) -> Option<u64> {
        if self.epoch.closed || self.native_id == Some(native_id) {
            return None;
        }
        let next = self.epoch.advance()?;
        *self = Self {
            epoch: self.epoch,
            native_id: Some(native_id),
            unavailable_code: self.native_id.map(|_| IpcErrorCode::Navigated),
            ..Self::default()
        };
        Some(next)
    }

    pub fn current(&self, navigation: u64) -> bool {
        self.epoch.current(navigation)
    }

    pub fn request_error(&self) -> Option<IpcErrorCode> {
        if self.epoch.closed {
            Some(IpcErrorCode::Closed)
        } else if self.current(self.epoch.navigation) {
            None
        } else {
            Some(self.unavailable_code.unwrap_or(IpcErrorCode::NotReady))
        }
    }

    pub fn accepts(&self, proof: &DocumentActivation) -> bool {
        self.epoch.accepts(self.proof.as_ref(), proof)
    }

    pub fn begin_hello(&mut self, proof: &DocumentActivation) -> bool {
        if !self.accepts(proof) || self.hello_pending || self.generation.is_some() {
            return false;
        }
        self.hello_pending = true;
        true
    }
}

/// Keep the challenge behind the wrapper's own nonce check. A replacement
/// document's fake activate method must never receive an old proof.
#[cfg(test)]
pub(super) fn activation_script(proof: &DocumentActivation) -> serde_json::Result<String> {
    activation_script_for(proof, super::APP_ORIGIN, false)
}

pub(super) fn activation_script_for(
    proof: &DocumentActivation,
    origin: &str,
    carrier: bool,
) -> serde_json::Result<String> {
    let activate = if carrier {
        crate::native_ipc::activation_script_local(proof)?
    } else {
        crate::native_ipc::activation_script(proof)?
    };
    let origin = serde_json::to_string(origin)?;
    Ok(format!(
        "(()=>{{'use strict';if(window!==window.top||location.origin!=={origin})return false;return {activate}===true;}})()"
    ))
}

#[cold]
#[inline(never)]
pub(super) fn error(code: IpcErrorCode) -> IpcError {
    IpcError::new(
        code,
        code.as_str(),
        "reload the trusted app document or reduce concurrent IPC work",
    )
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;

    #[test]
    fn local_hello_requires_carrier_v1_before_proof_can_be_admitted() {
        let hello = r#"{"kind":"hello","callId":"1","navigation":"1","documentNonce":"01010101010101010101010101010101","challenge":"02020202020202020202020202020202","wireVersion":3,"contractName":"test","contractMajor":1,"schemaHash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}"#;
        let bundled: Control = serde_json::from_str(hello).unwrap();
        assert!(bundled.into_hello(false).is_some());
        let missing: Control = serde_json::from_str(hello).unwrap();
        assert!(missing.into_hello(true).is_none());
        let local = hello.replacen(
            "\"kind\":\"hello\"",
            "\"kind\":\"hello\",\"nativeCarrierVersion\":1",
            1,
        );
        let valid: Control = serde_json::from_str(&local).unwrap();
        assert!(valid.into_hello(true).is_some());
        let forbidden: Control = serde_json::from_str(&local).unwrap();
        assert!(forbidden.into_hello(false).is_none());
        let wrong: Control = serde_json::from_str(
            &local.replace("\"nativeCarrierVersion\":1", "\"nativeCarrierVersion\":2"),
        )
        .unwrap();
        assert!(wrong.into_hello(true).is_none());
    }

    #[test]
    fn disconnect_without_credential_is_not_a_control_message() {
        assert!(
            serde_json::from_str::<Control>(r#"{"kind":"disconnect","generation":"1"}"#).is_err()
        );
        let message = serde_json::from_str::<Control>(
            r#"{"kind":"disconnect","generation":"1","token":"01010101010101010101010101010101"}"#,
        )
        .unwrap();
        assert!(
            matches!(message, Control::Disconnect { generation, token } if generation == "1" && nonce(&token).is_some())
        );
    }

    #[test]
    fn duplicate_hello_cannot_replace_the_pending_call() {
        let mut document = Document::default();
        let navigation = document.start(1).unwrap();
        document.epoch.commit();
        let proof = DocumentActivation {
            navigation,
            document_nonce: [1; 16],
            challenge: [2; 16],
        };
        document.proof = Some(proof.clone());
        assert!(document.begin_hello(&proof));
        assert!(!document.begin_hello(&proof));
        assert!(document.accepts(&proof));
        let mut forged = proof.clone();
        forged.challenge = [3; 16];
        assert!(!document.begin_hello(&forged));
        assert!(!Document::default().begin_hello(&proof));
        document.start(2);
        assert!(!document.begin_hello(&proof));
    }

    #[test]
    fn evaluated_wrapper_never_hands_old_proof_to_replacement_bootstrap() {
        let proof = DocumentActivation {
            navigation: 1,
            document_nonce: [1; 16],
            challenge: [2; 16],
        };
        let script = serde_json::to_string(&activation_script(&proof).unwrap()).unwrap();
        // Execute the production wrapper in a JS engine, not a source-text
        // assertion. Node is already part of the repository's test toolchain.
        let harness = format!(
            r#"
const vm = require('node:vm');
const assert = require('node:assert/strict');
function run(nonce, main = true, origin = 'https://app.webui.localhost') {{
  let lookedUp = 0;
  const calls = [];
  const window = {{}};
  window.top = main ? window : {{}};
  window.__webuiDesktopIpcV2 = {{
    documentNonce: nonce,
    get activate() {{ lookedUp++; return proof => {{ calls.push(proof); return true; }}; }}
  }};
  const result = vm.runInNewContext({script}, {{window, location: {{origin}}}});
  return {{result, lookedUp, calls}};
}}
for (const result of [
  run('03'.repeat(16)), // Same URL, replacement document and fake bootstrap.
  run('01'.repeat(16), false),
  run('01'.repeat(16), true, 'https://remote.example')
]) {{
  assert.equal(result.result, false);
  assert.equal(result.lookedUp, 0);
  assert.equal(result.calls.length, 0);
}}
const current = run('01'.repeat(16));
assert.equal(current.result, true);
assert.equal(current.calls.length, 1);
assert.equal(current.calls[0].navigation, '1');
assert.equal(current.calls[0].challenge, '02'.repeat(16));
"#
        );
        let output = std::process::Command::new("node")
            .args(["-e", &harness])
            .output()
            .expect("Node.js from the repository test toolchain must be installed");
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn authority_is_exact_and_reserved_routes_cannot_escape() {
        assert!(app_url("https://app.webui.localhost/a"));
        assert!(app_url("https://app.webui.localhost#fragment"));
        for url in [
            "https://app.webui.localhost.evil/a",
            "https://app.webui.localhost@evil/a",
            "https://app.webui.localhost:444/a",
            "https://evil/a",
            "http://app.webui.localhost/a",
        ] {
            assert!(!app_url(url));
        }
        assert_eq!(
            reserved_path("https://app.webui.localhost/_webui/ipc?token=x"),
            Some("/_webui/ipc?token=x")
        );
        assert!(reserved_path("https://app.webui.localhost/_webui/ipc-other").is_none());
        assert!(reserved_path("https://app.webui.localhost/_webui/ipc/runtime.js").is_none());
        assert!(reserved_path("https://app.webui.localhost/_webui/ipc/bootstrap.js?v=2").is_none());
    }

    #[test]
    fn late_resource_requests_preserve_native_retirement_reason() {
        let mut document = Document::default();
        assert_eq!(document.request_error(), Some(IpcErrorCode::NotReady));
        document.start(10).unwrap();
        assert_eq!(document.request_error(), Some(IpcErrorCode::NotReady));
        document.epoch.commit();
        assert_eq!(document.request_error(), None);
        assert_eq!(document.start(10), None);
        assert_eq!(document.request_error(), None);

        document.start(11).unwrap();
        // An outgoing GET/POST may arrive before its queued JS close control.
        assert_eq!(document.request_error(), Some(IpcErrorCode::Navigated));
        assert_eq!(document.start(11), None);
        assert_eq!(document.request_error(), Some(IpcErrorCode::Navigated));
        document.epoch.commit();
        assert_eq!(document.request_error(), None);

        for code in [IpcErrorCode::Closed, IpcErrorCode::Transport] {
            document.epoch.committed = false;
            document.unavailable_code = Some(code);
            assert_eq!(document.request_error(), Some(code));
        }
        document.epoch.closed = true;
        assert_eq!(document.request_error(), Some(IpcErrorCode::Closed));
    }

    #[test]
    fn old_same_url_proof_cannot_match_new_document_or_reply() {
        let mut document = Document::default();
        let old = document.start(10).unwrap();
        document.epoch.commit();
        let proof = DocumentActivation {
            navigation: old,
            document_nonce: [1; 16],
            challenge: [2; 16],
        };
        document.proof = Some(proof.clone());
        assert!(document.accepts(&proof));
        assert_eq!(document.start(10), None); // Redirect, not a new document.
        assert!(document.accepts(&proof));
        let new = document.start(11).unwrap();
        document.epoch.commit();
        document.proof = Some(DocumentActivation {
            navigation: new,
            document_nonce: [3; 16],
            challenge: [4; 16],
        });
        assert!(!document.current(old));
        assert!(!document.accepts(&proof));
        let mut forged = proof;
        forged.navigation = new;
        assert!(!document.accepts(&forged));
        document.epoch.closed = true;
        assert!(!document.current(new));
    }

    #[test]
    fn correlation_and_proof_fields_are_bounded_canonical_values() {
        assert_eq!(decimal("18446744073709551615"), Some(u64::MAX));
        for bad in ["0", "01", "-1", "1.0", "18446744073709551616"] {
            assert_eq!(decimal(bad), None);
        }
        assert_eq!(nonce("0123456789abcdef0123456789abcdef").unwrap()[0], 1);
        assert!(nonce("0123456789ABCDEF0123456789ABCDEF").is_none());
        assert!(nonce("🦀0000000000000000000000000000").is_none());
    }
}