1use crate::*;
2use rmcp::{
3 ErrorData, RoleServer, ServerHandler,
4 model::{
5 CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock,
6 ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
7 ToolAnnotations,
8 },
9 service::RequestContext,
10};
11use scraper::{Html, Selector};
12
13const MODEL_PATTERN: &str = r"^[a-z0-9][a-z0-9._-]{0,127}$";
14
15pub struct Backend {
16 pub(crate) origin: url::Url,
17 http: reqwest::Client,
18 slots: Semaphore,
19}
20impl Backend {
21 pub fn new(address: &str, http: reqwest::ClientBuilder) -> Result<Self> {
22 let origin = url::Url::parse(address)?;
23 if origin.scheme() != "https"
24 || origin.host_str().is_none()
25 || !origin.username().is_empty()
26 || origin.password().is_some()
27 || origin.path() != "/"
28 || origin.query().is_some()
29 || origin.fragment().is_some()
30 {
31 return Err(Error::new(500, "Set an HTTPS origin for Shale."));
32 }
33 Ok(Self {
34 origin,
35 http: http
36 .redirect(reqwest::redirect::Policy::none())
37 .retry(reqwest::retry::never())
38 .build()?,
39 slots: Semaphore::new(8),
40 })
41 }
42 async fn get(
43 &self,
44 path: &str,
45 session: Option<&str>,
46 ) -> Result<(StatusCode, HeaderMap, String)> {
47 self.request(self.origin.join(path)?, session, "text/html")
48 .await
49 }
50 async fn request(
51 &self,
52 target: url::Url,
53 session: Option<&str>,
54 accept: &str,
55 ) -> Result<(StatusCode, HeaderMap, String)> {
56 if target.origin() != self.origin.origin()
57 || !target.username().is_empty()
58 || target.password().is_some()
59 || target.fragment().is_some()
60 {
61 return Err(Error::new(400, "Open a page on this Shale instance."));
62 }
63 let _slot = tokio::time::timeout(Duration::from_secs(5), self.slots.acquire())
64 .await
65 .map_err(|_| Error::new(429, "Shale is busy. Try again in a moment."))??;
66 let mut request = self.http.get(target.clone()).header("accept", accept);
67 if let Some(session) = session {
68 let mut cookie = axum::http::HeaderValue::from_str(&format!("SessionID={session}"))?;
69 cookie.set_sensitive(true);
70 request = request.header("cookie", cookie);
71 }
72 let mut response = request
73 .send()
74 .await
75 .map_err(|_| Error::new(502, "Shale couldn't answer. Open it and check its status."))?;
76 let status = response.status();
77 let headers = response.headers().clone();
78 let mut body = Vec::new();
79 while let Some(chunk) = response.chunk().await.map_err(|_| {
80 Error::new(
81 502,
82 "The Shale response was interrupted. Open it to check the result.",
83 )
84 })? {
85 if body.len() + chunk.len() > 4 * 1024 * 1024 {
86 return Err(Error::new(
87 502,
88 "The Shale page is too large. Narrow the selection.",
89 ));
90 }
91 body.extend_from_slice(&chunk);
92 }
93 Ok((status, headers, String::from_utf8(body)?))
94 }
95 async fn page(&self, target: &url::Url, session: &str, accept: &str) -> Result<String> {
96 let (status, _, body) = self
97 .request(target.clone(), Some(session), accept)
98 .await?;
99 match status {
100 StatusCode::OK => Ok(body),
101 StatusCode::BAD_REQUEST => Err(Error::new(
102 400,
103 "Shale rejected this request. Check the fields or use Shale's issue filter syntax.",
104 )),
105 StatusCode::FORBIDDEN | StatusCode::NOT_FOUND => Err(Error::new(
106 403,
107 "Shale doesn't allow access to this repository. Check your account's permissions.",
108 )),
109 status if status.is_redirection() || status == StatusCode::UNAUTHORIZED => {
110 Err(Error::new(401, "The Shale session expired. Link it again."))
111 }
112 _ => Err(Error::new(
113 502,
114 "Shale couldn't open this page. Check it in Shale.",
115 )),
116 }
117 }
118 async fn json(&self, target: &url::Url, session: &str) -> Result<Value> {
119 let body = self.page(target, session, "application/json").await?;
120 serde_json::from_str(&body)
121 .map_err(|_| Error::new(502, "Shale didn't return JSON. Open it to check the result."))
122 }
123}
124
125fn text(element: scraper::ElementRef<'_>) -> String {
126 element.text().collect::<String>().trim().to_owned()
127}
128fn repository_path(origin: &url::Url, repository: &str, suffix: &[&str]) -> Result<url::Url> {
129 if repository.is_empty()
130 || repository.len() > 255
131 || repository
132 .split('/')
133 .any(|part| matches!(part, "" | "." | ".." | "-"))
134 || repository
135 .chars()
136 .any(|c| c.is_control() || c.is_whitespace() || "\\%?#".contains(c))
137 {
138 return Err(Error::new(
139 400,
140 "Choose a repository from this connection's access.",
141 ));
142 }
143 let mut target = origin.clone();
144 target
145 .path_segments_mut()
146 .unwrap()
147 .clear()
148 .extend(repository.split('/'))
149 .extend(suffix.iter().copied());
150 Ok(target)
151}
152fn session(app: &App, owner: &str) -> Result<String> {
153 let credential = mcp::get(
154 &app.mcp.db.lock().unwrap(),
155 &format!("shale-session:{owner}"),
156 )?;
157 if credential["origin"] != app.shale.origin.as_str() {
158 return Err(Error::new(
159 401,
160 "Link your Shale account from the dashboard's MCP tab.",
161 ));
162 }
163 credential["session"]
164 .as_str()
165 .map(str::to_owned)
166 .ok_or_else(|| Error::new(401, "Link your Shale account from the dashboard's MCP tab."))
167}
168pub(crate) async fn verified_session(app: &App, owner: &str) -> Result<String> {
169 let session = session(app, owner)?;
170 username(
171 &app.shale
172 .page(&app.shale.origin.join("/-/settings")?, &session, "text/html")
173 .await?,
174 )?;
175 Ok(session)
176}
177pub async fn repositories(app: &App, owner: &str) -> Result<Vec<Value>> {
178 let session = verified_session(app, owner).await?;
179 let value = app.shale.json(&app.shale.origin, &session).await?;
180 let entries = value.as_array().filter(|v| v.len() <= 1024)
181 .ok_or_else(|| Error::new(502, "Shale's repository list changed. Open Shale to browse it."))?;
182 let mut repositories = Vec::new();
183 for entry in entries {
184 let name = entry["name"].as_str()
185 .ok_or_else(|| Error::new(502, "Shale's repository list changed. Open Shale to browse it."))?;
186 repository_path(&app.shale.origin, name, &[""])?;
187 if repositories.iter().any(|r: &Value| r["id"] == name) {
188 return Err(Error::new(502, "Shale's repository list changed. Open Shale to browse it."));
189 }
190 repositories.push(json!({"id":name,"name":name,"description":entry["description"]}));
191 }
192 Ok(repositories)
193}
194fn issue(value: Value, repository: &str, id: u64) -> Result<Value> {
195 let issue = &value["issue"];
196 if id == 0 || issue["number"].as_u64() != Some(id)
197 || !issue["title"].as_str().is_some_and(|s| !s.is_empty())
198 || !issue["status"].as_str().is_some_and(|s| !s.is_empty())
199 || !value["actions"].is_array() || !value["labels"].is_array()
200 {
201 return Err(Error::new(502, "Shale's issue response changed. Open the issue to check it."));
202 }
203 let comments: Vec<_> = array(&value["actions"]).iter()
204 .filter(|action| action["kind"] == "comment" && action["deleted_on"].is_null())
205 .map(|action| json!({"author":action["actor"],"createdAt":action["added_on"],"text":action["payload"]}))
206 .collect();
207 Ok(json!({"repository":repository,"id":id,"title":issue["title"],"status":issue["status"],"labels":value["labels"],"comments":comments}))
208}
209
210fn labels(html: &str, repository: &str) -> Result<Value> {
211 let document = Html::parse_document(html);
212 if document.select(&Selector::parse("body#page-labels").unwrap()).next().is_none()
213 || document.select(&Selector::parse("meta[name='astheno.shale.repo.name']").unwrap()).next()
214 .and_then(|meta| meta.attr("content")) != Some(repository)
215 {
216 return Err(Error::new(502, "Shale's label page changed. Open its labels page."));
217 }
218 let mut labels = Vec::new();
219 for row in document.select(&Selector::parse(".grid-container table tbody tr").unwrap()) {
220 let cells: Vec<_> = row.select(&Selector::parse("td").unwrap()).collect();
221 let label = row
222 .select(&Selector::parse("a.issuelabel[data-label-id][data-color]").unwrap())
223 .next();
224 if cells.len() != 3 || label.is_none() {
225 return Err(Error::new(
226 502,
227 "Shale's label list changed. Open its labels page.",
228 ));
229 }
230 let label = label.unwrap();
231 let id = label
232 .attr("data-label-id")
233 .and_then(|s| s.parse::<u64>().ok())
234 .filter(|id| *id > 0)
235 .ok_or_else(|| Error::new(502, "Shale's label IDs changed. Open its labels page."))?;
236 let open = text(cells[2])
237 .parse::<u64>()
238 .map_err(|_| Error::new(502, "Shale's label counts changed. Open its labels page."))?;
239 labels.push(json!({"id":id,"name":text(label),"description":text(cells[1]),"color":label.attr("data-color"),"openIssues":open}));
240 }
241 Ok(json!({"repository":repository,"labels":labels}))
242}
243
244fn current(app: &App, grant: &Value, credential: &str) -> Result<()> {
245 let db = app.mcp.db.lock().unwrap();
246 if mcp::get(&db, &format!("grant:{}", string(&grant["id"])))? != *grant
247 || mcp::get(&db, &format!("shale-session:{}", string(&grant["user"])))?["session"]
248 != credential
249 {
250 return Err(Error::new(
251 401,
252 "This connection changed or was revoked. Connect again.",
253 ));
254 }
255 Ok(())
256}
257
258#[derive(Clone)]
259struct Shale(Arc<App>);
260impl ServerHandler for Shale {
261 fn get_info(&self) -> ServerConfig {
262 ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
263 .with_instructions("Every write requires the actual model identifier in model and uses a durable ai-[owner]-[model] account on behalf of the connection owner. Never invent a model or supply a different owner. Label writes require the repository owner’s connection. Status writes require the owner’s connection or an explicit repository delegation. Issue text automatically receives an Assisted-by trailer matching model. Create confirmed tasks with status todo; use triage for unanswered questions (the default). Never retry an uncertain write without reading its outcome.")
264 }
265 async fn list_tools(
266 &self,
267 _: Option<PaginatedRequestParams>,
268 _: RequestContext<RoleServer>,
269 ) -> std::result::Result<ListToolsResult, ErrorData> {
270 let tools = [
271 ("list_repositories", "List repositories granted to this connection.", json!({}), json!([]), true),
272 ("list_issues", "List issues in one granted repository.", json!({"repository":{"type":"string"},"q":{"type":"string","maxLength":4096,"description":"Shale filters using is, status, sort, limit, label, or author prefixes, such as is:open. Plain text search is unsupported."}}), json!(["repository"]), true),
273 ("list_labels", "List repository label IDs, names, descriptions, colors, and open issue counts.", json!({"repository":{"type":"string"}}), json!(["repository"]), true),
274 ("create_label", "Create a repository label using its owner's connection.", json!({"repository":{"type":"string"},"name":{"type":"string","minLength":1,"maxLength":256},"description":{"type":"string","maxLength":4096},"color":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$"}}), json!(["repository","name","description","color"]), false),
275 ("update_label", "Replace a label's name, description, and color using its owner's connection.", json!({"repository":{"type":"string"},"label_id":{"type":"integer","minimum":1},"name":{"type":"string","minLength":1,"maxLength":256},"description":{"type":"string","maxLength":4096},"color":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$"}}), json!(["repository","label_id","name","description","color"]), false),
276 ("delete_label", "Delete a repository label using its owner's connection. Labels referenced by issue history cannot be deleted.", json!({"repository":{"type":"string"},"label_id":{"type":"integer","minimum":1}}), json!(["repository","label_id"]), false),
277 ("set_issue_labels", "Replace an issue's labels with repository label IDs using its owner's connection. An empty array clears them.", json!({"repository":{"type":"string"},"id":{"type":"integer","minimum":1},"labels":{"type":"array","items":{"type":"integer","minimum":1},"maxItems":100,"uniqueItems":true}}), json!(["repository","id","labels"]), false),
278 ("get_issue", "Read an issue with rendered comment text and labels.", json!({"repository":{"type":"string"},"id":{"type":"integer","minimum":1}}), json!(["repository","id"]), true),
279 ("create_issue", "Create an issue. If the outcome is unknown, inspect the repository before retrying.", json!({"repository":{"type":"string"},"title":{"type":"string","minLength":1,"maxLength":4096},"description":{"type":"string","maxLength":262144},"status":{"type":"string","enum":["todo","triage"],"default":"triage","description":"todo for confirmed tasks; triage for unanswered questions."}}), json!(["repository","title"]), false),
280 ("comment_issue", "Add a comment. If the outcome is unknown, inspect the issue before retrying.", json!({"repository":{"type":"string"},"id":{"type":"integer","minimum":1},"comment":{"type":"string","minLength":1,"maxLength":262144}}), json!(["repository","id","comment"]), false),
281 ("set_issue_status", "Change issue status using an available Shale status.", json!({"repository":{"type":"string"},"id":{"type":"integer","minimum":1},"status":{"type":"string","maxLength":64}}), json!(["repository","id","status"]), false),
282 ("set_issue_title", "Change an issue title.", json!({"repository":{"type":"string"},"id":{"type":"integer","minimum":1},"title":{"type":"string","minLength":1,"maxLength":4096}}), json!(["repository","id","title"]), false),
283 ].into_iter().map(|(name, description, properties, required, read)| {
284 let mut properties = properties;
285 let mut required = required;
286 if !read {
287 properties["model"] = json!({"type":"string","pattern":MODEL_PATTERN,"description":"Actual model identifier; determines the durable author account."});
288 required.as_array_mut().unwrap().push(json!("model"));
289 }
290 Tool::new(name, description, json!({"type":"object","properties":properties,"required":required,"additionalProperties":false}).as_object().unwrap().clone())
291 .with_annotations(ToolAnnotations::new().read_only(read).idempotent(read))
292 }).collect();
293 Ok(ListToolsResult {
294 tools,
295 ttl_ms: Some(0),
296 cache_scope: Some(CacheScope::Private),
297 ..Default::default()
298 })
299 }
300 async fn call_tool(
301 &self,
302 request: CallToolRequestParams,
303 context: RequestContext<RoleServer>,
304 ) -> std::result::Result<CallToolResponse, ErrorData> {
305 let result: Result<Value> = async {
306 let app = &self.0;
307 let grant = &context.extensions.get::<axum::http::request::Parts>()
308 .and_then(|p| p.extensions.get::<mcp::Grant>())
309 .ok_or_else(|| Error::new(401, "This connection expired. Connect again."))?.0;
310 let name = request.name.as_ref();
311 let arguments = request.arguments.unwrap_or_default();
312 let allowed: &[&str] = match name {
313 "list_repositories" => &[], "list_issues" => &["repository", "q"], "get_issue" => &["repository", "id"],
314 "list_labels" => &["repository"], "create_label" => &["repository", "name", "description", "color"],
315 "update_label" => &["repository", "label_id", "name", "description", "color"], "delete_label" => &["repository", "label_id"],
316 "set_issue_labels" => &["repository", "id", "labels"],
317 "create_issue" => &["repository", "title", "description", "status"], "comment_issue" => &["repository", "id", "comment"],
318 "set_issue_status" => &["repository", "id", "status"], "set_issue_title" => &["repository", "id", "title"],
319 _ => return Err(Error::new(404, "No tool with that name.")),
320 };
321 if arguments.keys().any(|key| key != "model" && !allowed.contains(&key.as_str())) {
322 return Err(Error::new(400, "Use the fields listed for this tool."));
323 }
324 let write = !matches!(name, "list_repositories" | "list_issues" | "list_labels" | "get_issue");
325 if !array(&grant["scopes"]).iter().any(|s| s == if write {"shale:write"} else {"shale:read"}) {
326 return Err(Error::new(403, "This connection allows reads only. Connect again to request issue editing."));
327 }
328 let model = if write {
329 Some(arguments.get("model").and_then(Value::as_str)
330 .filter(|id| regex::Regex::new(MODEL_PATTERN).unwrap().is_match(id))
331 .ok_or_else(|| Error::new(400, "Supply the actual model identifier in model."))?)
332 } else {
333 if arguments.contains_key("model") { return Err(Error::new(400, "Read tools do not need a model.")); }
334 None
335 };
336 let model = model.map(|id| if id == "qwen3.8-27b" { "qwen-3.8-27b" } else { id });
337 let credential = session(app, string(&grant["user"]))?;
338 current(app, grant, &credential)?;
339 if name == "list_repositories" {
340 let mut repositories = repositories(app, string(&grant["user"])).await?;
341 repositories.retain(|r| grant["resources"] == "all" || array(&grant["resources"]).contains(&r["id"]));
342 current(app, grant, &credential)?;
343 return Ok(json!({"repositories":repositories}));
344 }
345 let repository = arguments.get("repository").and_then(Value::as_str)
346 .filter(|r| grant["resources"] == "all" || array(&grant["resources"]).iter().any(|id| id == *r))
347 .ok_or_else(|| Error::new(403, "Choose a repository granted to this connection."))?;
348 if matches!(name, "create_label" | "update_label" | "delete_label" | "set_issue_labels") {
349 let mut fields = arguments.clone();
350 fields.remove("repository");
351 current(app, grant, &credential)?;
352 let result = host::call(json!({"operation":"shale.write","grant":grant["id"],"repository":repository,"action":name,"arguments":fields})).await.map_err(|error| if error.status >= 500 { Error::new(502, "The label write outcome is unknown. Check the labels in Shale before retrying.") } else { error })?;
353 current(app, grant, &credential).map_err(|_| Error::new(502, "The label write outcome is unknown. Check the labels in Shale before retrying."))?;
354 return Ok(result);
355 }
356 if name == "list_labels" {
357 let target = repository_path(&app.shale.origin, repository, &["issues", "labels"])?;
358 let result = labels(&app.shale.page(&target, &credential, "text/html").await?, repository)?;
359 current(app, grant, &credential)?;
360 return Ok(result);
361 }
362 let mut target = repository_path(&app.shale.origin, repository, &["issues", ""])?;
363 let issue_id = if matches!(name, "list_issues" | "create_issue") { None } else {
364 Some(arguments.get("id").and_then(Value::as_u64).filter(|n| *n > 0)
365 .ok_or_else(|| Error::new(400, "Choose a positive issue ID."))?)
366 };
367 if let Some(id) = issue_id { target = repository_path(&app.shale.origin, repository, &["issues", &id.to_string()])?; }
368 if let Some(q) = arguments.get("q") {
369 let q = q.as_str().filter(|q| q.len() <= 4096).ok_or_else(|| Error::new(400, "Narrow the issue search."))?;
370 target.query_pairs_mut().append_pair("q", q);
371 }
372 let mut fields = HashMap::new();
373 for (key, max) in [("title", 4096), ("description", 262144), ("comment", 262144), ("status", 64)] {
374 if allowed.contains(&key) && !(key == "status" && name == "create_issue") {
375 let value = arguments.get(key).and_then(Value::as_str)
376 .filter(|v| v.len() <= max && (key == "description" || !v.trim().is_empty()))
377 .or_else(|| (key == "description" && !arguments.contains_key(key)).then_some(""))
378 .ok_or_else(|| Error::new(400, format!("Enter {key} within the tool's size limit.")))?;
379 fields.insert(key.to_owned(), value.to_owned());
380 }
381 }
382 if matches!(name, "create_issue" | "comment_issue") {
383 let model = model.unwrap();
384 let field = if name == "create_issue" { "description" } else { "comment" };
385 let body = fields.get_mut(field).unwrap();
386 if let Some(existing) = crate::shale_page::assisted_model(body) {
387 if existing != model { return Err(Error::new(400, "The model and Assisted-by trailer differ. Use the actual model identifier in both.")); }
388 } else {
389 *body = format!("{}\n\nAssisted-by: {model}", body.trim_end());
390 if crate::shale_page::assisted_model(body) != Some(model) { return Err(Error::new(400, "Close the code block before adding the model trailer.")); }
391 if body.len() > 262144 { return Err(Error::new(400, "Shorten the comment to leave room for its Assisted-by trailer.")); }
392 }
393 }
394 username(&app.shale.page(&app.shale.origin.join("/-/settings")?, &credential, "text/html").await?)?;
395 if name == "list_issues" {
396 let value = app.shale.json(&target, &credential).await?;
397 let rows = value.as_array()
398 .ok_or_else(|| Error::new(502, "Shale's issue list changed. Open it in Shale."))?;
399 let mut issues = Vec::new();
400 for row in rows {
401 let id = row["number"].as_u64().filter(|id| *id > 0)
402 .ok_or_else(|| Error::new(502, "Shale's issue list changed. Open it in Shale."))?;
403 issues.push(json!({"id":id,"title":row["title"],"status":row["status"],"author":row["author"],"modifiedAt":row["last_updated"]}));
404 }
405 current(app, grant, &credential)?;
406 return Ok(json!({"repository":repository,"issues":issues}));
407 }
408 if !write {
409 let issue = issue(app.shale.json(&target, &credential).await?, repository, issue_id.unwrap())?;
410 current(app, grant, &credential)?;
411 return Ok(json!({"issue":issue}));
412 }
413 if name == "create_issue" {
414 let status = match arguments.get("status").and_then(Value::as_str) {
415 None if !arguments.contains_key("status") => "needs_triage",
416 Some("triage") => "needs_triage",
417 Some("todo") => "todo",
418 _ => return Err(Error::new(400, "Choose todo or triage for a new issue.")),
419 };
420 fields.insert("status".into(), status.into());
421 } else {
422 issue(app.shale.json(&target, &credential).await?, repository, issue_id.unwrap())?;
423 }
424 let mut fields = serde_json::to_value(fields)?;
425 if let Some(id) = issue_id { fields["id"] = json!(id); }
426 fields["model"] = json!(model.unwrap());
427 current(app, grant, &credential)?;
428 let result = host::call(json!({"operation":"shale.write","grant":grant["id"],"repository":repository,"action":name,"arguments":fields})).await
429 .map_err(|error| if error.status >= 500 { Error::new(502, "The write outcome is unknown. Check Shale before retrying.") } else { error })?;
430 let id = result["id"].as_u64().ok_or_else(|| Error::new(502, "The write outcome is unknown. Check Shale before retrying."))?;
431 let target = repository_path(&app.shale.origin, repository, &["issues", &id.to_string()])?;
432 let result = issue(app.shale.json(&target, &credential).await?, repository, id)?;
433 current(app, grant, &credential).map_err(|_| Error::new(502, "The write outcome is unknown. Check Shale before retrying."))?;
434 Ok(json!({"issue":result}))
435 }.await;
436 Ok(match result {
437 Ok(value) => CallToolResult::structured(value),
438 Err(error) => CallToolResult::error(vec![ContentBlock::text(error.message)]),
439 }
440 .into())
441 }
442}
443pub fn router(app: Arc<App>) -> Router {
444 let state = app.clone();
445 mcp::router(app, "shale", move || Ok(Shale(state.clone())))
446}
447
448fn session_cookie(headers: &HeaderMap) -> Result<String> {
449 let sessions: Vec<_> = headers
450 .get_all("set-cookie")
451 .iter()
452 .filter_map(|value| value.to_str().ok())
453 .filter_map(|value| value.split(';').next()?.strip_prefix("SessionID="))
454 .collect();
455 if sessions.len() != 1
456 || sessions[0].is_empty()
457 || sessions[0].len() > 4096
458 || !sessions[0]
459 .bytes()
460 .all(|b| matches!(b, 0x21 | 0x23..=0x2b | 0x2d..=0x3a | 0x3c..=0x5b | 0x5d..=0x7e))
461 {
462 return Err(Error::new(
463 502,
464 "Shale didn't return a session. Link it again.",
465 ));
466 }
467 Ok(sessions[0].to_owned())
468}
469fn fields(query: &str) -> Result<HashMap<String, String>> {
470 if query.len() > 16384 {
471 return Err(Error::new(
472 400,
473 "This sign-in response is too large. Link Shale again.",
474 ));
475 }
476 let mut fields = HashMap::new();
477 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
478 if fields
479 .insert(key.into_owned(), value.into_owned())
480 .is_some()
481 {
482 return Err(Error::new(
483 400,
484 "This sign-in response has repeated fields. Link Shale again.",
485 ));
486 }
487 }
488 Ok(fields)
489}
490fn username(page: &str) -> Result<String> {
491 let document = Html::parse_document(page);
492 if document
493 .select(&Selector::parse("body#page-user-settings").unwrap())
494 .next()
495 .is_none()
496 {
497 return Err(Error::new(401, "The Shale session expired. Link it again."));
498 }
499 let names: Vec<_> = document
500 .select(&Selector::parse("kbd").unwrap())
501 .map(|element| element.text().collect::<String>())
502 .collect();
503 if names.len() != 1 || names[0].is_empty() {
504 return Err(Error::new(
505 502,
506 "Shale's account page changed. Open Shale to check your account.",
507 ));
508 }
509 Ok(names.into_iter().next().unwrap())
510}
511
512pub async fn manage(
513 app: Arc<App>,
514 method: &Method,
515 owner: &Value,
516 body: &Value,
517) -> Result<Response> {
518 let owner_id = string(&owner["id"]);
519 let key = format!("shale-session:{owner_id}");
520 match *method {
521 Method::GET => match repositories(&app, owner_id).await {
522 Ok(resources) => {
523 Ok(axum::Json(json!({"linked":true,"resources":resources})).into_response())
524 }
525 Err(error) if error.status == 401 => {
526 Ok(axum::Json(json!({"linked":false,"resources":[]})).into_response())
527 }
528 Err(error) => Err(error),
529 },
530 Method::POST => {
531 let pending = if let Some(id) = body["request"].as_str() {
532 let db = app.mcp.db.lock().unwrap();
533 let key = format!("pending:{}", mcp::hash(id));
534 let pending = mcp::get(&db, &key)?;
535 if pending["owner"] != owner_id || pending["resource"] != app.mcp.resource("shale")
536 {
537 return Err(Error::new(
538 403,
539 "Open your Shale connection request before linking.",
540 ));
541 }
542 Some(id.to_owned())
543 } else {
544 None
545 };
546 let (status, headers, _) = app.shale.get("/-/login", None).await?;
547 if status != StatusCode::FOUND {
548 return Err(Error::new(
549 502,
550 "Shale couldn't start sign-in. Open Shale and try again.",
551 ));
552 }
553 let authorization = url::Url::parse(
554 headers
555 .get("location")
556 .and_then(|v| v.to_str().ok())
557 .unwrap_or_default(),
558 )?;
559 let issuer = &app.auth.origin;
560 let parameters = fields(authorization.query().unwrap_or_default())?;
561 if authorization.origin() != issuer.origin()
562 || authorization.path() != "/auth/oidc/authorize"
563 || !authorization.username().is_empty()
564 || authorization.password().is_some()
565 || authorization.fragment().is_some()
566 || parameters.get("redirect_uri")
567 != Some(&app.shale.origin.join("/-/callback")?.to_string())
568 || parameters.get("response_type").map(String::as_str) != Some("code")
569 || parameters
570 .get("state")
571 .is_none_or(|s| s.is_empty() || s.len() > 1024)
572 {
573 return Err(Error::new(
574 502,
575 "Shale's sign-in destination doesn't match this instance. Check its OIDC settings.",
576 ));
577 }
578 let nonce = mcp::secret();
579 let mut db = app.mcp.db.lock().unwrap();
580 let tx = db.transaction()?;
581 tx.execute("DELETE FROM records WHERE substr(key,1,11)='shale-link:' AND json_extract(value,'$.owner')=?", [owner_id])?;
582 mcp::put(
583 &tx,
584 &format!("shale-link:{}", mcp::hash(&nonce)),
585 &json!({"owner":owner_id,"authorization":authorization.as_str(),"phase":"prepared","request":pending}),
586 600,
587 )?;
588 tx.commit()?;
589 Ok(axum::Json(json!({"redirect":app.shale.origin.join(&format!("/-/snowglobe-mcp/{nonce}"))?.as_str()})).into_response())
590 }
591 Method::DELETE => {
592 let session = {
593 let mut db = app.mcp.db.lock().unwrap();
594 let tx = db.transaction()?;
595 let session = mcp::get(&tx, &key)?;
596 mcp::delete(&tx, &key)?;
597 for grant in mcp::list(&tx, "grant:")? {
598 if grant["user"] == owner_id && grant["resource"] == app.mcp.resource("shale") {
599 mcp::revoke(&tx, string(&grant["id"]))?;
600 }
601 }
602 tx.execute("DELETE FROM records WHERE substr(key,1,11)='shale-link:' AND json_extract(value,'$.owner')=?", [owner_id])?;
603 tx.commit()?;
604 session
605 };
606 if session["origin"] == app.shale.origin.as_str() {
607 app.shale
608 .get("/-/logout", session["session"].as_str())
609 .await?;
610 }
611 Ok(StatusCode::NO_CONTENT.into_response())
612 }
613 _ => Err(Error::new(405, "Link or unlink Shale from MCP settings.")),
614 }
615}
616
617pub async fn oauth(app: Arc<App>, request: Request) -> Response {
618 let callback = request.uri().path() == "/oauth/shale/callback";
619 let result: Result<Response> = async move {
620 if request.method() != Method::GET
621 || request.headers().get("host").and_then(|v| v.to_str().ok()) != Some(&app.shale.origin[url::Position::BeforeHost..url::Position::AfterPort])
622 || request.headers().get("origin").is_some_and(|v| v.to_str().ok() != Some(app.shale.origin.origin().ascii_serialization().as_str()))
623 {
624 return Err(Error::new(403, "Start Shale linking from your dashboard's MCP tab."));
625 }
626 if let Some(nonce) = request.uri().path().strip_prefix("/oauth/shale/link/") {
627 if nonce.len() != 43 || !nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) || request.uri().query().is_some() {
628 return Err(Error::new(400, "This Shale link is incomplete. Start linking again."));
629 }
630 let mut db = app.mcp.db.lock().unwrap();
631 let tx = db.transaction()?;
632 let key = format!("shale-link:{}", mcp::hash(nonce));
633 let mut link = mcp::get(&tx, &key)?;
634 if link.is_null() || link["phase"] != "prepared" {
635 return Err(Error::new(410, "This Shale link expired or was used. Start linking again."));
636 }
637 link["phase"] = json!("claimed");
638 tx.execute("UPDATE records SET value=? WHERE key=?", rusqlite::params![link.to_string(), key])?;
639 tx.commit()?;
640 return Ok((StatusCode::FOUND, [
641 ("location", string(&link["authorization"]).to_owned()),
642 ("set-cookie", format!("snowglobe_mcp_shale_link={nonce}; Path=/-/callback; Secure; HttpOnly; SameSite=Lax; Max-Age=600")),
643 ]).into_response());
644 }
645 if !callback {
646 return Err(Error::new(404, "No Shale sign-in endpoint here."));
647 }
648 let cookies: Vec<_> = request.headers().get_all("cookie").iter()
649 .filter_map(|v| v.to_str().ok()).flat_map(|v| v.split(';'))
650 .filter_map(|part| part.trim().strip_prefix("snowglobe_mcp_shale_link=")).collect();
651 if cookies.len() != 1 || cookies[0].len() != 43 {
652 return Err(Error::new(400, "This Shale link cookie is missing. Start linking again."));
653 }
654 let query = request.uri().query().unwrap_or_default().to_owned();
655 let parameters = fields(&query)?;
656 let pending_key = format!("shale-link:{}", mcp::hash(cookies[0]));
657 let link = {
658 let mut db = app.mcp.db.lock().unwrap();
659 let tx = db.transaction()?;
660 let mut link = mcp::get(&tx, &pending_key)?;
661 if link.is_null() || link["phase"] != "claimed" {
662 return Err(Error::new(410, "This Shale link expired or was used. Start linking again."));
663 }
664 let authorization = url::Url::parse(string(&link["authorization"]))?;
665 let expected = fields(authorization.query().unwrap_or_default())?;
666 if parameters.get("state") != expected.get("state") {
667 return Err(Error::new(403, "This response belongs to another Shale sign-in. Start linking again."));
668 }
669 link["phase"] = json!("processing");
670 tx.execute("UPDATE records SET value=? WHERE key=?", rusqlite::params![link.to_string(), pending_key])?;
671 tx.commit()?;
672 link
673 };
674 if parameters.get("code").is_none_or(|code| code.is_empty() || code.len() > 4096) || parameters.contains_key("error") {
675 return Err(Error::new(400, "Shale sign-in was declined or incomplete. Start linking again."));
676 }
677 let expected_username = oidc::username(&app.auth, string(&link["owner"]), "shale")?;
678 let (status, headers, _) = app.shale.get(&format!("/-/callback?{query}"), None).await?;
679 if !status.is_redirection() {
680 return Err(Error::new(502, "Shale couldn't finish sign-in. Link it again."));
681 }
682 let session = session_cookie(&headers)?;
683 let verified: Result<()> = async {
684 let (status, _, body) = app.shale.get("/-/settings", Some(&session)).await?;
685 if status != StatusCode::OK || username(&body)? != expected_username {
686 return Err(Error::new(403, "Sign in to Shale with the same account as your dashboard, then link it again."));
687 }
688 let owner = string(&link["owner"]);
689 let session_key = format!("shale-session:{owner}");
690 let previous = mcp::get(&app.mcp.db.lock().unwrap(), &session_key)?;
691 if previous["origin"] == app.shale.origin.as_str() && previous["session"] != session {
692 app.shale.get("/-/logout", previous["session"].as_str()).await?;
693 }
694 let mut db = app.mcp.db.lock().unwrap();
695 let tx = db.transaction()?;
696 if mcp::get(&tx, &pending_key)?["phase"] != "processing" {
697 return Err(Error::new(410, "This Shale link was cancelled. Start linking again."));
698 }
699 mcp::put(&tx, &session_key, &json!({"origin":app.shale.origin.as_str(),"session":session,"linkedAt":now()}), 0)?;
700 mcp::delete(&tx, &pending_key)?;
701 tx.commit()?;
702 Ok(())
703 }.await;
704 if let Err(error) = verified {
705 let _ = app.shale.get("/-/logout", Some(&session)).await;
706 return Err(error);
707 }
708 let target = app.mcp.origin.join(&match link["request"].as_str() {
709 Some(request) => format!("connect/{request}"),
710 None => "mcp/settings/shale".to_owned(),
711 })?;
712 Ok((StatusCode::SEE_OTHER, [("location", target.to_string())]).into_response())
713 }.await;
714 let mut response = match result {
715 Ok(response) => response,
716 Err(error) => error.into_response(),
717 };
718 response
719 .headers_mut()
720 .insert("cache-control", "no-store".parse().unwrap());
721 response
722 .headers_mut()
723 .insert("referrer-policy", "no-referrer".parse().unwrap());
724 if callback {
725 response.headers_mut().append(
726 "set-cookie",
727 "snowglobe_mcp_shale_link=; Path=/-/callback; Secure; HttpOnly; SameSite=Lax; Max-Age=0"
728 .parse()
729 .unwrap(),
730 );
731 }
732 response
733}
734
735#[cfg(test)]
736mod tests {
737 use super::*;
738 #[test]
739 fn label_catalog_keeps_native_ids_and_rejects_wrong_pages() {
740 let page = "<meta name='astheno.shale.repo.name' content='chat'><body id=page-labels><div class=grid-container><table><tbody><tr><td><a class=issuelabel data-label-id=75 data-color='#123456'>Bug &amp; fix</a></td><td>Description</td><td>2</td></tr></tbody></table></div></body>";
741 let catalog = labels(page, "chat").unwrap();
742 assert_eq!(
743 catalog["labels"][0],
744 json!({"id":75,"name":"Bug & fix","description":"Description","color":"#123456","openIssues":2})
745 );
746 assert!(labels(page, "other").is_err());
747 assert!(
748 labels(
749 &page.replace("data-label-id=75", "data-label-id=bad"),
750 "chat"
751 )
752 .is_err()
753 );
754 }
755 #[test]
756 fn repository_names_cannot_change_origin_or_path_segments() {
757 let origin = url::Url::parse("https://shale.snowglobe.test").unwrap();
758 for name in [
759 "",
760 ".",
761 "..",
762 "-",
763 "../other",
764 "one//two",
765 "one/../two",
766 "one/./two",
767 "one/-/two",
768 "one/",
769 "one\\two",
770 "%2e%2e",
771 "one?x",
772 "one#x",
773 "one\n",
774 "//foreign.test",
775 ] {
776 assert!(
777 repository_path(&origin, name, &["issues", "1"]).is_err(),
778 "{name:?}"
779 );
780 }
781 let path = repository_path(&origin, "雪☃", &["issues", "1"]).unwrap();
782 assert_eq!(path.origin(), origin.origin());
783 assert_eq!(path.path(), "/%E9%9B%AA%E2%98%83/issues/1");
784 let path = repository_path(
785 &origin,
786 "userscripts/discord-pluralkit-predict",
787 &["issues", "1"],
788 )
789 .unwrap();
790 assert_eq!(path.origin(), origin.origin());
791 assert_eq!(
792 path.path(),
793 "/userscripts/discord-pluralkit-predict/issues/1"
794 );
795 }
796 #[test]
797 fn issue_json_keeps_markdown_and_excludes_deleted_actions() {
798 let value = json!({"issue":{"number":3,"title":"Snow & ☃","status":"done"},"labels":["bug"],"actions":[
799 {"actor":"owner","kind":"comment","payload":"**Markdown** <angle> ☃","added_on":"2026-10-13T00:00:00Z","deleted_on":null},
800 {"actor":"owner","kind":"update_status","payload":"done","deleted_on":null},
801 {"actor":"owner","kind":"comment","payload":"deleted","deleted_on":"2026-10-13T01:00:00Z"}
802 ]});
803 let parsed = issue(value.clone(), "owned", 3).unwrap();
804 assert_eq!(parsed["comments"], json!([{"author":"owner","createdAt":"2026-10-13T00:00:00Z","text":"**Markdown** <angle> ☃"}]));
805 assert_eq!(parsed["labels"], json!(["bug"]));
806 assert!(issue(value.clone(), "owned", 4).is_err());
807 assert!(issue(value.clone(), "owned", 0).is_err());
808 for field in ["issue", "actions", "labels"] {
809 let mut incomplete = value.clone();
810 incomplete.as_object_mut().unwrap().remove(field);
811 assert!(issue(incomplete, "owned", 3).is_err());
812 }
813 }
814 #[test]
815 fn account_identity_uses_html_text_and_rejects_login_or_changed_markup() {
816 assert_eq!(
817 username("<body id=page-user-settings><kbd>snow&amp;flake☃</kbd>").unwrap(),
818 "snow&flake☃"
819 );
820 for html in [
821 "<body><kbd>snow</kbd>",
822 "<body id=page-user-settings>",
823 "<body id=page-user-settings><kbd>snow</kbd><kbd>other</kbd>",
824 ] {
825 assert!(username(html).is_err());
826 }
827 }
828 #[test]
829 fn callback_fields_and_session_cookie_refuse_ambiguity_and_header_injection() {
830 assert!(fields("state=one&state=two").is_err());
831 assert!(fields(&"s".repeat(16385)).is_err());
832 let mut headers = HeaderMap::new();
833 headers.append(
834 "set-cookie",
835 "SessionID=owned:signature; Path=/; Secure; HttpOnly"
836 .parse()
837 .unwrap(),
838 );
839 assert_eq!(session_cookie(&headers).unwrap(), "owned:signature");
840 headers.append("set-cookie", "SessionID=other; Path=/".parse().unwrap());
841 assert!(session_cookie(&headers).is_err());
842 for value in [
843 "SessionID=",
844 "SessionID=with space",
845 "SessionID=bad,other",
846 "SessionID=\"quoted\"",
847 ] {
848 let mut headers = HeaderMap::new();
849 headers.insert("set-cookie", value.parse().unwrap());
850 assert!(session_cookie(&headers).is_err());
851 }
852 }
853}