vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.71k stars 26.84k forks source link

TypeError: Failed to normalize algorithm: 'salt' of 'Pbkdf2Params' (passed algorithm) is not instance of ArrayBuffer, Buffer, TypedArray, or DataView. #69277

Closed guyeisenbach closed 1 month ago

guyeisenbach commented 1 month ago

Link to the code that reproduces this issue

https://github.com/guyeisenbach/minimal-nextjs-error-reproduction

To Reproduce

Working version

  1. clone the repository git clone https://github.com/guyeisenbach/minimal-nextjs-error-reproduction.git
  2. cd minimal-nextjs-error-reproduction/my-app-working
  3. npm i
  4. npm run dev
  5. curl http://localhost:3000
  6. In the logs you should see {"v": "8340f6a4-62c0-11ef-9667-8a920c4a2cd4", "u": "8340f5c8-62c0-11ef-9667-8a920c4a2cd4", "t": 1724577344000, "s": 100, "a": "c"}

NOT working version

  1. clone the repository git clone https://github.com/guyeisenbach/minimal-nextjs-error-reproduction.git
  2. cd minimal-nextjs-error-reproduction/my-app-not-working
  3. npm i
  4. npm run dev
  5. curl http://localhost:3000
  6. In the logs you should see the error:
    - error Error [TypeError]: Failed to normalize algorithm: 'salt' of 'Pbkdf2Params' (passed algorithm) is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.

Current vs. Expected behavior

I executed an decryption algorithm PBKDF2 which worked on 13.4.5-canary.2 but stopped working on 13.4.5-canary.3 (and forwarded versions). The error I received is:

Failed to normalize algorithm: 'salt' of 'Pbkdf2Params' (passed algorithm) is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000
Binaries:
  Node: 18.18.2
  npm: 10.8.1
  Yarn: 1.22.22
  pnpm: N/A
Relevant packages:
  next: 13.4.5-canary.3
  eslint-config-next: N/A
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.3.3

Which area(s) are affected? (Select all that apply)

Runtime

Which stage(s) are affected? (Select all that apply)

next dev (local), next start (local), Other (Deployed)

Additional context

I tested my app code using next with version 13.4.5-canary.2. After upgrading next to version 13.4.5-canary.3 an exception is thrown. I tested it with more newer versions of next and it still does not work.

JesseKoldewijn commented 1 month ago

I'll try to take a look tomorrow after work πŸ‘

DanBezalelpx commented 1 month ago

I'm facing the same issue, please help

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote πŸ‘ on the issue description or subscribe to the issue for updates. Thanks!

JesseKoldewijn commented 1 month ago

I'll try to take a look tomorrow after work πŸ‘

I'll most likely will be able to take a look at this in about 3 to 4 hours. But in the meantime do you mind checking if the code you got in the middleware triggers the same errors when placed in a route handler instead? @guyeisenbach

guyeisenbach commented 1 month ago

I'll try to take a look tomorrow after work πŸ‘

I'll most likely will be able to take a look at this in about 3 to 4 hours. But in the meantime do you mind checking if the code you got in the middleware triggers the same errors when placed in a route handler instead? @guyeisenbach

@JesseKoldewijn Checked it, it seems to work fine. I created the file app/api/route.ts with the code:

export async function GET(request: Request) {
    console.log(await pbkdf2Decrypt("vucmai0dDDT5X8TFMQ2TnXJYxzS5lxLBp8bH88fENehHcyRxK26gi2qMAK74dMQq",
        "Xejc98gptDn7Dov12RcZZN+29M7NxWwTdMAfvldXXHA98PH3NJOBjLDFZIm8tJLZKxIZgtFzmfbtnJLx12Ij1SWaKpP0Lz2tx/Ga7CrlFTdKOX64qoJuVvSh9rQioFU1+OhXGV3ZSw2tI06fHxOPGw8n2/5k4EznmxEulNN/waldqLcUGXOJmwBFUqK6zoGB",
        1000,
        "NIA+hzM5wkE="))

    return new Response("ok")
}

function base64ToArrayBuffer(base64String: string): ArrayBufferLike {
    const binaryString = atob(base64String);
    const length = binaryString.length;
    const bytes = new Uint8Array(length);
    binaryString.split('').forEach((char, index) => {
        bytes[index] = char.charCodeAt(0);
    });
    return bytes.buffer;
}
async function pbkdf2Decrypt(secret: string, encryptedString: string, iterations: number, salt: string): Promise<string>{
    const ivlen = 16;
    const keylen = 32;
    const bitsLength = (ivlen + keylen) * 8;

    const encodedPassword = new TextEncoder().encode(secret);
    const encodedSalt = base64ToArrayBuffer(salt);
    const importedKey = await crypto.subtle.importKey('raw', encodedPassword, 'PBKDF2', false, ['deriveBits']);
    const params = { name: 'PBKDF2', hash: 'SHA-256', salt: encodedSalt, iterations: iterations };
    const derivation = await crypto.subtle.deriveBits(params, importedKey, bitsLength);

    const derivedKey = derivation.slice(0, keylen);
    const iv = derivation.slice(keylen);
    const cookieBuffer = base64ToArrayBuffer(encryptedString);
    const importedDecryptionKey = await crypto.subtle.importKey('raw', derivedKey, { name: 'AES-CBC' }, false, [
        'decrypt',
    ]);
    const decrypted = await crypto.subtle.decrypt(
        {
            name: 'AES-CBC',
            iv: iv,
        },
        importedDecryptionKey,
        cookieBuffer,
    );
    return new TextDecoder('utf-8').decode(decrypted);
}

And it DOES print the decrypted string to the console on http://localhost:3000/api

JesseKoldewijn commented 1 month ago

In that case it's probably not a nextjs specific issue and more an edge runtime issue.

guyeisenbach commented 1 month ago

@JesseKoldewijn WDYM? how can I solve it?

JesseKoldewijn commented 1 month ago

@JesseKoldewijn WDYM? how can I solve it?

What I meant is that this is most likely going to be an edge runtime specific issue. Meaning that I'll still will take a look when I'm home ofc. Just saying what the likely issue could be related toπŸ€™