File size: 9,459 Bytes
bee6636 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
use std::error::Error;
use oxc::{
allocator::{Allocator, StringBuilder},
ast::ast::{
AssignmentExpression, AssignmentTarget, CallExpression, DebuggerStatement,
ExportAllDeclaration, ExportNamedDeclaration, Expression, FunctionBody,
IdentifierReference, ImportDeclaration, ImportExpression, MemberExpression, MetaProperty,
NewExpression, ObjectExpression, ObjectPropertyKind, ReturnStatement, StringLiteral,
ThisExpression, UnaryExpression, UnaryOperator, UpdateExpression,
},
ast_visit::{Visit, walk},
span::{Atom, GetSpan, Span},
};
use crate::{
cfg::{Config, Flags, UrlRewriter},
changes::JsChanges,
rewrite::rewrite,
};
// js MUST not be able to get a reference to any of these because sbx
//
// maybe move this out of this lib?
const UNSAFE_GLOBALS: &[&str] = &[
"window",
"self",
"globalThis",
"this",
"parent",
"top",
"location",
"document",
"eval",
"frames",
];
pub struct Visitor<'alloc, 'data, E>
where
E: UrlRewriter,
{
pub alloc: &'alloc Allocator,
pub jschanges: JsChanges<'alloc, 'data>,
pub error: Option<Box<dyn Error + Sync + Send>>,
pub config: &'data Config,
pub rewriter: &'data E,
pub flags: Flags,
}
impl<'data, E> Visitor<'_, 'data, E>
where
E: UrlRewriter,
{
fn rewrite_url(&mut self, url: &StringLiteral<'data>, module: bool) {
let mut builder = StringBuilder::from_str_in(&self.config.prefix, self.alloc);
if self.error.is_some() {
builder.push_str("__URL_REWRITER_ALREADY_ERRORED__");
} else if let Err(err) =
self.rewriter
.rewrite(self.config, &self.flags, &url.value, &mut builder, module)
{
self.error.replace(err);
builder.push_str("__URL_REWRITER_ERROR__");
}
let text = builder.into_str();
self.jschanges
.add(rewrite!(url.span.shrink(1), Replace { text }));
}
fn rewrite_ident(&mut self, name: &Atom, span: Span) {
if UNSAFE_GLOBALS.contains(&name.as_str()) {
self.jschanges.add(rewrite!(span, WrapFn { wrap: true }));
}
}
fn walk_member_expression(&mut self, it: &Expression) -> bool {
match it {
Expression::Identifier(s) => {
self.rewrite_ident(&s.name, s.span);
true
}
Expression::StaticMemberExpression(s) => self.walk_member_expression(&s.object),
Expression::ComputedMemberExpression(s) => self.walk_member_expression(&s.object),
_ => false,
}
}
fn scramitize(&mut self, span: Span) {
self.jschanges.add(rewrite!(span, Scramitize));
}
}
impl<'data, E> Visit<'data> for Visitor<'_, 'data, E>
where
E: UrlRewriter,
{
fn visit_identifier_reference(&mut self, it: &IdentifierReference) {
// if self.config.capture_errors {
// self.jschanges.insert(JsChange::GenericChange {
// span: it.span,
// text: format!(
// "{}({}, typeof arguments != 'undefined' && arguments)",
// self.config.wrapfn, it.name
// ),
// });
// } else {
//
if UNSAFE_GLOBALS.contains(&it.name.as_str()) {
self.jschanges
.add(rewrite!(it.span, WrapFn { wrap: false }));
}
// }
}
fn visit_new_expression(&mut self, it: &NewExpression<'data>) {
self.walk_member_expression(&it.callee);
walk::walk_arguments(self, &it.arguments);
}
fn visit_member_expression(&mut self, it: &MemberExpression<'data>) {
// TODO
// you could break this with ["postMessage"] etc
// however this code only exists because of recaptcha whatever
// and it would slow down js execution a lot
if let MemberExpression::StaticMemberExpression(s) = it {
if s.property.name == "postMessage" {
self.jschanges.add(rewrite!(s.property.span, SetRealmFn));
walk::walk_expression(self, &s.object);
return; // unwise to walk the rest of the tree
}
if !self.flags.strict_rewrites
&& !UNSAFE_GLOBALS.contains(&s.property.name.as_str())
&& let Expression::Identifier(_) | Expression::ThisExpression(_) = &s.object
{
// cull tree - this should be safe
return;
}
if self.flags.scramitize
&& !matches!(s.object, Expression::MetaProperty(_) | Expression::Super(_))
{
self.scramitize(s.object.span());
}
}
walk::walk_member_expression(self, it);
}
fn visit_this_expression(&mut self, it: &ThisExpression) {
self.jschanges.add(rewrite!(it.span, WrapThisFn));
}
fn visit_debugger_statement(&mut self, it: &DebuggerStatement) {
// delete debugger statements entirely. some sites will spam debugger as an anti-debugging measure, and we don't want that!
self.jschanges.add(rewrite!(it.span, Delete));
}
// we can't overwrite window.eval in the normal way because that would make everything an
// indirect eval, which could break things. we handle that edge case here
fn visit_call_expression(&mut self, it: &CallExpression<'data>) {
if let Expression::Identifier(s) = &it.callee {
// if it's optional that actually makes it an indirect eval which is handled separately
if s.name == "eval" && !it.optional {
self.jschanges.add(rewrite!(
it.span,
Eval {
inner: Span::new(s.span.end + 1, it.span.end),
}
));
// then we walk the arguments, but not the callee, since we want it to resolve to
// the real eval
walk::walk_arguments(self, &it.arguments);
return;
}
}
if self.flags.scramitize {
self.scramitize(it.span);
}
walk::walk_call_expression(self, it);
}
fn visit_import_declaration(&mut self, it: &ImportDeclaration<'data>) {
self.rewrite_url(&it.source, true);
walk::walk_import_declaration(self, it);
}
fn visit_import_expression(&mut self, it: &ImportExpression<'data>) {
self.jschanges.add(rewrite!(
Span::new(it.span.start, it.span.start + 7),
ImportFn
));
walk::walk_import_expression(self, it);
}
fn visit_export_all_declaration(&mut self, it: &ExportAllDeclaration<'data>) {
self.rewrite_url(&it.source, true);
}
fn visit_export_named_declaration(&mut self, it: &ExportNamedDeclaration<'data>) {
if let Some(source) = &it.source {
self.rewrite_url(source, true);
}
// do not walk further, we don't want to rewrite the identifiers
}
#[cfg(feature = "debug")]
fn visit_try_statement(&mut self, it: &oxc::ast::ast::TryStatement<'data>) {
// for debugging we need to know what the error was
if self.flags.capture_errors
&& let Some(h) = &it.handler
&& let Some(name) = &h.param
&& let Some(ident) = name.pattern.get_identifier_name()
{
let start = h.body.span.start + 1;
self.jschanges
.add(rewrite!(Span::new(start, start), ScramErr { ident }));
}
walk::walk_try_statement(self, it);
}
fn visit_object_expression(&mut self, it: &ObjectExpression<'data>) {
for prop in &it.properties {
if let ObjectPropertyKind::ObjectProperty(p) = prop
&& let Expression::Identifier(s) = &p.value
&& UNSAFE_GLOBALS.contains(&s.name.to_string().as_str())
&& p.shorthand
{
self.jschanges
.add(rewrite!(s.span, ShorthandObj { name: s.name }));
return;
}
}
walk::walk_object_expression(self, it);
}
fn visit_function_body(&mut self, it: &FunctionBody<'data>) {
// tag function for use in sourcemaps
if self.flags.do_sourcemaps {
self.jschanges
.add(rewrite!(Span::new(it.span.start, it.span.start), SourceTag));
}
walk::walk_function_body(self, it);
}
fn visit_return_statement(&mut self, it: &ReturnStatement<'data>) {
// if let Some(arg) = &it.argument {
// self.jschanges.insert(JsChange::GenericChange {
// span: Span::new(it.span.start + 6, it.span.start + 6),
// text: format!(" $scramdbg((()=>{{ try {{return arguments}} catch(_){{}} }})(),("),
// });
// self.jschanges.insert(JsChange::GenericChange {
// span: Span::new(expression_span(arg).end, expression_span(arg).end),
// text: format!("))"),
// });
// }
walk::walk_return_statement(self, it);
}
fn visit_unary_expression(&mut self, it: &UnaryExpression<'data>) {
if matches!(it.operator, UnaryOperator::Typeof) {
// don't walk to identifier rewrites since it won't matter
return;
}
walk::walk_unary_expression(self, it);
}
fn visit_update_expression(&mut self, _it: &UpdateExpression<'data>) {
// then no, don't walk it, we don't care
}
fn visit_meta_property(&mut self, it: &MetaProperty<'data>) {
if it.meta.name == "import" {
self.jschanges.add(rewrite!(it.span, MetaFn));
}
}
fn visit_assignment_expression(&mut self, it: &AssignmentExpression<'data>) {
match &it.left {
AssignmentTarget::AssignmentTargetIdentifier(s) => {
if ["location"].contains(&s.name.to_string().as_str()) {
self.jschanges.add(rewrite!(
it.span,
Assignment {
name: s.name,
rhs: it.right.span(),
op: it.operator,
}
));
// avoid walking rest of tree, i would need to figure out nested rewrites
// somehow
return;
}
}
AssignmentTarget::ArrayAssignmentTarget(_) => {
// [location] = ["https://example.com"]
// this is such a ridiculously specific edge case. just ignore it
return;
}
_ => {
// only walk the left side if it isn't an identifier, we can't replace the
// identifier with a function obviously
walk::walk_assignment_target(self, &it.left);
}
}
walk::walk_expression(self, &it.right);
}
}
|