iwlink 0.1.1

IntelliWallet Link - encrypted phone to computer protocol for IntelliWallet for Browser
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Protocol messages.
//!
//! Every message is a JSON object with a `type` field. Decoding is strict
//! about the type (an unknown one is an error, because acting on a message
//! that is not understood is worse than dropping it) and lenient about fields
//! (unknown ones are ignored, so a newer peer can add optional fields without
//! a version bump).
//!
//! Site identity travels as **origins only**: scheme, host and port, never a
//! path or query string, which can carry tokens and personal data. The phone
//! derives host and registrable domain from the origin with iwcore's rules;
//! nothing on the computer side does domain logic.
//!
//! Password fields are [`Zeroizing`], so the plaintext is wiped when a message
//! is dropped. [`Message::encode`] returns zeroizing bytes for the same reason.
//!
//! Every text field has a length limit, checked on decode. The limits are far
//! above anything real and exist so that a hostile peer cannot make the other
//! side allocate or display unbounded data.

use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use crate::error::{LinkError, Result};
use crate::noise::MAX_PLAINTEXT;

/// Longest request id.
pub const MAX_ID_LEN: usize = 64;
/// Longest origin.
pub const MAX_ORIGIN_LEN: usize = 2_048;
/// Longest title, username or display name.
pub const MAX_TEXT_LEN: usize = 1_024;
/// Longest password.
pub const MAX_PASSWORD_LEN: usize = 4_096;
/// Most candidates in one answer.
pub const MAX_CANDIDATES: usize = 200;

/// How well a login matches the requested site, best first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MatchTier {
    /// Same host.
    Exact,
    /// Same registrable domain (eTLD+1).
    Registrable,
    /// One host is a label-aligned suffix of the other.
    Suffix,
}

/// One login offered for a site. Carries no password.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
    /// Vault item id, or the record id of a login saved but not yet merged.
    pub id: String,
    pub title: String,
    pub username: String,
    /// Saved from a browser or AutoFill and not yet merged into the vault.
    pub staged: bool,
    pub tier: MatchTier,
}

/// What a save is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SaveKind {
    New,
    PasswordChanged,
}

/// Outcome of an approved save.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SaveOutcome {
    /// Written to the journal; merged into the vault on the next app unlock.
    Staged,
    /// The journal is full; the user must open the app first.
    JournalFull,
}

/// Why a request was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DenyReason {
    /// The user tapped Deny.
    UserDenied,
    /// No answer in time.
    TimedOut,
    /// AutoFill is switched off in the app.
    AutofillOff,
    /// The AutoFill index is missing or expired; the user must open the app.
    OpenApp,
    /// Too many requests from this computer.
    RateLimited,
    /// Too many requests already waiting.
    Busy,
    /// The app lost the request (it was restarted); send it again.
    Retry,
    /// A `Reveal` without a live grant, or for an item not in the grant.
    NoGrant,
    /// The request was malformed.
    Invalid,
}

/// State of the AutoFill index on the phone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IndexState {
    Ready,
    Missing,
    Expired,
}

/// Why a session is being closed on purpose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ByeReason {
    /// The pairing was removed on this side.
    Unpaired,
    /// AutoFill was switched off, which unpairs every computer.
    AutofillOff,
    /// The app or helper is quitting.
    ShuttingDown,
}

/// A protocol message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum Message {
    /// Helper to phone: logins wanted for a site.
    Query {
        id: String,
        /// Origin of the frame holding the login form.
        frame_origin: String,
        /// Origin of the top level page; differs from `frame_origin` for a
        /// login form inside a frame.
        top_origin: String,
        /// Browser name, for the notification text.
        browser: String,
    },
    /// Phone to helper: the request is waiting for the user.
    Pending { id: String },
    /// Phone to helper: logins for an approved query.
    Candidates {
        id: String,
        /// Seconds the grant to pick one remains valid.
        grant_ttl_secs: u32,
        candidates: Vec<Candidate>,
    },
    /// Helper to phone: the password for one candidate.
    Reveal { id: String, item: String },
    /// Phone to helper: a released login.
    Secret {
        id: String,
        username: String,
        password: Zeroizing<String>,
    },
    /// Helper to phone: store a login the user submitted.
    Save {
        id: String,
        /// Stored as the item's LINK.
        frame_origin: String,
        username: String,
        password: Zeroizing<String>,
        kind: SaveKind,
    },
    /// Phone to helper: result of an approved save.
    Saved { id: String, outcome: SaveOutcome },
    /// Phone to helper: a request was refused.
    Denied { id: String, reason: DenyReason },
    /// Helper to phone: the browser gave up on a request.
    Cancel { id: String },
    /// Phone to helper: what the phone can do right now.
    Status {
        autofill_on: bool,
        notifications_on: bool,
        index: IndexState,
    },
    /// Either way: liveness check.
    Ping,
    /// Either way: answer to `Ping`.
    Pong,
    /// Either way: the session is closing on purpose.
    Bye { reason: ByeReason },
}

impl Message {
    /// Encode as JSON. The bytes are wiped when dropped, since they may hold a
    /// password.
    pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>> {
        self.validate()?;
        let bytes = Zeroizing::new(
            serde_json::to_vec(self).map_err(|e| LinkError::BadMessage(e.to_string()))?,
        );
        if bytes.len() > MAX_PLAINTEXT {
            return Err(LinkError::TooLarge);
        }
        Ok(bytes)
    }

    /// Decode and validate.
    pub fn decode(bytes: &[u8]) -> Result<Message> {
        if bytes.len() > MAX_PLAINTEXT {
            return Err(LinkError::TooLarge);
        }
        let message: Message = serde_json::from_slice(bytes).map_err(|e| {
            // serde_json's message quotes at most a short fragment of the
            // input around the error, never a whole field, but a fragment of a
            // password is still a fragment of a password. Keep the category
            // and position only.
            LinkError::BadMessage(format!("{:?} at column {}", e.classify(), e.column()))
        })?;
        message.validate()?;
        Ok(message)
    }

    /// The request id, for messages that belong to a request.
    pub fn request_id(&self) -> Option<&str> {
        match self {
            Message::Query { id, .. }
            | Message::Pending { id }
            | Message::Candidates { id, .. }
            | Message::Reveal { id, .. }
            | Message::Secret { id, .. }
            | Message::Save { id, .. }
            | Message::Saved { id, .. }
            | Message::Denied { id, .. }
            | Message::Cancel { id } => Some(id),
            Message::Status { .. } | Message::Ping | Message::Pong | Message::Bye { .. } => None,
        }
    }

    /// Check every length limit.
    pub fn validate(&self) -> Result<()> {
        if let Some(id) = self.request_id() {
            check_id(id)?;
        }
        match self {
            Message::Query {
                frame_origin,
                top_origin,
                browser,
                ..
            } => {
                check_origin(frame_origin)?;
                check_origin(top_origin)?;
                check_text(browser, "browser")?;
            }
            Message::Candidates { candidates, .. } => {
                if candidates.len() > MAX_CANDIDATES {
                    return Err(LinkError::BadMessage("too many candidates".into()));
                }
                for c in candidates {
                    check_nonempty(&c.id, MAX_ID_LEN, "candidate id")?;
                    check_text(&c.title, "title")?;
                    check_text(&c.username, "username")?;
                }
            }
            Message::Reveal { item, .. } => check_nonempty(item, MAX_ID_LEN, "item")?,
            Message::Secret {
                username, password, ..
            } => {
                check_text(username, "username")?;
                check_password(password)?;
            }
            Message::Save {
                frame_origin,
                username,
                password,
                ..
            } => {
                check_origin(frame_origin)?;
                check_text(username, "username")?;
                check_password(password)?;
                if password.is_empty() {
                    return Err(LinkError::BadMessage("empty password".into()));
                }
            }
            _ => {}
        }
        Ok(())
    }
}

fn check_id(id: &str) -> Result<()> {
    check_nonempty(id, MAX_ID_LEN, "id")
}

fn check_nonempty(value: &str, max: usize, what: &str) -> Result<()> {
    if value.is_empty() || value.len() > max {
        return Err(LinkError::BadMessage(format!("{what} length")));
    }
    Ok(())
}

fn check_text(value: &str, what: &str) -> Result<()> {
    if value.len() > MAX_TEXT_LEN {
        return Err(LinkError::BadMessage(format!("{what} too long")));
    }
    Ok(())
}

fn check_password(value: &str) -> Result<()> {
    if value.len() > MAX_PASSWORD_LEN {
        return Err(LinkError::BadMessage("password too long".into()));
    }
    Ok(())
}

/// An origin is `scheme://host[:port]` with nothing after it. Only the shape
/// is checked here; the phone parses the host.
fn check_origin(value: &str) -> Result<()> {
    check_nonempty(value, MAX_ORIGIN_LEN, "origin")?;
    let Some((scheme, rest)) = value.split_once("://") else {
        return Err(LinkError::BadMessage("origin without scheme".into()));
    };
    let scheme_ok = !scheme.is_empty()
        && scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    if !scheme_ok || rest.is_empty() || rest.contains(['/', '?', '#', '@']) {
        return Err(LinkError::BadMessage("not an origin".into()));
    }
    Ok(())
}

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

    fn secret() -> Message {
        Message::Secret {
            id: "r1".into(),
            username: "anna".into(),
            password: Zeroizing::new("hunter2".into()),
        }
    }

    fn all_messages() -> Vec<Message> {
        vec![
            Message::Query {
                id: "r1".into(),
                frame_origin: "https://login.example.com".into(),
                top_origin: "https://example.com".into(),
                browser: "Chrome".into(),
            },
            Message::Pending { id: "r1".into() },
            Message::Candidates {
                id: "r1".into(),
                grant_ttl_secs: 60,
                candidates: vec![Candidate {
                    id: "item-1".into(),
                    title: "Example".into(),
                    username: "anna".into(),
                    staged: false,
                    tier: MatchTier::Registrable,
                }],
            },
            Message::Reveal {
                id: "r1".into(),
                item: "item-1".into(),
            },
            secret(),
            Message::Save {
                id: "r2".into(),
                frame_origin: "https://example.com:8443".into(),
                username: "anna".into(),
                password: Zeroizing::new("new pass".into()),
                kind: SaveKind::PasswordChanged,
            },
            Message::Saved {
                id: "r2".into(),
                outcome: SaveOutcome::JournalFull,
            },
            Message::Denied {
                id: "r3".into(),
                reason: DenyReason::NoGrant,
            },
            Message::Cancel { id: "r3".into() },
            Message::Status {
                autofill_on: true,
                notifications_on: false,
                index: IndexState::Expired,
            },
            Message::Ping,
            Message::Pong,
            Message::Bye {
                reason: ByeReason::AutofillOff,
            },
        ]
    }

    #[test]
    fn every_message_round_trips() {
        for m in all_messages() {
            let bytes = m.encode().unwrap();
            assert_eq!(Message::decode(&bytes).unwrap(), m);
        }
    }

    #[test]
    fn wire_format_is_camel_case_with_a_type_tag() {
        let bytes = Message::Query {
            id: "r1".into(),
            frame_origin: "https://a.example".into(),
            top_origin: "https://a.example".into(),
            browser: "Firefox".into(),
        }
        .encode()
        .unwrap();
        let text = std::str::from_utf8(&bytes).unwrap();
        assert!(text.contains(r#""type":"query""#), "{text}");
        assert!(
            text.contains(r#""frameOrigin":"https://a.example""#),
            "{text}"
        );
        let ping = Message::Ping.encode().unwrap();
        assert_eq!(ping.as_slice(), br#"{"type":"ping"}"#);
    }

    #[test]
    fn unknown_type_is_an_error_and_unknown_fields_are_ignored() {
        assert!(Message::decode(br#"{"type":"teleport","id":"x"}"#).is_err());
        let m = Message::decode(br#"{"type":"pending","id":"x","future":1}"#).unwrap();
        assert_eq!(m, Message::Pending { id: "x".into() });
    }

    #[test]
    fn origins_are_checked() {
        let query = |origin: &str| Message::Query {
            id: "r".into(),
            frame_origin: origin.into(),
            top_origin: "https://ok.example".into(),
            browser: String::new(),
        };
        for good in [
            "https://example.com",
            "http://localhost:3000",
            "https://[::1]:8080",
        ] {
            assert!(query(good).validate().is_ok(), "{good}");
        }
        for bad in [
            "",
            "example.com",
            "https://",
            "https://example.com/login",
            "https://example.com?token=1",
            "https://example.com#x",
            "https://user@example.com",
        ] {
            assert!(query(bad).validate().is_err(), "{bad}");
        }
    }

    #[test]
    fn limits_are_enforced_on_decode() {
        let long_id = format!(
            r#"{{"type":"pending","id":"{}"}}"#,
            "x".repeat(MAX_ID_LEN + 1)
        );
        assert!(Message::decode(long_id.as_bytes()).is_err());
        assert!(Message::decode(br#"{"type":"pending","id":""}"#).is_err());

        let many = Message::Candidates {
            id: "r".into(),
            grant_ttl_secs: 60,
            candidates: vec![
                Candidate {
                    id: "i".into(),
                    title: String::new(),
                    username: String::new(),
                    staged: false,
                    tier: MatchTier::Exact,
                };
                MAX_CANDIDATES + 1
            ],
        };
        assert!(many.encode().is_err());

        let long_password = Message::Secret {
            id: "r".into(),
            username: String::new(),
            password: Zeroizing::new("p".repeat(MAX_PASSWORD_LEN + 1)),
        };
        assert!(long_password.encode().is_err());
    }

    #[test]
    fn empty_save_password_is_refused() {
        let m = Message::Save {
            id: "r".into(),
            frame_origin: "https://example.com".into(),
            username: "a".into(),
            password: Zeroizing::new(String::new()),
            kind: SaveKind::New,
        };
        assert!(m.validate().is_err());
    }

    #[test]
    fn decode_errors_do_not_quote_input() {
        let bad = br#"{"type":"secret","id":"r","username":"a","password":"hunter2""#;
        let error = Message::decode(bad).unwrap_err().to_string();
        assert!(!error.contains("hunter2"), "{error}");
    }

    #[test]
    fn request_ids() {
        assert_eq!(secret().request_id(), Some("r1"));
        assert_eq!(Message::Ping.request_id(), None);
    }
}