Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 1 addition & 22 deletions src/js/node/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Hardcoded module "node:crypto"
const StringDecoder = require("node:string_decoder").StringDecoder;
const LazyTransform = require("internal/streams/lazy_transform");
const { guardCallback } = require("internal/shared");
const { defineCustomPromisifyArgs } = require("internal/promisify");
const Writable = require("internal/streams/writable");
const { CryptoHasher } = Bun;
Expand Down Expand Up @@ -51,7 +50,7 @@
} = $cpp("node_crypto_binding.cpp", "createNodeCryptoBinding");

const {
pbkdf2: _pbkdf2,
pbkdf2,
pbkdf2Sync,
timingSafeEqual,
randomInt,
Expand Down Expand Up @@ -141,27 +140,7 @@
return CryptoHasher.hash(algorithm, input, outputEncoding);
};

// TODO: move this to zig

Check warning on line 143 in src/js/node/crypto.ts

View check run for this annotation

Claude / Claude Code Review

Stale TODO comment left after removing JS pbkdf2 wrapper

The `// TODO: move this to zig` comment was attached to the JS `pbkdf2` wrapper this PR deletes; the TODO is now done (pbkdf2 is fully native), but the stale comment remains directly above `crypto_exports.pbkdf2 = pbkdf2;`. It should be removed in this PR.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
function pbkdf2(password, salt, iterations, keylen, digest, callback) {
if (typeof digest === "function") {
callback = digest;
digest = undefined;
}

const promise = _pbkdf2(password, salt, iterations, keylen, digest, callback);
if (callback) {
// Guarded so a throw inside the callback is an uncaughtException, as in node.
const cb = guardCallback(callback);
promise.then(
result => cb(null, result),
err => cb(err),
);
return;
}

promise.then(() => {});
}

crypto_exports.pbkdf2 = pbkdf2;
crypto_exports.pbkdf2Sync = pbkdf2Sync;

Expand Down
46 changes: 31 additions & 15 deletions src/runtime/crypto/PBKDF2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

use bun_boringssl_sys as boringssl;
use bun_jsc::{
ArrayBuffer, CallFrame, JSGlobalObject, JSPromiseStrong, JSValue, Job, JobContext, JsResult,
JsThread,
ArrayBuffer, CallFrame, JSGlobalObject, JSValue, Job, JobContext, JsResult, JsThread, Strong,
};

use crate::node::{Flavor, StringObjects, StringOrBuffer};
Expand Down Expand Up @@ -70,7 +69,12 @@
call_frame: &CallFrame,
flavor: Flavor,
) -> JsResult<PBKDF2> {
let [arg0, arg1, arg2, arg3, arg4, arg5] = call_frame.arguments_as_array::<6>();
let [arg0, arg1, arg2, arg3, mut arg4, mut arg5] = call_frame.arguments_as_array::<6>();
// pbkdf2(password, salt, iterations, keylen, callback): digest omitted.
if flavor == Flavor::Async && arg4.is_function() {
arg5 = arg4;
arg4 = JSValue::UNDEFINED;
}

if !arg3.is_number() {
return Err(global_this.throw_invalid_argument_type_value(b"keylen", b"number", arg3));
Expand Down Expand Up @@ -266,9 +270,15 @@
pub err: bool,
}

/// JS-thread state for [`Pbkdf2Job`]: the user callback, invoked as `(err)` or `(null, buffer)`.
#[derive(bun_jsc::JsAffine)]
pub(crate) struct Pbkdf2Js {
pub callback: Strong,
}

impl JobContext for Pbkdf2Job {
type OffThread = Self;
type Js = JSPromiseStrong;
type Js = Pbkdf2Js;

fn run(this: &mut Self, done: bun_jsc::Completion<Self>) -> Option<bun_jsc::Completion<Self>> {
let len = this.pbkdf2.length;
Expand All @@ -289,29 +299,34 @@
Some(done)
}

fn then(mut this: Self, mut promise: JSPromiseStrong, cx: &JsThread<'_>) -> JsResult<()> {
fn then(mut this: Self, js: Pbkdf2Js, cx: &JsThread<'_>) -> JsResult<()> {
let global_this = cx.global();
let promise = promise.swap();
let event_loop = global_this.bun_vm().event_loop_mut();
let callback = js.callback.get();
if this.err {
let err = global_this.create_error_instance(format_args!("PBKDF2 derivation failed"));
promise.reject_with_async_stack(global_this, Ok(err))?;
event_loop.run_callback(callback, global_this, JSValue::UNDEFINED, &[err]);
return Ok(());
}

let output_slice = core::mem::take(&mut this.output);
debug_assert!(output_slice.len() == this.pbkdf2.length);
// Ownership transfers to JSC (freed via MarkedArrayBuffer_deallocator → mimalloc free).
let buffer_value = JSValue::create_buffer(global_this, output_slice.leak());
promise.settle(global_this, buffer_value)?;
let buffer_value = JSValue::create_buffer(global_this, output_slice.leak())?;

Check warning on line 315 in src/runtime/crypto/PBKDF2.rs

View check run for this annotation

Claude / Claude Code Review

pbkdf2 callback never invoked if create_buffer fails in then()

If `create_buffer` fails here, `?` propagates out of `then()` and the user callback is never invoked — pre-PR the same `Err` flowed into `promise.settle()`, which rejected the promise so the JS wrapper's `err => cb(err)` fired. Match the `this.err` branch just above and `run_callback` with the error instead of `?`-propagating past the callback (REVIEW.md: "Invoke the done/completion callback on every path").
Comment thread
robobun marked this conversation as resolved.
Resolved
event_loop.run_callback(
callback,
global_this,
JSValue::UNDEFINED,
&[JSValue::NULL, buffer_value],
);
Ok(())
}
}

/// Schedule the derivation on the work pool; returns its promise.
pub(crate) fn create_job(global_this: &JSGlobalObject, data: PBKDF2) -> JSValue {
/// Schedule the derivation on the work pool; `callback` was validated by
/// `from_js(.., Flavor::Async)`.
pub(crate) fn create_job(global_this: &JSGlobalObject, data: PBKDF2, callback: JSValue) {
let cx = global_this.js_thread();
let promise = JSPromiseStrong::init(global_this);
let value = promise.value();
Job::<Pbkdf2Job>::schedule(
&cx,
Pbkdf2Job {
Expand All @@ -320,7 +335,8 @@
output: Vec::new(),
err: false,
},
promise,
Pbkdf2Js {
callback: Strong::create(callback.with_async_context_if_needed(global_this), global_this),
},
);
value
}
10 changes: 8 additions & 2 deletions src/runtime/node/node_crypto_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1142,9 +1142,15 @@

#[bun_jsc::host_fn]
fn pbkdf2(global_this: &JSGlobalObject, call_frame: &CallFrame) -> JsResult<JSValue> {
let data = PBKDF2::from_js(global_this, call_frame, Flavor::Async)?;

Ok(pbkdf2::create_job(global_this, data))
// `from_js` accepted the callback in either the 5th or 6th position.
let callback = if call_frame.argument(4).is_function() {
call_frame.argument(4)
} else {
call_frame.argument(5)
};
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
pbkdf2::create_job(global_this, data, callback);
Ok(JSValue::UNDEFINED)

Check warning on line 1153 in src/runtime/node/node_crypto_binding.rs

View check run for this annotation

Claude / Claude Code Review

crypto.pbkdf2.length regressed from 6 to 5

Removing the JS wrapper drops `crypto.pbkdf2.length` from 6 to 5 — the native function is registered with arity 5 in `create_node_crypto_binding_zig`, but Node's `pbkdf2(password, salt, iterations, keylen, digest, callback)` has `.length === 6`. Bump the 4th arg of `JSFunction::create(global, "pbkdf2", __jsc_host_pbkdf2, 5, ...)` to `6`.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

#[bun_jsc::host_fn]
Expand Down
20 changes: 20 additions & 0 deletions test/js/node/crypto/pbkdf2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,23 @@ test("pbkdf2Sync reads the salt buffer only after every argument has been coerce
expect(salt.byteLength).toBe(0);
expect(key).toStrictEqual(crypto.pbkdf2Sync("password", new Uint8Array(0), 1, 32, "sha256"));
});

test("pbkdf2 callback gets (null, Buffer), keeps AsyncLocalStorage context, and validates like Node", async () => {
const { AsyncLocalStorage } = require("node:async_hooks");
const als = new AsyncLocalStorage();
const { promise, resolve } = Promise.withResolvers<unknown[]>();
const returned = als.run("ctx", () =>
crypto.pbkdf2("pw", "salt", 1, 8, "sha256", function (...args) {
resolve([args.length, args[0], Buffer.isBuffer(args[1]), args[1].toString("hex"), als.getStore()]);
}),
);
expect(returned).toBeUndefined();
expect(await promise).toEqual([2, null, true, "6f4ad8c78ec365c0", "ctx"]);
// digest omitted: the callback shifts into the digest slot and digest is reported as undefined
expect(() => crypto.pbkdf2("pw", "salt", 1, 8, (() => {}) as any)).toThrow(
expect.objectContaining({ code: "ERR_INVALID_ARG_TYPE", message: expect.stringContaining('"digest"') }),
);
expect(() => (crypto.pbkdf2 as any)("pw", "salt", 1, 8, "sha256")).toThrow(
expect.objectContaining({ code: "ERR_INVALID_ARG_TYPE", message: expect.stringContaining('"callback"') }),
);
});
Loading