1use std::collections::BTreeMap;
4
5use crate::error::{DiagCode, Diagnostic};
6use crate::span::Span;
7use crate::value::Value;
8
9pub const ZERO_JS_CSP_HEADER: &str =
11 "default-src 'self'; script-src 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
12
13pub fn call_web(
15 path: &str,
16 args: &[Value],
17 span: Span,
18) -> Result<Option<Value>, Diagnostic> {
19 match path {
20 "web.response" => {
21 let status = extract_i64(args, 0, "web.response(status, content_type, body)", span)?;
22 let content_type =
23 extract_str(args, 1, "web.response(status, content_type, body)", span)?;
24 let body_val = args.get(2).cloned().unwrap_or(Value::String(String::new()));
25 let body_str = match &body_val {
26 Value::String(s) | Value::Iri(s) => s.clone(),
27 Value::Record(r) => r
28 .get("hex")
29 .and_then(|v| match v {
30 Value::String(h) => Some(h.clone()),
31 _ => None,
32 })
33 .unwrap_or_else(|| format!("{body_val:?}")),
34 _ => format!("{body_val:?}"),
35 };
36
37 let mut headers = BTreeMap::new();
38 headers.insert(
39 "Content-Security-Policy".to_string(),
40 Value::String(ZERO_JS_CSP_HEADER.to_string()),
41 );
42 headers.insert(
43 "X-Webizen-Runtime".to_string(),
44 Value::String("vibescript/vbc1; zero-js=1; cbor-ld=1".to_string()),
45 );
46
47 let mut rec = BTreeMap::new();
48 rec.insert("status".to_string(), Value::I64(status));
49 rec.insert("content_type".to_string(), Value::String(content_type));
50 rec.insert("body".to_string(), Value::String(body_str));
51 rec.insert("payload".to_string(), body_val);
52 rec.insert("zero_js".to_string(), Value::Bool(true));
53 rec.insert("headers".to_string(), Value::Record(headers));
54 Ok(Some(Value::Record(rec)))
55 }
56 "web.range_response" => {
57 let total = extract_i64(
58 args,
59 0,
60 "web.range_response(total_bytes, start_byte, end_byte, crc32c)",
61 span,
62 )?;
63 let start = extract_i64(
64 args,
65 1,
66 "web.range_response(total_bytes, start_byte, end_byte, crc32c)",
67 span,
68 )?;
69 let end = extract_i64(
70 args,
71 2,
72 "web.range_response(total_bytes, start_byte, end_byte, crc32c)",
73 span,
74 )?;
75 let crc = extract_str(
76 args,
77 3,
78 "web.range_response(total_bytes, start_byte, end_byte, crc32c)",
79 span,
80 )?;
81
82 if start < 0 || end < start || total <= end {
83 return Err(Diagnostic::new(
84 DiagCode::E100,
85 span,
86 "web.range_response: invalid byte range bounds",
87 ));
88 }
89 let slice_len = (end - start) + 1;
90 let content_range = format!("bytes {start}-{end}/{total}");
91
92 let mut rec = BTreeMap::new();
93 rec.insert("status".to_string(), Value::I64(206));
94 rec.insert(
95 "accept_ranges".to_string(),
96 Value::String("bytes".to_string()),
97 );
98 rec.insert("content_range".to_string(), Value::String(content_range));
99 rec.insert("content_length".to_string(), Value::I64(slice_len));
100 rec.insert("crc32c".to_string(), Value::String(crc));
101 rec.insert("zero_js".to_string(), Value::Bool(true));
102 Ok(Some(Value::Record(rec)))
103 }
104 "web.route_mail" => {
105 let alias = extract_str(
106 args,
107 0,
108 "web.route_mail(alias, sender_email, allowed_sender)",
109 span,
110 )?;
111 let sender = extract_str(
112 args,
113 1,
114 "web.route_mail(alias, sender_email, allowed_sender)",
115 span,
116 )?;
117 let allowed = extract_str(
118 args,
119 2,
120 "web.route_mail(alias, sender_email, allowed_sender)",
121 span,
122 )?;
123
124 let local_part = alias.split('@').next().unwrap_or("unknown").to_string();
125 let mut rec = BTreeMap::new();
126 rec.insert("alias".to_string(), Value::String(alias));
127 rec.insert(
128 "relationship".to_string(),
129 Value::String(local_part.clone()),
130 );
131
132 if allowed.starts_with("hook:") {
133 rec.insert(
134 "verdict".to_string(),
135 Value::String("ExecuteProgrammableHook".to_string()),
136 );
137 rec.insert("hook".to_string(), Value::String(allowed));
138 rec.insert("admitted".to_string(), Value::Bool(true));
139 } else if sender.eq_ignore_ascii_case(&allowed) {
140 rec.insert(
141 "verdict".to_string(),
142 Value::String("DeliverToRelationshipThread".to_string()),
143 );
144 rec.insert("admitted".to_string(), Value::Bool(true));
145 } else {
146 rec.insert(
147 "verdict".to_string(),
148 Value::String("RejectedUnauthorizedSender".to_string()),
149 );
150 rec.insert(
151 "pinpointed_leak_source".to_string(),
152 Value::String(local_part),
153 );
154 rec.insert("admitted".to_string(), Value::Bool(false));
155 }
156 Ok(Some(Value::Record(rec)))
157 }
158 "web.check_permit" => {
159 let tier = extract_i64(args, 0, "web.check_permit", span)?;
160 let util_pct = extract_i64(args, 1, "web.check_permit", span)?;
161 let req_units = extract_i64(args, 2, "web.check_permit", span)?;
162 let peer_quota = extract_i64(args, 3, "web.check_permit", span)?;
163
164 let tier_ceiling = match tier {
165 0 => 100,
166 1 => 95,
167 2 => 80,
168 _ => 50,
169 };
170
171 let admitted = req_units <= peer_quota && util_pct <= tier_ceiling;
172 let status = if req_units > peer_quota {
173 "DeniedPeerQuotaExhausted"
174 } else if util_pct > tier_ceiling {
175 "ShedByHostBudgetPriorityRule"
176 } else {
177 "Admitted"
178 };
179
180 let mut rec = BTreeMap::new();
181 rec.insert("admitted".to_string(), Value::Bool(admitted));
182 rec.insert("status".to_string(), Value::String(status.to_string()));
183 rec.insert("tier_ceiling_pct".to_string(), Value::I64(tier_ceiling));
184 rec.insert(
185 "remaining_peer_units".to_string(),
186 Value::I64((peer_quota - req_units).max(0)),
187 );
188 Ok(Some(Value::Record(rec)))
189 }
190 _ => Ok(None),
191 }
192}
193
194fn extract_str(args: &[Value], idx: usize, ctx: &str, span: Span) -> Result<String, Diagnostic> {
195 match args.get(idx) {
196 Some(Value::String(s)) | Some(Value::Iri(s)) => Ok(s.clone()),
197 _ => Err(Diagnostic::new(
198 DiagCode::E100,
199 span,
200 format!("{ctx}: argument #{idx} must be a string"),
201 )),
202 }
203}
204
205fn extract_i64(args: &[Value], idx: usize, ctx: &str, span: Span) -> Result<i64, Diagnostic> {
206 match args.get(idx) {
207 Some(Value::I64(n)) => Ok(*n),
208 Some(Value::U64(n)) => Ok(*n as i64),
209 Some(Value::F64(n)) => Ok(*n as i64),
210 _ => Err(Diagnostic::new(
211 DiagCode::E100,
212 span,
213 format!("{ctx}: argument #{idx} must be a number"),
214 )),
215 }
216}