Skip to content

feat: emulator branch changes#18

Closed
wabicai wants to merge 5 commits intoonekeyfrom
emulator
Closed

feat: emulator branch changes#18
wabicai wants to merge 5 commits intoonekeyfrom
emulator

Conversation

@wabicai
Copy link
Member

@wabicai wabicai commented Jun 17, 2025

This PR merges the changes from the emulator branch into the onekey branch.

Summary by CodeRabbit

  • New Features
    • Added support for configuring the HTTP server port via a new command-line parameter, allowing users to specify a custom port instead of the default.
  • Documentation
    • Expanded README with a new "Launch Parameters" section, updated usage examples, and clarified API documentation regarding configurable ports.
  • Chores
    • Updated an indirect dependency to a newer version.
    • Incremented the application version to 2.2.2.

@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The update adds a -p launch parameter to set the HTTP server port, replacing hardcoded values with dynamic configuration throughout the codebase. Documentation now explains how to use this parameter. Function signatures and struct fields were updated to support the configurable port. The version number and a dependency were also updated.

Changes

File(s) Change Summary
README.md Added "Launch Parameters" section; updated examples and docs for new -p port parameter.
VERSION Bumped version from 2.2.1 to 2.2.2.
go.mod Updated indirect dependency github.com/BurntSushi/toml from v1.2.1 to v1.5.0.
onekey.go Added -p flag for HTTP port; updated call to server.New to pass new port parameter.
server/http.go Added port field to Server struct; updated New function and server binding logic for port.
server/status/status.go Added port field to status struct; updated function signatures and logic for dynamic port use.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Main
    participant Server
    participant Status

    User->>Main: Launch with -p <port>
    Main->>Server: New(core, ..., httpPort)
    Server->>Status: ServeStatus(router, core, ..., httpPort)
    Server->>Status: ServeStatusRedirect(router, httpPort)
    Server->>Server: Start HTTP server on :<httpPort>
    User->>Server: HTTP request to :<httpPort>
    Server->>Status: Handle status/redirect with dynamic port
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 224ddfe and 1300ddd.

📒 Files selected for processing (1)
  • onekey.go (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch emulator
  • Post Copyable Unit Tests in Comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🔭 Outside diff range comments (1)
onekey.go (1)

105-115: Validate user-supplied port before use

flag.IntVar(&httpPort, …) allows negative numbers and values > 65535.
A quick range check prevents accidental crashes or privilege issues.

 flag.Parse()

+if httpPort <= 0 || httpPort > 65535 {
+	log.Fatalf("invalid HTTP port: %d (must be 1-65535)", httpPort)
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 3c1f421 and 224ddfe.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • README.md (3 hunks)
  • VERSION (1 hunks)
  • go.mod (1 hunks)
  • onekey.go (3 hunks)
  • server/http.go (3 hunks)
  • server/status/status.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
onekey.go (1)
server/http.go (1)
  • New (28-75)
server/http.go (2)
server/status/status.go (2)
  • ServeStatus (39-55)
  • ServeStatusRedirect (26-33)
server/api/api.go (1)
  • ServeAPI (26-54)
server/status/status.go (3)
server/status/origincheck.go (1)
  • OriginCheck (30-38)
core/core.go (1)
  • Core (98-133)
memorywriter/memorywriter.go (1)
  • MemoryWriter (22-32)
🪛 LanguageTool
README.md

[uncategorized] ~17-~17: Possible missing comma found.
Context: ...n OneKey bridge runs an HTTP server on port 21320 by default. You can change this p...

(AI_HYDRA_LEO_MISSING_COMMA)


[style] ~35-~35: Consider a more concise word here.
Context: ..../onekeyd -e 54935` To disable all USB in order to run on some virtual environments,launch...

(IN_ORDER_TO_PREMIUM)


[misspelling] ~54-~54: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ...I documentation onekey-bridge starts a HTTP server on http://localhost:21320...

(EN_A_VS_AN)

🪛 markdownlint-cli2 (0.17.2)
README.md

20-20: Lists should be surrounded by blank lines
null

(MD032, blanks-around-lists)


25-25: Lists should be surrounded by blank lines
null

(MD032, blanks-around-lists)


38-38: Lists should be surrounded by blank lines
null

(MD032, blanks-around-lists)

🪛 Gitleaks (8.26.0)
server/status/status.go

24-24: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (4)
go.mod (1)

14-14: Make sure go.sum is regenerated after the TOML bump

Updating an indirect dependency should be followed by
go mod tidy so that go.sum reflects the new hashes.
Otherwise CI may fail on checksum mismatch in clean clones.

Run:

#!/bin/bash
go mod tidy
git diff --exit-code go.sum
VERSION (1)

1-2: Version bump looks good
No concerns.

server/http.go (1)

38-40: Bind on localhost only — intentional?

Hard-coding 127.0.0.1 prevents remote access even in trusted LAN setups.
If that is not intentional, accept 0.0.0.0 when the user passes
-p but also wants exposure.

-Addr: fmt.Sprintf("127.0.0.1:%d", httpPort),
+Addr: fmt.Sprintf(":%d", httpPort), // listen on all interfaces
server/status/status.go (1)

21-22: port field is written but never read

status.port gets set in ServeStatus (line 45) yet nothing in this file reads it. Unused data adds noise and may rot.

Either remove the field or actually use it (e.g. expose it in templates or helpers).

Comment on lines +173 to 176
s, err := server.New(c, stderrWriter, shortMemoryWriter, longMemoryWriter, version, httpPort)

if err != nil {
stderrLogger.Fatalf("https: %s", err)
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Handle “address already in use” gracefully

Right now server.New returns an http.Server that will fail only when
Run() is called. Consider binding early so you can surface a clearer
error (e.g., “port 21320 busy”) before the heavy initialisation work.

🤖 Prompt for AI Agents
In onekey.go around lines 173 to 176, the current code initializes the server
but only detects port conflicts when Run() is called, which delays error
reporting. Modify the server.New function or its usage to perform an early bind
to the specified port before full initialization, so that if the port is already
in use, the error can be caught and reported immediately with a clear message
like "port 21320 busy." This will require attempting to listen on the port early
and returning an error if binding fails, allowing the caller to handle it
gracefully before proceeding with heavy setup.

Comment on lines 24 to 26
writer io.Writer
port int
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

port field is never read

Server.port is assigned but not used elsewhere. Either:

  1. Remove the field to keep the struct lean, or
  2. Expose a getter so callers can ask the server which port it bound.

Leaning toward option 1 for now.

🤖 Prompt for AI Agents
In server/http.go around lines 24 to 26, the port field in the Server struct is
assigned but never read or used. To fix this, remove the port field entirely
from the Server struct to keep it lean and avoid unused code.

Comment on lines +17 to +24
OneKey bridge runs an HTTP server on port 21320 by default. You can change this port using the `-p` parameter.

**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321

This is useful when:
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix article and punctuation

-OneKey bridge runs an HTTP server on port 21320 by default. You can change this port using the `-p` parameter.
+OneKey Bridge runs an HTTP server on port 21320 by default; you can change the port with the `-p` parameter.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
OneKey bridge runs an HTTP server on port 21320 by default. You can change this port using the `-p` parameter.
**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321
This is useful when:
OneKey Bridge runs an HTTP server on port 21320 by default; you can change the port with the `-p` parameter.
**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321
This is useful when:
🧰 Tools
🪛 LanguageTool

[uncategorized] ~17-~17: Possible missing comma found.
Context: ...n OneKey bridge runs an HTTP server on port 21320 by default. You can change this p...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 markdownlint-cli2 (0.17.2)

20-20: Lists should be surrounded by blank lines
null

(MD032, blanks-around-lists)

🤖 Prompt for AI Agents
In README.md around lines 17 to 24, correct the article usage and punctuation in
the description about the OneKey bridge HTTP server port. Change "an HTTP
server" to "a HTTP server" if following the pronunciation rule or keep "an HTTP
server" if considering the 'H' sound, and ensure punctuation such as colons and
periods are properly placed after the examples and sentences for clarity and
grammatical correctness.

Comment on lines +19 to +23
**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Blank line before list to satisfy Markdownlint (MD032)

-**Examples:**
+**Examples:**  
+
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321
**Examples:**
- `./onekeyd` - Uses default port 21320
- `./onekeyd -p 21325` - Uses port 21325
- `./onekeyd -p 21321` - Uses port 21321
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

20-20: Lists should be surrounded by blank lines
null

(MD032, blanks-around-lists)

🤖 Prompt for AI Agents
In README.md around lines 19 to 23, add a blank line before the list of examples
to satisfy Markdownlint rule MD032. This means inserting an empty line above the
line starting with "**Examples:**" to separate the preceding paragraph or
content from the list.

Comment on lines 52 to 54
"/status/": "",
"/status/log.gz": "http://127.0.0.1:21320",
"/status/log.gz": fmt.Sprintf("http://127.0.0.1:%d", httpPort),
}))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Origin map can be built once

fmt.Sprintf runs on every request middleware chain build. Not critical, but you could pre-compute the map for clarity:

allowed := map[string]string{
    "/status/":       "",
    "/status/log.gz": fmt.Sprintf("http://127.0.0.1:%d", httpPort),
}
r.Use(OriginCheck(allowed))
🤖 Prompt for AI Agents
In server/status/status.go around lines 52 to 54, the origin map is being built
with fmt.Sprintf inside the middleware setup, causing it to be recomputed on
every request. To fix this, precompute the allowed origins map once before
setting up the middleware by creating the map with the formatted string assigned
to "/status/log.gz" and then pass this precomputed map to the OriginCheck
middleware. This improves clarity and avoids unnecessary repeated computation.

Comment on lines +26 to +29
func ServeStatusRedirect(r *mux.Router, httpPort int) {
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
redirect(w, r, httpPort)
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Sanity-check httpPort before using it

ServeStatusRedirect trusts the incoming httpPort. If the caller passes 0 or a negative/invalid value you’ll generate a broken URL like http://127.0.0.1:0/status/.

Add a quick guard:

+if httpPort <= 0 || httpPort > 65535 {
+    httpPort = 21320 // fallback or return an error
+}
🤖 Prompt for AI Agents
In server/status/status.go around lines 26 to 29, the ServeStatusRedirect
function uses the httpPort parameter without validation, which can lead to
invalid URLs if httpPort is zero or negative. Add a guard clause at the start of
ServeStatusRedirect to check if httpPort is a positive integer; if not, set it
to a default valid port number or return early to avoid creating broken redirect
URLs.

Comment on lines +35 to 37
func redirect(w http.ResponseWriter, r *http.Request, httpPort int) {
http.Redirect(w, r, fmt.Sprintf("http://127.0.0.1:%d/status/", httpPort), http.StatusMovedPermanently)
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Use 307 or 308 for redirects that preserve method

For local tooling a permanent 301 works, but if clients might POST to / you could break them. Consider a 307/308 which keeps the HTTP method intact:

-http.Redirect(w, r, fmt.Sprintf("http://127.0.0.1:%d/status/", httpPort), http.StatusMovedPermanently)
+http.Redirect(w, r, fmt.Sprintf("http://127.0.0.1:%d/status/", httpPort), http.StatusTemporaryRedirect)
🤖 Prompt for AI Agents
In server/status/status.go around lines 35 to 37, the redirect uses HTTP status
301 which does not preserve the HTTP method and can break POST requests. Change
the status code in the http.Redirect call to either 307 or 308 to ensure the
HTTP method is preserved during the redirect.

@wabicai wabicai closed this Jun 17, 2025
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.

1 participant