Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 15 additions & 21 deletions src/jsc/ConsoleObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4314,29 +4314,18 @@ pub mod formatter {
failed: false,
estimated_line_length: &mut self.estimated_line_length,
};
let mut str = OwnedString::new(BunString::empty());

value.json_stringify(self.global_this, self.indent, &mut str)?;
writer.add_for_new_line(str.length());
if js_type == jsc::JSType::JSDate {
// in the code for printing dates, it never exceeds this amount
let mut iso_string_buf = [0u8; 36];
let mut out_buf: &[u8] = {
use std::io::Write as _;
let mut cursor = &mut iso_string_buf[..];
let start_len = cursor.len();
let _ = write!(cursor, "{str}");
let written = start_len - cursor.len();
&iso_string_buf[..written]
};

if out_buf == b"null" {
out_buf = b"Invalid Date";
} else if out_buf.len() > 2 {
// trim the quotes
out_buf = &out_buf[1..out_buf.len() - 1];
}

// Format from the Date's internal [[DateValue]] so that own/overridden
// `toJSON`/`toISOString` properties are never invoked (they could throw
// out of console.log or spoof the output). `to_iso_string` reads
// `DateInstance::internalNumber()` directly; `None` means NaN.
let mut iso_string_buf = [0u8; 64];
let out_buf: &[u8] = value
.to_iso_string(self.global_this, &mut iso_string_buf)
.unwrap_or(b"Invalid Date");

writer.add_for_new_line(out_buf.len());
writer.print(format_args!(
"{}{}{}",
pfmt!("<r><magenta>", C),
Expand All @@ -4349,6 +4338,11 @@ pub mod formatter {
return Ok(());
}

let mut str = OwnedString::new(BunString::empty());

value.json_stringify(self.global_this, self.indent, &mut str)?;
writer.add_for_new_line(str.length());

writer.print(format_args!("{str}"));
if writer.failed {
self.failed = true;
Expand Down
36 changes: 14 additions & 22 deletions src/runtime/test_runner/pretty_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1862,29 +1862,16 @@ impl<'a> Formatter<'a> {
writer.write_all(b"\n");
}
Tag::JSON => {
let mut str = bun_core::String::empty();

value.json_stringify(self.global_this, self.indent, &mut str)?;
self.add_for_new_line(str.length());
if js_type == JSType::JSDate {
// in the code for printing dates, it never exceeds this amount
let mut iso_string_buf = [0u8; 36];
let mut out_buf: &[u8] = {
use std::io::Write;
let mut cursor = &mut iso_string_buf[..];
match write!(cursor, "{}", str) {
Ok(()) => {
let written = 36 - cursor.len();
&iso_string_buf[..written]
}
Err(_) => b"",
}
};
if out_buf.len() > 2 {
// trim the quotes
out_buf = &out_buf[1..out_buf.len() - 1];
}

// Format from the Date's internal [[DateValue]] so that own/overridden
// `toJSON`/`toISOString` properties are never invoked. `to_iso_string`
// reads `DateInstance::internalNumber()` directly; `None` means NaN.
let mut iso_string_buf = [0u8; 64];
let out_buf: &[u8] = value
.to_iso_string(self.global_this, &mut iso_string_buf)
.unwrap_or(b"Invalid Date");

self.add_for_new_line(out_buf.len());
writer.print(format_args!(
"{}{}{}",
pretty_fmt_const::<ENABLE_ANSI_COLORS>("<r><magenta>"),
Expand All @@ -1894,6 +1881,11 @@ impl<'a> Formatter<'a> {
return Ok(());
}

let mut str = bun_core::String::empty();

value.json_stringify(self.global_this, self.indent, &mut str)?;
self.add_for_new_line(str.length());

writer.print(format_args!("{}", str));
}
Tag::Event => {
Expand Down
71 changes: 71 additions & 0 deletions test/js/bun/util/inspect.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,77 @@ it("new Date(..)", () => {
expect(Bun.inspect(new Date("Invalid Date"))).toBe("Invalid Date");
});

it("Date ignores own toJSON/toISOString when formatting", () => {
// The formatter must read the Date's internal [[DateValue]] and never call
// user-provided toJSON/toISOString (which could throw or spoof the output).
const iso = "1970-01-01T00:00:00.000Z";

const a = new Date(0);
a.toISOString = () => {
throw new Error("iso-boom");
};
expect(() => Bun.inspect(a)).not.toThrow();
expect(Bun.inspect(a)).toBe(iso);

const b = new Date(0);
b.toISOString = 5;
expect(() => Bun.inspect(b)).not.toThrow();
expect(Bun.inspect(b)).toBe(iso);

const c = new Date(0);
c.toJSON = () => "SPOOFED";
expect(Bun.inspect(c)).toBe(iso);

const d = new Date(0);
d.toJSON = () => ({ nested: { fake: 1 } });
expect(Bun.inspect(d)).toBe(iso);

const e = new Date(0);
e.toJSON = () => {
throw new Error("mid");
};
expect(() => Bun.inspect(["before", e, "after"])).not.toThrow();
expect(Bun.inspect(["before", e, "after"])).toBe(`[ "before", ${iso}, "after" ]`);

const f = new Date(NaN);
f.toJSON = () => "SPOOFED-INVALID";
expect(Bun.inspect(f)).toBe("Invalid Date");

class SubDate extends Date {
toJSON() {
throw new Error("sub-boom");
}
}
expect(Bun.inspect(new SubDate(0))).toBe(iso);
});

it("console.log of Date with throwing toJSON does not throw", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const a = new Date(0);
a.toISOString = () => { throw new Error("iso-boom"); };
console.log(a);
const e = new Date(0);
e.toJSON = () => { throw new Error("mid"); };
console.log(["before", e, "after"]);
console.log("DONE");
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.replaceAll("\r\n", "\n"), stderr, exitCode }).toEqual({
stdout: `1970-01-01T00:00:00.000Z\n[ "before", 1970-01-01T00:00:00.000Z, "after" ]\nDONE\n`,
stderr: "",
exitCode: 0,
});
});

it("Bun.inspect.custom exists", () => {
expect(Bun.inspect.custom).toBe(util.inspect.custom);
});
Expand Down
Loading