Skip to content

feat: stack upgrades#308

Open
hieu-w wants to merge 57 commits intomasterfrom
feat/stack-upgrades
Open

feat: stack upgrades#308
hieu-w wants to merge 57 commits intomasterfrom
feat/stack-upgrades

Conversation

@hieu-w
Copy link
Contributor

@hieu-w hieu-w commented Feb 26, 2026

Jira Link

https://consensyssoftware.atlassian.net/browse/W3APD-5328

Description

Migrate the entire tkey SDK from legacy cryptography libraries (bn.js, elliptic, Buffer, @toruslabs/tweetnacl-js) to modern alternatives (bigint, @noble/curves, Uint8Array).

Key changes:

  • Replace bn.js (BN) with native bigint across all packages (common-types, core, service-providers, modules)
  • Replace elliptic secp256k1 operations with @noble/curves/secp256k1
  • Replace @toruslabs/tweetnacl-js ED25519 operations with @noble/curves/ed25519
  • Replace Buffer usage with Uint8Array throughout
  • Add bigIntReplacer utility for JSON serialization of bigint values (since JSON.stringify cannot serialize bigint natively)
  • Fix ThresholdKey.fromJSON() deserialization to properly reconstruct ShareStore, AuthMetadata, and PublicShare instances from JSON
  • Remove the @tkey/tss package (to be migrated separately)
  • Upgrade CI workflow action versions and Node.js version

Packages affected: common-types, core, default, private-keys, security-questions, seed-phrase, service-provider-base, service-provider-torus, service-provider-sfa, share-serialization, share-transfer, storage-layer-torus, chrome-storage, web-storage

How has this been tested?

  • All existing unit tests updated to use bigint/@noble/curves APIs
  • npm run build passes for all 14 packages
  • npm run test -w packages/common-types — all passing
  • npm run test -w packages/core — all passing
  • npm run test -w packages/share-serialization — all passing
  • npm run test -w packages/default — 264 passing, 0 failing

Screenshots (if appropriate)

N/A — no UI changes

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

Checklist

  • My code follows the code style of this project. (run lint)
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

@socket-security
Copy link

socket-security bot commented Feb 26, 2026

@socket-security
Copy link

socket-security bot commented Feb 26, 2026

Warning

MetaMask internal reviewing guidelines:

  • Do not ignore-all
  • Each alert has instructions on how to review if you don't know what it means. If lost, ask your Security Liaison or the supply-chain group
  • Copy-paste ignore lines for specific packages or a group of one kind with a note on what research you did to deem it safe.
    @SocketSecurity ignore npm/PACKAGE@VERSION
Action Severity Alert  (click "▶" to expand/collapse)
Warn Low
Potential code anomaly (AI signal): npm @babel/core is 100.0% likely to have a medium risk anomaly

Notes: The examined code is a standard, benign helper for constructing and wrapping configuration items from descriptors within Babel’s tooling. There is no evidence of data leakage, exfiltration, backdoors, or other malicious activity in this fragment. The combination of immutability, brand-based identity, and non-enumerable descriptor storage indicates a well-scoped internal utility rather than anything suspicious.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@babel/register@7.28.6npm/@toruslabs/torus-scripts@8.0.0npm/nyc@17.1.0npm/@babel/core@7.29.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@babel/core@7.29.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm @lerna/create is 100.0% likely to have a medium risk anomaly

Notes: The fragment is characteristic of legitimate package-management tooling (lerna/npm-like) with credential management for registry access. While there are no explicit malware indicators, credential handling practices (storing base64-encoded passwords, opaque nerfed-key storage via dynamic accessors) present security concerns that could lead to credential leakage or misconfiguration if logs or local storage are compromised. The code appears purpose-built for managing credentials and performing registry operations rather than executing arbitrary code, but the insecure storage pattern and obfuscated storage keys justify a cautious security risk rating. Recommended improvements: replace base64 password storage with proper encryption, harden credential storage not to leak in logs, add explicit validation/auditing around nerfed keys, and ensure no writes to logs contain sensitive credential values.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4npm/@lerna/create@8.2.4

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@lerna/create@8.2.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm @napi-rs/wasm-runtime is 100.0% likely to have a medium risk anomaly

Notes: The fragment appears to implement a substantial WASI/N-API bridge with comprehensive memory and filesystem interfacing. There is no concrete evidence of malicious payloads such as data exfiltration, backdoors, or remote command execution in this snippet. The primary concerns relate to the unusual in-browser input path (readStdin) and the large surface area for data flows across threads and FFI boundaries. A targeted, broader audit of the complete module and any wasm payloads loaded through these bindings is recommended to ensure rights enforcement and memory safety. Overall risk is moderate but current evidence does not indicate active malware.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/@napi-rs/wasm-runtime@0.2.12

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@napi-rs/wasm-runtime@0.2.12. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm @toruslabs/session-manager is 61.0% likely to have a medium risk anomaly

Notes: The ServerHandler implements a standard client-side encrypted storage interaction with server-side persistence, binding data to a derived public key and ensuring integrity via signatures. No explicit malicious behavior is evident within this fragment. Primary risks arise from external trust (session server integrity), proper secret/key management by callers (private key handling and exposure risk), and incomplete lifecycle methods that may affect data cleanup or policy enforcement. The code appears sound for its described use, but the placeholder methods and lack of input validation warrant caution and further hardening in a production environment.

Confidence: 0.61

Severity: 0.58

From: package-lock.jsonnpm/@toruslabs/customauth@22.1.0npm/@toruslabs/session-manager@5.3.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@toruslabs/session-manager@5.3.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ajv is 100.0% likely to have a medium risk anomaly

Notes: The code is a straightforward build script to bundle and minify a specified package using Browserify and UglifyJS. The primary security concern is potential path manipulation: json.main is used to form a require path without validating that it stays within the target package directory. If a malicious or misconfigured package.json includes an absolute path or traversal outside the package, the script could bundle unintended files. Otherwise, the script does not perform network access, data exfiltration, or backdoor actions, and there is no hard-coded secrets or dynamic code execution beyond standard bundling/minification.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/eslint@9.39.3npm/ajv@6.14.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ajv@6.14.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ajv is 100.0% likely to have a medium risk anomaly

Notes: The code augments a meta-schema to permit remote dereferencing of keyword schemas via a hardcoded data.json resource. This introduces network dependency and potential changes to validation semantics at runtime. While not inherently malicious, the remote reference constitutes a notable security and reliability risk that should be mitigated with local fallbacks, input validation, and explicit remote-resource governance.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/eslint@9.39.3npm/ajv@6.14.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ajv@6.14.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ajv is 100.0% likely to have a medium risk anomaly

Notes: This module generates JavaScript code at runtime via standaloneCode(...) and then immediately executes it with require-from-string. Because the generated code can incorporate user-supplied schemas or custom keywords without sanitization or sandboxing, an attacker who controls those inputs could inject arbitrary code and achieve remote code execution in the Node process. Users should audit and lock down the standaloneCode output or replace dynamic evaluation with a safer, static bundling approach.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/ajv@8.18.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ajv@8.18.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ajv is 100.0% likely to have a medium risk anomaly

Notes: The code implements a standard AJV-like dynamic parser generator for JTD schemas. There are no explicit malware indicators in this fragment. The primary security concern is the dynamic code generation and execution from external schemas, which introduces a medium risk if schemas are untrusted. With trusted schemas and proper schema management, the risk is typically acceptable within this pattern.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/ajv@8.18.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ajv@8.18.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ajv is 100.0% likely to have a medium risk anomaly

Notes: The code implements standard timestamp validation with clear logic for normal and leap years and leap seconds. There is no network, file, or execution of external code within this isolated fragment. The only anomalous aspect is assigning a string to validTimestamp.code, which could enable external tooling to inject behavior in certain environments, but this does not constitute active malicious behavior in this isolated snippet. Overall, low to moderate security risk in typical usage; no malware detected within the shown code.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/ajv@8.18.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ajv@8.18.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm axios is 100.0% likely to have a medium risk anomaly

Notes: The code provides a simple, non-obfuscated data-format normalization transform that prepends a zlib header when the incoming first byte is not 0x78. While this can enable downstream consumers that expect a zlib-like header, it can also corrupt data streams that are already compressed or use a different framing. There is no malicious activity detected, but the transformation should be used with clear data-format expectations and possibly a configurable option to enable/disable header insertion.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4npm/axios@1.13.5

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/axios@1.13.5. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm axios is 100.0% likely to have a medium risk anomaly

Notes: The analyzed code is a standard Axios defaults/module implementation with no malicious behavior detected. It handles request/response transformations and content-type management in a typical, safe manner. No data exfiltration, backdoors, or privacy-invasive actions are present within this fragment.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4npm/axios@1.13.5

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/axios@1.13.5. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm consola is 100.0% likely to have a medium risk anomaly

Notes: The analyzed code fragment is a feature-rich, standard Consola logging utility responsible for redirecting and managing log output with throttling, pausing, and reporter integration. There is no direct evidence of malicious activity, hardcoded secrets, or exfiltration within this snippet. However, the powerful I/O overrides pose privacy and data flow risks if reporters or downstream sinks are untrusted. The security posture hinges on trusted reporters and proper governance of the overall supply chain.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/torus-scripts@8.0.0npm/consola@3.4.2

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/consola@3.4.2. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm get-intrinsic is 100.0% likely to have a medium risk anomaly

Notes: The GetIntrinsic module is a conventional intrinsic resolver designed for sandboxed JavaScript environments. It includes careful validation, alias handling, and selective dynamic evaluation for specific intrinsics. While there is a real potential risk from Function-based evaluation if exposed to untrusted input, in this isolated code path there is no evidence of data leakage, backdoors, or external communications. The component is acceptable with proper sandbox boundaries; the most important mitigations are ensuring inputs are trusted and that dynamic evaluation cannot be triggered by untrusted sources.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/karma@6.4.4npm/jsdom@26.0.0npm/assert@2.1.0npm/json-stable-stringify@1.3.0npm/lerna@8.2.4npm/get-intrinsic@1.3.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/get-intrinsic@1.3.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ignore is 100.0% likely to have a medium risk anomaly

Notes: The code fragment represents a conventional, well-structured path-ignore utility with caching and recursive parent-directory evaluation. Windows path normalization is present for compatibility but does not indicate malicious intent. No indicators of data leakage, external communication, or covert backdoors were found. Security impact primarily revolves around correct ignore semantics rather than intrinsic vulnerabilities. The component remains appropriate for use in a broader security-conscious pipeline if used with careful awareness of what is being ignored.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/eslint-config-typescript@5.0.0npm/ignore@7.0.5

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ignore@7.0.5. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm jiti is 100.0% likely to have a medium risk anomaly

Notes: The fragment implements a sophisticated on-the-fly loader using JITI for transpilation and execution, with careful handling of JSON interop based on nearby package.json type. There is no explicit malicious behavior identified (no external network activity, no hardcoded secrets). However, the dynamic code execution path introduced by _wrapSource and the synthetic module environment represents a potential risk vector if untrusted inputs are loaded, or if jiti/mjs execution context could be manipulated. This warrants strict review of the loader environment, the version and security of JITI, and checks on the sources being loaded to mitigate potential code execution or supply chain concerns.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/@toruslabs/torus-scripts@8.0.0npm/eslint@9.39.3npm/jiti@2.6.1

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/jiti@2.6.1. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm js-yaml is 100.0% likely to have a medium risk anomaly

Notes: The script functions as a straightforward JSON↔YAML translator CLI with standard error handling. The primary security concern is the use of yaml.loadAll without a safeLoad alternative, which could enable YAML deserialization risks if inputs contain crafted tags. To improve security, switch to a safe loader (e.g., yaml.safeLoadAll or equivalent) or ensure the library is configured to restrict risky constructors. Overall, no malware indicators were observed; the risk is confined to YAML deserialization semantics.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/nyc@17.1.0npm/js-yaml@3.14.2

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/js-yaml@3.14.2. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm lerna is 100.0% likely to have a medium risk anomaly

Notes: The code appears to implement standard, though sensitive, credential management for npm-like registry access within a tooling context. While there is no explicit malicious activity detected (no exfiltration to external domains beyond typical registry endpoints or backdoors), the credential handling pathways—especially multiple sources, base64 encoding/decoding, and per-registry storage—pose security risks if misconfigured or logged insecurely. The overall risk is medium; proper access control, secure logging practices, and minimal logging of sensitive values are essential in the broader codebase to mitigate leakage or misuse.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/lerna@8.2.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm lerna is 100.0% likely to have a medium risk anomaly

Notes: The code fragment appears to be a legitimate component of npm/Lerna tooling with credential handling, registry interactions, and OTP prompts consistent with publish/install workflows. While sensitive (credential storage, OTP handling, and external process execution), there is no clear evidence of malicious activity or supply-chain sabotage within this fragment alone. The primary concerns relate to proper protection of credentials (access controls, log sanitization, and secure storage) and ensuring OTP prompts do not leak to insecure channels. Overall risk is moderate due to credential handling and external process capabilities, but no demonstrated malware or backdoors in this excerpt.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/lerna@8.2.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm lerna is 100.0% likely to have a medium risk anomaly

Notes: Overall, no definitive malicious payload or backdoor is evident in the provided fragment. The code reflects standard patterns for npm/lerna configuration, credential management, and registry communication. While credential management paths exist, they operate within expected npm tooling semantics. There is a moderate risk surface around credential handling and interactive OTP prompts in automated environments, but this is not inherently malicious. Recommendation: review how credentials are sourced and stored in the host environment, ensure secure handling and least-privilege access, and audit network calls for unintended data exposure in your deployment pipelines.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/lerna@8.2.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm mocha is 100.0% likely to have a medium risk anomaly

Notes: The code is a small, benign utility for cache invalidation in Node.js. It enables reloading behavior but bears potential risk if used on critical modules or without validation. Overall security risk is low to moderate depending on usage context.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/mocha@11.7.5

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/mocha@11.7.5. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm nx is 100.0% likely to have a medium risk anomaly

Notes: This module implements Nx migration fetching and execution logic. It legitimately fetches migration configs from registries or via temporary installs and then dynamically requires and runs migration implementation code from packages. While the code itself contains no obfuscated or clearly malicious payloads, it provides a sink that executes arbitrary third-party code (migration implementations) and runs package manager installers. That behavior is an expected part of a migration system but represents a supply-chain risk: a malicious package can include a migration that performs unauthorized file system changes, runs shell commands, or exfiltrates data when migrations are executed. Recommend reviewing migration implementations from untrusted sources before running, running in isolated environments, and applying additional sandboxing or code review for high-risk contexts.

Confidence: 1.00

Severity: 0.60

From: package-lock.jsonnpm/lerna@8.2.4npm/nx@19.8.14

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/nx@19.8.14. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

See 9 more rows in the dashboard

Ignoring alerts on:

  • @inquirer/external-editor@1.0.3
  • @unrs/resolver-binding-wasm32-wasi@1.11.1
  • giget@2.0.0
  • napi-postinstall@0.3.4
  • node-fetch-native@1.6.7
  • ox@0.12.4
  • pkg-types@2.3.0
  • tree-kill@1.2.2
  • unrs-resolver@1.11.1
  • viem@2.46.3
  • glob@13.0.6
  • @noble/curves@2.0.1
  • @toruslabs/customauth@22.1.0
  • http-errors@2.0.1
  • statuses@2.0.2
  • loader-runner@4.3.1
  • workerpool@9.3.4

View full report

@tuna1207 tuna1207 marked this pull request as ready for review February 27, 2026 06:47
chaitanyapotti
chaitanyapotti previously approved these changes Mar 2, 2026
@hieu-w hieu-w requested a review from ieow March 2, 2026 12:37
@matthiasgeihs
Copy link
Contributor

@cursor can you do a review? (don't commit anything)

@cursor
Copy link

cursor bot commented Mar 2, 2026

Here is my code review of the feat/stack-upgrades PR. No commits have been made.


Code Review: feat: stack upgrades — Crypto Library Migration

Overall, this is a large and well-structured migration. The bn.js/elliptic/Buffer removal is thorough across all 14 packages, and the fromJSON deserialization fixes are a significant correctness improvement. Below are the findings organized by severity.


Critical / High Severity

1. Bug: acquireWriteLock / releaseWriteLock crash when privKey is undefined

  async acquireWriteLock(params: { serviceProvider?: IServiceProvider; privKey?: bigint }): Promise<{ status: number; id?: string }> {
    const { serviceProvider, privKey } = params;
    // ...
    if (privKey) {
      signature = signDataWithPrivKey(data, privKey);
    } else {
      signature = serviceProvider.sign(/* ... */);
    }
    const metadataParams = {
      key: bytesToHex(getPubKeyECC(privKey)),  // <-- privKey may be undefined here!
      // ...
    };

When the else branch executes (using serviceProvider), line 210 still calls getPubKeyECC(privKey) where privKey is undefined. This will throw at runtime. The same bug exists in releaseWriteLock at line 230. Compare with generateMetadataParams (lines 155-194) which correctly handles both branches by using serviceProvider.retrievePubKeyPoint() in the else case. This may be a pre-existing bug, but it's worth fixing in this PR.

2. Verify @noble/curves v2 API compatibility

Several patterns depend on v2-specific API behavior that should be confirmed:

  • secp256k1.sign(..., { format: "recovered" }) and { format: "der" } — used in authMetadata.ts:38, TorusStorageLayer.ts:28,174, ServiceProviderBase.ts:61. In standard @noble/curves v1.x, sign() returns a Signature object and does not accept a format option. If v2 doesn't support these options, the code would fail at runtime since it treats the return value as Uint8Array (calling .slice(), passing to bytesToHex()).

  • secp256k1.Point.CURVE() called as a function — used in Polynomial.ts:15, lagrangeInterpolatePolynomial.ts:7, SECP256K1Format.ts:14, SecurityQuestionsModule.ts:51,78,112,135. If CURVE is a property rather than a method, this throws.

  • secp256k1.utils.randomSecretKey() vs randomPrivateKey() — the v1 name was randomPrivateKey(). If v2 renamed it, usage at lagrangeInterpolatePolynomial.ts:10, ED25519Format.ts:30, etc. needs to match.

These are likely fine if testing passes end-to-end, but they represent an implicit coupling to a specific @noble/curves version that isn't obvious from the type signatures.


Medium Severity

3. hexToBigInt("") silently returns 0n

export function hexToBigInt(s: string): bigint {
  return s.length > 0 ? BigInt(`0x${s}`) : 0n;
}

A zero scalar is never a valid secp256k1 private key or share index. If a caller passes "" due to a bug, this silently produces a cryptographically dangerous zero value. Consider throwing an error for empty strings, or at minimum documenting this as intentional.

4. Metadata.toJSON() mutates polyIDList in-place

      const sortedShareIndexes = shareIndexes.sort((a: string, b: string) => {
        const aBig = BigInt(`0x${a}`);
        const bBig = BigInt(`0x${b}`);
        return aBig < bBig ? -1 : aBig > bBig ? 1 : 0;
      });

Array.sort() mutates the original array. Since shareIndexes is a reference to this.polyIDList[i][1], calling toJSON() has the side effect of reordering the internal data. Use [...shareIndexes].sort(...) to avoid mutation during serialization.

5. Metadata.clone() may corrupt bigint values in general/tkey/scoped stores

  clone(): Metadata {
    return Metadata.fromJSON(JSON.parse(stringify(this, { replacer: bigIntReplacer })));
  }

bigIntReplacer converts ALL bigints to hex strings, but Metadata.fromJSON only restores bigints for known fields (pubKey, polyIDList, etc.). Module data stored via setGeneralStoreDomain (e.g., SecurityQuestionStore.nonce, SecurityQuestionStore.shareIndex) would be serialized as hex strings but never converted back to bigint, potentially causing type mismatches downstream.

6. @toruslabs/eccrypto still used — incomplete migration

generatePrivate() from @toruslabs/eccrypto is still imported in:

  • packages/common-types/src/utils.ts:4
  • packages/share-transfer/src/ShareTransferModule.ts:16

This could be replaced with secp256k1.utils.randomSecretKey() from @noble/curves to consolidate random key generation to a single source. The encrypt/decrypt wrappers around eccrypto are fine since they implement ECIES, not raw curve operations.

7. fromJSON type detection is fragile

      if (keys.length === AuthMetadataKeys.length && keys.every((val) => AuthMetadataKeys.includes(val))) {
        // ...
      } else if (keys.length === ShareStoreKeys.length && keys.every((val) => ShareStoreKeys.includes(val))) {
        // ...
      }

The deserialization logic at ThresholdKey.fromJSON identifies types by matching JSON key counts and names against dummy instances. If any type's shape changes (add/remove field), or if two types coincidentally share the same keys, this breaks silently. Consider adding a type discriminator field to serialized objects.


Low Severity

8. Dead code: shareToShareStore unreachable return

  shareToShareStore(share: bigint): ShareStore {
    // ...
    let returnShare: ShareStore;
    // ... loop that returns directly on line 297 ...
    if (!returnShare) {       // always true — returnShare is never assigned
      throw CoreError.fromCode(1307);
    }
    return returnShare;       // dead code
  }

The variable returnShare is declared but never assigned. The function either returns inside the loop or falls through to the throw. The final return is unreachable. Simplify by removing returnShare and just throwing after the loop.

9. normalize() function — likely dead code with type issues

export function normalize(input: number | string): string {
  if (!input) {
    return undefined;  // Return type says `string`, returns `undefined`
  }

Returns undefined from a string-typed function. Also, !input catches 0 which is a valid number. No callers found in the codebase — consider removing.

10. Legacy naming artifacts

  • BNUtils.ts no longer contains any BN references — consider renaming to keyUtils.ts
  • "elliptic-compressed" string literal in Point.encode() — the method is deprecated, consider removing if no callers exist
  • BufferObj type in aggregateTypes.ts — document as migration-period compat or remove if unneeded
  • // @flow comments in 7+ files should be removed

11. ShareRequest.ts backward-compat shim

    if (encPubKey instanceof Uint8Array) {
      this.encPubKey = encPubKey;
    } else if ((encPubKey as BufferObj).type === "Buffer") {
      this.encPubKey = new Uint8Array((encPubKey as BufferObj).data);
    } else {
      this.encPubKey = Uint8Array.from(Object.values(encPubKey as ArrayLike<number>));
    }

The third branch relies on Object.values() ordering on array-like objects, which is engine-dependent in edge cases. If this is needed for migration, add a comment explaining it's temporary. As reviewer @chaitanyapotti noted, this depends on your serialization format — verify the Buffer branch is actually needed for persisted data.

12. Minor: bigint | string union types remain

In aggregateTypes.ts lines 159-165, 179-181, the SecurityQuestionStoreArgs and ShareTransferStorePointerArgs still use bigint | string. Per reviewer @ieow's comment, these should be bigint only, with string-to-bigint conversion pushed into fromJSON() methods.


Summary

The migration is well-executed overall — no remaining BN/elliptic/Buffer/tweetnacl references in source code, and the fromJSON fixes are a significant improvement. The highest-risk items are:

  1. The acquireWriteLock/releaseWriteLock bug (will crash when using serviceProvider without privKey)
  2. Confirming @noble/curves v2 API compatibility for format options and CURVE() syntax
  3. The Metadata.clone() bigint-to-string leakage in module stores

Everything else is cleanup and hardening. Nice work on a complex migration.

Open in Web Open in Cursor 

ieow
ieow previously approved these changes Mar 2, 2026
Copy link
Contributor

@ieow ieow left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm
But it would be great to add backward compability tests

Copy link
Contributor

@matthiasgeihs matthiasgeihs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've skimmed over it and looks good at first glance.
For a thorough review I'd probably need half a day to a day which is hard for me to allocate at the moment, and not sure if it's needed. I let the Cursor bot double check the PR. It found some potential issues, which I think are worth looking into. Nothing major though, I believe. (1. should be easy to fix, 2. is a false positive, I believe.)

@hieu-w
Copy link
Contributor Author

hieu-w commented Mar 3, 2026

1. Bug: acquireWriteLock / releaseWriteLock crash when privKey is undefined

  async acquireWriteLock(params: { serviceProvider?: IServiceProvider; privKey?: bigint }): Promise<{ status: number; id?: string }> {
    const { serviceProvider, privKey } = params;
    // ...
    if (privKey) {
      signature = signDataWithPrivKey(data, privKey);
    } else {
      signature = serviceProvider.sign(/* ... */);
    }
    const metadataParams = {
      key: bytesToHex(getPubKeyECC(privKey)),  // <-- privKey may be undefined here!
      // ...
    };
When the else branch executes (using serviceProvider), line 210 still calls getPubKeyECC(privKey) where privKey is undefined. This will throw at runtime. The same bug exists in releaseWriteLock at line 230. Compare with generateMetadataParams (lines 155-194) which correctly handles both branches by using serviceProvider.retrievePubKeyPoint() in the else case. This may be a pre-existing bug, but it's worth fixing in this PR.

=> fix in commit 411e983

@hieu-w
Copy link
Contributor Author

hieu-w commented Mar 3, 2026

Verify @noble/curves v2 API compatibility

Several patterns depend on v2-specific API behavior that should be confirmed:

secp256k1.sign(..., { format: "recovered" }) and { format: "der" } — used in authMetadata.ts:38, TorusStorageLayer.ts:28,174, ServiceProviderBase.ts:61. In standard @noble/curves v1.x, sign() returns a Signature object and does not accept a format option. If v2 doesn't support these options, the code would fail at runtime since it treats the return value as Uint8Array (calling .slice(), passing to bytesToHex()).

secp256k1.Point.CURVE() called as a function — used in Polynomial.ts:15, lagrangeInterpolatePolynomial.ts:7, SECP256K1Format.ts:14, SecurityQuestionsModule.ts:51,78,112,135. If CURVE is a property rather than a method, this throws.

secp256k1.utils.randomSecretKey() vs randomPrivateKey() — the v1 name was randomPrivateKey(). If v2 renamed it, usage at lagrangeInterpolatePolynomial.ts:10, ED25519Format.ts:30, etc. needs to match.

These are likely fine if testing passes end-to-end, but they represent an implicit coupling to a specific @noble/curves version that isn't obvious from the type signatures.

=> invalid, v2 support these options

@hieu-w
Copy link
Contributor Author

hieu-w commented Mar 3, 2026

hexToBigInt("") silently returns 0n

export function hexToBigInt(s: string): bigint {
  return s.length > 0 ? BigInt(`0x${s}`) : 0n;
}
A zero scalar is never a valid secp256k1 private key or share index. If a caller passes "" due to a bug, this silently produces a cryptographically dangerous zero value. Consider throwing an error for empty strings, or at minimum documenting this as intentional.

fix in 44252f7

@hieu-w hieu-w dismissed stale reviews from ieow and chaitanyapotti via d95ef69 March 3, 2026 04:54
chaitanyapotti
chaitanyapotti previously approved these changes Mar 3, 2026

const msgHash = hexToBytes(stripHexPrefix(keccak256(utf8ToBytes(stringify(data, { replacer: bigIntReplacer })))));
if (!secp256k1.verify(hexToBytes(sig), msgHash, m.pubKey.toSEC1(true), { prehash: false, format: "der" })) {
if (!secp256k1.verify(hexToBytes(sig), msgHash, m.pubKey.toSEC1(true), { prehash: false, format: "der", lowS: false })) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will this cause issue for the new AuthMetdata that genereate signature with lowS:true?
Maybe we can add as the fallback for signature verification
using lowS: true and low:S false

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like verify lowS:false can verify signature with lowS:true
we could add comment on the verification mentioning lowS:true is to support backward compability

@ieow
Copy link
Contributor

ieow commented Mar 3, 2026

packages/default/test/run.test.js still imports and uses BN from bn.js (lines 1, 6, 7)
Uses new BN(...) instead of BigInt(...)
Calls .toBuffer() which doesn't exist on bigint

@ieow
Copy link
Contributor

ieow commented Mar 3, 2026

CODE_REVIEW_REPORT.md

I think only the first point need to confirmed ( check )
Signature recovery parameter (v): Changed from hardcoded 0 to actual recovery value (0 or 1)
the backend ( metadata server) should need to be able to verify with both the new signature generation and old signature generation ( backward compatibility )

@hieu-w
Copy link
Contributor Author

hieu-w commented Mar 3, 2026

@SocketSecurity ignore npm/workerpool@9.3.4
devDeps only, and mocha will be removed in next PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants