| 1 | //! Decides that Teams sign-in is finished only when the page holds a fresh access token. |
| 2 | //! |
| 3 | //! Local storage key names that contain `accesstoken` or `refreshtoken` are not enough: a wiped |
| 4 | //! cache still has those names, and treating them as success restarts Chromium and drops the |
| 5 | //! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption |
| 6 | //! cookie persists across restarts, because an expired session still unseals its old entries. |
| 7 | |
| 8 | use serde_json::Value; |
| 9 | |
| 10 | /// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with |
| 11 | /// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn` |
| 12 | /// is still in the future, in the clear or among the opened entries. |
| 13 | pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => { |
| 14 | const sealed = []; |
| 15 | const plain = []; |
| 16 | for (let index = 0; index < localStorage.length; index++) { |
| 17 | const key = localStorage.key(index); |
| 18 | let entry; |
| 19 | try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; } |
| 20 | if (!entry || typeof entry !== 'object') continue; |
| 21 | if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]); |
| 22 | else plain.push(entry); |
| 23 | } |
| 24 | const openedEntries = []; |
| 25 | const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption=')); |
| 26 | let sealing = null; |
| 27 | try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {} |
| 28 | if (sealing && sealing.key && sealing.id && sealed.length) { |
| 29 | const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), (character) => character.charCodeAt(0)); |
| 30 | const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']); |
| 31 | for (const [key, entry] of sealed) { |
| 32 | if (entry.id !== sealing.id) continue; |
| 33 | const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), '']; |
| 34 | for (const context of new Set(contexts)) { |
| 35 | try { |
| 36 | const derived = await crypto.subtle.deriveKey( |
| 37 | {name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)}, |
| 38 | base, {name: 'AES-GCM', length: 256}, false, ['decrypt']); |
| 39 | const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data)); |
| 40 | openedEntries.push(JSON.parse(new TextDecoder().decode(data))); |
| 41 | break; |
| 42 | } catch (error) {} |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | const now = Date.now(); |
| 47 | const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0; |
| 48 | return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)}; |
| 49 | })()"#; |
| 50 | |
| 51 | /// True when the page holds a valid access token, either plain or decrypted from a sealed entry. |
| 52 | /// Key names and expired unsealed entries are ignored on purpose. |
| 53 | pub(crate) fn sign_in_ready_from_page(value: &Value) -> bool { |
| 54 | value |
| 55 | .get("freshAccess") |
| 56 | .and_then(Value::as_bool) |
| 57 | .unwrap_or(false) |
| 58 | } |
| 59 | |
| 60 | #[cfg(test)] |
| 61 | mod tests { |
| 62 | use super::*; |
| 63 | use serde_json::json; |
| 64 | |
| 65 | #[test] |
| 66 | fn key_names_without_a_usable_token_are_not_ready() { |
| 67 | let report = json!({"opened": 0, "freshAccess": false, "keyNames": true}); |
| 68 | assert!(!sign_in_ready_from_page(&report)); |
| 69 | } |
| 70 | |
| 71 | #[test] |
| 72 | fn opened_sealed_entries_without_a_fresh_access_token_are_not_ready() { |
| 73 | assert!(!sign_in_ready_from_page( |
| 74 | &json!({"opened": 3, "freshAccess": false}) |
| 75 | )); |
| 76 | } |
| 77 | |
| 78 | #[test] |
| 79 | fn a_fresh_access_token_is_ready_plain_or_sealed() { |
| 80 | assert!(sign_in_ready_from_page( |
| 81 | &json!({"opened": 0, "freshAccess": true}) |
| 82 | )); |
| 83 | assert!(sign_in_ready_from_page( |
| 84 | &json!({"opened": 2, "freshAccess": true}) |
| 85 | )); |
| 86 | } |
| 87 | |
| 88 | #[test] |
| 89 | fn a_missing_report_is_not_ready() { |
| 90 | assert!(!sign_in_ready_from_page(&json!({}))); |
| 91 | assert!(!sign_in_ready_from_page(&json!(null))); |
| 92 | } |
| 93 | } |