BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / task_dialog / sdk.rs

sdk.rs

sdk.rs 16.4 KiB Download Raw
1use serde_json::{Map, Value, json};
2
3pub const HOST_ORIGIN: &str = "https://teams.cloud.microsoft";
4pub const HOST_PAGE_PATH: &str = "/__rusty/dialog";
5const SDK_VERSION: &str = "2.1.0";
6const FRAME_CONTEXT: &str = "task";
7const CLIENT_TYPE: &str = "web";
8const HOST_NAME: &str = "Teams";
9const LOCALE: &str = "en-us";
10const NOT_SUPPORTED: &str = "not supported";
11const NO_SSO_RESOURCE: &str = "resourceDisabled";
12const TOKEN_MARGIN_MS: u64 = 60_000;
13const CHANNEL_SUFFIX: &str = "@thread.tacv2";
14const HOST_PAGE_TEMPLATE: &str = include_str!("host_page.html");
15
16pub fn host_page_url() -> String {
17 format!("{HOST_ORIGIN}{HOST_PAGE_PATH}")
18}
19
20#[derive(Debug, Clone, PartialEq)]
21pub struct HostContext {
22 pub user_id: String,
23 pub user_display_name: String,
24 pub tenant_id: String,
25 pub conversation_id: String,
26 pub app_id: String,
27 pub session_id: String,
28 pub dark: bool,
29 pub web_application_resource: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub enum Effect {
34 Submit(Value),
35 Resize {
36 width: Option<u32>,
37 height: Option<u32>,
38 },
39 OpenLink(String),
40}
41
42#[derive(Debug, Default, PartialEq)]
43pub struct Handled {
44 pub directives: Vec<Value>,
45 pub effect: Option<Effect>,
46}
47
48struct Request {
49 id: Value,
50 uuid: Value,
51 func: String,
52 args: Vec<Value>,
53}
54
55impl Request {
56 fn parse(envelope: &Value) -> Option<Request> {
57 let message = envelope.get("message")?;
58 Some(Request {
59 id: message.get("id").cloned().unwrap_or(Value::Null),
60 uuid: message.get("uuidAsString").cloned().unwrap_or(Value::Null),
61 func: message.get("func")?.as_str()?.to_owned(),
62 args: message
63 .get("args")
64 .and_then(Value::as_array)
65 .cloned()
66 .unwrap_or_default(),
67 })
68 }
69
70 fn reply(&self, args: Vec<Value>) -> Value {
71 json!({
72 "kind": "post",
73 "message": {"id": self.id, "uuidAsString": self.uuid, "args": args},
74 })
75 }
76
77 fn auth_token(&self, resource: &str) -> Value {
78 json!({
79 "kind": "authToken",
80 "id": self.id,
81 "uuidAsString": self.uuid,
82 "resource": resource,
83 })
84 }
85}
86
87pub fn handle(raw: &str, context: &HostContext) -> Handled {
88 let Ok(envelope) = serde_json::from_str::<Value>(raw) else {
89 return Handled::default();
90 };
91 match envelope.get("kind").and_then(Value::as_str) {
92 Some("sdk") => Request::parse(&envelope)
93 .map_or_else(Handled::default, |request| call(&request, context)),
94 Some("newWindow") => new_window(&envelope),
95 _ => Handled::default(),
96 }
97}
98
99fn new_window(envelope: &Value) -> Handled {
100 let link = envelope
101 .get("url")
102 .and_then(Value::as_str)
103 .unwrap_or_default();
104 Handled {
105 directives: Vec::new(),
106 effect: is_web_link(link).then(|| Effect::OpenLink(link.to_owned())),
107 }
108}
109
110fn is_web_link(link: &str) -> bool {
111 link.starts_with("https://") || link.starts_with("http://")
112}
113
114fn call(request: &Request, context: &HostContext) -> Handled {
115 match request.func.as_str() {
116 "initialize" => answer(request.reply(vec![
117 json!(FRAME_CONTEXT),
118 json!(CLIENT_TYPE),
119 json!(runtime_config().to_string()),
120 json!(SDK_VERSION),
121 ])),
122 "getContext" => answer(request.reply(vec![legacy_context(context)])),
123 "authentication.getAuthToken" => {
124 answer(match context.web_application_resource.as_deref() {
125 Some(resource) => request.auth_token(resource),
126 None => request.reply(vec![json!(false), json!(NO_SSO_RESOURCE)]),
127 })
128 }
129 "tasks.completeTask" | "tasks.submitTask" | "dialog.url.submit" => Handled {
130 directives: Vec::new(),
131 effect: request
132 .args
133 .first()
134 .filter(|result| !result.is_null())
135 .cloned()
136 .map(Effect::Submit),
137 },
138 "tasks.updateTask" | "dialog.update.resize" => Handled {
139 directives: Vec::new(),
140 effect: Some(resize_of(request.args.first())),
141 },
142 "executeDeepLink" | "app.openLink" => open_link(request),
143 "registerHandler" => register_handler(request, context),
144 name if is_notification(name) => Handled::default(),
145 _ => answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)])),
146 }
147}
148
149fn answer(directive: Value) -> Handled {
150 Handled {
151 directives: vec![directive],
152 effect: None,
153 }
154}
155
156fn is_notification(name: &str) -> bool {
157 name.starts_with("appInitialization.") || name == "readyToUnload" || name == "setFrameContext"
158}
159
160fn resize_of(dimensions: Option<&Value>) -> Effect {
161 let pixels = |key: &str| {
162 dimensions
163 .and_then(|dimensions| dimensions.get(key))
164 .and_then(Value::as_u64)
165 .and_then(|pixels| u32::try_from(pixels).ok())
166 };
167 Effect::Resize {
168 width: pixels("width"),
169 height: pixels("height"),
170 }
171}
172
173fn open_link(request: &Request) -> Handled {
174 let link = request
175 .args
176 .first()
177 .and_then(Value::as_str)
178 .unwrap_or_default();
179 if is_web_link(link) {
180 Handled {
181 directives: vec![request.reply(vec![json!(true)])],
182 effect: Some(Effect::OpenLink(link.to_owned())),
183 }
184 } else {
185 answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)]))
186 }
187}
188
189fn register_handler(request: &Request, context: &HostContext) -> Handled {
190 let wants_theme = request.args.first().and_then(Value::as_str) == Some("themeChange");
191 Handled {
192 directives: if wants_theme {
193 vec![json!({
194 "kind": "post",
195 "message": {"func": "themeChange", "args": [theme_name(context.dark)]},
196 })]
197 } else {
198 Vec::new()
199 },
200 effect: None,
201 }
202}
203
204fn theme_name(dark: bool) -> &'static str {
205 if dark { "dark" } else { "default" }
206}
207
208pub fn runtime_config() -> Value {
209 json!({
210 "apiVersion": 4,
211 "hostVersionsInfo": {"adaptiveCardSchemaVersion": {"major": 1, "minor": 5}},
212 "isLegacyTeams": true,
213 "supports": {
214 "dialog": {
215 "card": {"bot": {}},
216 "url": {"bot": {}, "parentCommunication": {}},
217 "update": {},
218 },
219 "logs": {},
220 "teamsCore": {},
221 },
222 })
223}
224
225pub fn legacy_context(context: &HostContext) -> Value {
226 let mut fields = Map::new();
227 let mut put = |key: &str, value: Value| {
228 fields.insert(key.to_owned(), value);
229 };
230 put("locale", json!(LOCALE));
231 put("theme", json!(theme_name(context.dark)));
232 put("frameContext", json!(FRAME_CONTEXT));
233 put("hostClientType", json!(CLIENT_TYPE));
234 put("hostName", json!(HOST_NAME));
235 put("sessionId", json!(context.session_id));
236 put("appSessionId", json!(context.session_id));
237 put("userObjectId", json!(context.user_id));
238 put("userDisplayName", json!(context.user_display_name));
239 put("tid", json!(context.tenant_id));
240 put("appId", json!(context.app_id));
241 put("isFullScreen", json!(false));
242 let conversation_key = if context.conversation_id.ends_with(CHANNEL_SUFFIX) {
243 "channelId"
244 } else {
245 "chatId"
246 };
247 put(conversation_key, json!(context.conversation_id));
248 Value::Object(fields)
249}
250
251pub struct HostPage<'a> {
252 pub task_url: &'a str,
253 pub background: u32,
254 pub token_acquirer_script: &'a str,
255}
256
257impl HostPage<'_> {
258 pub fn html(&self) -> String {
259 let config = json!({"url": self.task_url, "marginMs": TOKEN_MARGIN_MS});
260 let safe_config = config.to_string().replace('<', "\\u003c");
261 HOST_PAGE_TEMPLATE
262 .replace("__BACKGROUND__", &format!("#{:06x}", self.background))
263 .replace("__CONFIG__", &safe_config)
264 .replace("__ACQUIRE__", self.token_acquirer_script)
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 fn context() -> HostContext {
273 HostContext {
274 user_id: "user-1".into(),
275 user_display_name: "Ada".into(),
276 tenant_id: "tenant-1".into(),
277 conversation_id: "19:chat@thread.v2".into(),
278 app_id: "app-1".into(),
279 session_id: "session-1".into(),
280 dark: true,
281 web_application_resource: Some("api://bot.example/app-1".into()),
282 }
283 }
284
285 fn call(func: &str, args: Value) -> String {
286 json!({"kind": "sdk", "message": {"id": 7, "uuidAsString": "uuid-7", "func": func, "args": args}})
287 .to_string()
288 }
289
290 fn reply_args(handled: &Handled) -> Value {
291 handled.directives[0]["message"]["args"].clone()
292 }
293
294 #[test]
295 fn replies_carry_the_numeric_id_and_the_uuid_string() {
296 let handled = handle(&call("getContext", json!([])), &context());
297 let message = &handled.directives[0]["message"];
298 assert_eq!(handled.directives[0]["kind"], "post");
299 assert_eq!(message["id"], 7);
300 assert_eq!(message["uuidAsString"], "uuid-7");
301 }
302
303 #[test]
304 fn initialize_answers_a_task_frame_on_the_web_client_with_a_runtime_config_string() {
305 let handled = handle(&call("initialize", json!(["2.0.0", 4, []])), &context());
306 let args = reply_args(&handled);
307 assert_eq!(args[0], "task");
308 assert_eq!(args[1], "web");
309 let runtime: Value = serde_json::from_str(args[2].as_str().unwrap()).unwrap();
310 assert_eq!(runtime, runtime_config());
311 assert_eq!(args[3], SDK_VERSION);
312 assert!(handled.effect.is_none());
313 }
314
315 #[test]
316 fn the_runtime_config_supports_bot_url_dialogs_and_resizing() {
317 let runtime = runtime_config();
318 assert_eq!(runtime["apiVersion"], 4);
319 assert!(runtime["supports"]["dialog"]["url"]["bot"].is_object());
320 assert!(runtime["supports"]["dialog"]["update"].is_object());
321 }
322
323 #[test]
324 fn get_context_describes_the_user_tenant_chat_and_theme() {
325 let args = reply_args(&handle(&call("getContext", json!([])), &context()));
326 let legacy = &args[0];
327 assert_eq!(legacy["frameContext"], "task");
328 assert_eq!(legacy["hostClientType"], "web");
329 assert_eq!(legacy["hostName"], "Teams");
330 assert_eq!(legacy["locale"], "en-us");
331 assert_eq!(legacy["theme"], "dark");
332 assert_eq!(legacy["userObjectId"], "user-1");
333 assert_eq!(legacy["tid"], "tenant-1");
334 assert_eq!(legacy["chatId"], "19:chat@thread.v2");
335 assert_eq!(legacy["appSessionId"], "session-1");
336 assert!(legacy.get("channelId").is_none());
337 }
338
339 #[test]
340 fn channel_conversations_are_reported_as_channels() {
341 let mut channel = context();
342 channel.conversation_id = "19:abc@thread.tacv2".into();
343 let legacy = legacy_context(&channel);
344 assert_eq!(legacy["channelId"], "19:abc@thread.tacv2");
345 assert!(legacy.get("chatId").is_none());
346 }
347
348 #[test]
349 fn a_light_theme_is_called_default() {
350 let mut light = context();
351 light.dark = false;
352 assert_eq!(legacy_context(&light)["theme"], "default");
353 }
354
355 #[test]
356 fn auth_tokens_are_requested_from_the_page_for_the_app_resource() {
357 let handled = handle(
358 &call("authentication.getAuthToken", json!([[], null, false])),
359 &context(),
360 );
361 assert_eq!(
362 handled.directives,
363 vec![json!({
364 "kind": "authToken",
365 "id": 7,
366 "uuidAsString": "uuid-7",
367 "resource": "api://bot.example/app-1",
368 })]
369 );
370 }
371
372 #[test]
373 fn auth_tokens_fail_when_the_app_has_no_sso_resource() {
374 let mut without_resource = context();
375 without_resource.web_application_resource = None;
376 let handled = handle(
377 &call("authentication.getAuthToken", json!([])),
378 &without_resource,
379 );
380 assert_eq!(reply_args(&handled), json!([false, NO_SSO_RESOURCE]));
381 }
382
383 #[test]
384 fn submitting_hands_the_result_to_the_bot() {
385 for func in [
386 "tasks.completeTask",
387 "tasks.submitTask",
388 "dialog.url.submit",
389 ] {
390 let handled = handle(&call(func, json!([{"choice": "a"}, ["app-1"]])), &context());
391 assert_eq!(handled.effect, Some(Effect::Submit(json!({"choice": "a"}))));
392 assert!(handled.directives.is_empty());
393 }
394 }
395
396 #[test]
397 fn submitting_without_a_result_sends_nothing() {
398 let handled = handle(&call("tasks.completeTask", json!([])), &context());
399 assert_eq!(handled, Handled::default());
400 }
401
402 #[test]
403 fn resizing_takes_numeric_dimensions_only() {
404 let handled = handle(
405 &call(
406 "tasks.updateTask",
407 json!([{"width": 700, "height": "large"}]),
408 ),
409 &context(),
410 );
411 assert_eq!(
412 handled.effect,
413 Some(Effect::Resize {
414 width: Some(700),
415 height: None
416 })
417 );
418 }
419
420 #[test]
421 fn web_links_open_in_the_browser_and_other_schemes_are_refused() {
422 let handled = handle(
423 &call("executeDeepLink", json!(["https://example.com/page"])),
424 &context(),
425 );
426 assert_eq!(
427 handled.effect,
428 Some(Effect::OpenLink("https://example.com/page".into()))
429 );
430 assert_eq!(reply_args(&handled), json!([true]));
431 let refused = handle(
432 &call("executeDeepLink", json!(["file:///etc/passwd"])),
433 &context(),
434 );
435 assert!(refused.effect.is_none());
436 assert_eq!(reply_args(&refused), json!([false, NOT_SUPPORTED]));
437 }
438
439 #[test]
440 fn popups_of_the_page_open_in_the_browser() {
441 let popup = |url: &str| json!({"kind": "newWindow", "url": url}).to_string();
442 let handled = handle(&popup("https://example.com/docs"), &context());
443 assert_eq!(
444 handled.effect,
445 Some(Effect::OpenLink("https://example.com/docs".into()))
446 );
447 assert!(
448 handle(&popup("javascript:alert(1)"), &context())
449 .effect
450 .is_none()
451 );
452 }
453
454 #[test]
455 fn registering_a_theme_handler_pushes_the_current_theme() {
456 let handled = handle(&call("registerHandler", json!(["themeChange"])), &context());
457 assert_eq!(
458 handled.directives,
459 vec![json!({"kind": "post", "message": {"func": "themeChange", "args": ["dark"]}})]
460 );
461 let other = handle(&call("registerHandler", json!(["load"])), &context());
462 assert_eq!(other, Handled::default());
463 }
464
465 #[test]
466 fn lifecycle_notifications_are_not_answered() {
467 for func in [
468 "appInitialization.appLoaded",
469 "appInitialization.success",
470 "appInitialization.failure",
471 "readyToUnload",
472 ] {
473 assert_eq!(
474 handle(&call(func, json!([])), &context()),
475 Handled::default()
476 );
477 }
478 }
479
480 #[test]
481 fn unknown_calls_are_answered_as_unsupported() {
482 let handled = handle(&call("media.captureImage", json!([])), &context());
483 assert_eq!(reply_args(&handled), json!([false, NOT_SUPPORTED]));
484 }
485
486 #[test]
487 fn malformed_or_foreign_messages_are_ignored() {
488 for raw in [
489 "not json",
490 r#"{"kind":"other"}"#,
491 r#"{"kind":"sdk","message":{"id":1}}"#,
492 ] {
493 assert_eq!(handle(raw, &context()), Handled::default());
494 }
495 }
496
497 #[test]
498 fn the_host_page_embeds_the_task_url_and_cannot_be_broken_out_of() {
499 let page = HostPage {
500 task_url: "https://bot.example/task?x=</script><script>alert(1)",
501 background: 0x0f0f10,
502 token_acquirer_script: "(async () => () => null)",
503 }
504 .html();
505 assert!(page.contains("#0f0f10"));
506 assert!(page.contains("(async () => () => null)"));
507 assert!(page.contains(r"\u003c/script>\u003cscript>alert(1)"));
508 assert_eq!(page.matches("</script>").count(), 1);
509 assert!(
510 !page.contains("__CONFIG__")
511 && !page.contains("__ACQUIRE__")
512 && !page.contains("__BACKGROUND__")
513 );
514 }
515
516 #[test]
517 fn the_host_page_url_lives_on_an_origin_the_sdk_trusts() {
518 assert_eq!(
519 host_page_url(),
520 "https://teams.cloud.microsoft/__rusty/dialog"
521 );
522 }
523}