Skip to content

feat: isolate hardware factory and test APIs - #882

Open
wabicai wants to merge 1 commit into
factory/apifrom
feature/factory-test-protobuf-integration
Open

wabicai wants to merge 1 commit into
factory/apifrom
feature/factory-test-protobuf-integration

Conversation

@wabicai

@wabicai wabicai commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

What

  • add @onekeyfe/hd-test-api as the separately publishable package for factory and automated hardware-test methods
  • add a generic Core method/protobuf extension SPI with destructive-operation authorization
  • remove non-production factory/test methods and protobuf definitions from the production Core API
  • keep deviceReadSEPublicCert and deviceSESignMessage in CoreApi for the production verification flow
  • expose factory, debug, and test commands through one extension registry and one schema fragment per protocol

Why

Factory and automated-test workflows need access to private hardware commands without exposing those commands through the production HD Core surface or shipping their protobuf definitions in the production schema.

Impact

  • production consumers keep the two secure-element methods required by deviceVerify
  • factory/test consumers opt in through @onekeyfe/hd-test-api
  • destructive write/erase/provisioning methods remain disabled unless explicitly authorized
  • the Common SDK lifecycle remains process-global, so one SDK instance should be used per JavaScript runtime

Checks

  • built @onekeyfe/hd-transport, @onekeyfe/hd-core, @onekeyfe/hd-common-connect-sdk, and @onekeyfe/hd-test-api in dependency order
  • 6 focused Jest suites / 21 tests passed
  • tsc --noEmit -p packages/hd-test-api/tsconfig.json
  • scoped ESLint passed
  • yarn check-versions passed for all 31 packages
  • git diff --check passed

No physical hardware write, erase, provisioning, or firmware operation was executed.

Known draft state

factory/api advanced after this worktree was created and GitHub currently reports a merge
conflict. The new base includes DeviceFactoryPermanentLock; syncing it requires an explicit
follow-up migration of that newly added factory API into this package and revalidation against the
latest protobuf schema.

@wabicai
wabicai marked this pull request as ready for review November 19, 2026 08:27
@sidmorizon

Copy link
Copy Markdown
Contributor

@codex review

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex security review

@sidmorizon

Copy link
Copy Markdown
Contributor

Cursor review failed.

Remote error: cursor_permission_denied: HTTP 403 Forbidden: Cloud Agent is not available for free users. Please upgrade to Pro.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T08:42:48.684443Z ed6f2a6 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cursor

cursor Bot commented Nov 19, 2026

Copy link
Copy Markdown

Skipping Bugbot: Bugbot is disabled for this repository. Visit the Bugbot dashboard to update your settings.

@sidmorizon

Copy link
Copy Markdown
Contributor

Devin Cloud review ↗

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed6f2a68bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +127 to +131
return call({
...(usesDeviceId ? params : deviceIdOrParams),
connectId,
...(usesDeviceId ? { deviceId: deviceIdOrParams } : {}),
method,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Redact sensitive test-method inputs before forwarding calls

Calling the newly exposed deviceLoad or bixinLoadDevice sends mnemonic material through Common SDK's call(), which logs the complete parameters because neither method receives a log-block label. Core's additional sanitization recognizes mnemonic but not the actual mnemonics field. Consequently, seed material is retained in log history and emitted through log events even with debugging disabled; this also happens when destructive authorization subsequently rejects the call. Add sensitive-method blocking or sanitization at every logging boundary before exposing these methods.

AGENTS.md reference: AGENTS.md:L64-L65

Useful? React with 👍 / 👎.

}

async run() {
const res = await this.device.commands.typedCall('SdProtect', 'Success');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Pass the initialized parameters into the wire calls

When deviceSdProtect is called with an operation, init() captures it but run() sends no request parameters, so the requested SD-protection operation never reaches the device. The same omission exists in the newly added GetPublicKeyMultiple, ListResDir, NFTWriteData, and NFTWriteInfo implementations, dropping their addresses, path, or write payloads. Pass this.params as the third argument in these calls so the methods execute the requested operation rather than encoding an empty/default request.

Useful? React with 👍 / 👎.

this.allowDeviceMode = [...this.allowDeviceMode, UI_REQUEST.BOOTLOADER];
this.params = {
address: this.payload.address,
len: formatAnyHex(this.payload.data),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read the SPI flash length from the declared len parameter

For a valid deviceSpiFlashRead(connectId, { address, len }) call, this code reads payload.data instead of payload.len. The exported API accepts SpiFlashRead, whose required length field is len, so normal callers produce an undefined wire length and their requested byte count is lost. Use the numeric payload.len directly; hex formatting is appropriate for write data, not a uint32 read length.

Useful? React with 👍 / 👎.

Comment on lines +18 to +22
value: this.payload.key,
encrypt: this.payload.key,
ask_on_encrypt: this.payload.key,
ask_on_decrypt: this.payload.key,
iv: this.payload.key,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Map each cipher parameter from its corresponding input

For cryptoCipherKeyValue, every field after key is also populated from payload.key, ignoring the caller's value, encryption direction, confirmation flags, and IV. In particular, a decrypt request with encrypt: false becomes an encrypt request for any nonempty key because protobuf converts that string to a truthy boolean, while the bytes being processed are the key label rather than the supplied ciphertext. Map each field from its corresponding payload property, as the production CipherKeyValue implementation does.

Useful? React with 👍 / 👎.

// init params
this.params = {
address_n: addressN,
branch: new Uint8Array(4),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the caller's Tezos transaction branch

Every tezosSignTx request replaces the supplied branch with four zero bytes. The exported TezosSignTxParams includes the transaction's branch, but that value never reaches the device, so even an otherwise valid transaction is submitted with an unrelated, invalid branch and cannot produce a usable signature for the requested operation. Validate and forward the supplied branch instead of constructing a placeholder buffer.

Useful? React with 👍 / 👎.

Comment on lines +29 to +33
const res = await this.device.commands.typedCall('BinanceSignTx', 'BinanceTxRequest', {
...this.params,
});

return Promise.resolve(res.message);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Complete the signing exchange before returning success

For a Binance transaction requiring message data, this method returns immediately after receiving BinanceTxRequest, which is an empty intermediate request rather than the BinanceSignedTx promised by the exported API. The new EOS signer has the same problem with EosTxActionRequest versus EosSignedTx. Neither implementation sends transaction messages/actions, and searching the Core and test-package method registries finds no continuation API to complete these exchanges. Accept the necessary transaction data and handle the request/ack sequence through the final signed response before resolving the public call.

Useful? React with 👍 / 👎.

}

async run() {
return this.device.commands.typedCall('SignIdentity', 'ECDHSessionKey', this.params);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Expect SignedIdentity from the identity-signing command

When a V1 device successfully processes cryptoSignIdentity, its SignIdentity response is SignedIdentity, containing the public key and signature, not ECDHSessionKey, which belongs to GetECDHSessionKey. This expected-response argument causes DeviceCommands.typedCall() to reject the successful signing response with ResponseUnexpectTypeError, making the new method unusable. Expect SignedIdentity here and update the exported return declaration in test-api-types/cryptoSignIdentity.ts to match.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed6f2a68bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +127 to +128
return call({
...(usesDeviceId ? params : deviceIdOrParams),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Redact device-load secrets before routing through Common SDK

Calling the newly exposed deviceLoad or bixinLoadDevice APIs forwards mnemonic material (and, for deviceLoad, the PIN) into Common SDK's call, which logs the complete parameters because getLogBlockLabel does not block these methods. This happens before destructive-operation authorization, so even rejected calls leak their secrets. The logger retains arguments and emits LOG_EVENT messages even with console debugging disabled; additionally, Core and transport redaction recognize mnemonic but not the new mnemonics field. Redact these requests at the Common SDK ingress and cover the plural mnemonic field in downstream sanitizers before exposing these methods.

AGENTS.md reference: AGENTS.md:L64-L65

Useful? React with 👍 / 👎.

// init params
this.params = {
address_n: addressN,
branch: new Uint8Array(4),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the caller's branch when signing Tezos operations

Every tezosSignTx call discards the required branch supplied through TezosSignTxParams and instead sends four zero bytes to the device. A mocked command-boundary check with a nonzero 32-byte branch confirms that the outgoing request contains only [0, 0, 0, 0]. Consequently, the device cannot sign the operation requested by the caller: it either rejects the malformed branch or signs different operation bytes. Validate and forward this.payload.branch rather than synthesizing a replacement.

Useful? React with 👍 / 👎.

Comment on lines +18 to +22
value: this.payload.key,
encrypt: this.payload.key,
ask_on_encrypt: this.payload.key,
ask_on_decrypt: this.payload.key,
iv: this.payload.key,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Map cipher inputs from their corresponding payload fields

For every cryptoCipherKeyValue request, the key label is also sent as the value, encryption flag, both confirmation flags, and IV. A mocked command-boundary check confirms that even an explicit encrypt: false request loses its ciphertext, IV, and operation selection. Normal encryption/decryption requests therefore fail or operate on different inputs instead of performing the requested cryptographic operation. Map and validate each field independently, as the existing production CipherKeyValue implementation does, and add focused encryption/decryption vectors.

AGENTS.md reference: AGENTS.md:L69-L70

Useful? React with 👍 / 👎.

}

async run() {
return this.device.commands.typedCall('SignIdentity', 'ECDHSessionKey', this.params);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Expect SignedIdentity from identity-signing requests

When a device successfully handles SignIdentity, the corresponding response is SignedIdentity, containing the address, public key, and signature—not ECDHSessionKey, which belongs to GetECDHSessionKey. DeviceCommands.typedCall enforces the supplied response type with assertType, so this method rejects a successful identity signature as an unexpected response and cannot complete identity-authentication workflows. Expect SignedIdentity, correct the exported return declaration, and add a focused successful-response test.

AGENTS.md reference: AGENTS.md:L69-L70

Useful? React with 👍 / 👎.

@sidmorizon

Copy link
Copy Markdown
Contributor

Comment on lines +86 to +87
testInitializeDeviceDuration: TestInitializeDeviceDuration,
testProtocolV2Ping: TestProtocolV2Ping,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 迁移 Expo 示例中的诊断调用

Problem

testInitializeDeviceDuration 和 testProtocolV2Ping 从 Core 的 createCoreApi 移到这里,但 Expo Playground 的 app/utils/hardwareInstance.ts:47 仍初始化默认 Common SDK,app/services/hardwareService.ts:364 仍在该实例上查找这两个方法。Expo Example 的初始化耗时测试也保留了旧调用。

Impact

Playground 的两个诊断入口在 WebUSB 和 emulator 下都会返回 Method … not found。Expo Example 的 V1 耗时测试也无法调用已移走的方法。

Recommendation

把示例中的诊断调用迁移到加载扩展的 SDK,保留生产 Core 的隔离,并按 transport 覆盖示例的诊断入口。

Codex local session ↗

Comment on lines +25 to +26
export { default as deviceGetFirmwareHash } from './manager/DeviceGetFirmwareHash';
export { default as deviceUnlockPath } from './manager/DeviceUnlockPath';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 让固件哈希与路径解锁匹配实际协议

Problem

DeviceGetFirmwareHash 和 DeviceUnlockPath 继承 BaseMethod.getSupportedProtocols() 的 V1 默认值。它们在 run() 中使用的 GetFirmwareHash、FirmwareHash、UnlockPath 和 UnlockedPathRequest 只存在于 V2 schema,当前和 legacy V1 的生产及扩展 schema 都缺少这些消息。

Impact

V2 设备在 Core 协议守卫处直接被拒绝。V1 设备通过守卫后在编码请求时查找不到消息。两个公开 API 因此都无法完成调用。

Recommendation

按固件和 schema 确认支持范围,为已有 V2 消息声明 V2 支持。如果需要 V1,补齐对应固件的 schema,并验证请求与响应的实际编解码。

Codex local session ↗

Comment on lines +10 to +12
init() {
this.useDevicePassphraseState = false;
this.skipForceUpdateCheck = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 让固件测试方法进入受支持的 bootloader 模式

Problem

firmwareErase、firmwareEraseEx 和 firmwareUploadTest 的 init() 都沿用 BaseMethod 默认的 allowDeviceMode。V1 已进入 bootloader 时,Device.hasUnexpectedMode() 会拦截这三个方法,生产上传流程则在该模式下调用这些命令。

Impact

即使工厂调用方显式设置了 allowDestructiveOperations: true,Core 仍会在 run() 前返回 NotAllowInBootloaderMode,导致固件擦除与上传测试无法到达目标设备。

Recommendation

按指令的固件契约允许或要求 bootloader 模式,保留现有操作授权,并用 mock 验证已授权调用能到达命令边界。

Codex local session ↗

Comment on lines +16 to +21
await updateResource(
this.device.commands.typedCall.bind(this.device.commands),
this.payload.name,
this.payload.data
);
return Promise.resolve(true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 按公开参数约定发送资源字节

Problem

test-api-types/resourceUpdate.ts:9 声明 data 为 string,这里却把它原样传给需要 ArrayBuffer 的 updateResource()。辅助函数以 data.byteLength 计算总长度和首块边界,这个属性在字符串上是 undefined。方法还把成功响应替换成 true,而公开类型声明为 Response<Success>。

Impact

调用方按公开类型传入任何非空资源字符串时,首包长度缺失,数据块为空,无法上传输入的资源。

Recommendation

统一公开类型与字节输入,或先按明确的编码解码并校验字符串,然后传输实际字节。返回辅助函数取得的 Success payload。

Codex local session ↗

Comment on lines +15 to +22
async run() {
return this.device.commands.typedCall(
'WebAuthnListResidentCredentials',
'WebAuthnCredentials',
{
...this.params,
}
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 让测试 API 返回声明的成功结果

Problem

WebAuthnListResidentCredentials.run() 直接返回 DeviceCommands.typedCall() 的 { type, message }。core/index.ts:661 把它原样放入成功响应的 payload,但 test-api-types/webAuthnListResidentCredentials.ts:8 声明的是 Response<WebAuthnCredentials>。Binance/EOS 地址或公钥、部分 Crypto/Bixin 方法及 WebAuthn 新增方法中也有相同的返回模式。

Impact

例如固件成功列出凭据后,按声明读取的 payload.credentials 是 undefined,实际字段位于 payload.message.credentials。依赖公开类型的工厂测试会误判或在访问字段时出错。

Recommendation

让这些方法从 typedCall() 解包 response.message 后交给 Core,按公开声明校验成功响应。对存在额外字段约定的方法也应返回声明的结构。

Codex local session ↗

Comment on lines +48 to +55
const result = {
path: serializedPath(param.address_n),
address,
watch_key,
};
responses.push(result);

this.postPreviousAddressMessage(result);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 从地址进度事件中移除 Monero 观察密钥

Problem

moneroGetWatchKey 把包含 watch_key 的返回对象传给 postPreviousAddressMessage()。该方法原样构造 PREVIOUS_ADDRESS_RESULT,Common SDK 将它广播给通用 UI 订阅者并记录完整事件,也会记录包含同一字段的成功响应。

Impact

每次固件返回观察密钥时,通用 UI 或日志订阅者都可能取得该密钥,并据此查看钱包交易。关闭 debug 控制台输出仍会保留日志记录和日志事件。

Recommendation

构造地址进度事件时仅复制 address 和 path,把 watch_key 限定在调用结果中,并在 Common SDK 和下游响应日志中脱敏。

Codex local session ↗

Comment on lines +25 to +27
export type DeviceCertificateSignature = {
signature?: string;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 保留工厂挑战签名的响应字段

Problem

这里把 DeviceCertificateSignature 声明为 { signature?: string }。V2 扩展 schema 将响应字段解码为 data,factory/methods.ts:109-110 直接返回 response.message。迁移前的公开类型也把该字段声明为 data。

Impact

按新类型读取 payload.signature 会得到 undefined,现有工厂工具迁移后读取 payload.data 也无法通过类型检查,因而无法按公开契约取得签名。

Recommendation

将返回类型恢复为 { data: string } 并在新包添加成功响应断言。若要更名,在方法内显式映射并处理调用方的兼容性。

Codex local session ↗

Comment on lines +76 to +81
deviceProvisionFactoryInfo: DeviceFactoryInfoSet,
deviceReadFactoryInfo: DeviceFactoryInfoGet,
deviceWriteFactoryCertificate: DeviceFactoryCertificateWrite,
deviceReadFactoryCertificate: DeviceFactoryCertificateRead,
deviceSignFactoryChallenge: DeviceFactoryChallengeSign,
deviceInfoSettings: DeviceInfoSettings,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 更新仍导入已删除模块的 Core 测试

Problem

工厂方法和 Ping.ts 迁出 Core 后,packages/core/__tests__/protocol-v2.test.ts:16-20 仍通过相对路径导入五个已删除的工厂模块,protocol-v2-ping.test.ts:1 仍导入已删除的 Ping.ts。

Impact

Jest 在加载这两个 suite 时就会遇到模块解析错误。protocol-v2.test.ts 中未迁移的设备、钱包和固件用例也无法执行。

Recommendation

将用到已迁出实现的工厂和 Ping 测试移到 hd-test-api,更新导入和 typedCallExtension mock,保留 Core suite 的其他用例。

Codex local session ↗

Comment on lines +17 to +22
paths: this.payload.paths.map((path: string) => {
const addressN = validatePath(path);
return {
address_n: addressN,
show_display: this.payload.show_display,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 按批量公钥接口声明解析每项路径

Problem

test-api-types/cryptoBatchGetPublickeys.ts:4-11 把 paths 声明为 { path, show_display? }[]。实现把整个对象交给只接受字符串或数组的 validatePath(),并从顶层读取 show_display。

Impact

按公开类型传入任意非空批次都会抛出 Not a valid path。每条路径设置的设备显示选项也没有被转发。

Recommendation

逐项解构并校验 path,从同一项读取 show_display,用包含多条路径和各自显示选项的输入验证编码前的请求。

Codex local session ↗

Comment on lines +17 to +21
const res = await this.device.commands.typedCall(
'DebugLinkGetState',
'DebugLinkState',
this.params
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 为 debugLinkStop 发送停止指令

Problem

debugLinkStop() 调用 DebugLinkGetState 并传入查询状态的等待参数。两份 V1 扩展 schema 为 DebugLinkStop 单独定义了空请求和消息 ID 103,状态查询使用 ID 101。

Impact

支持该命令的调试固件只会收到状态查询,调用方等待的停止操作一直没有发出。查询成功也会掩盖该问题。

Recommendation

按目标固件的调试协议发送 DebugLinkStop,并让返回类型及是否等待回复与停止命令的契约一致。

Codex local session ↗

connectId: string,
deviceId: string,
params: CommonParams & BTCAuthorizeCoinJoin
): Response<OwnershipProof>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P2 让 CoinJoin 授权类型返回实际的 Success

Problem

btcAuthorizeCoinJoin() 声明 Response<OwnershipProof>,但 BTCAuthorizeCoinJoin.ts:31-35 要求固件返回 Success 并返回其消息体。OwnershipProof 由单独的 btcGetOwnershipProof() 提供。

Impact

授权成功后,按类型读取 payload.ownership_proof 或 payload.signature 会得到 undefined,调用方可能将授权结果误用为所有权证明。

Recommendation

将授权方法声明为 Response<Success>,把证明的读取留给 btcGetOwnershipProof()。

Codex local session ↗

Comment on lines +18 to +22
const optionalJsonFiles = [
'../messages-protocol-v2.json',
'../../hd-test-api/src/protobuf/messages-v1.json',
'../../hd-test-api/src/protobuf/messages-protocol-v2.json',
];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P2 让 protobuf 类型生成保留工厂类型边界

Problem

新增的扩展 JSON 输入会经过现有的 SKIP 过滤,但 DeviceInfoSettings、GetDeviceInfo、WriteSEPublicCert 和 WriteSEPrivateKey 没有被排除。同一精确 head 的隔离副本直接运行 protobuf-types.js typescript 后,这四个已从 hd-transport 生成源移除的类型和 MessageType 条目全部恢复。

Impact

下一次常规 protobuf 生成会把这些工厂类型重新放进 hd-transport 的公开 TypeScript 注册表,使生成输出和本次迁移的包边界不一致。

Recommendation

让生成器按同一份工厂类型规则过滤输出,保留测试包仍需从 transport 导入的类型,并增加一个覆盖重新生成的边界断言。

Codex local session ↗

Comment on lines +11 to +17
if (targetValue === undefined) {
target[key] = sourceValue;
return;
}

if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
mergeNamespace(targetValue, sourceValue, currentPath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 合并 schema 时保留各扩展片段的独立性

Problem

mergeNamespace() 遇到新定义时把 sourceValue 的对象引用直接写进结果。后续扩展补充同一命名空间时会递归写入这个引用,因而修改先前传入的 schema 片段。独立验证副本用两个普通片段复现了源对象被改写。

Impact

第一次加载两个扩展后,即使后续只注册第一个扩展,重新合并仍会带上已移除扩展的定义。新配置的结果因此依赖上一次加载了哪些扩展。

Recommendation

把新增对象按值复制到合并结果,确保每次合并只修改本次结果。增加合并后检查输入,以及移除第二个片段后重新合并的测试。

Codex local session ↗

Comment on lines +8 to +13
const currentPath = path ? `${path}.${key}` : key;
const targetValue = target[key];

if (targetValue === undefined) {
target[key] = sourceValue;
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P2 在合并时拒绝重复的 protobuf 消息 ID

Problem

合并逻辑仅使用 schema 键名检查冲突。新 MessageType 名称可复用已有数字 ID,在独立验证副本中两个不同名的消息以相同 ID 一起通过合并。transport 编码按消息名取数字 ID,解码则通过 valuesById 从一个数字取一个名称。

Impact

扩展无意复用生产消息 ID 时,合并阶段仍返回成功,两个消息无法各自按名称完成协议往返。问题会延迟到 transport 配置或实际调用时才暴露。

Recommendation

合并时检查由名称和 wire ID 组成的双向映射,发现同一 ID 对应不同消息时立即返回包含冲突名称的错误。增加不同名称使用同一 ID 的测试。

Codex local session ↗

Comment on lines +213 to +219
export const createHardwareCommonConnectSdk = (options: HardwareCommonConnectSdkOptions = {}) =>
HardwareSdk({
eventEmitter,
init: createInit(options),
call,
cancel,
dispose,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 把设备操作授权绑定到初始化 SDK 的入口

Problem

createHardwareCommonConnectSdk() 只为 init 绑定 coreOptions。各返回对象共享 call 和 dispose,postMessage() 总是使用模块级 _core。只有授权工厂入口完成初始化时,默认 Common SDK 入口也会使用这个 Core 的授权选项。隔离副本中的模拟调用已确认,未初始化的默认入口能到达受保护的方法。

Impact

同一应用中,工厂流程初始化后,仍使用默认 SDK 入口的代码会继承该流程的授权,也可以释放该流程的活动 Core。这个问题只需要一个已初始化的 SDK。

Recommendation

将活动 Core 绑定到完成初始化的 SDK 入口。在调用和释放时校验归属,并测试未显式授权的默认入口在工厂入口初始化之后仍会被拒绝。

Codex local session ↗

}

async run() {
const res = await this.device.commands.typedCall('DoPreauthorized', 'Success');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 在同一次设备调用中完成 CoinJoin 预授权握手

Problem

deviceDoPreauthorized() 只接受 Success。固定固件在授权有效时发送 PreauthorizedRequest,随后等待实际操作。当前 typedCall() 会把这个中间响应判为类型错误,方法也没有继续处理。 固件处理函数

Impact

合法的 CoinJoin 预授权流程会在设备收到后续操作前中止。仅把公开返回类型改成中间响应仍无法完成流程。

Recommendation

将预授权和后续获准的操作放在同一个设备调用中,保留固件授权校验,并用模拟的中间响应和最终响应覆盖完整往返。

Codex local session ↗

Comment on lines +13 to +23
const { path, coin } = this.payload;

const addressN = validatePath(path);

const { coinName, scriptType } = getCoinAndScriptType(addressN, coin, false);

this.params = {
address_n: addressN,
coin_name: coinName,
multisig: this.payload.multisig,
script_type: scriptType || 'SPENDADDRESS',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 保留 Bitcoin 所有权请求指定的脚本类型

Problem

btcGetOwnershipProof() 与 btcGetOwnershipId() 都公开接受 scriptType,实现却不读取它,并把 false 传给 getCoinAndScriptType()。对于 BIP48 SegWit 多签路径,辅助函数会把首段推导出的 SPENDMULTISIG 降为 SPENDADDRESS。固定固件使用收到的脚本类型校验路径并生成对应脚本的证明或标识。 固件的路径匹配规则

Impact

调用方指定 SPENDWITNESS 或 SPENDP2SHWITNESS 时,固件接收的是不同的脚本类型,可能拒绝有效的多签请求或基于不同脚本计算结果。

Recommendation

校验并转发调用方指定的 scriptType。省略时根据 BIP48 子路径以及是否提供 multisig 选择类型,并覆盖两种 SegWit 多签。

Codex local session ↗

Comment on lines +16 to +19
const res = await this.device.commands.typedCall(
'DebugLinkMemoryRead',
'DebugLinkMemory',
this.params

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 在发送前验证 transport 支持 DebugLink

Problem

新增 DebugLink 方法统一走 DeviceCommands.typedCall(),底层使用当前业务会话。WebUSB 和 Node USB 只为该设备建立一个业务接口,没有为 DebugLink 选择独立会话。固定的 V1 固件在 USB 上将普通和调试收发分开,并按该类别查找消息。 固件的 USB 路由

Impact

在带独立 DebugLink 接口的 V1 设备上,SDK 可以编码调试请求,但 debugLinkMemoryRead() 和 debugLinkGetState() 等调用会发到普通接口,无法完成请求往返。

Recommendation

让调试 API 明确要求具备 DebugLink 能力并已授权的调试 transport。缺少能力时在发送前返回清晰错误,并用模拟 transport 覆盖会话选择。

Codex local session ↗

Comment on lines +13 to +16
const res = await this.device.commands.typedCall(
'DebugLinkGetState',
'DebugLinkLog',
this.params

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 按固件实际响应处理 DebugLink 命令

Problem

debugLinkGetState() 等待 DebugLinkLog,固定固件返回 DebugLinkState。debugLinkFlashErase() 等待 DebugLinkLayout,该命令的协议定义不使用这个响应。debugLinkDecision() 也固定等待 Success,固件的等待布局模式会发出 DebugLinkLayout。 调试消息契约

Impact

即使请求已通过支持 DebugLink 的 transport 正确送达,正常状态响应仍会被 typedCall() 拒绝。动作类命令也可能在设备已经处理后被 SDK 判为失败或超时。

Recommendation

按固定固件的请求契约分别处理同步回复、异步布局事件和无同步应答的情况,同时更新公开返回类型。以 DebugLinkState 成功响应覆盖状态读取。

Codex local session ↗

Comment on lines +46 to +51
export { default as debugLinkGetState } from './debug/DebugLinkGetState';
export { default as debugLinkMemoryRead } from './debug/DebugLinkMemoryRead';
export { default as debugLinkMemoryWrite } from './debug/DebugLinkMemoryWrite';
export { default as debugLinkRecordScreen } from './debug/DebugLinkRecordScreen';
export { default as debugLinkReseedRandom } from './debug/DebugLinkReseedRandom';
export { default as debugLinkStop } from './debug/DebugLinkStop';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1 在记录调试状态前屏蔽设备秘密

Problem

新增 debugLinkGetState() 会请求 DebugLinkState,其中固定固件可能填充 mnemonic_secret。DeviceCommands.ts:306-312 在检查预期响应类型前就记录该消息。getSafeTransportLogPayload() 会保留解码成字符串的 mnemonic_secret,隔离副本已用合成字段验证。 固定固件的状态响应

Impact

当已授权的调试 transport 收到含敏感字段的状态回复时,该字段会进入 SDK 日志。即使上层最终因响应类型不符返回失败,日志也已经生成。

Recommendation

记录前按消息类型屏蔽 DebugLinkState 的 payload,并对调试方法的调用结果日志应用同一规则。用合成数据验证失败分支也不会留下敏感字段。

Codex local session ↗


private static async configureProtocolV2Messages() {
const protocolV2Messages = DataManager.getProtobufMessages('v2Schema');
const protocolV2Messages = this.getMessages('v2Schema');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P2 让 V2 扩展 schema 校验错误可见

Problem

Core.init() 通过 DeviceConnector 只加载 V1 默认 schema。V2 schema 首次在 configureProtocolV2Messages() 合并,扩展命中同名冲突时抛出的错误却被 configure() 外层捕获。隔离副本的模拟 transport 确认调用以成功结束,但只完成了 V1 配置。

Impact

配置不兼容扩展的集成方会收到初始化成功,后续设备探测或 V2 调用才因 codec 缺失失败,拿不到真正的冲突原因。

Recommendation

在发布可调用的 Core 前校验所配置的扩展 schema,或在延迟配置时向调用方返回明确的 schema 错误。测试中同时断言调用失败与错误保留冲突位置。

Codex local session ↗

@originalix

Copy link
Copy Markdown
Contributor

Automated review needs attention

Review of commit ed6f2a68bb8f finished, but some comments could not be published automatically.

Publication requires a retry or human review. This is not an automated approval.

This branch has not been deployed

No deployments
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.

3 participants