fix(session): read tokens from a sealed MSAL cache
Right after the first sign-in, Outlook web seals its MSAL localStorage cache (AES-GCM, key in the msal.cache.encryption session cookie). The fetch script only read plaintext entries, so it found no Graph token and the app stayed on "Sign-in required" until a restart. The fetch script now opens sealed entries in the page the same way MSAL.js does (HKDF-SHA-256 with the entry nonce and client id, then AES-GCM), so tokens still never leave the page. A missing token now also reports the page's plain, sealed and opened entry counts in its detail.
@@ -3,15 +3,55 @@
3
3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
4
4
const covers = (value, name) => value === name || value === name + '.all';
5
5
const entries = [];
6
const sealed = [];
6
7
let activeHome = null;
8
let opened = 0;
9
const take = (key, entry) => {
10
if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId;
11
if (typeof entry.secret === 'string') entries.push(entry);
12
};
7
13
for (let index = 0; index < localStorage.length; index++) {
8
14
const key = localStorage.key(index);
9
15
let entry;
10
16
try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; }
11
17
if (!entry || typeof entry !== 'object') continue;
12
if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId;
13
if (typeof entry.secret === 'string') entries.push(entry);
18
if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);
19
else take(key, entry);
14
20
}
21
const plain = entries.length;
22
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.
23
const unseal = async () => {
24
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
25
let sealing = null;
26
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
27
if (!sealing || !sealing.key || !sealing.id) return;
28
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),
29
(character) => character.charCodeAt(0));
30
const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());
31
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
32
for (const [key, entry] of sealed) {
33
if (entry.id !== sealing.id) continue;
34
if (!memo.has(entry.nonce)) {
35
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.
36
const contexts = [...(key.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
37
for (const context of new Set(contexts)) {
38
try {
39
const derived = await crypto.subtle.deriveKey(
40
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
41
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
42
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
43
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));
44
break;
45
} catch (error) {}
46
}
47
}
48
if (memo.has(entry.nonce)) {
49
take(key, memo.get(entry.nonce));
50
opened++;
51
}
52
}
53
};
54
if (sealed.length) await unseal();
15
55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
16
56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
17
57
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
@@ -61,7 +101,8 @@
61
101
return {token, refreshError};
62
102
};
63
103
const {token, refreshError} = await acquire(resource, scope);
64
if (!token) return {noToken: true, refreshError};
104
const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};
105
if (!token) return {noToken: true, refreshError, page};
65
106
const run = async (request) => {
66
107
try {
67
108
let requestBody = request.body;
@@ -3,15 +3,55 @@3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');4
const covers = (value, name) => value === name || value === name + '.all';4
const covers = (value, name) => value === name || value === name + '.all';5
const entries = [];5
const entries = [];6
const sealed = [];6
let activeHome = null;7
let activeHome = null;8
let opened = 0;9
const take = (key, entry) => {10
if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId;11
if (typeof entry.secret === 'string') entries.push(entry);12
};7
for (let index = 0; index < localStorage.length; index++) {13
for (let index = 0; index < localStorage.length; index++) {8
const key = localStorage.key(index);14
const key = localStorage.key(index);9
let entry;15
let entry;10
try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; }16
try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; }11
if (!entry || typeof entry !== 'object') continue;17
if (!entry || typeof entry !== 'object') continue;12
if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId;18
if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);13
if (typeof entry.secret === 'string') entries.push(entry);19
else take(key, entry);14
}20
}21
const plain = entries.length;22
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.23
const unseal = async () => {24
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));25
let sealing = null;26
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}27
if (!sealing || !sealing.key || !sealing.id) return;28
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),29
(character) => character.charCodeAt(0));30
const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());31
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);32
for (const [key, entry] of sealed) {33
if (entry.id !== sealing.id) continue;34
if (!memo.has(entry.nonce)) {35
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.36
const contexts = [...(key.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];37
for (const context of new Set(contexts)) {38
try {39
const derived = await crypto.subtle.deriveKey(40
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},41
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);42
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));43
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));44
break;45
} catch (error) {}46
}47
}48
if (memo.has(entry.nonce)) {49
take(key, memo.get(entry.nonce));50
opened++;51
}52
}53
};54
if (sealed.length) await unseal();15
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;16
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];17
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});57
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});@@ -61,7 +101,8 @@61
return {token, refreshError};101
return {token, refreshError};62
};102
};63
const {token, refreshError} = await acquire(resource, scope);103
const {token, refreshError} = await acquire(resource, scope);64
if (!token) return {noToken: true, refreshError};104
const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};105
if (!token) return {noToken: true, refreshError, page};65
const run = async (request) => {106
const run = async (request) => {66
try {107
try {67
let requestBody = request.body;108
let requestBody = request.body;@@ -7,7 +7,7 @@ use crate::request::Outcome;
7
7
use crate::scope::Scope;
8
8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};
9
9
10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";
10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError, page};";
11
11
const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);";
12
12
13
13
/// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`.
@@ -69,11 +69,14 @@ impl Session {
69
69
"{app} app is not granted {scope}"
70
70
)));
71
71
}
72
let detail = if reason.is_empty() {
72
let mut detail = if reason.is_empty() {
73
73
String::new()
74
74
} else {
75
75
format!(" (token refresh failed in {app}: {reason})")
76
76
};
77
if let Some(page) = outcome.page {
78
detail.push_str(&format!(" [{app}: {page}]"));
79
}
77
80
return Err(Error::NoFreshToken {
78
81
scope: scope.to_string(),
79
82
detail,
@@ -7,7 +7,7 @@ use crate::request::Outcome;7
use crate::scope::Scope;7
use crate::scope::Scope;8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};9
9
10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError, page};";11
const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);";11
const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);";12
12
13
/// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`.13
/// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`.@@ -69,11 +69,14 @@ impl Session {69
"{app} app is not granted {scope}"69
"{app} app is not granted {scope}"70
)));70
)));71
}71
}72
let detail = if reason.is_empty() {72
let mut detail = if reason.is_empty() {73
String::new()73
String::new()74
} else {74
} else {75
format!(" (token refresh failed in {app}: {reason})")75
format!(" (token refresh failed in {app}: {reason})")76
};76
};77
if let Some(page) = outcome.page {78
detail.push_str(&format!(" [{app}: {page}]"));79
}77
return Err(Error::NoFreshToken {80
return Err(Error::NoFreshToken {78
scope: scope.to_string(),81
scope: scope.to_string(),79
detail,82
detail,@@ -178,6 +178,28 @@ pub(crate) struct Outcome {
178
178
pub results: Option<Vec<WireResult>>,
179
179
#[serde(default, rename = "refreshError")]
180
180
pub refresh_error: Option<String>,
181
#[serde(default)]
182
pub page: Option<PageState>,
183
}
184
185
/// What the page held when it had no token, to tell an unreadable cache apart from a missing sign-in.
186
#[derive(Debug, Deserialize)]
187
pub(crate) struct PageState {
188
pub visibility: String,
189
pub plain: usize,
190
pub sealed: usize,
191
#[serde(default)]
192
pub opened: usize,
193
}
194
195
impl std::fmt::Display for PageState {
196
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197
write!(
198
formatter,
199
"page {}, {} plain / {} sealed cache entries ({} opened)",
200
self.visibility, self.plain, self.sealed, self.opened
201
)
202
}
181
203
}
182
204
183
205
impl From<WireResult> for ApiResponse {
@@ -291,4 +313,17 @@ mod tests {
291
313
assert!(outcome.results.is_none());
292
314
assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
293
315
}
316
317
#[test]
318
fn describes_the_page_state_of_a_no_token_outcome() {
319
let outcome: Outcome = serde_json::from_value(json!({
320
"noToken": true,
321
"page": {"visibility": "hidden", "plain": 3, "sealed": 40, "opened": 38},
322
}))
323
.unwrap();
324
assert_eq!(
325
outcome.page.unwrap().to_string(),
326
"page hidden, 3 plain / 40 sealed cache entries (38 opened)"
327
);
328
}
294
329
}
@@ -178,6 +178,28 @@ pub(crate) struct Outcome {178
pub results: Option<Vec<WireResult>>,178
pub results: Option<Vec<WireResult>>,179
#[serde(default, rename = "refreshError")]179
#[serde(default, rename = "refreshError")]180
pub refresh_error: Option<String>,180
pub refresh_error: Option<String>,181
#[serde(default)]182
pub page: Option<PageState>,183
}184
185
/// What the page held when it had no token, to tell an unreadable cache apart from a missing sign-in.186
#[derive(Debug, Deserialize)]187
pub(crate) struct PageState {188
pub visibility: String,189
pub plain: usize,190
pub sealed: usize,191
#[serde(default)]192
pub opened: usize,193
}194
195
impl std::fmt::Display for PageState {196
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {197
write!(198
formatter,199
"page {}, {} plain / {} sealed cache entries ({} opened)",200
self.visibility, self.plain, self.sealed, self.opened201
)202
}181
}203
}182
204
183
impl From<WireResult> for ApiResponse {205
impl From<WireResult> for ApiResponse {@@ -291,4 +313,17 @@ mod tests {291
assert!(outcome.results.is_none());313
assert!(outcome.results.is_none());292
assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));314
assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));293
}315
}316
317
#[test]318
fn describes_the_page_state_of_a_no_token_outcome() {319
let outcome: Outcome = serde_json::from_value(json!({320
"noToken": true,321
"page": {"visibility": "hidden", "plain": 3, "sealed": 40, "opened": 38},322
}))323
.unwrap();324
assert_eq!(325
outcome.page.unwrap().to_string(),326
"page hidden, 3 plain / 40 sealed cache entries (38 opened)"327
);328
}294
}329
}@@ -50,6 +50,7 @@ impl Default for SessionConfig {
50
50
#[derive(Default)]
51
51
struct TokenSearch {
52
52
refresh_error: Option<String>,
53
pages: Vec<String>,
53
54
ungranted: HashSet<App>,
54
55
}
55
56
@@ -168,10 +169,13 @@ impl Session {
168
169
if !diagnosis.app_tab_open {
169
170
return Err(Error::NoAppTab);
170
171
}
171
let detail = search
172
let mut detail = search
172
173
.refresh_error
173
174
.map(|reason| format!(" (token refresh failed in {reason})"))
174
175
.unwrap_or_default();
176
if !search.pages.is_empty() {
177
detail.push_str(&format!(" [{}]", search.pages.join("; ")));
178
}
175
179
Err(Error::NoFreshToken {
176
180
scope: scope.to_string(),
177
181
detail,
@@ -204,6 +208,11 @@ impl Session {
204
208
if let Some(results) = outcome.results {
205
209
return Ok(Some(results.into_iter().map(WireResult::into).collect()));
206
210
}
211
if let Some(page) = &outcome.page {
212
let line = format!("{app}: {page}");
213
search.pages.retain(|seen| !seen.starts_with(&format!("{app}:")));
214
search.pages.push(line);
215
}
207
216
if let Some(reason) = outcome.refresh_error {
208
217
if reason.starts_with(NOT_GRANTED_PREFIX) {
209
218
search.ungranted.insert(app);
@@ -50,6 +50,7 @@ impl Default for SessionConfig {50
#[derive(Default)]50
#[derive(Default)]51
struct TokenSearch {51
struct TokenSearch {52
refresh_error: Option<String>,52
refresh_error: Option<String>,53
pages: Vec<String>,53
ungranted: HashSet<App>,54
ungranted: HashSet<App>,54
}55
}55
56
@@ -168,10 +169,13 @@ impl Session {168
if !diagnosis.app_tab_open {169
if !diagnosis.app_tab_open {169
return Err(Error::NoAppTab);170
return Err(Error::NoAppTab);170
}171
}171
let detail = search172
let mut detail = search172
.refresh_error173
.refresh_error173
.map(|reason| format!(" (token refresh failed in {reason})"))174
.map(|reason| format!(" (token refresh failed in {reason})"))174
.unwrap_or_default();175
.unwrap_or_default();176
if !search.pages.is_empty() {177
detail.push_str(&format!(" [{}]", search.pages.join("; ")));178
}175
Err(Error::NoFreshToken {179
Err(Error::NoFreshToken {176
scope: scope.to_string(),180
scope: scope.to_string(),177
detail,181
detail,@@ -204,6 +208,11 @@ impl Session {204
if let Some(results) = outcome.results {208
if let Some(results) = outcome.results {205
return Ok(Some(results.into_iter().map(WireResult::into).collect()));209
return Ok(Some(results.into_iter().map(WireResult::into).collect()));206
}210
}211
if let Some(page) = &outcome.page {212
let line = format!("{app}: {page}");213
search.pages.retain(|seen| !seen.starts_with(&format!("{app}:")));214
search.pages.push(line);215
}207
if let Some(reason) = outcome.refresh_error {216
if let Some(reason) = outcome.refresh_error {208
if reason.starts_with(NOT_GRANTED_PREFIX) {217
if reason.starts_with(NOT_GRANTED_PREFIX) {209
search.ungranted.insert(app);218
search.ungranted.insert(app);