Compare commits

..

551 Commits
v1.4.0 ... main

Author SHA1 Message Date
Guoguo
d8553cf40b docs: add 2.5.4 changelog entries 2026-11-10 10:27:44 +08:00
梁子月
bb7194eb6c Merge pull request #982 from liangzhuohua/feat/storage-file-manager-ui
feat(storage): adopt the NanoKVM Go file-manager UI
2026-11-06 18:52:26 +08:00
916BGAI
44c420e28b fix: prevent black screen after application upgrades
Serialize service operations and finish migration before starting services.
Install the startup script atomically, remove recursive restarts, and keep
the migration marker until required changes succeed.

Claim video ownership before clearing orphan VENC/VPSS resources, always
finish recovery SYS cleanup, and retain resource state on teardown failures.
Rebuild the bundled libkvm_mmf.so with these fixes.

Validated cross-builds, ABI and recovery failure paths, plus a 2.4.3 to 2.5.3
upgrade on hardware with 1080p browser WebRTC and MJPEG playback.
2026-11-04 19:45:09 +08:00
916BGAI
4b54fc4768 refactor(video): use Sophgo SDK for H.264 and MJPEG
Use per-codec capture locks and encoder backpressure, simplify frame ownership, and follow HDMI input dimensions. Refresh prebuilt video libraries while preserving server-only builds and deployment instructions.
2026-11-04 14:57:49 +08:00
Guoguo
02242c1908 docs: add 2.5.2 and 2.5.3 changelog entries 2026-11-03 09:59:38 +08:00
watermeko
509a22f6bd feat: add multiuser permission system (#958)
* feat(auth): add fine-grained feature permissions for multi-user access

Introduce a grantable permission catalog on top of the admin/user roles:
administrators keep implicit full access, while regular users receive an
explicit permission set covering console view/control, power, media
mount/manage, terminal, device, network, update, mcp, tailscale and ai
feature groups. Media access splits along the trust boundary: mounting
library media and reading it is media.mount, while changing library
contents (uploads, deletes, file exchange with the target) is media.manage.

Server:
- store permissions on the account record; nil keeps the pre-permission
  user behavior (console view/control and power) so upgrades are seamless
- add RequirePermission middleware and map every route to its group;
  user management stays admin-only
- require console.view in the grant set a regular user ends up with,
  including when a role change alone would leave an account without it,
  since nothing in the app renders without that grant
- let a user who may mount media read the library and follow an image
  download, while starting, cancelling or deleting stays media.manage
- scope console.control to input: keyboard, mouse, paste, and the input
  region that maps pointer motion onto the target screen. Video encoding,
  quality, resolution and capture recovery need only console.view, since
  every account holds it and a watcher still has to pick a quality its
  link can carry
- websocket console drops keyboard/mouse reports for view-only sessions
- permission changes keep the login valid: TokenVersion is only bumped
  for role/enabled changes, a grant that changes a long-lived
  connection's cached state drops that channel with a dedicated 4403
  close code so the client reconnects with fresh permissions, and the
  frontend is notified over the console websocket to refresh in place;
  a rejected request also triggers a silent account refresh
- document the catalog, the media split, the input-only scope of
  console.control and the grants that reach the whole device (terminal,
  device, update, mcp, ai) in server/README.md and README_ZH.md
- warn in the account editor that mcp hands out a device-wide API key
  which keeps working after the grant is revoked, the same way the ai
  grant is flagged for reaching the device outside the other grants

Web:
- account endpoint returns effective permissions; menus, settings tabs,
  storage page actions and editors render per permission instead of the
  isAdmin flag, and the terminal and storage routes are guarded by the
  matching grant
- a session without console.control stops capturing the pointer and the
  keyboard, hides the input-region editor and its stale-region cleanup,
  and marks the console as view only, mirroring the server that drops
  those reports; the client also gates a report already in flight
- user management gains a grouped permission editor with the console-view
  grant pinned, and warning hints on the mcp and ai grants; rows use
  aligned icon actions with tooltips
- every page refreshes the account when its grants change: the console
  socket handles the auth event itself, pages without a socket re-read on
  route change and when they become visible, and the ai sidebar closes
  once the grant is gone
- the terminal, the WebRTC viewer and the console all honor the 4403
  permission-change close instead of stranding the page or the login

Localization:
- ship every string this feature adds, including the permission editor,
  the view-only badge and the mcp/ai warnings, in all 24 supported
  locales

Verified with go vet, go test for authn/middleware/service auth, tsc
--noEmit, eslint, prettier, and a key-by-key comparison of every locale
against en.ts (694 keys, none missing).

* fix(auth): keep the emulated USB devices under the device grant

The virtual disk and the RNDIS adapter toggle the emulated USB gadget in
Settings > Device: the disk hands the target machine the raw data
partition, the adapter hands it a network interface. Neither is a media
or a network operation, so both follow `device` instead of media.mount
and network.

- route /vm/device/virtual through `device` only, so no handler has to
  narrow a union to the device a request touches
- render both switches wherever the device settings are visible, and
  read the medium state, stop a transfer, or pick the disk warning only
  with the matching media grant
- the storage page offers to enable the virtual disk only to accounts
  that may toggle it; the others are told which account has to do it,
  with the new string added in every locale
- document that attaching a medium needs the virtual disk, and that
  `device` can hand out the raw data partition and a network interface

Verified with go vet, go test for authn/middleware/service auth, tsc
--noEmit, eslint, prettier, and a key-by-key comparison of every locale
against en.ts (695 keys, none missing).

* fix(auth): repair the permission editor and the refresh path

The permission editor and the code around it shipped with several defects:

- the editor kept its field values after the modal was destroyed (antd forms
  preserve values by default), so opening it for a second account showed the
  previous account's grants and saving wrote them onto that account. The
  selection now lives in component state and is seeded when the editor opens,
  so a cancelled edit is dropped as well
- a save closed the dialog even when the server refused the change, and the
  reason was replaced by a generic message. updateUser reports success now and
  the server's own refusal (an omitted console.view, an invalid role, ...) is
  shown next to the failure
- a refused virtual-disk toggle in Settings > Device only reached the console.
  A device holder without media.manage cannot cancel the transfer that holds
  /data, so that refusal is expected and now says why the switch did not move
- losing the grant behind an open settings tab left an empty panel, and a
  vanished update tab could keep the modal locked and unclosable
- a role change bumped the token version and logged the account out mid
  session, while a permission change did not. Only disabling an account
  invalidates the login now: a role change resolves to its implicit grants and
  takes the same notify-and-reconnect path as a grant edit, so a promoted or
  demoted account keeps working and simply reconnects with new capabilities
- the console offered a mouse menu whose items only shape input, and mounted
  the on-screen keyboard, for accounts that cannot send input at all
- the account rows stopped wrapping on narrow screens and the icon-only
  actions had no accessible name
- the editor groups grants by what they reach, with media.mount next to
  media.manage instead of under the console grants, and gained a title, a
  Save/Cancel pair and a localized Media section

Server side, authn.Has replaces three copies of the same lookup, the
permission-aware channel map documents that console.view is pinned, and the
HDMI reset keeps its console.view grant with the reasoning written down.
The documentation follows: a permission change no longer claims to interrupt
the video stream, HDMI reset is listed with the view operations, and only
disabling an account invalidates a login.

* feat(auth): give the service grants their own permission group

mcp, tailscale and ai reach the device on their own — an API key outside the
web session, a VPN mesh, an agent driving the local loopback interface —
instead of through the settings the remaining grants cover, so they no longer
share the Administration section with terminal, device, network and update.

The editor renders them as a Services section between Media and
Administration, and the label ships in all 24 locales.

* refactor(auth): model grants as a catalog with implied grants

Replace the media-aware flat grant list with a catalog the server serves to the
account editor: each grant carries a group, a risk level and the grants it
implies, so labels, sections and risk marks cannot drift from what the server
enforces.

Server:
- resolve implied grants before answering a request, which removes the
  route-level unions: console.control implies console.view, and both
  medium.attach and library.write imply library.read
- split media access three ways along the trust boundary: medium.attach mounts,
  ejects and writes into the shared partition the target machine reads,
  library.write changes what the library keeps, and library.read lists and
  downloads. The file endpoints serve an image and the partition through one
  path, so they admit either grant and check the medium type in the request
- stop pinning console.view: with control implying view, an account may hold no
  console access at all, and the web app lands on a page that offers the
  sections its grants open
- materialize the grant set when the account file is read, so a record written
  before fine-grained permissions keeps exactly what the user role granted, and
  nil no longer means different behavior later; the split media grants are
  translated on load
- keep grants this build does not know instead of refusing the file, so a
  downgrade cannot lock the device out
- serve the stored set to the account list and the effective closure to the
  account endpoint

Web:
- render the editor from the catalog: grouped sections, a per-grant tooltip with
  a risk marker, implied grants shown as included, and the grants that amount to
  full device control summarized in one line
- show an administrator's stored set read-only with what a demotion restores,
  and refuse to edit while the catalog cannot be loaded
- guard the terminal, storage and console routes and the in-page actions that
  were gated by the isAdmin flag by the matching grant instead
- add a landing page for an account without console access, and let the account
  list say how many grants each account holds
- ship the new strings in all 24 locales

Docs: describe the catalog, the media split, the implied grants and the
unpinned console in server/README.md and server/README_ZH.md.

* fix(web): align the settings icons with the rest of the menu

The settings icon carried a 3px top padding to compensate for the baseline gap
an inline svg leaves inside an antd Badge, which pushed it below the other menu
icons. A flex wrapper removes the gap instead, so the icon centers the way every
MenuItem does.

- center the settings modal tab icons in their 16px box instead of leaving them
  on the box baseline
- draw the account and the Tailscale tabs at 16px: both used an 18px icon inside
  a 16px box, and the Tailscale icon now takes a size prop instead of a class

* fix(web): draw CJK punctuation with a CJK face

antd components (tooltips, dialogs) and the Tailwind-styled page text used
different font stacks, so the ideographic comma and full stop could resolve to
different faces: a Latin font in antd's stack draws them above the baseline,
which made Chinese and Japanese tooltips look misaligned.

- pin U+3001 and U+3002 to a real CJK face through a @font-face with
  unicode-range, falling back to the rest of the stack when none of the local
  fonts is installed
- give the app one stack, shared by html/body and antd's font-family token

* feat(web): list administrators above regular users

An account that can change everyone else belongs at the top of the list, and the
row reads differently at a glance: administrators get a lighter card than the
regular accounts they administer.

The sort is stable, so accounts keep the order the account file lists them in
within each group.

* fix(auth): keep a granted capability reachable from the page that configures it

Two defects in the same catalog. The grants whose controls live in the
console menu could be handed out without console.view, and nothing outside
the console renders them, so an account could hold a capability no page
offered. And the catalog carried a third risk level the editor never used.

- imply console.view from power, device, network, update, mcp, tailscale
  and ai, the way console.control already did, so every grant has a page
  that can use it; terminal and the media grants keep their own pages
- collapse risk to two levels: warn now marks the three grants that amount
  to full device control (terminal, mcp, ai), while device, update and the
  grants that change settings everyone shares are plain info
- default a user-role account created without naming a grant set to what
  the user role granted before grants existed, so a script that only knows
  about roles keeps working; an explicit empty set still means empty
- document the implied console, the two levels and the create default

* fix(web): repair the account permission editor and its confirmations

The editor treated an explicitly stored grant that another selection
already implies as editable, so console.view looked free to uncheck on an
account where device settings brought it back; it also attributed the
grant to that other selection, which describes a default permission
backwards. Saving closed the dialog, and an administrator's reference set
was described by a banner above thirteen boxes it contradicted.

- lock any grant a selected grant already brings in, and only add the
  "included by" note to a grant the account does not store itself
- keep the dialog open after a save and let the footer button say Saved
  for a moment; editing again drops the confirmation
- drop the administrator banner and render the whole catalog as its
  read-only set, so a freshly created administrator no longer trips the
  empty-set warning
- render the catalog's two risk levels: warn draws the shield and the
  full-control summary, info stays a plain help mark
- ship the new Saved label, rename the summary key and retire the demote
  hint in all 24 locales, and mirror the catalog in the mocked handlers

* fix(web): honor the grants for the storage mount mode and the mouse menu

The full storage page still offered the mount-mode selector to an account
that cannot attach, where the console menu already hid it, and the mouse
menu vanished for a view-only account even though its cursor style is
local to the screen and needs no grant.

- hide the mount-mode selector on the storage page unless medium.attach,
  the way the console menu does
- keep the mouse menu for a view-only account with the cursor style as its
  only entry, instead of returning nothing

* refactor(web): use antd for the chat composer and drop the scroll-area primitive

The chat input was the last visible raw form control, and the settings
dialog and shortcut lists scrolled through a Radix primitive whose styling
does not match the scrollbars the rest of the app draws.

- send the chat message through antd's Input.TextArea; the composer's
  shape is carried by important utilities rather than a second styling
  system, and Enter-to-send plus the IME handling stay as they were
- replace the Radix scroll area with the native scroll container the other
  pages use, so the settings dialog and the shortcut lists scroll alike
- remove the component that wrapped it and the @radix-ui/react-scroll-area
  dependency

* fix(auth): close the gaps between grants and what they reach

- require library.write for a partition upload of an .iso/.img and for
  deleting a partition file or folder that holds one: every image on /data
  is a library entry, so medium.attach alone could add or remove them
- mark update as warn: an offline package is checked only against the
  checksum its uploader supplies, so the grant amounts to root
- regenerate the device-wide MCP API key when an account loses the mcp
  grant (revoked, demoted, disabled or deleted), so a copied key stops
  working with the grant
- re-read the account after a session registers, so a grant edit landing
  between authentication and registration can no longer leave a
  long-lived connection on the old grants
- return the account before and after from Store.Update under one lock,
  so concurrent edits diff against the state they actually changed
- keep stored grants this build does not know when a request replaces
  the set, instead of refusing or dropping them
- push the auth refresh event off the admin request path
- cover the catalog closure, legacy translation, unknown-grant carry-over,
  warn levels and the library guard with tests

* fix(web): follow the grant fixes in the account and tailscale pages

- show the memory and swap settings in the Tailscale menu only with
  device, which their endpoints require
- let only the latest account refresh set the state, and coalesce the
  focus and visibilitychange events that fire together on tab return
- keep the storage page console socket across auth pushes by depending
  on the grant instead of the hasPermission identity
- send only catalog grants from the permission editor; the server keeps
  stored ones it does not know
- describe the MCP key rotation in all 24 locales, add the singular
  grant count, and mirror the update risk level in the mocks

* fix(auth): check the on-disk name and report a failed key rotation

- check a partition upload against the file it actually replaces: exFAT
  folds case with its own table, so a name that is not an image in the
  request can still overwrite one on disk
- report a failed MCP key rotation to the administrator instead of
  answering OK while the old key keeps working
- re-read the account after registration only for the long-lived
  channels a grant edit can drop, so short requests do not read the
  account file twice

* feat(auth): let the administrator choose whether to rotate the MCP key

Regenerating the device-wide MCP API key disconnects every MCP client, so
rotating it on every revocation took a decision away from the person who
has to live with it. A change that takes the mcp grant away now warns
first and leaves the rotation to the administrator.

- server: rotate only when the request asks for it (rotateMcpKey in the
  update body, a query parameter on delete) and report mcpKeyRotated in
  the response; a kept key is logged as a warning
- web: before saving a grant set, changing the role, disabling or deleting
  an account that would lose the key, show a warning with a "Regenerate
  the MCP API key" checkbox, checked by default; unchecking it explains
  that a copied key stays valid, and a rotation is confirmed afterwards
- describe the choice in the mcp grant help and the server READMEs, and
  ship the new strings in all 24 locales

---------

Co-authored-by: Guoguo <i@qwq.trade>
2026-10-21 15:19:45 +08:00
watermeko
5572e1de35 feat(storage): browse a medium and exchange files with the target machine (#957)
* feat(storage): browse a medium and exchange files with the target machine

The image menu and the download page are replaced by one storage page: it
lists the media the emulated USB disk can carry, mounts and ejects them, and
browses the files inside a medium over that same gadget, so the two machines
exchange files without going through the terminal.

Mediated media:

* Add the media API (list, state, mount, eject, delete, download, files) and a
  file browser on top of it, and keep the pre-2.6 image endpoints working as a
  compatibility layer over the same code.
* Add diskfs: an image is mounted through a loop device so the kernel's exFAT
  and FAT drivers read it, and the data partition is browsed in place, because
  the emulated disk already hands that very directory to the target machine.
* Keep the one-writer policy the read-only mounts introduced: an image is
  served read-only in every mode, and the whole data partition is remounted
  read-only here while the target machine is its writer, through the same
  SetDataWritable the virtual disk switch uses. The file manager refuses those
  writes itself as well, so a request does not depend on a mount state.
* Name the mounted medium and the USB device after the image file, cut to the
  SCSI inquiry product field and the USB product string, and restore the
  defaults when the medium is released.
* Close the HID devices around a gadget re-enumeration and reopen them after,
  since mounting and a forced eject drop them.
* Report transfers through one job slot with progress, queueing behind a
  running transfer, and a free space preflight before an upload starts. Image
  uploads keep the volume descriptor and partition table check, so an unusable
  image is rejected while it streams.

The shared folder view:

* Refresh it on a timer while the target machine owns the partition. The
  target's block level writes land in this device's page cache, which the
  mounted exFAT shares, so the file data here is already current - but the
  dentry and inode caches are not, and a file the target grew keeps the size
  it was first read with. Dropping those caches and pushing a storage event
  makes the web UI follow the target machine within a second of its own
  writeback. The partition's write counter cannot drive this: it only moves
  once this side writes its dirty pages back, which is tens of seconds later
  or never.
* Send the refresh notifications from their own goroutine, so a client that
  stopped reading cannot hold up the refresh loop.

The web UI:

* Add the storage page: the medium list with mount and eject, the file browser
  with search and sorting, uploads, downloads and deletes, and transfer
  progress.
* Gate writing on the target machine owning the disk - image uploads and file
  uploads alike - instead of letting the server answer with an error the page
  has to surface, and drop the medium rows' download and delete buttons there
  too.
* Give the shared folder, .iso and .img their own glyphs, and pick the file
  icon from the extension, so a listing can be read at a glance.
* Name the partition the way the storage page does in the desktop menu as
  well, instead of showing the API's untranslated string.
* Read the mounted medium in Settings - Device from the media state, now that
  the storage API it used is gone.
* Tell an ISO 9660 image apart from a filesystem that cannot be read at all:
  the kernel of this device carries no iso9660 support (CONFIG_ISO9660_FS), so
  the contents of an ISO cannot be listed while the image itself is served to
  the target machine like any other medium.

Localization:

* Translate the new strings for every locale, keep the Settings - Device
  strings the read-only mounts added, and drop the keys the retired image menu
  and download page left behind.

Chores:

* Remove the desktop image menu, the download page and the API they used.

* fix(storage): harden media file transfers

Serialize medium deletion with gadget attachment and restore /data write access after failed mount transitions.

Use available filesystem space for upload limits, refine virtual-device and shared-file handling, and update media path and installation test coverage.

Pin an image while it is streamed out, so a writable mount cannot start between the check and the last byte; sweep stale upload temporaries from the whole data partition at startup, which the file manager itself cannot delete; and preflight URL downloads against the response size, which only the upload path did.

Show dot files in the file browser again: only the two transfer temporary prefixes stay hidden, which is what the dot filter was for.

Delete folders recursively after the web UI confirms, refusing when an attached or mounted medium lives inside the directory; accept every .iso and .img upload by name instead of sniffing volume descriptors; and show image and file transfers in one progress display at the top of the storage page.

* fix(storage): make cache drops work and close delete and gadget races

- drop_caches only accepts 1..4 on 5.10: write 4 once to silence the log,
  then 2/3. Writing 6/7 failed with EINVAL, so the shared folder never
  saw what the target machine wrote.
- Resolve a delete path to its on-disk spelling (exFAT is case-insensitive)
  before checking it against the attached and loop-mounted media, refuse
  deleting a loop-mounted image or a folder holding an upload target, and
  fail closed when the disk state cannot be read.
- GetMediaState no longer fails when the virtual disk is off and lun.0 does
  not exist; browsing works with the virtual disk off.
- An explicit enable for the virtual disk compares against the disk being
  configured, so it leaves a served image alone; the settings toggle keeps
  the #937 semantics.
- Restore /data write access after a failed gadget script or network switch.
- eject clears the LUN file before resetting ro/cdrom, so a refused eject
  does not change the type of the medium still being served.
- Mount loop images with MS_NOSYMFOLLOW and open files with O_NOFOLLOW.
- Accept UDF images as optical media.
- Only refuse deleting transfer temporaries while a transfer runs; sweep
  stale ones in the background, by exact name, and not on a read-only /data;
  hide them from listings.
- Cap URL downloads without Content-Length at the free space and verify the
  received length.
- Encode Content-Disposition filename* strictly per RFC 5987.
- Restore image_test.go and add tests for the above.

* fix(web): keep the file browser and transfers consistent on the storage page

- Tag a listing with the medium and path it belongs to, so entries of the
  previous directory are never shown or acted on under a new path.
- Poll the desktop storage menu only while it is open.
- Show a dedicated message for a checksum mismatch.
- Bring back the USB / SCP / TF card hints behind a help button.
- Pick up a transfer already running when the page opens; make uploads
  cancellable; track concurrent uploads separately; let a failed job be
  dismissed; show a success state and guard the progress display by task.
- Handle request errors that were left unhandled.
- Dedicated confirmation for deleting a folder recursively.
- Treat UDF images as optical, send credentials on the image download
  pre-check, translate the remaining Hungarian string.

---------

Co-authored-by: Guoguo <i@qwq.trade>
2026-10-19 09:44:30 +08:00
watermeko
d0ff328db8 fix(web): import react-simple-keyboard by its named export
`react-simple-keyboard` ships only a UMD/CJS bundle whose `module.exports`
is `{ KeyboardReact, default: KeyboardReact }` with `__esModule: true`.

Vite 8 applies Node-compatible CJS interop for ESM importers, so the
default import resolved to the whole `module.exports` object instead of
the component. Rendering it made React throw "Minified React error #130"
(`got: object`) as soon as the on-screen keyboard was opened.

Import the `KeyboardReact` named export, which is the same component,
and keep `KeyboardButtonTheme` as a type-only import.

Fixes #936
2026-09-29 10:15:53 +08:00
watermeko
ff45b46c49 feat(storage): mount images read-only and hand /data to one writer (#937)
Only one side may write the mounted image or the /data partition at a time,
and uploaded images are validated before they are stored.

Image mounts:

* Serve every mounted image read-only, in CD-ROM and mass storage mode alike:
  detach the LUN first and set the read-only flag before the image is
  attached, so the target machine can neither write to nor format it. The
  flags were previously only written for CD-ROM mounts, so a mass storage
  mount inherited ro=0 and the image stayed writable from the host.
* Report the virtual disk as on only while the LUN really carries the /data
  partition. With an image mounted the switch used to stay active but
  unchangeable, and enabling the disk is now a confirmed action instead of a
  rejected one: it cancels the mounted image, and the confirm also warns that
  the image download is interrupted because /data becomes read-only here.
* Ask before mounting: the image list warns that the virtual disk is released
  for the image, or offers to enable it first when it is off, instead of
  dropping the /data share silently. The new strings are translated for every
  locale.
* Name the mounted medium and the USB device after the image file, cut to the
  16 bytes of the SCSI inquiry product field and the 126 bytes of the USB
  product string, and restore the previous names on unmount.
* Reset the LUN flags on every gadget restart. They survived a restart, so
  the shared partition came back to the host read-only, or as an optical
  drive, after an image had been mounted.

The /data handover:

* Mount /data read-only at boot whenever the virtual disk serves the raw
  partition as a writable disk, so the handover holds from the first boot on.
* Add SetDataWritable(), which remounts /data and verifies the new state.
  Enabling the virtual disk makes /data read-only before the host can write
  it, and refuses to expose the disk when the remount fails instead of taking
  the risk. Unmounting an image, which hands the raw partition back to the
  host, does the same, while mounting an image switches /data back to
  writable because a served image is read-only for the host.
* Cancel a running image transfer before the handover and wait for it to
  stop, and report the state in the image list, where mounting still works
  while deleting and uploading do not. The delete action is disabled with a
  hint, and the downloader offers to turn the virtual disk off.

Image uploads:

* Validate the volume descriptors while streaming, so an unusable image is
  rejected in seconds instead of after the whole transfer: accept ISO 9660 and
  UDF volume descriptors (CD001, BEA01) as well as raw disk images (GPT, APFS,
  HFS+, MBR), and reject anything else. Require the image to fit in /data with
  a 128 MiB reserve before any of it is received, log the underlying errors on
  the rejection paths, and keep the temporary file, the progress ticker and the
  close handling in defers.

Add unit tests for the upload header check, the free space preflight and the
image name truncation.
2026-09-24 09:17:24 +08:00
Guoguo
bd070b2f5c docs: add 2.5.1 changelog entries (#929) 2026-09-09 16:38:14 +08:00
watermeko
5c0bef019f fix(terminal): start a root login shell
Launch Web terminal sessions in /root as login shells so they load the root profile and display the configured prompt.
2026-09-04 17:25:51 +08:00
watermeko
283c1390e5 feat(shell): add informative SSH prompt
Create a default root profile when one does not already exist. Show the user, hostname, and working directory while preserving custom profiles.
2026-09-04 17:25:51 +08:00
watermeko
7f95fe9bbd fix(stream): isolate H264 subscribers
Keep slow WebRTC consumers from blocking the shared H264 source by dropping buffered frames until the next keyframe. Restore the WebRTC NACK and RTCP report interceptors while retaining a safe RTP MTU, and enable linker --as-needed for libkvm to remove unused OpenCV dependencies.
2026-09-01 15:34:20 +08:00
watermeko
a9e1ef2459 perf(stream): share H264 capture frames
Route Direct and WebRTC consumers through one H264 capture source to avoid duplicate VENC reads. Overlap WebRTC capture with ordered RTP/SRTP writes and packetize each access unit once for all WebRTC clients.

Add libopencv_video.so.409 into dl_lib.
2026-09-01 15:34:20 +08:00
watermeko
2ba45a2147 feat(web): enhance configurable input regions
Make input-region calibration work across MJPEG and H.264 video modes, including robust four-sided black-border detection and initial-selection edge snapping. Persist multiple reusable manual regions, keep manual and original-resolution choices mutually exclusive, migrate legacy settings, and localize the new controls for every supported language.
2026-08-25 09:36:13 +08:00
watermeko
9e6d280826 feat(web): add configurable mouse input regions
Add device-level input-region APIs for reading, validating, and atomically persisting absolute mouse calibration settings, including automatic, manual, and disabled modes.

Introduce a shared screen viewport that keeps the rendered media geometry and configured input region aligned across MJPEG, direct H.264, and WebRTC streams. Add automatic black-border detection and a manual selection overlay with dragging, resizing, magnified preview, keyboard locking, and cancellation support.

Provide original-resolution presets so manual calibration can be recalculated for common aspect ratios, expose the controls from the desktop mouse menu, close menus before entering selection mode, and preserve active file transfers when the download menu closes.

Add localized control-region labels and messages for all supported locales, and update direct-frame rendering so media dimensions are reported after the canvas has been drawn.
2026-08-25 09:36:13 +08:00
watermeko
527caeff6a fix(web): correct mouse coordinates for direct h264 frames 2026-08-25 09:36:13 +08:00
肆月
71ab9127dd feat: add secure multi-user support (#876) 2026-08-20 14:29:56 +08:00
肆月
d382f0621d fix: report and retry WebRTC connection failures (#866) 2026-08-13 14:56:01 +08:00
watermeko
9415afb359 fix(mouse): improve touch interaction and screen fitting (#857)
- Add touch gestures for relative mouse mode, including tap, drag, long press, double-tap drag, and two-finger scrolling.

- Improve absolute mouse touch handling and prevent black letterbox areas from generating remote mouse events.

- Fit H.264 and MJPEG screens with contain scaling and disable browser touch handling on the screen elements.

- Move golang.org/x/sys to the direct dependency list.
2026-08-11 09:47:04 +08:00
肆月
e5f6dfabaa fix(ota): isolate updates in persistent workspaces (#863)
* fix(ota): isolate updates in persistent workspaces

Stage online and offline update archives under /root/.kvmcache/nanokvm-update-* and validate storage, manifests, and archive contents before changing the installed application.

* fix(ota): harden storage safety and release gates

Preserve the last rollback backup when update storage is insufficient, and verify the actual application mount point before installation.

Move the shared transfer sentinel from /tmp to /run, enforce device package limits in release verification, and run that verification in package CI.
2026-08-10 14:49:29 +08:00
watermeko
757e0f61c5 feature: provide HDMI status in /api/vm/hdmi (#859)
* feature: provide HDMI status in  /api/vm/hdmi

* fix: return false when HDMI idle in  /api/vm/hdmi
2026-08-07 09:43:22 +08:00
肆月
761b02ed7e feat(web): upgrade build tooling to Vite 8 (#853)
Upgrade Vite to 8.2.0 and @vitejs/plugin-react to 6.0.5.

Use Vite's native tsconfig path resolver and remove vite-tsconfig-paths.

Verified with pnpm build and pnpm lint (existing warnings only).
2026-08-06 14:25:55 +08:00
Guoguo
562ea8277c feat: add dev container for full-stack development (#861)
Layer the frontend toolchain on top of the existing release builder
image so a single container covers Go, C support-layer and web
development, with the builder image remaining the single source of
truth for the cross toolchain, Go and MaixCDK.

- Mount the workspace at /home/build/NanoKVM, where the Makefile and
  support/sg2002/build expect it, and resync MaixCDK components via
  update_lib on create so C builds never use stale sources
- Install Node from official dist tarballs (integrity-checked, pinned
  to the major used by CI), with NODE_DIST_MIRROR / NPM_REGISTRY /
  BASE_IMAGE build args for restrictive or mirrored corporate networks
- Export the MaixCDK virtualenv via remoteEnv so non-interactive
  processes (tasks, extensions, exec) get it too; make
  updateRemoteUserUID explicit since the published builder image bakes
  the CI runner's uid
- Run pnpm non-interactively during post-create (no TTY) and give the
  skeleton-less home a standard ~/.profile -> ~/.bashrc chain
- Make the web toolchain convention explicit via package.json engines
  (Node >= 22, pnpm >= 11, matching CI) and document it in web/README
- Document the dev container in the README, point server/README at the
  container flow that works on any host OS, and ignore .pnpm-store/
2026-08-06 11:00:40 +08:00
Guoguo
7abec3cbad docs: add 2.5.0 changelog entries (#860) 2026-08-06 10:18:29 +08:00
Guoguo
8fc31553f7 ci: prefix GitHub Release titles with nanokvm (#856) 2026-08-05 11:52:22 +08:00
watermeko
9e50040713 fix(ota): keep update lock through service restart 2026-08-05 11:50:39 +08:00
watermeko
0f8ef20fb5 feat(ota): verify offline update checksums 2026-08-05 11:50:39 +08:00
watermeko
7cda3b2920 feat(ota): add custom update server support
+ Add persistent custom update server configuration, authenticated URL support, manifest validation, and the settings UI.

+ Keep application updates rebootless by coordinating video shutdown, migration-time service startup, and online/offline service restarts.

+ Localize the custom update server workflow across all supported languages.
2026-08-05 11:50:39 +08:00
Guoguo
40bbeab8ae ci: split package, tag, and release workflows (#855) 2026-08-04 16:33:56 +08:00
肆月
eb20fb41aa feat: show remote keyboard lock status (#838)
* feat: show remote keyboard lock status

* fix(keyboard-led-status): eliminate polling and improve delivery

* fix(keyboard-led-status): simplify indicator labels
2026-08-04 09:28:14 +08:00
watermeko
21e834b4c8 perf: reduce latency in 60 Hz mode (#844)
- Add decode-driven flow control and bounded GOP-aware queues to prevent stale H.264 frames from accumulating in TCP and WebSocket buffers.
- Isolate slow clients with dedicated writer goroutines, write deadlines, and safer connection lifecycle handling.
- Move the Direct H.264 socket into the worker, simplify the low-latency decode path, and improve reconnect behavior.
2026-07-31 19:08:07 +08:00
916BGAI
8773605715 Merge pull request #845 from imguoguo/ci/release-package
ci: release package
2026-07-31 19:00:18 +08:00
Guoguo
b23eb33611 ci: build identifiable NanoKVM release packages 2026-07-31 03:47:54 -07:00
Guoguo
ef432da2fe build: allow overriding the builder image and install patchelf
Groundwork for building outside an interactive terminal.

- IMAGE_NAME becomes overridable so a prebuilt image can be used instead
  of building one locally
- docker run no longer hardcodes -it on the app and support recipes:
  allocating a TTY fails where there is none. shell stays interactive
- install patchelf, which server/build.sh needs to set the RPATH on the
  server binary
2026-07-30 19:55:30 -07:00
Guoguo
96c86f6098 fix(build): correct exit codes in support/sg2002/build
The script has no error handling of its own, so these all pass silently.

- update_lib exited 1 after succeeding, so callers could not chain it
- a failed maixcdk build printed "Build Error!" and exited 0, letting a
  caller carry on with no artifacts
- add_to_kvmapp did the same when the source did not exist
- the copies in update_lib were unchecked; since update_lib is what keeps
  the SDK components in sync with the source tree, a silent failure there
  yields libraries built from stale sources
2026-07-30 19:52:34 -07:00
watermeko
a7d7574e70 fix: warn about mixed H264 stream modes (#843) 2026-07-31 10:48:52 +08:00
watermeko
b587b9f912 fix: stop HDMI capture when logged out (#841)
* fix: stop HDMI capture when logged out

* feat: stop HDMI capture when viewers are idle

* fix: keep HDMI capture active for consumers
2026-07-30 17:29:07 +08:00
watermeko
004fd59093 fix(sg2002): harden VI state sharing 2026-07-30 16:08:48 +08:00
watermeko
774d314ce9 fix(sg2002): share VI debug state between processes 2026-07-30 16:08:48 +08:00
watermeko
e4d23014ba fix(sg2002): read VI debug state without shell pipelines 2026-07-30 16:08:48 +08:00
BeaconCat
dc050d1f19 fix(usb): assign deterministic gadget MAC so the host NIC stays stable (#828)
The USB network gadget (rndis.usb0 / ncm.usb0) is created without dev_addr or
host_addr, so the kernel picks a random MAC for both the device side and the
host side on every bind. S10uuid later pins the device-side usb0 via
'ip link set', but the host_addr -- the MAC the attached PC's RNDIS/NCM adapter
uses -- stays random and changes on every re-enumeration/reboot. The host then
registers a brand-new network adapter each time, piling up stale adapters/MACs
(e.g. ~10 after a few reboots) and breaking anything that keys off the MAC.

Derive both MACs from the chip UID (same scheme S10uuid already uses for eth0
and usb0), before binding the gadget:
  dev_addr  = 48:da:35:6e:<uid>
  host_addr = 48:da:35:6d:<uid>

Verified on a NanoKVM Cube: host_addr went from random a6:3f:5d:8a:7d:52 to a
stable 48:da:35:6d:26:62, identical across two reboots.

Fixes #740

Co-authored-by: BeaconCat <BeaconCat@users.noreply.github.com>
2026-07-29 16:29:53 +08:00
SiYue-ZO
57e1f6a4d6 fix(picoclaw): cancel runtime lifecycle on mode switch
Cancel PicoClaw start/readiness waits when MCP takes control, clear held manual input state after failed release reports, and keep paste duration below the control-mode wait budget.

Also add MCP copy failure translations and avoid reconnect effect churn when the locale changes.
2026-07-29 15:16:06 +08:00
SiYue-ZO
d578c63036 i18n(picoclaw): add MCP control translations
Add locale coverage for MCP settings, AI-control ownership, PicoClaw runtime operations, and related conflict states.
2026-07-29 15:16:06 +08:00
SiYue-ZO
6b98f5415f feat(web): add MCP settings and control handoff UI
Add the MCP settings view and frontend API bindings for configuring remote-control access.

Expose AI-control ownership state in PicoClaw, lock conflicting keyboard input paths, and preserve chat state when control is released.
2026-07-29 15:16:06 +08:00
SiYue-ZO
64ce12cc0d feat(mcp): add authenticated remote control backend
Add an MCP Streamable HTTP server with token authentication, screenshot capture, keyboard, and mouse tools.

Introduce shared control-mode and input-control coordination so MCP, PicoClaw, and local HID paths serialize ownership safely.

Integrate PicoClaw gateway/runtime control handoff with PID-managed startup and focused unit coverage.
2026-07-29 15:16:06 +08:00
watermeko
183f8dc983 fix: reuse existing container users and groups 2026-07-27 10:28:46 +08:00
watermeko
7eee77a33d fix: fix container slow caused by uid/gid 2026-07-27 10:28:46 +08:00
watermeko
c1986acf65 fix(web): keep direct H264 playback low latency 2026-07-24 15:41:02 +08:00
watermeko
c999a883bd perf(sg2002): integrate zero-copy H.264 capture
Move frame ownership and zero-copy VENC handling into the tracked MMF
and Vision sources instead of relying on a preload hook. Keep the sensor
name mapping aligned with middleware enums and release deferred VI frames
safely across encoder lifecycle changes.
2026-07-24 15:41:02 +08:00
肆月
70f8503cbb fix: prevent OLED sleep duration truncation (#834)
OLED sleep settings are stored as seconds, but the kvm_system reader parsed the value into a uint8_t before assigning it to the uint16_t state field. Values above 255 seconds wrapped, so 5 min, 10 min, 30 min, and 1 hour did not behave as selected.

Parse the setting into a uint16_t-sized temporary value and terminate the read buffer before atoi so all configured durations up to 3600 seconds are preserved.

Closes #826
2026-07-22 17:46:39 +08:00
Guoguo
5b0a7d2a91 feat: add sha256sum check (#832)
* feat(download): add sha256sum check and cancellable downloads

+ server/proto/download.go
	+ add DownloadImageReq and sha256 argument

server/router/download.go
	+ add cancel download router

server/service/download/service.go
	+ sha256 decode and check
	+ remove HEAD request
	+ cancel download

* refactor(download): synchronize image and application transfers

sovel the the problem that image downloading and app downloading would conflict
at same time

* fix: optimized UI of image download and locale issue

* fix: locale
2026-07-17 18:17:04 +08:00
watermeko
4fee758ff0 fix: fix api/storage/image/mounted error when using HID-Only mode (#833) 2026-07-17 18:02:07 +08:00
watermeko
736259baa3 fix: locale 2026-07-17 07:47:25 +00:00
watermeko
83b600bbee fix: optimized UI of image download and locale issue 2026-07-16 11:16:36 +00:00
watermeko
6071a6f57c refactor(download): synchronize image and application transfers
sovel the the problem that image downloading and app downloading would conflict
at same time
2026-07-16 11:03:07 +00:00
watermeko
69f5da6fc7 feat(download): add sha256sum check and cancellable downloads
+ server/proto/download.go
	+ add DownloadImageReq and sha256 argument

server/router/download.go
	+ add cancel download router

server/service/download/service.go
	+ sha256 decode and check
	+ remove HEAD request
	+ cancel download
2026-07-16 11:03:07 +00:00
916BGAI
3b2ba7c0c1 docs: add 2.4.3 changelog entries 2026-06-09 18:06:03 +08:00
916BGAI
208998c13a support lt6911d 2026-06-09 18:00:32 +08:00
wenjie
3de4a18eb4 chore: update js-cookie for security fix 2026-05-22 10:43:17 +08:00
wenjie
863fea9ab8 release: nanokvm@2.4.2 2026-05-20 16:23:16 +08:00
wenjie
f65c1b06aa chore: refresh desktop menu ordering and community links
- Replace the Discussion community link with Discord
- Align terminal and script ordering in the menu and appearance settings
- Remove the divider before the leader key menu item
2026-05-20 15:07:59 +08:00
wenjie
fe34008ce3 fix: handle left-button touch cancel and contextmenu cleanup 2026-05-20 14:49:33 +08:00
wenjie
961d7f2e89 fix: validate Wi-Fi password field 2026-05-20 11:53:53 +08:00
wenjie
94749ea621 fix: harden Wake-on-LAN MAC handling
Normalize stored MAC addresses, avoid shell execution for ether-wake, handle missing WOL history gracefully, and improve the WOL menu display for named MAC entries.
2026-05-20 11:38:14 +08:00
wenjie
6ae742deed fix: improve WebRTC loading indicator 2026-05-19 17:31:19 +08:00
wenjie
b653f905e4 perf: improve H264 streaming client handling
Use client snapshots for stream fanout, reduce frame queue latency, expose backend ICE server configuration to the WebRTC client, and clean up disconnected WebRTC clients more aggressively.
2026-05-19 17:04:57 +08:00
wenjie
af19795c29 refactor: remove legacy h264 stream package 2026-05-19 16:49:41 +08:00
wenjie
be7584d908 feat: show HDMI capture status on desktop screen
Track capture results for each stream mode, broadcast status updates over WebSocket, and display localized warning/error overlays in the desktop view.
2026-05-19 15:02:34 +08:00
wenjie
a960417739 fix: stabilize PicoClaw session switching
- Wait for gateway session release before reconnecting to a new or selected session
- Refresh runtime status before deciding whether a selected history session can reconnect
- Render structured thought messages from gateway payload metadata
- Prevent PicoClaw history rows from overflowing horizontally
- Add localized labels for the verifying install stage
2026-05-18 17:26:00 +08:00
wenjie
3f0621e7ed Merge pull request #799 from BeaconCat/feat/picoclaw-v3-session-history
feat(picoclaw): support sk_v1_ opaque session keys for V3 history
2026-05-18 15:31:39 +08:00
wenjie
515c5e2a76 Merge pull request #798 from BeaconCat/feat/picoclaw-v3-config
feat(picoclaw): adapt to PicoClaw V3 config format
2026-05-18 15:23:05 +08:00
wenjie
cb025f04b4 chore(web): update PostCSS and MSW worker
- Bump PostCSS to 8.5.10 and refresh the pnpm lockfile
- Regenerate the MSW service worker for msw 2.12.10
- Add pnpm build approvals for frontend tooling
2026-05-18 15:02:31 +08:00
wenjie
2ca5b19efe release: nanokvm@2.4.1 2026-05-08 18:16:58 +08:00
wenjie
40f3917014 fix: update translation of DNS description 2026-05-08 17:34:27 +08:00
wenjie
a40433522c fix: improve DHCP DNS fallback detection
Read DHCP DNS from /tmp/resolv.conf when the cached DHCP resolv file is empty, and only fall back to the active resolv.conf when DHCP mode is active or no manual boot config exists.
2026-05-08 17:13:13 +08:00
wenjie
8470b89214 fix(i18n): sync translations for supported locales
- Add missing localized strings for recent UI features, including keyboard shortcuts, clipboard paste, Wi-Fi AP auth, terminal options, device settings, Tailscale, updates, and PicoClaw.
- Align non-English locale resources with the English translation keys.
2026-05-08 16:19:37 +08:00
wenjie
5a08170518 ui: optimize the scrollbar style of the settings 2026-05-08 14:56:50 +08:00
BeaconCat
dff794cee4 feat(picoclaw): adapt to PicoClaw V3 config format
- channels -> channel_list with nested settings struct (V3 format)
- security channels -> channel_list.pico.settings.token
- Remove broken pico- prefix token composition logic
- Token now uses exact match with PicoClaw gateway
- Add GitHub Actions CI for building update package
- Version: 2.4.0.Beacon
2026-05-08 08:30:08 +08:00
wenjie
36cf9c30d8 feat: add DNS management to Network settings
- Add DNS configuration APIs for manual and DHCP modes, including persistence and udhcpc hook support.
- Add a Network settings tab with DNS controls, move Wi-Fi and HTTPS settings into it, and update translations.
- Update locales
2026-05-07 17:03:25 +08:00
wenjie
1c43542919 fix: harden HID recovery and cleanup
- Open HID gadget handles lazily in nonblocking mode and clear stale handles on write failures
- Release keyboard and mouse state when HID queues close or writes fail
- Reopen HID devices with retry after USB PHY reset
- Make websocket client close idempotent and close HID queues safely
- Expire and renew PicoClaw session locks during gateway relay
2026-05-06 16:44:42 +08:00
BeaconCat
8eca1edf47 feat(picoclaw): support sk_v1_ opaque session keys for V3 history 2026-05-06 10:21:52 +08:00
wenjie
4080788cab chore: update README.md 2026-04-24 14:30:10 +08:00
wenjie
424302789e chore: update README.md 2026-04-24 14:17:32 +08:00
wenjie
6651167dd8 chore: upgrade vulnerable web dependencies
- Bump Axios, Vite, ESLint, TypeScript ESLint, and related lockfile entries.
- Add yaml as an explicit frontend dev dependency.
2026-04-24 10:40:20 +08:00
wenjie
2d67720022 fix: preserve loopback access for host configuration
- Keep internal loopback HTTP APIs reachable when the server is bound to a
specific non-loopback host by adding a dedicated 127.0.0.1 listener.

- Move listener address helpers into utils and normalize HTTPS redirect hosts so
IPv6 request hosts are not double-bracketed.
2026-04-24 10:29:16 +08:00
wenjie
1893912ba7 Merge pull request #792 from kmw0410/main
update korean translation for picoclaw
2026-04-24 10:05:43 +08:00
wenjie
e41ce2d6b8 Merge pull request #788 from ilyesAj/feat/add_french_layout
Add French keyboard layout support on paste window
2026-04-24 10:05:23 +08:00
wenjie
a5c6489f19 Merge pull request #770 from Voranto/Voranto-patch-2
Fix wrong message during support build
2026-04-24 09:55:51 +08:00
wenjie
fafef3d89a Merge pull request #779 from allmazz/feature/server_listen_host
Add `host` server config parameter
2026-04-24 09:46:11 +08:00
kmw0410
4b5f539445 update korean translation for picoclaw 2026-04-23 13:55:39 +09:00
wenjie
cefe0f9ab2 feat: add internal USB recovery and initialize picoclaw token 2026-04-16 17:00:16 +08:00
Kirill Nikiforov
7f3d29eba2 fix ipv6 2026-04-16 00:51:02 +04:00
Kirill Nikiforov
64681e2aac add host server config parameter 2026-04-14 06:51:06 +04:00
ilyesAj
fcb1f1c7fe Add French keyboard layout support and update language options 2026-04-11 22:39:40 +02:00
wenjie
aa0546ff37 release: nanokvm@2.4.0 2026-04-10 18:07:23 +08:00
wenjie
3254412017 Squashed commit of the following:
commit 3dea4b1cfcb866d50c9c093b797c0f4f48fec23f
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 17:11:07 2026 +0800

    fix(picoclaw): clean temp media and surface MCP screenshots in chat

    - remove shared load_image staging and pass source paths through directly
    - delete /tmp/picoclaw_media when a gateway session closes
    - push MCP screenshot observations to downstream websocket clients
    - hide null tool feedback messages and auto-scroll when screenshots load

commit f58ffe1e27f83f64e2b0e8c2f8dcac46af715ace
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 15:55:59 2026 +0800

    Harden PicoClaw local API auth and session locking

    Split PicoClaw routes by caller trust level and require the internal loopback token for local-only endpoints. Update the NanoKVM bridge script to send the internal token for loopback requests. Relax session lock acquisition for screenshot and action calls so the active session can perform local operations without permanently taking over the lock, and stop forcing the runtime dm_scope default.

commit 462a0670bbc5138c893fbd1155e72465b82c2065
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 13:52:39 2026 +0800

    fix(picoclaw): improve KVM reliability and sidebar behavior

    - follow HTTPS loopback redirects in the NanoKVM bridge script
    - enable MJPEG frame caching only during active PicoClaw gateway sessions
    - restore legacy screen zoom behavior across MJPEG and H264 renderers
    - keep the PicoClaw sidebar available on mobile without splitter layout conflicts
    - hide empty "null"/"undefined" chat messages and keep MJPEG failures on a black screen

commit bfda85c6368825c7ddf47d347ba5ec2588135885
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 11:37:15 2026 +0800

    fix(picoclaw): verify runtime downloads and remove unused config API

    - verify the downloaded runtime archive against the published SHA-512 checksum
    - remove the unused /api/picoclaw/config endpoints and related frontend state
    - rename runtime_control.go to runtime_constants.go for clearer intent

commit 10b34aaea59e10d70c3cdecb01915444561ceaf7
Author: wenjie <meetwenjie@gmail.com>
Date:   Thu Apr 9 16:32:30 2026 +0800

    fix: stabilize picoclaw runtime defaults and secure local MCP access

    - persist required NanoKVM startup defaults before launching picoclaw and after saving model config
    - force-enable the pico channel when loading config so runtime status can recover to ready
    - derive the local MCP URL from the configured HTTP port and keep loopback-only HTTP access behind an internal token
    - move loopback HTTP redirect logic into middleware to simplify main server startup
    - improve runtime/sidebar state handling and add the load-image endpoint for active picoclaw sessions

commit d20540195bf45ea290f727b473ee8cd2a1bbb68d
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Mar 27 17:55:29 2026 +0800

    feat(picoclaw): add picoclaw integration
2026-04-10 17:28:28 +08:00
BuGu
fda3c6b1a8 Add default mask for static IP 2026-03-27 10:50:18 +08:00
BuGu
97832557fb Fix the issue of occasional IP not displaying 2026-03-26 18:21:47 +08:00
wenjie
590db5b08c release: nanokvm@2.3.6 2026-03-12 16:02:18 +08:00
wenjie
10a512ec96 feat: Implement AP password authentication for the WiFi configuration page 2026-03-12 15:21:18 +08:00
wenjie
08093dddad Merge pull request #769 from Voranto/Voranto-patch-1
Enable support for 640x480 resolution
2026-03-12 11:21:17 +08:00
wenjie
86a85a61b7 Merge pull request #761 from klim4-bot/main
feat : Add Korean and Japanese virtual keyboard layouts
2026-03-12 11:20:54 +08:00
wenjie
cb3a2c562e Merge pull request #744 from tkmsst/pull-request
Update Japanese translation
2026-03-12 11:18:12 +08:00
Voranto
832832a716 Fix project name in build script for kvm_vision 2026-03-05 16:02:24 +01:00
Voranto
5fe6d0d48f Fix wrong message during ./build kvm_vision add_to_kvmapp 2026-03-05 15:57:44 +01:00
Voranto
67fe57f189 Enable support for 640x480 resolution 2026-03-05 15:52:49 +01:00
BuGu
44caee21ab Add encryption parameters for OLED distribution network 2026-03-04 17:11:42 +08:00
BuGu
5b2a1ff788 Add webpage logo generation tool and method 2026-03-04 17:09:52 +08:00
BuGu
dc5ba29bcf Add a logo file generator based on TUI 2026-03-03 19:12:59 +08:00
BuGu
89c14310c7 Add custom logo function 2026-03-03 18:50:35 +08:00
BuGu
3322a3c07f Add update mechanism for tailscale startup script 2026-03-03 18:49:02 +08:00
wj-xiao
9e1251ad6a release: nanokvm@2.3.5 2026-02-28 17:25:14 +08:00
wj-xiao
afec4efb34 feat: Implement login brute-force protection with lockout mechanism 2026-02-28 16:44:47 +08:00
wj-xiao
11980b9122 fix: improve Tailscale error handling in UI components and refine backend state mapping 2026-02-28 11:12:26 +08:00
wj-xiao
2a43fb5413 chore: update server and web dependencies 2026-02-28 10:53:31 +08:00
jason
57887f3f69 Add Korean and Japanese virtual keyboard layouts 2026-02-19 07:47:41 +09:00
tkmsst
2b8f640957 Update Japanese translation 2026-02-02 01:14:57 +09:00
wj-xiao
4af32fc703 release: nanokvm@2.3.4 2026-01-26 17:56:52 +08:00
wj-xiao
a611e5ef56 feat: support keyboard leader key functionality 2026-01-26 17:10:16 +08:00
wj-xiao
94051c3037 chore: added image version number v1.4.2 2026-01-26 11:23:17 +08:00
wj-xiao
d5cd706078 fix: compatible with non-standard modifier keys 2026-01-26 11:12:19 +08:00
wj-xiao
7460ebfd07 fix: the menu bar cannot be closed 2026-01-26 10:46:57 +08:00
wj-xiao
e3877308a0 fix: trigger update check when switching preview updates 2026-01-26 10:28:27 +08:00
wenjie
7c28fb8124 Merge pull request #737 from kmw0410/main
update korean translation
2026-01-26 10:08:02 +08:00
wenjie
b18873364f Merge pull request #733 from j796160836/feature/update_zh_tw
Update zh_tw translation
2026-01-26 10:07:37 +08:00
kmw0410
016a7d8a51 update korean translation 2026-01-25 22:04:24 +09:00
Johnny Sung
585f1bc2b5 feat: update zh_tw translation 2026-01-20 01:59:53 +08:00
wj-xiao
4fcc4c3747 release: nanokvm@2.3.3 2026-01-16 15:32:14 +08:00
wj-xiao
0d2c52adc3 feat: the menu bar supports setting the display mode 2026-01-16 11:47:56 +08:00
wj-xiao
af256e7f92 fix: compatible with IME composition 2026-01-15 17:04:17 +08:00
wj-xiao
84830421ee fix: compatible with Windows AltGr key 2026-01-15 16:45:48 +08:00
wj-xiao
9b278cdb0e fix: compatible with macOS's command key combinations 2026-01-14 17:58:25 +08:00
wj-xiao
9b40a5cf86 chore: update eslint 2026-01-14 17:58:25 +08:00
wj-xiao
b8d980be33 fix: the IntlBackslash key does not work on German virtual keyboard 2026-01-14 17:58:25 +08:00
wenjie
195037af87 Merge pull request #728 from imguoguo/main
ci: add missing parameters and push when issue closed
2026-01-14 15:48:07 +08:00
Guoguo
c98000069a ci: add missing parameters and push when issue closed 2026-01-14 07:43:19 +00:00
wenjie
2bd277b57d Merge pull request #725 from kmw0410/main
update korean translation
2026-01-14 10:30:40 +08:00
wj-xiao
4852ed813b chore: bump react-router-dom from 6.27.0 to 6.30.3 2026-01-14 10:27:08 +08:00
wj-xiao
fb08df9e4e fix: correct erroneous release date 2026-01-12 19:53:26 +08:00
kmw0410
64f3b49e21 update korean translation 2026-01-12 09:11:56 +09:00
wj-xiao
329c0a0001 release: nanokvm@2.3.2 2026-01-08 19:15:52 +08:00
wenjie
c28273d1f0 Merge pull request #721 from imguoguo/ci-use-jq
ci: use jq to format json
2026-01-08 17:33:40 +08:00
Guoguo
1d22d75889 ci: use jq to format json 2026-01-08 09:16:27 +00:00
wj-xiao
6ef8bb74e3 ui: update menu bar 2026-01-08 14:45:50 +08:00
wj-xiao
0e00760474 fix: fix touchscreen scrolling 2026-01-08 14:22:22 +08:00
wenjie
d969bd68ec Merge pull request #705 from imguoguo/add-issue-tracker
feat: add issue tracker
2026-01-06 16:15:31 +08:00
Guoguo
1e5f4cb24b feat: add issue tracker 2026-01-06 08:09:51 +00:00
wj-xiao
4d3b1c835e feat: support custom keyboard shortcuts 2026-01-06 13:58:53 +08:00
wj-xiao
e3558933b1 ui: menu bar stops auto-hiding when submenu is open 2026-01-06 11:08:57 +08:00
wj-xiao
7762706200 fix: set minimum width for mouse speed component 2026-01-05 18:19:06 +08:00
wj-xiao
b66707c959 refactor: support delete request 2026-01-05 17:45:38 +08:00
wj-xiao
a3440cf867 ui: update menu bar 2026-01-05 17:37:44 +08:00
wj-xiao
1b7021d64b refactor: refactor keyboard, mouse, and WebSocket 2026-01-05 16:49:17 +08:00
BuGu
687dd3bfc4 Fix the issue of old IP residue in static IP configuration 2026-01-04 18:18:00 +08:00
wj-xiao
cc072ab158 release: nanokvm@2.3.1 2025-12-26 19:12:33 +08:00
wenjie
b0a01a9837 Merge pull request #611 from lowtech-guy/main
Add user-friendly build system design
2025-12-26 18:27:02 +08:00
wj-xiao
2d575b916c feat:support setting mouse wheel direction 2025-12-26 16:44:12 +08:00
wj-xiao
1f908ef181 fix: add the restart_phy command 2025-12-26 16:11:28 +08:00
wj-xiao
fb2adf13ee refactor: refactor offline update function 2025-12-26 15:38:05 +08:00
wj-xiao
ad9eb44ad8 fix: web terminal may not close properly 2025-12-26 10:53:21 +08:00
wj-xiao
b4962e7a58 fix: custom port might not work 2025-12-26 10:49:29 +08:00
wj-xiao
14614e5e35 ui: optimize menu bar ui 2025-12-26 10:22:59 +08:00
wj-xiao
9a93ab24f5 refactor: refactor virtual devices and HID 2025-12-26 10:06:17 +08:00
wj-xiao
aaad552633 refactor: refactor the Wi-Fi module 2025-12-24 16:48:24 +08:00
wenjie
79cc1cc2bf Merge pull request #692 from Alexander-Ger-Reich/main
Upload lokal ISO files and Offline Updater
2025-12-24 09:48:02 +08:00
wenjie
01bcda6886 Merge pull request #698 from deftdawg/oled_sleep_param-fix
Fix oled_sleep_param only retaining lowest 8-bits of value
2025-12-23 16:13:09 +08:00
wenjie
ec49bffe06 Merge pull request #687 from Deses/ES-lang-update
Updated Spanish translation with all missing strings
2025-12-23 15:32:14 +08:00
wenjie
2db5d86a3c Merge pull request #686 from pekishev/paste_rus
Add support for pasting russian text
2025-12-23 15:31:06 +08:00
wenjie
da6d4840f8 Merge pull request #685 from imguoguo/add-scale
feat: add video scale
2025-12-23 15:19:02 +08:00
wenjie
9afa21a0b0 Merge pull request #679 from acidflash/main
Add missing variables from last version
2025-12-23 15:17:35 +08:00
wenjie
6168069301 Merge pull request #674 from kmw0410/main
update korean translation
2025-12-23 15:01:16 +08:00
wenjie
ffe71ae6b1 Merge pull request #673 from imguoguo/add-autostart-upstream
feat: add autostart feature
2025-12-23 14:59:28 +08:00
wj-xiao
a6a97df4e7 Update NanoKVM-PCIe schematic 2025-12-19 14:21:33 +08:00
deftdawg
f05467f45c Fix oled_sleep_param only retaining lowest 8-bits of value
providing oled_sleep_param with a 16-bit value (i.e. >256), results unpredictable display sleep times as only the low 8-bits are retained due to uint8_t (i.e. 5 minutes 300 seconds; shuts off in ~44s /  300s - 256s), this patch switches to uint16_t which should allow for up to sleeps of up to 65535 seconds.
2025-12-18 16:39:58 -05:00
Alexander-Ger-Reich
969e3a5e6a Update update.go 2025-12-13 16:00:09 +01:00
Alexander-Ger-Reich
f0e7dc069c Update update.go 2025-12-13 15:55:10 +01:00
Alexander-Ger-Reich
f5f70bd015 Update update.go 2025-12-13 15:46:07 +01:00
Alexander-Ger-Reich
aa80e1d7cc Update index.tsx 2025-12-13 15:45:23 +01:00
Alexander-Ger-Reich
d6b03a345b Update en.ts 2025-12-13 15:44:46 +01:00
Alexander-Ger-Reich
c0cfcfa31a Update de.ts 2025-12-13 15:44:30 +01:00
Alexander-Ger-Reich
afdbb179ad Update update.go 2025-12-13 15:37:44 +01:00
Alexander-Ger-Reich
ed9b7c5126 Update index.tsx 2025-12-13 15:37:17 +01:00
Alexander-Ger-Reich
551329a41d Update en.ts 2025-12-13 15:36:52 +01:00
Alexander-Ger-Reich
b3c6b6c53d Update de.ts 2025-12-13 15:36:39 +01:00
Alexander-Ger-Reich
5a9cd18f94 Update en.ts 2025-12-13 15:36:28 +01:00
Alexander-Ger-Reich
63c8fc8eb5 Update en.ts 2025-12-13 15:33:07 +01:00
Alexander-Ger-Reich
3305c69e2d Update de.ts 2025-12-13 15:32:55 +01:00
Alexander-Ger-Reich
56a0468a53 Update index.tsx 2025-12-13 14:55:25 +01:00
Alexander-Ger-Reich
52416dfdd7 Update application.go 2025-12-13 14:54:20 +01:00
Alexander-Ger-Reich
bcd0b717ee Update application.go 2025-12-13 14:54:03 +01:00
Alexander-Ger-Reich
d9c9eae4f9 Create index.tsx 2025-12-13 14:46:26 +01:00
Alexander-Ger-Reich
c1a21c2d69 Update service.go 2025-12-13 14:44:42 +01:00
Alexander-Ger-Reich
8d822948cf Update en.ts 2025-12-13 14:43:44 +01:00
Alexander-Ger-Reich
7404a205a5 Update de.ts 2025-12-13 14:43:29 +01:00
Alexander-Ger-Reich
d774bf8c58 Update download.tsx 2025-12-13 14:42:55 +01:00
Alexander-Ger-Reich
0e1fae8751 Update application.ts 2025-12-13 10:53:28 +01:00
Alexander-Ger-Reich
3ff64483df Update application.go 2025-12-13 10:51:36 +01:00
Alexander-Ger-Reich
fed92254d2 Update application.go 2025-12-13 10:50:09 +01:00
Alexander-Ger-Reich
dec1621850 Update version.go 2025-12-13 10:49:15 +01:00
Alexander-Ger-Reich
116bb50364 Update service.go 2025-12-13 10:04:10 +01:00
wj-xiao
957d86d64c update README 2025-12-12 11:59:04 +08:00
Alexander-Ger-Reich
1fa6f48d4e Update service.go 2025-12-11 23:17:57 +01:00
Alexander-Ger-Reich
0610f6fd1a Update download.tsx 2025-12-11 23:17:33 +01:00
Alexander-Ger-Reich
ade9ac863f Update de.ts 2025-12-11 22:40:30 +01:00
Alexander-Ger-Reich
61ff3c5b23 Update en.ts 2025-12-11 22:40:16 +01:00
Alexander-Ger-Reich
19076b2508 Update en.ts 2025-12-11 00:07:29 +01:00
Alexander-Ger-Reich
e175147674 Update de.ts 2025-12-11 00:06:54 +01:00
Alexander-Ger-Reich
2cc64d2208 Update download.tsx 2025-12-11 00:03:56 +01:00
Alexander-Ger-Reich
346315b4bb Update download.tsx 2025-12-11 00:03:26 +01:00
Alexander-Ger-Reich
648c9f866e Update service.go 2025-12-11 00:02:01 +01:00
Alexander-Ger-Reich
b5866088fc Update download.tsx 2025-12-11 00:01:27 +01:00
Alexander-Ger-Reich
cd954b6f24 Update download.go 2025-12-10 19:27:20 +01:00
Alexander-Ger-Reich
f27102d344 Update download.tsx 2025-12-10 00:25:33 +01:00
Alexander-Ger-Reich
ba8e8b7a5c Merge pull request #5 from Alexander-Ger-Reich/patch-6
Update en.ts
2025-12-10 00:24:25 +01:00
Alexander-Ger-Reich
cb3834bb71 Update en.ts 2025-12-10 00:24:04 +01:00
Alexander-Ger-Reich
8ec134c182 Merge pull request #4 from Alexander-Ger-Reich/patch-4
Update de.ts
2025-12-10 00:22:42 +01:00
Alexander-Ger-Reich
631d944d70 Merge pull request #3 from Alexander-Ger-Reich/patch-1
Update download.tsx
2025-12-10 00:21:40 +01:00
Alexander-Ger-Reich
f539576a49 Merge branch 'main' into patch-1 2025-12-10 00:21:30 +01:00
Alexander-Ger-Reich
fa11347f1b Merge pull request #2 from Alexander-Ger-Reich/patch-2
Update download.tsx
2025-12-10 00:18:55 +01:00
Alexander-Ger-Reich
34c66dbd8b Merge pull request #1 from Alexander-Ger-Reich/patch-5
Update en.ts
2025-12-10 00:18:21 +01:00
Alexander-Ger-Reich
3d5c14405c Update en.ts 2025-12-10 00:10:29 +01:00
Alexander-Ger-Reich
9e4408409f Update de.ts 2025-12-10 00:10:04 +01:00
Alexander-Ger-Reich
9b629c8dc0 Update download.tsx 2025-12-09 23:49:34 +01:00
Alexander-Ger-Reich
8da7a70bfc Update download.tsx 2025-12-09 23:23:40 +01:00
Deses
ea6ac3c903 Updated Spanish translation with all missing strings (compared with English) and fixed lots of little gramatical errors. 2025-12-09 05:04:13 +01:00
Yury Pekishev
6b783677e5 Use Dropdown with languages at paste
Fix translation
2025-12-09 01:31:02 +03:00
Yury Pekishev
1cc31c30a3 revert invisible change 2025-12-09 00:56:52 +03:00
Yury Pekishev
92d5f63679 Merge branch 'main' into paste_rus
# Conflicts:
#	web/src/pages/desktop/menu/keyboard/paste.tsx
2025-12-09 00:50:09 +03:00
Yury Pekishev
9fd3728aee Merge branch 'main' of https://github.com/pekishev/NanoKVM
# Conflicts:
#	web/src/pages/desktop/menu/keyboard/paste.tsx
2025-12-09 00:46:28 +03:00
Yury Pekishev
916803d0f0 Merge branch 'main' into paste_rus 2025-12-08 23:56:46 +03:00
Guoguo
8de298d245 feat: add video scale
Patch from https://github.com/sipeed/NanoKVM-USB/pull/50
2025-12-08 19:17:35 +08:00
wenjie
75fc8d09ce Merge pull request #681 from scpcom/fix-virtual-media-split-merge
S03usbdev: fix virtual media split merge
2025-12-02 09:32:14 +08:00
scpcom
b157b9fe28 S03usbdev: fix virtual media split merge 2025-12-01 23:34:17 +01:00
wenjie
53a800d252 Merge pull request #530 from tpretz/usb-disable
Add setting for disabling the usb-gadget
2025-12-01 17:51:35 +08:00
wenjie
124868e093 Merge branch 'main' into usb-disable 2025-12-01 17:51:28 +08:00
Thomas Pressnell
e684936d15 server side for full gadget disable
starting on frontend

# Conflicts:
#	kvmapp/system/init.d/S03usbdev
2025-12-01 17:26:41 +08:00
wenjie
5958fd5c6f Merge pull request #489 from tpretz/virtual-media-split
Virtual Media Changes
2025-12-01 15:30:02 +08:00
wenjie
4d7ee39ccf Merge branch 'main' into virtual-media-split 2025-12-01 15:28:50 +08:00
Jonas Byström
1bb91518b6 Add missing variables from last version 2025-11-30 21:19:55 +01:00
wj-xiao
2d0123cb18 Update README 2025-11-28 19:02:08 +08:00
kmw_
455bc19fab fix typo in ummountDesc 2025-11-27 21:11:08 +09:00
wj-xiao
0003be478e Fix Tailscale startup script
- The device no longer automatically switches to router mode
- Resolved IPv6 connectivity issues
2025-11-27 10:13:22 +08:00
kmw0410
d448f11861 update korean translation 2025-11-26 21:53:26 +09:00
Guoguo
53924dc8ef feat: add autostart feature 2025-11-26 15:58:19 +08:00
wj-xiao
9311b898f2 update CHANGELOG.md 2025-11-26 15:13:51 +08:00
wj-xiao
0e30a26db4 Streaming Refactor:
- H.264 WebRTC: Refactored to significantly reduce video latency
- H.264 Direct: Optimized data transmission; data parsing now continues correctly even when the tab is in the background
- MJPEG: Refactored to ensure the correct data length is sent

Bug Fixes
- Fixed an issue where certain keyboard modifier keys were not recognized
- Fixed vertical mouse cursor drift when the page is zoomed in or out

Optimizations
- Optimized HID write logic and updated the HID reset mechanism
- Added support for deleting images
- Added a Swap Memory option to the Tailscale page
- Added a confirmation dialog when uninstalling Tailscale to prevent accidental removal
- Improved the logic for updating the web page title
- Improved the UI for the Clipboard, Settings, Image Mounting, and App Update pages

Security
- Added a mandatory delay after failed login attempts to prevent brute-force attacks
- Updated dependencies to patch known security vulnerabilities
2025-11-26 10:57:30 +08:00
wj-xiao
24a460e64a fix en.ts 2025-11-21 12:07:39 +08:00
wenjie
f62320f3e1 Merge pull request #663 from patrickpilon/claude/add-clipboard-copy-paste-011CUogNYVLkp3YrnDiwZabG
Add clipboard copy/paste functionality for Chrome
2025-11-21 11:44:22 +08:00
wenjie
0d73e8b52a Merge branch 'main' into claude/add-clipboard-copy-paste-011CUogNYVLkp3YrnDiwZabG 2025-11-21 11:44:15 +08:00
wenjie
11d66da064 Merge pull request #661 from scpcom/storage-set-inquiry-string
server: storage: set inquiry string
2025-11-21 11:38:56 +08:00
wenjie
f24fecf01c Merge pull request #650 from scpcom/hostname-update-etc-hosts
Hostname update etc hosts
2025-11-21 11:37:57 +08:00
wenjie
1c16444614 Merge pull request #644 from Keylem/main
Adding Turkish translation
2025-11-21 11:37:08 +08:00
wenjie
8b7b1236ba Merge pull request #642 from scpcom/fix-hid-lock
Fix hid lock
2025-11-21 11:36:49 +08:00
wenjie
c44bf06cc9 Merge pull request #638 from lazydba247/patch-1
Correct set tailscale setting
2025-11-21 11:36:25 +08:00
wenjie
8230d59354 Merge pull request #631 from Alexander-Ger-Reich/main
Adds a German keyboard and more
2025-11-21 11:35:27 +08:00
wenjie
0f270c8823 Merge pull request #625 from Luccas-LF/main
Add Brazilian Portuguese in translation
2025-11-21 11:34:02 +08:00
wenjie
95970f87fa Merge pull request #618 from Zagur/translate-ca
Add catalan in translation
2025-11-21 11:33:44 +08:00
wenjie
469c1693bd Merge pull request #592 from acidflash/main
Add Swedish in translation
2025-11-21 11:33:15 +08:00
wenjie
2a45a8a8fa Merge pull request #549 from protonchang/zhtw-translation
Update zhTW Translation
2025-11-21 11:32:46 +08:00
wenjie
2180fa70f7 Merge pull request #529 from tpretz/hdmi-persist
Make HDMI toggle state persist across reboots
2025-11-21 11:31:48 +08:00
wenjie
b093e11aeb Merge pull request #528 from KRFOSS/main
Korean translation modification
2025-11-21 11:31:11 +08:00
Claude
140812606f Add clipboard copy/paste functionality for Chrome
Enhanced the paste feature with browser clipboard API integration:
- Added "Read from Clipboard" button to directly access browser clipboard
- Implemented proper permission handling and error messages
- Added validation for ASCII-only content and 1024 character limit
- Integrated user-friendly feedback with Ant Design message notifications
- Added comprehensive translation keys for all clipboard-related messages

This makes it much easier to paste content from Chrome without manually
copying into the text area.
2025-11-04 23:07:51 +00:00
scpcom
14239b8a6f server: storage: set inquiry string 2025-11-02 21:51:13 +01:00
Yury Pekishev
0d1dca3e0a translateRuToEnWithPunctuation 2025-10-30 14:40:59 +03:00
scpcom
dfee0934f0 service: hostname: set hostname immediately 2025-10-23 00:47:02 +02:00
scpcom
42c332a406 service: hostname: update /etc/hosts 2025-10-23 00:46:56 +02:00
Keylem
4c1ebc84e9 Adding Turkish translation
Adding (TR) Turkish translation.
2025-10-11 18:00:06 +02:00
scpcom
81a6e5d152 server: storage: mount: lock hid 2025-10-10 21:09:10 +02:00
scpcom
145a43d688 server: hid: lock before reset 2025-10-10 21:09:00 +02:00
lazydba247
386c5fa86c Correct set tailscale setting
before tailscaled is up, we just get an error running tailscale set command, so moved the command after the tailscaled is up.
also added example how to set the nanoKVM as your exit-node for the local network
2025-09-28 15:40:11 +03:00
Alexander-Ger-Reich
1499edd83c Update paste.go 2025-09-28 13:23:59 +02:00
Alexander-Ger-Reich
db719c32ad Update virtual-keyboard.tsx 2025-09-28 13:18:11 +02:00
Alexander-Ger-Reich
340477a31f Update mappings.ts 2025-09-28 13:11:27 +02:00
Alexander-Ger-Reich
fd57047e86 Update de.ts 2025-09-28 12:42:58 +02:00
Alexander-Ger-Reich
496b9f981e Update en.ts 2025-09-28 12:42:43 +02:00
Alexander-Ger-Reich
76dc2312b4 Update de.ts 2025-09-28 12:41:35 +02:00
Alexander-Ger-Reich
ade6d80f10 Update paste.tsx 2025-09-28 12:38:19 +02:00
Alexander-Ger-Reich
574b41a0a1 Update de.ts 2025-09-28 12:37:47 +02:00
Alexander-Ger-Reich
f907a340b6 Update en.ts 2025-09-28 12:36:41 +02:00
Alexander-Ger-Reich
0498b39f0e Update paste.tsx 2025-09-28 12:30:13 +02:00
Alexander-Ger-Reich
5d196ff8d8 Update hid.ts 2025-09-28 12:22:07 +02:00
Alexander-Ger-Reich
84d65fb167 Update paste.tsx 2025-09-28 12:20:22 +02:00
Alexander-Ger-Reich
0f22d53e7c Update hid.ts 2025-09-28 12:19:27 +02:00
Alexander-Ger-Reich
f44bc72201 Update paste.tsx 2025-09-28 12:15:47 +02:00
Alexander-Ger-Reich
310d550ff6 Update paste.tsx 2025-09-28 12:03:51 +02:00
Alexander-Ger-Reich
044292ccb4 Update paste.go 2025-09-28 11:36:54 +02:00
Alexander-Ger-Reich
0dc0f9ea73 Update paste.go 2025-09-27 23:55:14 +02:00
Alexander-Ger-Reich
5fcdf888b3 Update paste.go 2025-09-22 22:14:52 +02:00
Low Tech
dda98e2a61 Merge branch 'sipeed:main' into main 2025-09-20 16:07:25 +08:00
Alexander-Ger-Reich
f209cb1e0e Update virtual-keyboard.tsx 2025-09-14 18:42:35 +02:00
Alexander-Ger-Reich
7d3df10915 Update virtual-keys.ts 2025-09-14 18:41:45 +02:00
Alexander-Ger-Reich
fb9f127289 Update virtual-keys.ts 2025-09-14 18:31:41 +02:00
Alexander-Ger-Reich
bc64084516 Update virtual-keys.ts 2025-09-14 18:28:16 +02:00
Alexander-Ger-Reich
e86d385521 Update virtual-keyboard.tsx 2025-09-14 18:25:08 +02:00
Alexander-Ger-Reich
6ca0fa7626 Update virtual-keys.ts 2025-09-14 18:25:05 +02:00
Alexander-Ger-Reich
f8d8b04de3 Update virtual-keyboard.tsx 2025-09-14 18:15:39 +02:00
Alexander-Ger-Reich
305a75d1a7 Update virtual-keys.ts 2025-09-14 18:10:40 +02:00
Alexander-Ger-Reich
c3a9e9d402 Update virtual-keys.ts 2025-09-14 18:05:44 +02:00
Alexander-Ger-Reich
48c941fb86 Update virtual-keyboard.tsx 2025-09-14 18:01:34 +02:00
Alexander-Ger-Reich
1016853d25 Update virtual-keyboard.tsx 2025-09-14 17:54:13 +02:00
Alexander-Ger-Reich
90068a3c2d Update virtual-keyboard.tsx 2025-09-14 14:16:22 +02:00
Alexander-Ger-Reich
8fc71a2e36 Update virtual-keyboard.tsx 2025-09-14 14:14:48 +02:00
Alexander-Ger-Reich
8310e43b31 Update virtual-keys.ts 2025-09-14 14:08:53 +02:00
Alexander-Ger-Reich
0e30b62894 Update mappings.ts 2025-09-14 14:07:28 +02:00
Alexander-Ger-Reich
3de21f295b Update mappings.ts 2025-09-14 14:04:26 +02:00
Alexander-Ger-Reich
d8c4de9a01 Update virtual-keys.ts 2025-09-14 14:04:10 +02:00
Alexander-Ger-Reich
acf366d61e Update mappings.ts 2025-09-14 14:03:09 +02:00
Alexander-Ger-Reich
b9c85fad7b Update virtual-keyboard.tsx 2025-09-14 13:00:06 +02:00
Alexander-Ger-Reich
196b9555ab Update virtual-keys.ts 2025-09-14 12:58:59 +02:00
Alexander-Ger-Reich
e9cccd58ea Update virtual-keys.ts 2025-09-14 12:26:06 +02:00
Alexander-Ger-Reich
00d30efa45 Update virtual-keys.ts 2025-09-14 12:12:44 +02:00
Alexander-Ger-Reich
309b9665cb Update virtual-keys.ts 2025-09-14 12:06:30 +02:00
Alexander-Ger-Reich
759abc92c9 Update virtual-keyboard.tsx 2025-09-14 12:02:37 +02:00
Alexander-Ger-Reich
ae8f0e2236 Update virtual-keyboard.tsx 2025-09-14 11:58:35 +02:00
BuGu
815770fabf Update S30eth 2025-09-05 18:19:32 +08:00
Luccas Ferreira
e82069dea2 Delete web/src/i18n/locales/pt-br.ts 2025-09-03 12:22:57 -03:00
Luccas Ferreira
396aee7d0a Update languages.ts 2025-09-03 12:22:33 -03:00
Luccas Ferreira
3299c202b0 Update languages.ts 2025-09-03 12:19:50 -03:00
Luccas Ferreira
755cbe113d Create pt-br.ts 2025-09-03 12:17:37 -03:00
BuGu
bab729ed18 Add PID/VID Setting Function 2025-09-01 16:34:12 +08:00
BuGu
350dbdfe4b Add NanoKVM EDID Update tool 2025-08-29 19:51:48 +08:00
T3rr0rZ0n3
1b5ca8eef6 Add catalan translation 2025-08-28 20:37:33 +02:00
lowtech-guy
e8016c1d51 remove: comment the cache server line 2025-08-26 05:58:34 +08:00
lowtech-guy
c1e2bed94e add: add build system design for human friendly 2025-08-26 03:40:51 +08:00
Jonas Byström
ba242be427 Add swedish in translation 2025-07-28 09:25:57 +00:00
jingyuexing
fce974c146 update CHANGELOG.md 2025-07-15 15:04:44 +08:00
jingyuexing
a82aa792d8 Merge remote-tracking branch 'origin/main' 2025-07-15 10:38:50 +08:00
chiconws
105f77d9ec Add PT-BR translation 2025-07-15 10:38:33 +08:00
chiconws
b6d87b9799 Add PT-BR translation 2025-07-15 10:38:33 +08:00
jingyuexing
6279086b5a Merge pull request #554 from chiconws/main
Adding PT-BR translation
2025-07-15 10:17:18 +08:00
jingyuexing
61ea4bd385 chore: cherry pick 2025-07-14 14:52:48 +08:00
chiconws
7f3e039d1b Add PT-BR translation 2025-06-13 16:05:05 -03:00
chiconws
f2c91c09c7 Add PT-BR translation 2025-06-13 16:03:07 -03:00
wj-xiao
32c81f220d update CHANGELOG.md 2025-06-13 18:27:04 +08:00
wj-xiao
c77981cc0c fix(security): resolve parameter injection in serial port terminal 2025-06-13 17:50:11 +08:00
protonchang
cd767d16df Update zhTW Translation 2025-06-07 18:51:39 +08:00
kmw_
8591aecb9c update korean readme
updated to include the addition of nanokvm-pro
2025-06-01 20:14:02 +09:00
wj-xiao
34746afea3 update README.md 2025-05-26 18:17:51 +08:00
Thomas Pressnell
393328eaf6 Revert "cleanup and simplification" and adding reset flag
This reverts commit 7771d1f326.
2025-05-26 07:47:48 +01:00
Thomas Pressnell
7771d1f326 cleanup and simplification 2025-05-25 21:44:53 +01:00
Thomas Pressnell
2a34eb55e6 Update image.go
set imageNone to newline
2025-05-25 19:22:58 +01:00
kmw_
9d6cf49c3f fix missed translations 2025-05-25 14:26:02 +09:00
kmw0410
dcb87d0d89 add korean readme 2025-05-25 14:17:28 +09:00
Thomas Pressnell
9a0c77bb8b server side for full gadget disable
starting on frontend
2025-05-24 16:28:52 +01:00
Thomas Pressnell
6e45e6b135 make hdmi toggle persist 2025-05-24 14:03:50 +01:00
Thomas Pressnell
a1df6376ec split /data attachment from kvm media attachment
backend config for media control

remove .disabled

adding settings toggle

add default text
2025-05-24 13:29:35 +01:00
X
7f7e31bae9 터미널 수정 2025-05-23 22:29:49 +09:00
X
4499f9ed44 kmw0410, U-디스크 번역 수정 및 기타 수정 2025-05-23 22:23:12 +09:00
kmw0410
9a5ad1dff2 번역 수정 2025-05-23 22:13:24 +09:00
X
2f8f77cb89 번역 추가, 정렬 2025-05-23 21:49:17 +09:00
wj-xiao
a4978d93d6 update CHANGELOG.md 2025-05-22 14:13:18 +08:00
wj-xiao
01e28f10ae Fix direct H.264 issues and optimize UI
feat: support custom mouse wheel speed
fix: prevent direct H.264 stream buffer overflow and replay
style: optimize virtual keyboard layout
style: optimize menu bar and settings styling
2025-05-22 11:31:08 +08:00
wenjie
ea9068fd0d Merge pull request #520 from ethanperrine/main
Updated paste.go
2025-05-20 19:30:15 -07:00
wenjie
d85823abcf Merge pull request #508 from arbdevml/ru
Russian language file was updated in accordance with the new version.
2025-05-20 19:29:51 -07:00
wenjie
4c0027ffd3 Merge pull request #507 from arbdevml/uk
Ukrainian language file was updated in accordance with the new version.
2025-05-20 19:29:35 -07:00
wenjie
afb868af30 Merge pull request #501 from tpretz/hdmi-disable
Adding HDMI Enable/Disable Toggle for PCIe
2025-05-20 19:29:10 -07:00
wenjie
66b1d5dc30 Merge pull request #500 from felix068/feature/azerty-keyboard-layout
Feat: Add AZERTY layout (virtual keyboard) and keyboard layout settings
2025-05-20 19:27:48 -07:00
wenjie
7d8cdc74c6 Merge pull request #496 from kmw0410/main
revised some korean text
2025-05-20 19:25:11 -07:00
Quandale Dingle
809581df49 Update paste.go
Code now relies solely on the modifier byte within the main keyDown report to signal that shift is active. This is a more reliable approach.
2025-05-20 17:09:27 -04:00
Alexandro
5d47a8d48d Update ru.ts 2025-05-12 22:10:26 +00:00
Alexandro
6242f1931e Update uk.ts 2025-05-12 22:08:52 +00:00
Alexandro
b768219c18 Update uk.ts 2025-05-12 22:03:56 +00:00
Thomas Pressnell
6935923bd1 Adding HDMI Enable/Disable Toggle for PCIe 2025-05-10 19:41:25 +01:00
TPM-28
559e6e2556 Feat: Add AZERTY layout (virtual keyboard) and keyboard layout settings
This pull request introduces the following changes:

* **Added AZERTY Keyboard Layout:**
  Implemented support for the AZERTY keyboard layout in the virtual keyboard. This includes both the visual layout and the corresponding key code mappings.

* **Keyboard Layout Setting:**
  Added a new setting under *"Appearance"* to allow users to select their preferred keyboard layout (QWERTY Win, QWERTY Mac, AZERTY Win, Russian). The selected layout is saved to local storage and applied to the virtual keyboard.
2025-05-10 12:25:21 +02:00
kmw0410
f354fdfbf4 revised some korean text 2025-05-09 19:35:38 +09:00
wj-xiao
f242b5a378 update CHANGELOG.md 2025-05-08 16:39:13 +08:00
wj-xiao
e18ec2219d Support HTTPS and direct H.264
feat: add HTTPS support
feat: enable direct H.264 streaming over HTTP
style: optimize menu bar and settings styling
2025-05-08 14:50:32 +08:00
wenjie
d075ae58d9 Merge pull request #494 from 3limin4tor/patch-1
Finalized German translations
2025-05-07 23:23:39 -07:00
3limin4tor
e8ccac8e61 Update de.ts 2025-05-07 19:25:49 +02:00
3limin4tor
7c8f9f3cd8 Finalized german translations 2025-05-07 19:23:26 +02:00
3limin4tor
66e434db24 Finalized german translation 2025-05-07 19:17:44 +02:00
3limin4tor
0be553c4c8 Update de.ts
Started with new translation for German
2025-05-07 01:22:25 +02:00
wenjie
1dda0f29be Merge pull request #472 from pekishev/main
Add Russian virtual keyboard layout when UI language is 'ru'
2025-04-27 02:51:42 -07:00
wenjie
fbdedc7d8a Merge pull request #467 from click0/Update_Ukrainian_translation_for_v_2.2.6
Update translation into Ukrainian for version 2.2.6.
2025-04-27 02:49:53 -07:00
wenjie
e325352309 Merge pull request #466 from LeonStraathof/patch-1
Update nl.ts
2025-04-27 02:49:29 -07:00
wenjie
bf51b50346 Merge pull request #464 from LingkongSky/main
Fix bugs
2025-04-27 02:49:00 -07:00
wenjie
96b52f3ac0 Merge pull request #461 from polyzium/ru-translaton-fix
Russian translaton fix + more translation keys
2025-04-27 02:48:36 -07:00
vlad11
ad44db254b Update translation into Ukrainian for version 2.2.6. 2025-04-18 20:41:57 +03:00
Leon Straathof
736b89d7d1 Update nl.ts
Changed minor language mistakes like official use of the word wifi in Dutch, and replaced remaining English text.
2025-04-18 13:19:37 +02:00
凌空
3122531cae Merge branch 'sipeed:main' into main 2025-04-18 16:33:19 +08:00
LingkongSky
cbb47ab735 fix some bugs for the localstorage and add some translations 2025-04-18 16:32:15 +08:00
BuGu
fa8d4fd5ca Update CHANGELOG.md
Add instructions for fixing MIC issues
2025-04-18 11:28:30 +08:00
LingkongSky
423d05a087 Revert "add a switch to stop the hid in Web UI"
This reverts commit 7036e94dab.
2025-04-18 10:12:19 +08:00
LingkongSky
7036e94dab add a switch to stop the hid in Web UI 2025-04-17 21:24:21 +08:00
polyzium
3a19180a51 Make Swap title translateable 2025-04-17 15:43:39 +03:00
polyzium
f8f8920fc5 Make IP types translateable 2025-04-17 15:40:08 +03:00
polyzium
507b53c10e Update Russian translation 2025-04-17 15:40:04 +03:00
wj-xiao
6aafb78680 update CHANGELOG.md 2025-04-17 16:23:44 +08:00
wj-xiao
c83dc5565c Optimize some components
refactor: optimize mouse jiggler
refactor: custom swap file size
refactor: update power buttons ui
refactor: optimize web page title
perf: set the minimum screen size to 640x480
perf: add heartbeat in H.264
chore: upgrade axios and golang.org/x/net
2025-04-17 15:20:25 +08:00
BuGu
59a03cacef Update S30eth
To prevent some regions from not receiving the update package, add some DNS servers. However, please note that after setting a static IP, the /etc/resolv.conf file will be overwritten, and the old file will be stored as /etc/resolv.conf.old.
2025-04-16 16:01:25 +08:00
BuGu
c6af287b11 Merge pull request #421 from xitation/main
Resolve typo in eth config that breaks dns resolving.
2025-04-16 15:46:40 +08:00
BuGu
bc636bd9fd Merge pull request #409 from scpcom/fix-iptables-for-ssh
fix iptables for ssh
2025-04-16 15:02:28 +08:00
BuGu
1f2b6c5d44 Optimize IP display logic.
WiFi version:
Only display the corresponding IP when either ETH or WiFi is present;
otherwise, both IPs will alternate.
2025-04-15 14:31:07 +08:00
BuGu
b42ffe8e0b Add Function: Automatically wake up the screen
OLED will automatically wake up in the following scenarios:
1. Plug and unplug the network cable
2. Plug and unplug USB
3. WiFi connection status has changed
4. Plug and unplug HDMI
5. HDMI input resolution changes
6. The transmission format has changed
7. Change in transmission quality
2025-04-15 11:29:22 +08:00
BuGu
f9244b36df Fix security risks related to MIC
MIC driver will not be automatically loaded when powered on,
and the driver will be directly deleted
2025-04-14 14:51:14 +08:00
wenjie
87f697622c Merge pull request #453 from LingkongSky/main
add the Wol custom name
2025-04-13 23:30:48 -07:00
LingkongSky
52dbc0fe40 add the Wol custom name 2025-04-13 10:46:32 +08:00
wj-xiao
4a69bdcd12 upgrade golang-jwt 2025-04-11 10:41:11 +08:00
wenjie
e9e47d797c Merge pull request #434 from ChokunPlayZ/thai-tl
added missing thai translations
2025-04-10 19:13:46 -07:00
wenjie
66cdb5e376 Merge pull request #433 from LingkongSky/main
Finish the MouseJiggler and add it to WEBUI
2025-04-10 19:13:26 -07:00
wenjie
c7575393c9 Merge pull request #432 from S33G/feature/login-logo
Add logo to login screen
2025-04-10 19:10:43 -07:00
LingkongSky
3b9005e9a8 add the Web Title Edit bar into the Web UI 2025-04-10 19:10:44 +08:00
LingkongSky
e3fd5876d2 add the Hostname Editbar into the Web UI 2025-04-10 13:30:04 +08:00
LingkongSky
f71c2d3f8d add the power operation confirm selection in WEB UI 2025-04-08 22:16:42 +08:00
LingkongSky
7163854185 fix the indentation 2025-04-08 20:02:41 +08:00
LingkongSky
8037081e0c update the MouseJiggler,change to use the goroutine 2025-04-08 14:21:47 +08:00
Yury Pekishev
642a00051e add Rus virtual keyboard conditionally 2025-04-04 21:38:30 +03:00
Yury Pekishev
7f9bd1c457 add Rus virtual keyboard conditionally 2025-04-04 21:29:27 +03:00
Chokun Rojanapron
477f7dfa03 added missing thai translations 2025-04-04 23:06:15 +07:00
凌空
d45aaf6cb2 Merge branch 'sipeed:main' into main 2025-04-04 17:55:30 +08:00
LingkongSky
4650da8373 finish the MouseJiggler 2025-04-04 17:53:54 +08:00
s33g
13128a8a90 Add logo to login screen 2025-04-04 01:05:50 +01:00
wj-xiao
23b19015f4 update README.md 2025-04-03 18:05:54 +08:00
wj-xiao
843a1f97ce update README.md 2025-04-03 17:41:39 +08:00
wj-xiao
43d6002542 refactor: show all IP addresses in device info 2025-04-03 15:59:59 +08:00
LingkongSky
f9d9677bc0 add the function of MouseJiggler 2025-04-02 23:02:29 +08:00
BuGu
49220d8024 Update USB Gadget config 2025-04-01 11:44:22 +08:00
BuGu
013d76b006 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-04-01 11:43:16 +08:00
XiTatiON
c7d3755149 Merge pull request #1 from xitation/resolv_conf_fix
Update S30eth
2025-03-29 11:54:13 +11:00
XiTatiON
8d67ecd6a0 Update S30eth
Fix typo that creates wrong resolve.conf file and therefore dns doesn't work.
2025-03-29 11:52:48 +11:00
wenjie
6005bb1b8d Merge pull request #415 from LingkongSky/main
add the swap function in WebUI
2025-03-27 19:20:05 -07:00
Yury Pekishev
c4e8d19649 add rus keyboard layout 2025-03-27 23:38:59 +03:00
Yury Pekishev
82be18c469 add rus keyboard layout 2025-03-27 23:30:52 +03:00
LingkongSky
e6565fbe4b add the swap function in WebUI 2025-03-27 20:00:46 +08:00
wj-xiao
087dbaded9 update CHANGELOG.md 2025-03-26 17:06:11 +08:00
wj-xiao
6c42c57e59 update CHANGELOG.md 2025-03-26 17:04:13 +08:00
wj-xiao
3286cc2f85 feat: add HID-Only mode
feat: support preview updates
perf: optimize screen parameters for reading image
2025-03-26 15:26:59 +08:00
BuGu
d098a5ef09 Remove compatibility support for version 2.2.3 2025-03-26 10:22:32 +08:00
scpcom
040335ace0 fix iptables for ssh 2025-03-25 01:04:17 +01:00
BuGu
dbc74834cd Fix the issue of the server frequently crashing in version 2.2.4. 2025-03-24 17:22:48 +08:00
wj-xiao
f1b411e3b6 update CHANGELOG.md 2025-03-21 18:46:21 +08:00
BuGu
7a9f5f9e6e Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-21 16:22:03 +08:00
BuGu
cffa9a97f3 Delete S03usbdev 2025-03-21 16:21:22 +08:00
wj-xiao
1bf986d41b update libkvm.so 2025-03-21 16:19:05 +08:00
BuGu
eb343b0d31 Fix build script issues 2025-03-21 16:17:47 +08:00
BuGu
628cb3b8c9 Fix abnormal updates of some models
Add function: If the program does not execute after the update, execute a restart
2025-03-21 16:16:53 +08:00
BuGu
ebd391ec26 Reset USB on new app launch. 2025-03-21 12:02:03 +08:00
BuGu
a3b577e563 Fix USB initialization issue. 2025-03-21 11:03:18 +08:00
BuGu
f60adcc797 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-21 11:03:03 +08:00
BuGu
ee77f7bed1 Fix USB initialization issue. 2025-03-21 11:03:01 +08:00
wj-xiao
6ef83cb22f feat: support setting H.264 GOP
perf: merge H.264 SPS and PPS into I-frame
perf: refactor MJPEG frame detection
perf: update log timestamp to millisecond precision
perf: update script `update-nanokvm.py`
chore: bump Go to 1.23
chore: bump golang.org/x/net to v0.37.0
2025-03-20 18:31:09 +08:00
BuGu
1a3fd15fdf Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-20 18:02:57 +08:00
wenjie
3e5a46570c Merge pull request #392 from jobsidi/patch-1
Update README.md
2025-03-20 03:00:20 -07:00
wenjie
2c4fbf7179 Merge pull request #382 from mekaris/feature/serial_greater_support
Add more serial features
2025-03-20 02:59:30 -07:00
wenjie
5409fb783c Merge pull request #380 from reishoku/reishoku.202503.improve_update-nanokvm-python3
Improve and optimize update-nanokvm.py
2025-03-20 02:58:53 -07:00
BuGu
4cec610aba Fix the issue of build script copying errors 2025-03-20 17:43:33 +08:00
BuGu
57d88d7889 New products default to disabling mDNS 2025-03-20 17:42:53 +08:00
BuGu
7f305ae3cf Fix deadlock issue when HDMI res error occurs 2025-03-20 17:28:05 +08:00
BuGu
eb4ac33fcd Restore frame difference detection function
Optimize the detection algorithm to reduce the detection time to 3-4ms per frame, using set_frame_detact (xx); Dynamically set the number of detection interval frames
2025-03-20 16:43:42 +08:00
BuGu
7a3c6c1690 Add production testing version restrictions 2025-03-20 16:40:33 +08:00
jobsidi
ca63609545 Update README.md
fixed link
2025-03-17 18:56:53 +01:00
mekaris
bcaa8896ee Add more serial features 2025-03-15 00:14:39 +01:00
KOSHIKAWA Kenichi
13b19e3889 Improve update-nanokvm script 2025-03-15 05:44:05 +09:00
BuGu
99d1fc0a64 Modify the method for retrieving I-frames in H.264.
Use a single data packet to replace the SPS + PPS + I three packets retrieval.
Note: This modification may require synchronization support from the server.
2025-03-12 17:34:35 +08:00
BuGu
86b7d676dd Restore S30eth
The new script has rendered the static address unavailable; reverting to the previous version.
2025-03-12 17:18:13 +08:00
BuGu
1adf6edffc Merge pull request #355 from BlwAvg/init-cleanup
Minor Init.d Cleanup
2025-03-12 16:24:28 +08:00
wj-xiao
a16af99648 update CHANGELOG.md 2025-03-11 11:52:55 +08:00
wj-xiao
58d5ab2d37 update libkvm.so 2025-03-11 10:59:48 +08:00
wj-xiao
9aebabfd59 feat: support reboot
perf: update menu bar draggable bounds
perf: unify logout logic and styles in settings
2025-03-10 19:04:18 +08:00
BuGu
21b119294c Update .gitignore 2025-03-10 18:17:28 +08:00
BuGu
e3a79daf89 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-10 18:16:06 +08:00
BuGu
4813e8bd50 fix some important bug and add new features.
+ Add watchdog.
+ Add unsupported resolution output prompt.
+ Refactor automatic resolution detection function.
+ Add support for UE chip.
+ Fix the issue where the UE chip server cannot start.
2025-03-10 18:14:04 +08:00
BuGu
93c0f3d353 Add software watchdog. 2025-03-10 18:09:55 +08:00
BuGu
be5a9f7515 Add update_lib function
you can use `./build update_lib` to add necessary components to MaixCDK.
2025-03-10 18:08:56 +08:00
BuGu
36a1eb8eb8 Add startup scripts related to mDNS service. 2025-03-10 18:07:06 +08:00
BuGu
20b452f3c0 Add get_hdmi_version function 2025-03-10 18:06:05 +08:00
wj-xiao
b062569aab feat: support enable/disable mDNS
fix: remove redundant STUN server
perf:  support disable STUN server (for local networks)
perf:  update GOMEMLIMIT from 50 to 75
perf:  add `-b` parameter to `ether-wake`
chore: bump vite to v6.2.1
2025-03-07 17:22:57 +08:00
wenjie
c91ce5ab62 Merge pull request #367 from protonchang/zhtw-translation
Update zhTW Translation
2025-03-06 18:23:16 -08:00
wj-xiao
602615e489 refactor menu bar 2025-03-06 17:44:28 +08:00
protonchang
0e11855011 Update zhTW Translation 2025-03-06 16:00:06 +08:00
BuGu
c5c768b143 Refine chip version 2025-03-05 16:40:57 +08:00
wenjie
5c0f098069 Merge pull request #361 from Stoufiler/main
Fix missing translation according to en.ts
2025-03-05 14:11:18 +08:00
wenjie
8bd7e02ec5 Merge pull request #353 from polyzium/ru-translaton-fix
Add missing keys to the Russian locale file
2025-03-05 14:10:54 +08:00
wenjie
9233bd7c79 Merge pull request #351 from forumi0721/20250227/Draggable
Added Draggable Functionality for Main Menu Positioning
2025-03-05 14:10:39 +08:00
wenjie
7d2664acb5 Merge branch 'main' into 20250227/Draggable 2025-03-05 14:10:31 +08:00
wenjie
8c09cd7c44 Merge pull request #348 from forumi0721/20250223/ImageRefresh
Add Refresh Button for Image List
2025-03-05 14:05:51 +08:00
wenjie
aef8a7a851 Merge branch 'main' into 20250223/ImageRefresh 2025-03-05 14:04:53 +08:00
BuGu
8ed6e2eca3 Merge pull request #364 from scpcom/kvm_system-get_ping_allow_state-return-value
support: kvm_system: add return value to get_ping_allow_state
2025-03-05 10:49:02 +08:00
BuGu
a7b5091024 Merge pull request #363 from scpcom/kvm_system-fix-ip_address-empty-checks
support: kvm_system: fix 'const char' and 'std::nullptr_t' comparsion
2025-03-05 10:46:31 +08:00
BuGu
cd6da8b588 Update README 2025-03-04 16:43:08 +08:00
BuGu
2d755fdb98 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-04 16:35:05 +08:00
BuGu
f231df4f65 Add the necessary dependencies for compiling the vision module. 2025-03-04 16:34:59 +08:00
BuGu
95c8edcd3d Modify the directory structure in preparation for NanoKVM-Pro 2025-03-04 16:34:50 +08:00
BuGu
d94eba0ab1 Add compilation scripts and guidelines to simplify the compilation process 2025-03-04 16:31:15 +08:00
wenjie
b48729c594 Merge pull request #345 from CaffeeLake/readme_ja
Update Japanese Docs.
2025-03-04 14:20:28 +08:00
wenjie
b9ba107587 Merge pull request #338 from S33G/tooltips
Add tooltips to menu
2025-03-04 14:19:34 +08:00
scpcom
c2d3224552 support: kvm_system: add return value to get_ping_allow_state and ion_free_space 2025-03-04 00:00:51 +01:00
scpcom
592939895b support: kvm_system: fix 'const char' and 'std::nullptr_t' comparsion 2025-03-03 23:54:11 +01:00
BuGu
8d8c57bc48 Re-add kvm_system, supplement compilation instructions and the compilation script. 2025-03-03 16:44:37 +08:00
Stoufiler
8330b1b1fe Fix missing tranlastion according to en.ts 2025-03-02 17:42:16 +01:00
BlwAvg
9fdcb428c0 No more spacing issues! Should be consistent 2025-02-27 13:12:57 -07:00
BlwAvg
cee9bbb079 i dont know how to space things still 2025-02-27 13:11:04 -07:00
BlwAvg
fcc09e2ef0 spacing cont... 2025-02-27 13:07:44 -07:00
BlwAvg
5d96a8060f spacing 2025-02-27 13:02:14 -07:00
BlwAvg
023fb4b68b S03usbdev: Removed erroneous cat command
S30eth: Refactored to remove subshell

S30eth: Fixed spelling error for /etc/resolv.conf (not /etc/resolve.conf)

S50shd: Optimized the sshd script

S95nanokvm: Checked for IPTables rules before implementing to prevent duplicates.
2025-02-27 12:43:36 -07:00
BuGu
594c205a29 Update README 2025-02-27 18:58:54 +08:00
BuGu
fc436e2743 Add the kvmapp installation package. 2025-02-27 18:46:07 +08:00
BuGu
125eddffe1 Modify the file directory to reserve a location for the Pro project 2025-02-27 18:44:25 +08:00
polyzium
aad3d718e4 Add missing keys to the Russian locale file 2025-02-27 13:27:05 +03:00
forumi0721
e3575e629c Added Draggable Functionality for Main Menu Positioning 2025-02-27 00:11:33 +09:00
BuGu
7bd7b77fa9 Add a maximum limit for vi.
In rare cases, the LT6911 I2C may return incorrect resolution information, which is passed to vi and causes the system to freeze.
2025-02-25 18:21:02 +08:00
BuGu
ba620db901 Add lock to kvmv_read_img
In some cases, it can enhance the stability of the vision subsystem.
2025-02-25 18:09:49 +08:00
BuGu
3259379345 Configurable VENC automatic recycling feature 2025-02-25 18:03:32 +08:00
BuGu
08eb89dc5c Merge pull request #340 from scpcom/optimize-vb-pools
Optimize vb pools
2025-02-25 16:49:10 +08:00
BuGu
1376929897 Merge pull request #341 from scpcom/cleanup-middleware-linking
vison: kvm_mmf: remove unused middleware libs
2025-02-25 16:48:23 +08:00
BuGu
614ef4031c Stop outputting the WiFi configuration QR code.
The QR code used for WiFi configuration is only output to the file during debugging; it was forgotten to be deleted.
2025-02-24 16:26:07 +08:00
BuGu
d9a19e132a Add stop ping mode
Before starting the program, execute touch /etc/kvm/stop_ping to stop pinging the gateway for network detection (test functionality).
2025-02-24 16:20:14 +08:00
BuGu
7795191a46 Query the status information of the network section using the Linux system API.
After testing, calling the system API still cannot effectively detect the insertion/removal of the ETH cable; modifications were made only to the status retrieval part.
2025-02-24 15:53:20 +08:00
BuGu
5e3c4d98f2 Merge pull request #307 from TuningYourCode/rework-nic-state-code
Reworked the system state code
2025-02-24 10:13:45 +08:00
BuGu
de28273def Merge branch 'main' into rework-nic-state-code 2025-02-24 10:13:08 +08:00
forumi0721
148fb4e37b Fix build error 2025-02-23 15:51:07 +09:00
forumi0721
a920fcc58a Add image list refresh button 2025-02-23 15:43:13 +09:00
forumi0721
5021ab8d2f Update korean translations 2025-02-23 13:52:44 +09:00
seeg
0ae97e6dd7 Remove unused code 2025-02-23 01:04:05 +00:00
CaffeeLake
8c2e744d42 Update Japanese Docs. 2025-02-23 09:31:51 +09:00
seeg
1ea9dc0561 Merge branch 'main' into tooltips 2025-02-21 21:40:35 +00:00
wj-xiao
e4367f0b69 update CHANGELOG 2025-02-21 19:20:19 +08:00
wj-xiao
f973316f8f Fix cdrom translation 2025-02-21 15:04:39 +08:00
wj-xiao
b5e48a07e8 fix: mounted image were not being detected correctly
perf: add support for CD-ROM mode when mounting image
perf: add a loading state during login
perf: add changelog link in settings
2025-02-21 14:52:48 +08:00
scpcom
2ec5393bd0 vison: kvm_mmf: remove unused middleware libs 2025-02-20 23:02:02 +01:00
scpcom
01c837f6ac vison: kvm: cleanup venc on type change 2025-02-20 22:59:53 +01:00
scpcom
899aa48875 vison: kvm_mmf: reduce vi pool size 2025-02-20 22:59:40 +01:00
s33g
29dd37852d Add tooltips to menu 2025-02-20 18:56:27 +00:00
wenjie
9c0c50140b Merge pull request #334 from S33G/i18n/unexpected-error
Make unexpected error localizable
2025-02-20 17:01:44 +08:00
wenjie
33d0eb3297 Merge pull request #328 from Jonher937/update-available-string
Improve English strings in web interface
2025-02-20 17:00:39 +08:00
wenjie
922a7772b8 Merge pull request #327 from Jonher937/spelling
Fix spelling
2025-02-20 16:59:41 +08:00
wenjie
38ddd89e56 Merge pull request #326 from Jonher937/fix-formatted-logging
Use format logger where needed
2025-02-20 16:40:55 +08:00
wenjie
b664411992 Merge pull request #325 from Jonher937/cleanup-fmt
remove unecessary fmt
2025-02-20 16:37:05 +08:00
wenjie
7a301f588a Merge pull request #323 from polyzium/ru-translaton-fix
Update (and fix) Russian translation
2025-02-20 16:36:09 +08:00
wenjie
e5ebb36f78 Merge pull request #322 from Stoufiler/main
Fix French translation
2025-02-20 16:35:35 +08:00
wenjie
01e4802247 Merge pull request #320 from ChokunPlayZ/main
Add Thai Translation
2025-02-20 16:34:55 +08:00
Yanavut Rojanapron
66b1ea26c5 Merge branch 'sipeed:main' into main 2025-02-20 15:09:43 +07:00
s33g
fbf2531dbb Make unexpected error localizable 2025-02-20 00:08:18 +00:00
Chokun Rojanapron
3debfc4cf1 lang: added Thai (ภาษาไทย)
and complete translation.
2025-02-19 22:17:19 +07:00
BuGu
b35542a446 Update README.md 2025-02-19 14:20:35 +08:00
BuGu
dcf5bc99dd Merge pull request #329 from S33G/patch-1
Readme improvements
2025-02-19 11:44:44 +08:00
seeg
f984b9f870 Update README.md 2025-02-19 01:06:36 +00:00
Jonathan Herlin
8c547b8baa Improve English strings 2025-02-18 23:52:53 +01:00
Jonathan Herlin
a265eaef15 Fix spelling 2025-02-18 23:10:03 +01:00
Jonathan Herlin
f8eaa7f615 Use format logger where needed 2025-02-18 23:08:12 +01:00
Jonathan Herlin
c47fc483a2 remove unecessary fmt 2025-02-18 22:59:28 +01:00
BuGu
64254052c0 Add kvm_vision_test 2025-02-18 19:02:13 +08:00
BuGu
b99a8358a7 Add components/vision, replace the MaixCDK vision 2025-02-18 19:01:41 +08:00
BuGu
ed0a6f6681 Add components/kvm_mmf, which will compile to libkvm_mmf.so 2025-02-18 19:00:39 +08:00
BuGu
055df124b3 Add components/kvm, which will compile to libkvm.so 2025-02-18 19:00:16 +08:00
BuGu
06097068a2 Update kvm_system
Fix DNS issues
2025-02-18 18:59:49 +08:00
polyzium
ff5398ed67 Update (and fix) Russian translation
Add missing keys to the ru.ts file as well as fix errors introduced by machine translation.
2025-02-18 12:58:25 +03:00
wj-xiao
c8dcdf7921 update README and CHANGELOG 2025-02-18 09:57:51 +08:00
Stoufiler
e09a0b14e0 Fix French translation 2025-02-18 00:38:11 +01:00
TuningYourCode
59d5944398 Reworked the system state code 2025-02-09 20:06:05 +01:00
611 changed files with 102687 additions and 10105 deletions

52
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,52 @@
# Dev container image for VS Code / the devcontainer CLI.
#
# The release builder image (docker/Dockerfile) stays the single source of
# truth for the RISC-V cross toolchain, Go and MaixCDK. This layer only adds
# the frontend toolchain on top: the builder image deliberately ships without
# Node (`make web` runs on the host), but an IDE container should cover web
# development as well.
#
# BASE_IMAGE can be overridden to a locally built builder image, e.g. the
# output of `make builder-image` (nanokvm-builder-local-<uid>-<gid>).
ARG BASE_IMAGE=ghcr.io/sipeed/nanokvm-builder:latest
FROM ${BASE_IMAGE}
USER root
# Node major and pnpm major track .github/workflows/package.yml ("Set up
# Node" / "Set up pnpm") and web/package.json "engines" -- keep all of them
# in sync when CI bumps either.
ARG NODE_MAJOR=22
ARG PNPM_VERSION=11
# Both can be overridden behind restrictive or mirrored corporate networks
# via devcontainer.json, e.g.:
# "build": {"args": {
# "NODE_DIST_MIRROR": "https://registry.npmmirror.com/-/binary/node",
# "NPM_REGISTRY": "https://registry.npmmirror.com"
# }}
ARG NODE_DIST_MIRROR=https://nodejs.org/dist
ARG NPM_REGISTRY=https://registry.npmjs.org
# Install the latest Node of the pinned major from official dist tarballs;
# tracking the latest patch release is intentional (rebuild the container to
# pick up updates). The SHA-256 check guards download integrity -- it shares
# its origin with the tarball, so it is not an authenticity proof.
RUN set -eux; \
apt-get update; \
apt-get install -y ca-certificates curl xz-utils; \
rm -rf /var/lib/apt/lists/*; \
case "$(uname -m)" in \
x86_64) node_arch=x64 ;; \
aarch64) node_arch=arm64 ;; \
*) echo "unsupported architecture: $(uname -m)" >&2; exit 1 ;; \
esac; \
curl -fsSL "${NODE_DIST_MIRROR}/latest-v${NODE_MAJOR}.x/SHASUMS256.txt" \
-o /tmp/SHASUMS256.txt; \
tarball="$(grep -o "node-v[0-9.]*-linux-${node_arch}\.tar\.xz" /tmp/SHASUMS256.txt | head -n1)"; \
curl -fsSL "${NODE_DIST_MIRROR}/latest-v${NODE_MAJOR}.x/${tarball}" -o "/tmp/${tarball}"; \
cd /tmp && grep " ${tarball}\$" SHASUMS256.txt | sha256sum -c -; \
tar -xJf "/tmp/${tarball}" -C /usr/local --strip-components=1 --no-same-owner; \
rm -f "/tmp/${tarball}" /tmp/SHASUMS256.txt; \
node --version && npm --version
RUN npm install --global --registry "${NPM_REGISTRY}" "pnpm@${PNPM_VERSION}" \
&& pnpm --version

View File

@@ -0,0 +1,49 @@
// Dev container for NanoKVM: Go cross-compilation, MaixCDK C support layer
// and web frontend in a single container. See "Development" in README.md.
{
"name": "NanoKVM",
"build": {
"dockerfile": "Dockerfile"
},
// The Makefile and support/sg2002/build expect the repository at
// ~/NanoKVM of the baked-in "build" user -- mount it exactly there.
"workspaceMount": "source=${localWorkspaceFolder},target=/home/build/NanoKVM,type=bind,consistency=cached",
"workspaceFolder": "/home/build/NanoKVM",
"remoteUser": "build",
// The published builder image bakes in the CI runner's uid (currently
// 1001); on Linux hosts this remaps "build" to the local uid so the bind
// mount stays writable. The remap chowns /home/build once, which makes
// the first container creation noticeably slower.
"updateRemoteUserUID": true,
// Equivalent of `. ~/MaixCDK/bin/activate` for every process spawned in
// the container, interactive or not (tasks, extensions, exec).
"remoteEnv": {
"VIRTUAL_ENV": "/home/build/MaixCDK",
"PATH": "/home/build/MaixCDK/bin:${containerEnv:PATH}"
},
"forwardPorts": [3001],
"portsAttributes": {
"3001": {
"label": "web dev server (vite)"
}
},
"postCreateCommand": ".devcontainer/post-create.sh",
// This configuration itself mounts nothing from the host (VS Code may
// still forward your SSH agent and git credentials by default). To use
// git over SSH or reach a NanoKVM device from inside the container,
// uncomment the mount below.
// "mounts": [
// "source=${localEnv:HOME}/.ssh,target=/home/build/.ssh,type=bind,readonly"
// ],
"customizations": {
"vscode": {
"extensions": [
"golang.go",
"ms-vscode.cpptools",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"bradlc.vscode-tailwindcss"
]
}
}
}

37
.devcontainer/post-create.sh Executable file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Runs once inside the dev container after it is created (see
# .devcontainer/devcontainer.json). Keeps the container aligned with the
# CLI flow in the Makefile and scripts/build-in-container.sh.
set -euo pipefail
repo_root="$(cd "$(dirname "$0")/.." && pwd)"
# The MaixCDK components baked into the image can be older than this
# checkout; resync them so C builds never use stale sources (same reason
# scripts/build-in-container.sh runs update_lib first).
"$repo_root/support/sg2002/build" update_lib
# Frontend dependencies. postCreate has no TTY, and CI=true lets pnpm make
# its non-interactive choices -- e.g. purging a node_modules tree that was
# installed from the host OS through the bind mount.
(cd "$repo_root/web" && CI=true pnpm install --frozen-lockfile)
# Start every interactive shell with the MaixCDK virtualenv active,
# mirroring `make shell`.
activate_line='. "$HOME/MaixCDK/bin/activate"'
if ! grep -qxF "$activate_line" "$HOME/.bashrc" 2>/dev/null; then
printf '\n# MaixCDK virtualenv (added by .devcontainer/post-create.sh)\n%s\n' \
"$activate_line" >>"$HOME/.bashrc"
fi
# The build user's home has no shell skeleton files (useradd ran with
# --no-create-home), so login shells would skip ~/.bashrc; give them the
# standard Debian chain.
if [ ! -f "$HOME/.profile" ]; then
cat >"$HOME/.profile" <<'EOF'
# ~/.profile (added by .devcontainer/post-create.sh)
if [ -n "$BASH_VERSION" ] && [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
EOF
fi

13
.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
Dockerfile
!server/go.mod
server/go.sum
server/NanoKVM-Server
web
support/sg2002/kvm_system/build
support/sg2002/kvm_system/dist
support/sg2002/kvm_system/CMakeLists.txt
support/sg2002/kvm_vision_test/build
support/sg2002/kvm_vision_test/dist
support/sg2002/kvm_vision_test/CMakeLists.txt

132
.github/workflows/builder-image.yml vendored Normal file
View File

@@ -0,0 +1,132 @@
name: Builder Image
# Builds the nanokvm-builder image (riscv64 musl toolchain, Go, and a MaixCDK
# checkout patched with support/sg2002/additional) and publishes it to GHCR so
# the release workflow does not have to rebuild the SDK on every tag.
#
# The image is deliberately not rebuilt on every push: it only carries the
# toolchain. Release builds re-sync support/sg2002/additional into MaixCDK and
# recompile from the checked-out source, so a slightly stale image is harmless.
on:
workflow_dispatch:
push:
branches:
- main
paths:
- docker/**
- .github/workflows/builder-image.yml
concurrency:
group: builder-image
cancel-in-progress: false
jobs:
build:
name: Build and publish nanokvm-builder
runs-on: ubuntu-latest
timeout-minutes: 240
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Free up disk space
run: |
echo "Before:"
df -h /
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/share/boost /usr/local/share/powershell
sudo docker image prune -af
echo "After:"
df -h /
- name: Resolve image reference
id: image
env:
OWNER: ${{ github.repository_owner }}
run: |
# GHCR only accepts lowercase repository paths.
owner=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')
echo "ref=ghcr.io/$owner/nanokvm-builder" >> "$GITHUB_OUTPUT"
# Logging in before the build means a credential or registry problem fails
# in seconds instead of after a full SDK build.
- name: Log in to GHCR
env:
GHCR_USER: ${{ github.actor }}
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ok=0
for attempt in 1 2 3; do
if printf '%s' "$GHCR_TOKEN" \
| docker login ghcr.io -u "$GHCR_USER" --password-stdin; then
ok=1
break
fi
echo "login attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not log in to ghcr.io after 3 attempts"
exit 1
fi
- name: Build image
run: |
# The Dockerfile chowns MaixCDK to DOCKER_UID/DOCKER_GID and the
# entrypoint gosu's to the caller's ids, so bake in the ids the
# release job will actually run as. Otherwise the SDK tree belongs to
# 1000 and syncing components into it fails with permission denied.
docker build \
--build-arg DOCKER_UID="$(id -u)" \
--build-arg DOCKER_GID="$(id -g)" \
--tag "${{ steps.image.outputs.ref }}:latest" \
--tag "${{ steps.image.outputs.ref }}:${{ github.sha }}" \
--file docker/Dockerfile \
.
- name: Verify toolchain
run: |
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" go version
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" \
riscv64-unknown-linux-musl-gcc --version | head -1
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" patchelf --version
- name: Push image
env:
IMAGE_REF: ${{ steps.image.outputs.ref }}
SHA: ${{ github.sha }}
run: |
# ghcr.io occasionally times out; a retry is cheaper than rebuilding.
# Push the immutable sha tag first so a failure there cannot leave
# :latest — which release.yml pulls — already moved.
for tag in "$SHA" latest; do
ok=0
for attempt in 1 2 3; do
if docker push "$IMAGE_REF:$tag"; then
ok=1
break
fi
echo "push of $tag attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not push $IMAGE_REF:$tag after 3 attempts"
exit 1
fi
done
- name: Summary
run: |
{
echo "### Builder image published"
echo
echo '```'
echo "${{ steps.image.outputs.ref }}:latest"
echo "${{ steps.image.outputs.ref }}:${{ github.sha }}"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"

108
.github/workflows/create-tag.yml vendored Normal file
View File

@@ -0,0 +1,108 @@
name: NanoKVM Create Tag
on:
workflow_dispatch:
inputs:
version:
description: Numeric version to tag, e.g. 2.5.0
required: true
type: string
commit_sha:
description: Full commit SHA on main (empty uses latest main)
required: false
default: ''
type: string
concurrency:
group: create-tag-${{ inputs.version }}
cancel-in-progress: false
jobs:
create-tag:
name: Create annotated tag
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: main
- name: Validate target
id: target
env:
COMMIT_INPUT: ${{ inputs.commit_sha }}
VERSION_INPUT: ${{ inputs.version }}
run: |
VERSION="$VERSION_INPUT"
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "::error::invalid version '$VERSION', expected MAJOR.MINOR.PATCH"
exit 1
fi
git fetch --force --tags origin main
if [ -n "$COMMIT_INPUT" ]; then
if ! echo "$COMMIT_INPUT" | grep -qE '^[0-9a-fA-F]{40}$'; then
echo "::error::commit_sha must be a full 40-character hexadecimal SHA"
exit 1
fi
TARGET_SHA=$(git rev-parse "${COMMIT_INPUT}^{commit}" 2>/dev/null) || {
echo "::error::commit '$COMMIT_INPUT' does not exist"
exit 1
}
else
TARGET_SHA=$(git rev-parse 'origin/main^{commit}')
fi
if ! git merge-base --is-ancestor "$TARGET_SHA" origin/main; then
echo "::error::commit '$TARGET_SHA' is not reachable from origin/main"
exit 1
fi
set +e
git ls-remote --exit-code --tags origin "refs/tags/$VERSION" >/dev/null
TAG_STATUS=$?
set -e
case "$TAG_STATUS" in
0)
echo "::error::tag '$VERSION' already exists"
exit 1
;;
2) ;;
*)
echo "::error::failed to check whether tag '$VERSION' exists"
exit 1
;;
esac
echo "sha=$TARGET_SHA" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Create and push tag
env:
TARGET_SHA: ${{ steps.target.outputs.sha }}
VERSION: ${{ steps.target.outputs.version }}
run: |
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git tag -a "$VERSION" "$TARGET_SHA" -m "Release $VERSION"
git push origin "refs/tags/$VERSION"
./scripts/verify-release-tag.sh "$VERSION" "$TARGET_SHA" >/dev/null
- name: Summary
env:
TARGET_SHA: ${{ steps.target.outputs.sha }}
VERSION: ${{ steps.target.outputs.version }}
run: |
{
echo '### NanoKVM tag created'
echo
echo "- Tag: \`$VERSION\`"
echo "- Commit: \`$TARGET_SHA\`"
echo
echo 'No package, GitHub Release, or CDN object was created.'
} >> "$GITHUB_STEP_SUMMARY"

68
.github/workflows/issue-tracker.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: Issue Tracker
on:
issues:
types: [opened, reopened, closed]
jobs:
track-issue:
name: Track Issue Updates
runs-on: ubuntu-latest
steps:
- name: Send Issue Data to API
env:
RAW_TITLE: ${{ github.event.issue.title }}
RAW_BODY: ${{ github.event.issue.body }}
RAW_LABELS: ${{ toJSON(github.event.issue.labels) }}
RAW_ASSIGNEES: ${{ toJSON(github.event.issue.assignees) }}
API_URL: ${{ secrets.ISSUE_TRACKER_API_URL }}
VERIFY_TOKEN: ${{ secrets.VERIFY_TOKEN }}
run: |
ISSUE_DATA=$(jq -n \
--arg action "${{ github.event.action }}" \
--arg id "${{ github.event.issue.id }}" \
--arg num "${{ github.event.issue.number }}" \
--arg title "$RAW_TITLE" \
--arg body "$RAW_BODY" \
--arg state "${{ github.event.issue.state }}" \
--arg created_at "${{ github.event.issue.created_at }}" \
--arg updated_at "${{ github.event.issue.updated_at }}" \
--arg closed_at "${{ github.event.issue.closed_at }}" \
--arg url "${{ github.event.issue.html_url }}" \
--arg user_login "${{ github.event.issue.user.login }}" \
--arg repository "${{ github.repository }}" \
--argjson labels "$RAW_LABELS" \
--argjson assignees "$RAW_ASSIGNEES" \
'{
action: $action,
issue: {
id: ($id | tonumber),
number: ($num | tonumber),
title: $title,
body: $body,
state: $state,
created_at: $created_at,
updated_at: $updated_at,
closed_at: $closed_at,
url: $url,
user: { login: $user_login },
labels: $labels,
assignees: $assignees
},
repository: { name: $repository },
}')
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL" \
-H "Content-Type: application/json" \
-H "Token: $VERIFY_TOKEN" \
-d "$ISSUE_DATA")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
echo "Successfully sent issue data to API"
else
echo "Failed to send issue data to API"
exit 1
fi

296
.github/workflows/package.yml vendored Normal file
View File

@@ -0,0 +1,296 @@
name: NanoKVM Package
# Builds nanokvm_<version>.tar.gz and the latest.json manifest that the
# on-device updater consumes (server/service/application/). Pull requests get a
# uniquely identified, short-lived test artifact. Release publication is a
# separate, explicit workflow that calls this one for an existing tag.
#
# This workflow does NOT publish to cdn.sipeed.com. Uploading latest.json is what
# actually offers the update to every device in the field, so that step stays
# manual and deliberate.
on:
pull_request:
branches:
- main
paths:
- .github/workflows/create-tag.yml
- .github/workflows/package.yml
- .github/workflows/release.yml
- kvmapp/**
- scripts/**
- server/**
- support/**
- tools/nanokvm_update_edid/**
- web/**
- Makefile
workflow_dispatch:
inputs:
version:
description: Version to package, e.g. 2.4.4
required: true
type: string
workflow_call:
inputs:
version:
description: Numeric version to package
required: true
type: string
ref:
description: Existing tag or commit to check out
required: true
type: string
outputs:
artifact_name:
description: Uploaded Actions artifact name
value: ${{ jobs.package.outputs.artifact_name }}
version:
description: Packaged version
value: ${{ jobs.package.outputs.version }}
concurrency:
group: package-${{ github.event.pull_request.number || inputs.ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
package:
name: Build package
runs-on: ubuntu-latest
timeout-minutes: 180
outputs:
artifact_name: ${{ steps.version.outputs.artifact_name }}
version: ${{ steps.version.outputs.version }}
permissions:
contents: read
packages: read
steps:
- name: Checkout event ref
if: inputs.ref == ''
uses: actions/checkout@v4
with:
# package.sh derives SOURCE_DATE_EPOCH from the commit date.
fetch-depth: 0
# Build scripts from a pull request must not inherit checkout's token.
persist-credentials: false
- name: Checkout requested ref
if: inputs.ref != ''
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
ref: ${{ inputs.ref }}
- name: Resolve version
id: version
env:
EVENT_NAME: ${{ github.event_name }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
INPUT_VERSION: ${{ inputs.version }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REF_NAME: ${{ github.ref_name }}
run: |
BUILD_SHA=$(git rev-parse HEAD)
if [ "$EVENT_NAME" = "pull_request" ]; then
VERSION="0.${PR_NUMBER}.${GITHUB_RUN_NUMBER}"
SOURCE_SHA="$HEAD_SHA"
elif [ -n "$INPUT_VERSION" ]; then
VERSION="$INPUT_VERSION"
SOURCE_SHA="$BUILD_SHA"
else
VERSION="$REF_NAME"
SOURCE_SHA="$BUILD_SHA"
fi
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "::error::invalid version '$VERSION', expected MAJOR.MINOR.PATCH"
exit 1
fi
if [ -z "$SOURCE_SHA" ]; then
echo "::error::could not resolve source commit"
exit 1
fi
SHORT_SHA=$(printf '%s' "$SOURCE_SHA" | cut -c1-12)
if [ "$EVENT_NAME" = "pull_request" ]; then
ARTIFACT_NAME="nanokvm-pr-${PR_NUMBER}-${SHORT_SHA}-run-${GITHUB_RUN_ID}-attempt-${GITHUB_RUN_ATTEMPT}"
else
ARTIFACT_NAME="nanokvm-${VERSION}-${SHORT_SHA}-run-${GITHUB_RUN_ID}-attempt-${GITHUB_RUN_ATTEMPT}"
fi
{
echo "artifact_name=$ARTIFACT_NAME"
echo "build_sha=$BUILD_SHA"
echo "source_sha=$SOURCE_SHA"
echo "version=$VERSION"
} >> "$GITHUB_OUTPUT"
echo "Packaging version $VERSION as $ARTIFACT_NAME"
- name: Free up disk space
run: |
df -h /
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
df -h /
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Set up pnpm
run: npm install --global pnpm@11
- name: Build frontend
run: make web
- name: Log in to GHCR
if: github.event_name != 'pull_request'
env:
GHCR_USER: ${{ github.actor }}
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ok=0
for attempt in 1 2 3; do
if printf '%s' "$GHCR_TOKEN" \
| docker login ghcr.io -u "$GHCR_USER" --password-stdin; then
ok=1
break
fi
echo "login attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not log in to ghcr.io after 3 attempts"
exit 1
fi
- name: Pull builder image
id: image
env:
OWNER: ${{ github.repository_owner }}
run: |
# GHCR only accepts lowercase repository paths.
# shellcheck disable=SC2153 # OWNER is supplied through the step environment.
owner=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')
IMAGE_REPO="ghcr.io/$owner/nanokvm-builder"
TAGGED_REF="${IMAGE_REPO}:latest"
ok=0
for attempt in 1 2 3; do
if docker pull "$TAGGED_REF"; then
ok=1
break
fi
echo "pull attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not pull $TAGGED_REF - run the 'Builder Image' workflow first and ensure PR builds can pull it without credentials"
exit 1
fi
RESOLVED_REF=$(docker image inspect --format='{{index .RepoDigests 0}}' "$TAGGED_REF")
case "$RESOLVED_REF" in
"$IMAGE_REPO"@sha256:*) ;;
*)
echo "::error::could not resolve immutable digest for $TAGGED_REF (got '$RESOLVED_REF')"
exit 1
;;
esac
echo "Pulled $RESOLVED_REF"
echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT"
- name: Build riscv64 artifacts
run: |
make release-build \
DOCKER_TTY= \
IMAGE_NAME="${{ steps.image.outputs.ref }}"
- name: Assemble package
run: make package VERSION="${{ steps.version.outputs.version }}"
- name: Compare against the published release
# Informational only: highlights what changed relative to what devices
# are currently running. Never blocks the build.
continue-on-error: true
run: |
./scripts/compare-release.sh \
"build/release/nanokvm_${{ steps.version.outputs.version }}.tar.gz"
- name: Write build provenance
env:
ARTIFACT_NAME: ${{ steps.version.outputs.artifact_name }}
BUILDER_IMAGE: ${{ steps.image.outputs.ref }}
BUILD_SHA: ${{ steps.version.outputs.build_sha }}
PR_NUMBER: ${{ github.event.pull_request.number }}
SOURCE_SHA: ${{ steps.version.outputs.source_sha }}
VERSION: ${{ steps.version.outputs.version }}
run: |
TARBALL="build/release/nanokvm_${VERSION}.tar.gz"
TARBALL_NAME=$(basename "$TARBALL")
SHA256_HEX=$(sha256sum "$TARBALL" | cut -d' ' -f1)
SHA512_HEX=$(sha512sum "$TARBALL" | cut -d' ' -f1)
SHA512_BASE64=$(jq -er '.sha512 | select(type == "string" and length > 0)' \
build/release/latest.json)
ACTUAL_BASE64=$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)
if [ "$SHA512_BASE64" != "$ACTUAL_BASE64" ]; then
echo "::error::latest.json sha512 does not match $TARBALL"
exit 1
fi
printf '%s %s\n' "$SHA256_HEX" "$TARBALL_NAME" > build/release/sha256.txt
{
echo "artifact=${ARTIFACT_NAME}"
echo "version=${VERSION}"
echo "event=${GITHUB_EVENT_NAME}"
echo "pull_request=${PR_NUMBER}"
echo "source_sha=${SOURCE_SHA}"
echo "build_sha=${BUILD_SHA}"
echo "builder_image=${BUILDER_IMAGE}"
echo "run_id=${GITHUB_RUN_ID}"
echo "run_attempt=${GITHUB_RUN_ATTEMPT}"
echo "run_url=https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
echo "tarball=${TARBALL_NAME}"
echo "sha256_hex=${SHA256_HEX}"
echo "sha512_hex=${SHA512_HEX}"
echo "sha512_base64=${SHA512_BASE64}"
} > build/release/BUILD_INFO.txt
- name: Verify release assets
run: |
./scripts/verify-release-assets.sh \
build/release "${{ steps.version.outputs.version }}"
- name: Summary
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
{
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
echo "> [!WARNING]"
echo "> PR TEST ONLY — DO NOT PUBLISH TO CDN"
echo
fi
echo "### nanokvm_${VERSION}.tar.gz"
echo
echo '```text'
cat build/release/BUILD_INFO.txt
echo '```'
echo
echo '```json'
cat build/release/latest.json
echo '```'
echo
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
echo "Upload only the inner tarball through NanoKVM's manual offline update UI."
else
echo "Publishing to \`cdn.sipeed.com/nanokvm/\` is a separate manual step."
fi
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ steps.version.outputs.artifact_name }}
path: |
build/release/nanokvm_${{ steps.version.outputs.version }}.tar.gz
build/release/latest.json
build/release/sha256.txt
build/release/BUILD_INFO.txt
if-no-files-found: error
retention-days: ${{ github.event_name == 'pull_request' && 7 || 90 }}

244
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,244 @@
name: NanoKVM Release
on:
workflow_dispatch:
inputs:
tag:
description: Existing numeric tag to release, e.g. 2.5.0
required: true
type: string
release_action:
description: Publish a release or promote a tested prerelease
required: true
type: choice
options:
- publish-prerelease
- publish-stable
- promote-stable
# Latest is repository-global, so all Release changes must be serialized.
concurrency:
group: nanokvm-github-release
cancel-in-progress: false
jobs:
validate:
name: Resolve release tag
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
source_sha: ${{ steps.tag.outputs.source_sha }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Verify tag
id: tag
env:
TAG: ${{ inputs.tag }}
run: |
SOURCE_SHA=$(./scripts/verify-release-tag.sh "$TAG")
echo "source_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT"
package:
name: Build tag package
needs: validate
if: inputs.release_action != 'promote-stable'
permissions:
contents: read
packages: read
uses: ./.github/workflows/package.yml
with:
ref: ${{ needs.validate.outputs.source_sha }}
version: ${{ inputs.tag }}
publish:
name: Publish GitHub release
needs:
- validate
- package
if: inputs.release_action != 'promote-stable'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout release tooling
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Download package artifact
uses: actions/download-artifact@v4
with:
name: ${{ needs.package.outputs.artifact_name }}
path: build/release
- name: Publish release
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_ACTION: ${{ inputs.release_action }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
./scripts/verify-release-assets.sh build/release "$TAG"
case "$RELEASE_ACTION" in
publish-prerelease) IS_PRERELEASE=true ;;
publish-stable) IS_PRERELEASE=false ;;
*)
echo "::error::invalid publish action '$RELEASE_ACTION'"
exit 1
;;
esac
ENDPOINT="repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}"
set +e
HEADERS=$(gh api --include --silent "$ENDPOINT" 2>&1)
API_STATUS=$?
set -e
HTTP_STATUS=$(printf '%s\n' "$HEADERS" | awk '
$1 ~ /^HTTP\// { status = $2 }
END { print status }
')
if [ "$API_STATUS" -eq 0 ] && [ "$HTTP_STATUS" = 200 ]; then
echo "::error::release or draft '$TAG' already exists"
echo "Publishing is one-shot. Inspect it at https://github.com/${GITHUB_REPOSITORY}/releases."
exit 1
fi
if [ "$API_STATUS" -eq 0 ] || [ "$HTTP_STATUS" != 404 ]; then
echo "::error::failed to query release '$TAG' (HTTP status: ${HTTP_STATUS:-unknown})"
printf '%s\n' "$HEADERS" >&2
exit 1
fi
TARBALL="build/release/nanokvm_${TAG}.tar.gz"
SHA256=$(sha256sum "$TARBALL" | cut -d' ' -f1)
SHA512=$(jq -er '.sha512' build/release/latest.json)
# Backticks below are intentional Markdown, not command substitution.
# shellcheck disable=SC2016
NOTES=$(printf '%s\n' \
"Application package for NanoKVM ${TAG}." \
'' \
'### Checksums' \
'' \
'`SHA-256` (hex):' \
'' \
" ${SHA256}" \
'' \
'`SHA-512` (base64, as expected by the on-device updater):' \
'' \
" ${SHA512}" \
'' \
'To offer this build over OTA, publish it through the separate CDN workflow.')
STATE_ARGS=(--prerelease="$IS_PRERELEASE")
if [ "$IS_PRERELEASE" = true ]; then
STATE_ARGS+=(--latest=false)
fi
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
gh release create "$TAG" \
--verify-tag \
--title "nanokvm@${TAG}" \
--notes "$NOTES" \
"${STATE_ARGS[@]}" \
"$TARBALL" build/release/latest.json build/release/sha256.txt
- name: Summary
env:
RELEASE_ACTION: ${{ inputs.release_action }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
{
echo '### NanoKVM GitHub Release published'
echo
echo "- Tag: \`$TAG\`"
echo "- Commit: \`$SOURCE_SHA\`"
echo "- Action: \`$RELEASE_ACTION\`"
echo
echo 'No CDN object was uploaded.'
} >> "$GITHUB_STEP_SUMMARY"
promote:
name: Promote verified prerelease
needs: validate
if: inputs.release_action == 'promote-stable'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout release tooling
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Verify and promote release
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
RELEASE_JSON=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}")
if [ "$(jq -r '.draft' <<< "$RELEASE_JSON")" != false ]; then
echo "::error::release '$TAG' is a draft"
exit 1
fi
if [ "$(jq -r '.prerelease' <<< "$RELEASE_JSON")" != true ]; then
echo "::error::release '$TAG' is not a prerelease"
exit 1
fi
CURRENT_ASSETS=$(jq -r '.assets[].name' <<< "$RELEASE_JSON" | LC_ALL=C sort)
EXPECTED_ASSETS=$(printf '%s\n' \
latest.json "nanokvm_${TAG}.tar.gz" sha256.txt | LC_ALL=C sort)
if [ "$CURRENT_ASSETS" != "$EXPECTED_ASSETS" ]; then
echo "::error::release '$TAG' does not have the exact expected asset set"
exit 1
fi
mkdir -p build/release
gh release download "$TAG" --dir build/release \
--pattern "nanokvm_${TAG}.tar.gz" \
--pattern latest.json \
--pattern sha256.txt
./scripts/verify-release-assets.sh build/release "$TAG"
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
gh release edit "$TAG" --prerelease=false --latest
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
if [ "$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq '.prerelease')" != false ]; then
echo "::error::release '$TAG' was not promoted"
exit 1
fi
if [ "$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq '.tag_name')" != "$TAG" ]; then
echo "::error::release '$TAG' was not marked latest"
exit 1
fi
- name: Summary
env:
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
{
echo '### NanoKVM prerelease promoted'
echo
echo "- Tag: \`$TAG\`"
echo "- Commit: \`$SOURCE_SHA\`"
echo '- Assets: unchanged and checksum-verified'
echo
echo 'No package was rebuilt and no CDN object was uploaded.'
} >> "$GITHUB_STEP_SUMMARY"

23
.gitignore vendored
View File

@@ -5,6 +5,10 @@ web/node_modules
web/dist
web/web
# pnpm keeps its content-addressable store next to the project when the
# home directory is on a different filesystem (e.g. inside the dev container)
.pnpm-store/
.DS_Store
*.local
*.suo
@@ -16,4 +20,21 @@ web/web
.idea
.vscode
NanoKVM-Server
NanoKVM-Server
support/sg2002/kvm_system/build
support/sg2002/kvm_system/dist
support/sg2002/kvm_system/CMakeLists.txt
support/sg2002/kvm_vision_test/build
support/sg2002/kvm_vision_test/dist
support/sg2002/kvm_vision_test/CMakeLists.txt
support/sg2002/additional/original
kvmapp/server/dl_lib
kvmapp/kvm_system/kvm_system
# Release packages assembled by scripts/package.sh
/build/
kvmapp/server
kvmapp/version

View File

@@ -1,3 +1,537 @@
## 2.5.4 (2026-11-10)
### Features
* Reworked the storage page around the NanoKVM Go file manager: the storage menu is now a two-card picker, "Disk mount" and "File sharing", that opens dedicated windows, and file sharing became a real file manager for the shared folder with list and icon views (remembered per browser), sorting by name, size, type and modified time, search in the current folder, breadcrumbs, inline folder expansion, new folder, download, delete, and uploads from the picker or by drag and drop, including folder upload with nested directories (thanks to [@liangzhuohua](https://github.com/liangzhuohua))
* Kept the two storage windows openable while the virtual disk is switched off, and let a disabled write action name the steps that unlock it: eject the virtual USB drive on the target machine and turn off the Virtual Disk switch in Settings > Device
* Removed the manual resolution setting: the video now follows the HDMI input resolution automatically, and the pointer and input-region code use the size of the frame the browser is actually showing
### Bug Fixes
* Fixed an application update leaving the page black or answering 404: service operations are serialized with an init-script lock, the migration finishes before services start, the startup script is installed atomically, recursive restarts are gone and the migration marker is kept until every required change succeeds
* Fixed video recovery after an application update leaving the encoder and VPSS in a broken state: video ownership is claimed before orphan VENC/VPSS resources are cleared, and the recovery SYS cleanup always runs to completion
* Fixed an updated web interface being hidden by a cached document: `index.html` now revalidates on every load and content-hashed assets are cached as immutable only while the file exists, so a stale document or a cached 404 is never pinned in the browser
* Fixed keyboard input being stolen from text fields: forwarding now skips events aimed at an input, textarea, select or contenteditable element and releases held keys when focus moves into one, so typing and pasting in the new dialogs works
* Fixed `/data` staying read-only while no medium was attached after a failed remount or an exFAT error; the media state poll now heals it and writable opens and transfers retry before failing
* Fixed the disk mount window reporting transfers it did not start by keeping the media job in the file manager
### Performance
* Reworked H.264 and MJPEG capture on the Sophgo SDK: each codec gets its own capture session and lock with encoder backpressure, frame ownership is explicit, capture stops as soon as the last viewer leaves, and the bundled video libraries were rebuilt
### UI Improvements
* Made a menu picker that opens its own window close without collapsing the menu bar
### Localization
* Translated the new storage page and file manager strings for all supported locales
### Chores
* Added a `POST /api/storage/media/files/mkdir` endpoint for recreating a folder tree during upload, with the same permission model as upload and delete, path and symlinked-parent validation, and a distinct error when the name is already taken by a file
* Rebuilt the bundled `libkvm.so` and `libkvm_mmf.so` against the Sophgo SDK and refreshed the build and deployment instructions
* Added unit tests for media file creation, read-only `/data` healing and the static file cache headers
## 2.5.3 (2026-11-03)
### Features
* Replaced the desktop image menu and the download page with a storage page that lists the media the emulated USB disk can carry, mounts and ejects them, and browses the files inside a medium over the same gadget, so the two machines exchange files without going through the terminal
* Added uploads, downloads and deletes to the storage page, with search, sorting, folder deletion behind a confirmation, one transfer display for image and file transfers, cancellable uploads, a free space preflight and a checksum mismatch report
* Browsed only media whose filesystem this device can read, so an ISO 9660 image is still served to the target machine but cannot be listed here, and limited CD-ROM mode to ISO 9660 and UDF images
* Made the shared folder follow the target machine: while it owns the data partition the listing refreshes on a timer after dropping the dentry and inode caches, so a file the target machine wrote shows up within a second of its own writeback
* Added a fine-grained permission system on top of the `admin` and `user` roles: administrators keep implicit full access, while every other account receives an explicit set of grants covering the console, power, media, terminal, device, network, updates, MCP, Tailscale and AI features, with the groups, risk marks and implied grants shown in a permission editor; mounting a medium needs the virtual disk, and the storage page names the account that has to enable it when the current account cannot
* Added a view-only console session for an account that may watch but not send input: the pointer and keyboard capture, the mouse menu and the input region editor follow the grant, pages, menus, settings tabs and storage actions render only what the account is allowed to use, and an account without console access lands on a page offering the sections its grants open
* Changed permission handling so an open session picks up the new grants without ending the login: a change that invalidates a cached capability drops the long-lived connection with a dedicated close code so the page reconnects, and only disabling an account ends the login
* Added the choice of regenerating the device-wide MCP API key when an account loses the MCP grant, instead of rotating the key silently and disconnecting every MCP client
* Kept the pre-2.6 image endpoints working as a compatibility layer over the new media API, so existing clients and scripts keep working
* Treated UDF images, not only ISO 9660 ones, as optical media, and accepted uploads by extension (`.iso`/`.img`), leaving an unusable image to fail when it is mounted instead of while it is stored
### Bug Fixes
* Fixed HID input being lost after a medium was mounted or the gadget was otherwise reset, by reopening the HID devices with a retry instead of a single attempt that could fail while the new nodes were still coming up
* Fixed `/data` staying read-only after a failed gadget script or a network switch
* Fixed the settings menu icon sitting a few pixels below the other menu icons, and centered the dialog tab icons in their box
* Fixed Chinese and Japanese punctuation being drawn by a Latin face in tooltips and dialogs, which pushed the ideographic comma and full stop above the baseline
### UI Improvements
* Gave the shared folder, ISO and IMG entries their own glyphs and picked file icons from the extension, so a listing can be read at a glance
* Listed administrators above regular accounts and gave their rows a lighter card
* Moved the PicoClaw chat composer to an antd text area and replaced the Radix scroll area with the native scroll container, so the settings dialog and the shortcut lists scroll like the rest of the app
### Localization
* Translated every string the storage page, the permission editor, the view-only console and the MCP key rotation add for all 24 supported locales
* Removed the keys the retired image menu and download page left behind
### Security
* Mounted images are opened through loop devices that refuse symlinks, and files inside a medium are opened without following links
### Chores
* Removed the desktop image menu, the download page and their web client code
* Dropped the `@radix-ui/react-scroll-area` dependency
* Documented the permission catalog, the split between mounting media and writing the library, and the grants that reach the whole device in `server/README.md` and `server/README_ZH.md`
## 2.5.2 (2026-09-29)
### Features
* Added a one-writer policy for the emulated USB disk and the `/data` partition: `/data` is mounted read-only from boot while the virtual disk serves the raw partition to the target machine, enabling the disk remounts it read-only and verifies the state before the target machine can write it, refusing to expose the disk when the remount fails, and releasing a medium hands the raw partition back to the target machine the same way
* Added confirmation before a mounted medium and the virtual disk take the shared partition from each other, including a warning that a running image transfer is cancelled and that `/data` becomes read-only on this device
* Added cancellation of a running image transfer before the partition handover, showed the transfer state in the image list and disabled the actions that cannot run while a medium is mounted, with a hint explaining why
* Added names for the mounted medium and the emulated USB device taken from the image file, truncated to the SCSI inquiry product field and the USB product string and restored on unmount
* Added streaming validation of uploaded images: ISO 9660 and UDF volume descriptors and raw disk images (GPT, APFS, HFS+, MBR) are accepted and anything else is rejected in seconds instead of after the whole transfer, with a free space check that keeps a 128 MiB reserve before any byte is received
### Bug Fixes
* Fixed mass storage mounts staying writable from the target machine: every mounted image is now served read-only, with the flag set before the LUN is attached, so the target machine can neither write to nor format it
* Fixed the LUN flags surviving a gadget restart, which brought the shared partition back to the target machine read-only or as an optical drive after a medium had been mounted
* Fixed the virtual disk switch staying on but unchangeable while a medium was mounted; the disk now reports itself on only while the LUN really carries the `/data` partition
* Fixed the on-screen keyboard crashing the page with "Minified React error #130" as soon as it was opened, by importing the `react-simple-keyboard` component through its named export, which the CommonJS interop under Vite 8 no longer resolves from a default import
### Localization
* Translated the new virtual disk and image mounting strings for every locale
### Chores
* Added unit tests for the upload header check, the free space preflight and the image name truncation
## 2.5.1 (2026-09-09)
### Features
* Added device-level multi-user support with `admin` and `user` roles and a user management page under Settings, separating administrative areas (terminal, scripts, storage, network, updates, MCP, PicoClaw and Tailscale) from the video, keyboard, mouse, paste, wake-on-LAN and power controls every account keeps
* Moved sessions to HttpOnly cookies with a per-user token version, so changing a password or disabling an account immediately ends that user's open web and WebSocket sessions
* Added support for a custom update server, so the application can be updated from your own mirror, with credentials in the URL, manifest validation and a settings page for configuring it
* Added SHA-256 verification of offline update packages before they are installed
* Added configurable mouse input regions for absolute mode, with automatic black-border detection, manual selection of the controllable area on screen, and original-resolution presets, so the pointer stays aligned when the target machine outputs a letterboxed or non-16:9 signal
* Added touch gestures to relative mouse mode, including tap, drag, long press, double-tap drag and two-finger scroll, so relative mode is now usable from a phone or tablet
* Added a `signal` field to `/api/vm/hdmi` reporting whether an HDMI source is actually present, not just whether capture is enabled
* Added a default root shell profile showing the user, host and working directory in the prompt over SSH and the Web terminal
### Bug Fixes
* Fixed mouse coordinates being offset in Direct H.264 mode when the target machine pads the picture with black bars
* Fixed touch input in absolute mode, and stopped taps on the black letterbox area from being sent to the target machine
* Fixed the video area not fitting the window, by scaling H.264 and MJPEG playback to contain and letting the page handle touch instead of the browser
* Fixed WebRTC H.264 failures leaving a silent black screen; signaling, negotiation, ICE and playback failures now report what went wrong and offer a retry
* Fixed a slow WebRTC viewer stalling the shared H.264 source for everyone else, by dropping its buffered frames until the next key frame
* Fixed application updates running from a temporary directory that could be too small or shared with another update; online and offline updates are now staged in isolated persistent workspaces with archive, manifest and free-space checks, and the last rollback backup is kept when space runs short
* Fixed the update lock being released before the server finished restarting, which allowed a second update to start and be killed mid-install
* Fixed Web terminal sessions not loading the root profile, by starting them as login shells in `/root`
### Performance
* Routed Direct and WebRTC viewers through a single shared H.264 capture source instead of each reading the encoder separately
### Localization
* Synchronized translations of other languages according to English
### Chores
* Upgraded the web build tooling to Vite 8 and switched to Vite's native tsconfig path resolution
* Added a dev container for full-stack development
* Prefixed GitHub Release titles with `nanokvm`
* Added release asset verification with per-device package size limits to the packaging workflow
## 2.5.0 (2026-08-04)
### Features
* Added an MCP service that lets trusted MCP clients capture screenshots and control the keyboard and mouse with an API key, including a settings page for enabling it and regenerating the key
* Added coordinated device control so MCP, PicoClaw and manual input hand ownership over to each other instead of writing HID input at the same time
* Added remote keyboard lock indicators that show the target machine's Num Lock, Caps Lock and Scroll Lock state
* Added an optional SHA-256 checksum and cancellation to remote image downloads
### Bug Fixes
* Fixed the USB network gadget getting a random host-side MAC on every bind, which made the attached PC register a new network adapter after each reboot; both the device and host MAC are now derived from the chip UID (thanks to [@BeaconCat](https://github.com/BeaconCat))
* Fixed OLED sleep durations above 255 seconds being truncated, so the 5 min, 10 min, 30 min and 1 hour options now behave as selected
* Fixed the mounted image API returning an error in HID-Only mode
* Fixed image downloads and application updates interfering with each other when running at the same time
* Fixed Direct H.264 playback falling behind when the decoder queue backed up, by resynchronizing at the next key frame and preferring hardware decoding
* Added a warning when Direct and WebRTC H.264 stream modes are used at the same time
* Made the video input state shared between processes and read it without shell pipelines, so HDMI status stays consistent between `NanoKVM-Server` and `kvm_system`
### Performance
* Reduced latency in 60 Hz mode with decode-driven flow control, GOP-aware bounded queues, and dedicated writer goroutines with write deadlines so a slow client no longer stalls the others
* Integrated zero-copy H.264 capture into the video pipeline instead of relying on a preload hook
* Stopped HDMI capture when no user is logged in or all viewers are idle, reducing power consumption
### UI Improvements
* Tidied the image download dialog layout and truncated long file names in the upload box
### Localization
* Synchronized translations of other languages according to English
### Chores
* Split release automation into separate package, tag and release workflows, and produced identifiable build artifacts with checksums for pull requests
* Allowed overriding the builder image, installed `patchelf` in the build environment, and fixed the exit codes of `support/sg2002/build`
* Fixed slow container builds caused by uid/gid mismatch and reused existing container users and groups
## 2.4.3 (2026-06-09)
### Features
* Added LT6911D support
### Bug Fixes
* Improved USB network adapter compatibility on Windows
## 2.4.2 (2026-05-20)
### Features
* Added HDMI capture status detection with localized warning and error overlays on the desktop screen
### Bug Fixes
* Fixed left-button touch cancellation and context menu cleanup for mouse input
* Improved the WebRTC loading indicator
* Added Wi-Fi password field validation
* Hardened Wake-on-LAN MAC handling by normalizing stored addresses, avoiding shell execution, handling missing history gracefully, and improving named MAC display
* Stabilized PicoClaw session switching by waiting for gateway release, refreshing runtime status before reconnecting, rendering structured thought messages, and preventing history row overflow
### Performance
* Improved H.264 streaming client handling by reducing frame queue latency, using client snapshots for fanout, applying backend ICE server configuration, and cleaning up disconnected WebRTC clients more aggressively
### UI Improvements
* Refreshed desktop menu ordering and community links, including replacing the Discussion link with Discord
### Chores
* Removed the legacy H.264 stream package
* Updated PostCSS, refreshed the MSW worker, and added pnpm workspace build approvals
## 2.4.1 (2026-05-08)
### Features
* Added DNS management to Network settings, including DHCP/manual modes, effective DNS display, network details, IPv4/IPv6 server validation, and persistent udhcpc hook support
* Added a configurable server `host` option for binding NanoKVM to a specific listen address (thanks to [@allmazz](https://github.com/allmazz))
* Added French keyboard layout support and language options (thanks to [@ilyesAj](https://github.com/ilyesAj))
### Bug Fixes
* Hardened HID recovery and cleanup by adding non-blocking HID writes, bounded reopen retries, stale event draining, and release reports after write failures
* Fixed the `kvm_vision` project name and build output message in the SG2002 build script (thanks to [@Voranto](https://github.com/Voranto))
### UI Improvements
* Moved TLS and Wi-Fi settings into the Network settings section
* Optimized the Settings scrollbar style
### Localization
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
* Synchronized translations of other languages according to English
### Security
* Upgraded vulnerable web dependencies
## 2.4.0 (2026-04-10)
### Features
* **Introduced [PicoClaw](https://github.com/sipeed/picoclaw) support** — an AI-powered remote desktop assistant for NanoKVM. PicoClaw seamlessly integrates a lightweight AI agent with NanoKVM's underlying hardware capabilities. Key highlights include:
* **Zero-Agent Architecture:** Operates entirely through HDMI video capture (vision) and USB HID emulation (keyboard/mouse). No SSH access, network connection to the host, or OS-level software installation is required.
* **Natural Language Control:** Features a built-in chat interface allowing users to issue complex instructions in plain text.
* **Autonomous GUI Operation:** The AI agent can autonomously observe the remote host's screen, understand UI elements, reason about the task, and execute operations mimicking human behavior.
* **Installation Note:** PicoClaw is not built into the NanoKVM device or firmware. Install it separately when needed.
### Bug Fixes
* Added a default subnet mask for static IP configurations
* Fixed an issue where the IP address would occasionally not display
## 2.3.6 (2026-03-12)
### Features
* Implemented AP password authentication for the WiFi configuration page
* Added Korean and Japanese virtual keyboard layouts (thanks to [@klim4-bot](https://github.com/klim4-bot))
* Enabled support for 640x480 resolution (thanks to [@Voranto](https://github.com/Voranto))
* Added encryption parameters for OLED distribution network
* Added custom logo function and logo generation tools
* Added update mechanism for tailscale startup script
### Localization
* Updated Japanese translation (thanks to [@tkmsst](https://github.com/tkmsst))
## 2.3.5 (2026-02-28)
### Features
* Implemented login brute-force protection with lockout mechanism
### Bug Fixes
* Improved Tailscale error handling in UI components and refined backend state mapping
### Chores
* Updated server and web dependencies
## 2.3.4 (2026-01-26)
### Features
* Introduced `Leader Key` functionality to bypass local browser shortcut interception
### Bug Fixes
* Fixed an issue where the Right Shift key was not being recognized on Windows system
* Fixed a bug where the menu bar would fail to close correctly
### Localization
* Updated Traditional Chinese translations (thanks to [@j796160836](https://github.com/j796160836))
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
## 2.3.3 (2026-01-16)
### Features
* Added support for setting the display mode of the menu bar
### Bug Fixes
* Fixed a keyboard issue where IME composition events were not handled correctly
* Resolved an issue where the `AltGr` key was not recognized on the Windows system
* Fixed a bug where `Command` key combinations were not fully released on the macOS system
* Fixed input issues with the `IntlBackslash` key on the German virtual keyboard
### Localization
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
### Chores
* Bump react-router-dom from 6.27.0 to 6.30.3
* Updated eslint
## 2.3.2 (2026-01-08)
### Features
* Added support for custom keyboard shortcuts
* Added support for mouse Forward and Back buttons (reboot required)
* Added support for touchscreen mouse operation
* The menu bar now supports auto-hide and drag
### Bug Fixes
* Fixed an issue where the previous IP address was not released after configuring a static IP
### Performance
* Refactored the keyboard to support simultaneous keystrokes and a wider range of international layouts (reboot required)
* Refactored the mouse to improve response latency
* Refactored the WebSocket module to transmit keyboard and mouse data using the standard HID format
## 2.3.1 (2025-12-26)
### Features
* Added support for offline application updates (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Implemented support for uploading ISO images (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Extended clipboard compatibility to support Russian characters (thanks to [@pekishev](https://github.com/pekishev))
* Added configuration options for video scaling
* Added support for configuring mouse scroll wheel direction
### Bug Fixes
* Resolved an issue where custom port may not be accessible
* Fixed a bug where Web Terminal and Serial Terminal may not disconnect when the page is closed
### Security
* Enhanced validation logic on the Wi-Fi configuration page. Requests are now rejected when the device is not in AP mode to prevent unauthorized changes
### Chore
* Added a Docker image environment to support building `libkvm.so` and `NanoKVM-Server` (thanks to [@lowtech-guy](https://github.com/lowtech-guy))
* Optimized the Settings UI
### Localization
* Updated Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
* Updated Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
* Updated Spanish translation (thanks to [@Deses](https://github.com/Deses))
## 2.3.0 [0e30a26](https://github.com/sipeed/NanoKVM/commit/0e30a26db42cbc08416662b49a88a5d16ad93424) (2025-11-26)
### Features
* Added an EDID editor in the terminal with a built-in 1080P EDID template
* Added German virtual keyboard and German clipboard support (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Resetting the HID also resets the USB hardware
* Added support for deleting ISO images
### Refactoring & Improvements
* Video (H.264 WebRTC): Refactored the module to significantly reduce video latency
* Video (H.264 Direct): Refactored to optimize data transmission and support data parsing even when the page is in the background
* Video (MJPEG): Refactored and ensure correct data length transmission
* Added locking before resetting USB to prevent HID deadlock (thanks to [@scpcom](https://github.com/scpcom))
* Optimized HID writing logic
* Made HDMI toggle state persist across reboots (thanks to [@tpretz](https://github.com/tpretz))
* Enhanced the paste feature with browser clipboard API integration (thanks to [@patrickpilon](https://github.com/patrickpilon))
* Set the inquiry string for the virtual storage device (thanks to [@scpcom](https://github.com/scpcom))
* Hostname now updates `/etc/hosts` simultaneously and takes effect immediately (thanks to [@scpcom](https://github.com/scpcom))
* Improved compatibility for static IP configuration on Windows
* Optimized the web page title update logic
* Added a confirmation dialog when uninstalling Tailscale
* Improved UI for Clipboard, Image Mounting, and settings pages
### Bug Fixes
* Tailscale: Fixed an issue where Tailscale would turn the device into a router
* Tailscale: Fixed an issue where Tailscale would disable IPv6
* Tailscale: Added a swap memory option to prevent Tailscale Out-Of-Memory errors
* Tailscale: Fixed Tailscale accept-dns configuration (thanks to [@lazydba247](https://github.com/lazydba247))
* Fixed an issue where certain modifier keys were not recognized
* Fixed vertical mouse drift when the page is zoomed in or out
### Localization
* Update Korean translation (thanks to [@xenix4845](https://github.com/xenix4845))
* Update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
* Add Brazilian Portuguese translation (thanks to [@chiconws](https://github.com/chiconws) and [@Luccas-LF](https://github.com/Luccas-LF))
* Add Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
* Add Catalan translation (thanks to [@Zagur](https://github.com/Zagur))
* Add Turkish translation (thanks to [@Keylem](https://github.com/Keylem))
### Security
* Implemented a delay after failed login attempts to mitigate brute-force attacks
* Upgraded dependencies to fix known security vulnerabilities
## 2.2.9 [c77981c](https://github.com/sipeed/NanoKVM/commit/c77981cc0ceebd8f6705b6c5d8c3cf4edf4f6717) (2025-06-13)
* fix(security): resolve parameter injection in serial port terminal
## 2.2.8 [01e28f1](https://github.com/sipeed/NanoKVM/commit/01e28f10ae8b581d484bb6077ddfe7bbe4e57919) (2025-05-22)
* feat: add AZERTY virtual keyboard Layout (thanks to [@felix068](https://github.com/felix068))
* feat: add support for enabling/disabling HDMI output (PCIe version only) (thanks to [@tpretz](https://github.com/tpretz))
* feat: add support for custom mouse wheel speed
* fix: prevent direct H.264 stream buffer overflow and replay issues
* perf: improve keyboard paste performance (thanks to [@ethanperrine](https://github.com/ethanperrine))
* Localization
* update Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
* update Ukrainian translation (thanks to [@arbdevml](https://github.com/arbdevml))
* update Russian translation (thanks to [@arbdevml](https://github.com/arbdevml))
## 2.2.7 [e18ec22](https://github.com/sipeed/NanoKVM/commit/e18ec2219d22886529575d1fdaad5c320e05f5b2) (2025-05-08)
* feat: add HTTPS support
* feat: support direct H.264 streaming over HTTP
* Localization
* update Russian translation (thanks to [polyzium](https://github.com/polyzium))
* update Dutch translation (thanks to [LeonStraathof](https://github.com/LeonStraathof))
* update Ukrainian translation (thanks to [click0](https://github.com/click0))
* update German translation (thanks to [3limin4tor](https://github.com/3limin4tor))
## 2.2.6 [c83dc55](https://github.com/sipeed/NanoKVM/commit/c83dc5565c9dbed22336661a8832edbd93a06d11) (2025-04-17)
* feat: add mouse jiggler to prevent system sleep
* feat: add support for swap memory
* feat: add support for customizing the device hostname
* feat: add support for customizing the web page title
* feat: add support for assigning custom names to Wake-on-LAN MAC addresses
* feat: add confirmation prompts for power operations
* feat: add logo to the login page (thanks to [S33G](https://github.com/S33G))
* fix: fix possible privacy issues with MIC drivers. [Repair Record](https://github.com/sipeed/NanoKVM/commit/f9244b36df090a05cd59ba11ea4fd01e9b638995)
* fix: fix iptables rule that could interfere with SSH connections (thanks to [scpcom](https://github.com/scpcom))
* fix: fix the static IP gateway configuration might not apply correctly (thanks to [xitation](https://github.com/xitation))
* perf: optimized OLED display handling and sleep logic
* perf: improve H.264 streaming reliability by adding a heartbeat mechanism
* perf: set the minimum screen size to 640x480
* perf: add display of both wired and wireless IPv4 addresses in the settings page
* perf: update the Thai language translations (thanks to [ChokunPlayZ](https://github.com/ChokunPlayZ))
* chore: bump axios to 1.8.4
* chore: bump golang.org/x/net to v0.39.0
* chore: bump github.com/golang-jwt/jwt/v5 to to v5.2.2
## 2.2.5 [3286cc2](https://github.com/sipeed/NanoKVM/commit/3286cc2f85a14133d65935cb476c833dcf151459) (2025-03-26)
* fix: server crash caused by MJPEG frame detection error
* feat: add HID-Only mode
* feat: support preview updates
* perf: improve image reading performance by optimizing screen parameters
## 2.2.4 [1bf986d](https://github.com/sipeed/NanoKVM/commit/1bf986d41b34d568c1ffee5df90ce61b6b08456b) (2025-03-21)
* fix: resolve USB initialization issue
* fix: correct abnormal updates in certain models
* perf: add version restrictions for production testing
## 2.2.3 [6ef83cb](https://github.com/sipeed/NanoKVM/commit/6ef83cb22fcd77f721d32c97c85d12f2bfc3035a) (2025-03-21)
* feat: add support for setting H.264 GOP
* fix: resolve deadlock caused by HDMI resolution errors
* perf: merge H.264 SPS and PPS into I-frame
* perf: refactor MJPEG frame detection
* perf: added more configuration options to the serial port terminal (thanks to [@mekaris](https://github.com/mekaris))
* perf: improve the `update-nanokvm.py` script (thanks to [@reishoku](https://github.com/reishoku))
* perf: disable mDNS by default in new products
* perf: update log timestamp to millisecond precision
* chore: bump Go to 1.23
* chore: bump `golang.org/x/net` to v0.37.0
## 2.2.2 [58d5ab2](https://github.com/sipeed/NanoKVM/commit/58d5ab2d37244b1e1a68b925a5c23c324c489ad3) (2025-03-11)
* feat: add watchdog for NanoKVM-Server
* feat: add support for UE chip
* feat: support system reboot
* feat: support enable/disable mDNS
* fix: resolve UE chip cannot start server
* perf: refactor automatic resolution detection
* perf: add output prompt for unsupported resolutions
* perf: add lock to kvmv_read_img
* perf: configurable VENC automatic recycling feature
* perf: add maximum limit for vi
* perf: add tooltips to menu bar (thanks to [@S33G](https://github.com/S33G))
* perf: menu bar is now draggable (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: image list support auto-refresh (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: update translations
## 2.2.1 [b5e48a0](https://github.com/sipeed/NanoKVM/commit/b5e48a07e82df3aedd60442342ae50b95684a697) (2025-02-21)
* fix: mounted image were not being detected correctly
* perf: add support for CD-ROM mode when mounting image (thanks to [@scpcom](https://github.com/scpcom))
* perf: add a loading state during login
* perf: add changelog link in settings
* perf: update translation and cleanup the code (thanks to [@ChokunPlayZ](https://github.com/ChokunPlayZ) [@Stoufiler](https://github.com/Stoufiler) [@polyzium](https://github.com/polyzium) [@Jonher937](https://github.com/Jonher937) [@S33G](https://github.com/S33G))
## 2.2.0 [0dbf8c0](https://github.com/sipeed/NanoKVM/commit/0dbf8c007f2d0183d0f0601c3da6d3c3fccd8b31) (2025-02-17)
NanoKVM [Image v1.4.0](https://github.com/sipeed/NanoKVM/releases/tag/v1.4.0) has been released!
> Please refer to the [wiki](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/system/introduction.html) for more details about the image and application.
* fix: improve password update notification logic (thanks to [@li20034](https://github.com/li20034))
* perf: increase update wait time to 10s (from 6s)
* perf: update Korean translation (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
* refactor: update `libkvm.so` and `libkvm_mmf.so` libraries
## 2.1.6 [6eb4a4e](https://github.com/sipeed/NanoKVM/commit/6eb4a4ea6254f465a47f9881d13934c686649061) (2025-02-14)
* feat: support downloading image from online URL (thanks to [@Itxaka](https://github.com/Itxaka))
@@ -10,9 +544,9 @@
* perf: download Tailscale installation package from the official source
* perf: automatic enable/disable GOMEMLIMIT on tailscale start/stop
* perf: add JWT configuration
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
* refreshTokenDuration: customize token expiration time
* revokeTokensOnLogout: invalidate all JWT tokens on logout
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
* refreshTokenDuration: customize token expiration time
* revokeTokensOnLogout: invalidate all JWT tokens on logout
* perf: implement secure password storage using bcrypt hashing
* perf: implement integrity checks for online updates
* refactor: refactor HDMI module and remove the dependency `libmaixcam_lib.so`

152
Makefile Normal file
View File

@@ -0,0 +1,152 @@
# Makefile for NanoKVM Project
# Configuration
UID := $(shell id -u)
GID := $(shell id -g)
# ?= so a prebuilt image can be used instead, e.g. a GHCR-cached builder in CI.
IMAGE_NAME ?= nanokvm-builder-local-$(UID)-$(GID)
PWD := $(shell pwd)
VERSION ?=
# Docker run common parameters. Allocating a TTY breaks in environments without
# one, so it can be overridden with DOCKER_TTY=
DOCKER_TTY ?= -it
DOCKER_RUN_BASE := docker run -e UID=$(UID) -e GID=$(GID) -v $(PWD):/home/build/NanoKVM --rm
# Build the image with the host user's identity so entrypoint does not need
# to recursively rewrite the MaixCDK home directory at container startup.
DOCKER_BUILD_ARGS := --build-arg DOCKER_UID=$(UID) --build-arg DOCKER_GID=$(GID)
# Build commands
GO_BUILD_CMD := cd /home/build/NanoKVM/server && ./build.sh
SUPPORT_BUILD_CMD := . ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM/support/sg2002 && ./build kvm_system && ./build kvm_system add_to_kvmapp
VISION_BUILD_CMD := . ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM/support/sg2002 && ./build kvm_vision && ./build kvm_vision add_to_kvmapp
RELEASE_BUILD_CMD := /home/build/NanoKVM/scripts/build-in-container.sh
.PHONY: help check-root builder-image rebuild-image check-image shell app support vision \
web release-build package release all clean
# Default target
all: app support
# Help target
help:
@echo "NanoKVM Build System"
@echo ""
@echo "Available targets:"
@echo " help - Show this help message"
@echo " check-image - Check builder Docker image and show versions"
@echo " builder-image - Build Docker image if not exists"
@echo " rebuild-image - Force rebuild Docker image"
@echo " shell - Enter interactive builder environment"
@echo " app - Build Go application server"
@echo " support - Build kvm_system daemon"
@echo " vision - Build video libraries (libkvm.so)"
@echo " web - Build the frontend into web/dist"
@echo " all - Build both app and support (default)"
@echo " release-build - Build every riscv64 release artifact in one pass"
@echo " package - Assemble nanokvm_<VERSION>.tar.gz + latest.json"
@echo " release - release-build + web + package (needs VERSION=x.y.z)"
@echo " clean - Clean build artifacts"
@echo ""
@echo "Prerequisites:"
@echo " - Docker must be installed and running"
@echo " - Must not run as root user"
# Security check - prevent running as root
check-root:
@if [ "$$(id -u)" -eq 0 ]; then \
echo "Can't run as root"; \
exit 1; \
fi
# Check if builder image exists and show versions
check-image: check-root
@echo "Checking builder image..."
@echo "Golang version: " && \
docker run --rm -i $(IMAGE_NAME) go version && \
echo "" && \
echo "Host-tools version:" && \
docker run --rm -i $(IMAGE_NAME) riscv64-unknown-linux-musl-gcc -v && \
echo ""
# Build Docker image if it doesn't exist
builder-image: check-root
@if ! docker image inspect $(IMAGE_NAME) >/dev/null 2>&1; then \
echo "Building Docker image..."; \
docker build $(DOCKER_BUILD_ARGS) -t $(IMAGE_NAME) -f docker/Dockerfile ./; \
else \
echo "Docker image $(IMAGE_NAME) already exists."; \
fi
# Force rebuild Docker image
rebuild-image: check-root
@echo "Force rebuilding Docker image..."
@docker build --no-cache $(DOCKER_BUILD_ARGS) -t $(IMAGE_NAME) -f docker/Dockerfile ./
# Enter interactive shell (equivalent to build.sh with no arguments)
shell: check-root builder-image
@echo "Switching into builder..."
@$(DOCKER_RUN_BASE) -it $(IMAGE_NAME) /bin/bash -c ". ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM ; exec bash"
# Build Go application
app: check-root builder-image
@echo "Building app..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(GO_BUILD_CMD)'
# Build hardware support libraries
support: check-root builder-image
@echo "Building support..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(SUPPORT_BUILD_CMD)'
# Build video libraries (libkvm.so) into kvmapp/server/dl_lib
vision: check-root builder-image
@echo "Building vision..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(VISION_BUILD_CMD)'
# Build every riscv64 release artifact in one container pass
release-build: check-root builder-image
@echo "Building release artifacts..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(RELEASE_BUILD_CMD)'
# Build the frontend (runs on the host; the builder image has no Node)
web:
@echo "Building web..."
@cd web && pnpm install --frozen-lockfile && pnpm build
# Assemble the release package and its manifest
package:
@if [ -z "$(VERSION)" ]; then \
echo "VERSION is required, e.g. make package VERSION=2.4.4"; \
exit 1; \
fi
@scripts/package.sh "$(VERSION)"
# Full local release: riscv64 artifacts + frontend + package.
# Invoked as sub-makes rather than prerequisites: packaging asserts on what the
# earlier steps produce, so the order matters even under make -j.
release:
@$(MAKE) release-build
@$(MAKE) web
@$(MAKE) package VERSION="$(VERSION)"
# Clean build artifacts
clean:
@echo "Cleaning build artifacts..."
@if [ -f server/NanoKVM-Server ]; then \
rm -f server/NanoKVM-Server; \
echo "Removed server/NanoKVM-Server"; \
fi
@if [ -d support/sg2002/build ]; then \
rm -rf support/sg2002/build; \
echo "Removed support/sg2002/build"; \
fi
@if [ -d build/release ]; then \
rm -rf build/release; \
echo "Removed build/release"; \
fi
@if [ -d web/dist ]; then \
rm -rf web/dist; \
echo "Removed web/dist"; \
fi
@echo "Clean completed."

213
README.md
View File

@@ -1,123 +1,160 @@
NanoKVM
======
# NanoKVM
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html"> Quick Start </a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> Hardware </a>
</h3>
English | [中文](./README_ZH.md) | [日本語](./README_JA.md)
<br>
<img src="https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png" alt="NanoKVM" style="margin: 20px 0;">
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 Quick Start</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ Hardware Details</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 Firmware Releases</a>
</h3>
<br>
</div>
> Your NanoKVM Power by RISC-V !
> If you have any issues or suggestions, creating issue here, or tell us with [MaixHub Discussion](https://maixhub.com/discussion/nanokvm).
## 🌟 What is NanoKVM?
## Opensource & Contribution
NanoKVM is a series of compact, open-source IP-KVM devices based on the LicheeRV Nano (RISC-V). It lets you remotely access and control computers as if you were sitting in front of them, making it useful for servers, embedded systems, and other headless machines.
### Update 2025.02.14
Newest APP v2.1.6 add most security enhancements&bug fix, recommend regular users upgrade to this version or newer.
## 📦 Product Family
### Update 2025.02.05
For users concerned about security, you can read this issue: https://github.com/sipeed/NanoKVM/issues/301 , you will find explanations addressing all security concerns.
GitHub, as an open and transparent platform, provides a space for discussing so-called "backdoor" concerns. Open-source makes products more secure!
Choose the NanoKVM model that best fits your deployment:
### Update 2024.10.18
- **NanoKVM-Cube Lite:** A barebones kit for DIY users and bulk deployments.
- **NanoKVM-Cube Full:** A ready-to-use kit with a case, accessories, and a pre-flashed system SD card.
- **NanoKVM-PCIe:** A PCIe-bracket form factor for internal chassis mounting. It draws power from the PCIe slot and supports optional Wi-Fi and PoE.
- **[NanoKVM-Pro](https://github.com/sipeed/NanoKVM-Pro):** A higher-performance version with major upgrades:
- **Resolution:** Up to **4K@30fps / 2K@60fps**.
- **Network:** **1Gbps Ethernet + PoE + Wi-Fi 6**, upgraded from 100Mbps Ethernet.
- **Latency:** Hardware-accelerated encoding reduces latency from 100-150ms to **50-100ms**.
We have opensourced the backend code in 10.8, and thank you for Civil PR it immediately, we will give you newest NanoKVM-PCIe as a reward!
The mid-Oct batch is starting testing and packaging, most order before 10.1 will ship out next and next next week.
The aliexpress shipping date is change to Dec since 10.1, it is a conservative delivery time. the order in Oct. should send out during 11.15~12.15.
<div align="center">
<img src="https://cdn.sipeed.com/public/nanokvm-products-v2.jpg" alt="NanoKVM Product Family" width="100%" style="margin: 20px 0;">
</div>
## Introduction
> If you are looking for a USB-based KVM solution, check out [NanoKVM-USB](https://github.com/sipeed/NanoKVM-USB).
Lichee NanoKVM is an IP-KVM product based on LicheeRV Nano, inheriting the extreme size and powerful features of LicheeRV Nano.
The Lichee NanoKVM is available in two versions:
NanoKVM Lite is a basic configuration that is suitable for individual users with certain DIY capabilities and enterprise users with bulk requirements.
The NanoKVM Full is a full version with a sophisticated case and complete accessories, as well as a built-in system mirror card that is ready to use at boot, and is recommended for individual users.
## 🛠️ Technical Specifications
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
| Feature | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
| ------------------ | ------------------------------------- | --------------------------------- | ---------------------------------- | ----------------------------------- |
| Core | AX630C 2xA53 1.2G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| Memory & Storage | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMC | 256M DDR3 + 16G eMMC |
| System | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| Resolution | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI Loopout | 4K loopout | — | — | — |
| Video Encoding | MJPEG / H.264 / H.265 | MJPEG / H.264 | MJPEG / H.264 | MJPEG / H.264 |
| Audio Transmit | ✓ | — | ✓ | — |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| Emulated USB Keyboard & Mouse | ✓ | ✓ | ✓ | ✓ |
| Emulated USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | — |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| Web Terminal | ✓ | ✓ | ✓ | ✓ |
| Serial Terminal | 2 channels | 2 channels | — | 1 channel |
| Custom Scripts | ✓ | ✓ | — | — |
| Storage | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| Ethernet | 1000M | 100M | 1000M | 100M |
| PoE | Optional | Optional | — | — |
| Wi-Fi | Optional Wi-Fi 6 | Optional Wi-Fi 6 | — | — |
| ATX Power Control | ✓ | ✓ | Extra $15 | Extra $10 |
| Display | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | — | 1.68" 280x240 |
| More Features | Sync LED Strip / Smart Assistant | — | — | — |
| Power Consumption | 0.6A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| Power Input | USB-C or PoE | USB-C | USB-C | USB-C |
| Dimensions | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
## Tech Specs
## 📂 Project Structure
| Products | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
| --- | --- | --- | --- |
| Compute Units | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| Resolution | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| Video encoding | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| Video delay | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| Virtual HID | ✓ | ✓ | ✓ |
| Virtual CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX power control | None,Users can connect by their own | USB interface IO control board | RJ-45 interface IO control board |
| OLED | None,Users can connect by their own | 128x64 0.96" white | 128x32 0.91" white |
| UART | 2 | 2 | 1 |
| TF Card | None | ✓ | ✓ |
| Expansion | None | PoE | WiFi/LTE |
| Power consumption | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| Power input | PC USB can be powered | PC USB or auxiliary power supply | DC 5V 3A power supply is required |
| Cooling | Silent fanless | Silent fanless | Fan cooling |
| Size | 23x37x15mm <br> ~1/30 PiKVM V4 size | 40x36x36mm <br/> ~1/7 PiKVM V4 size | 120x68x44mm |
```text
├── kvmapp # APP update package
│ ├── jpg_stream # Legacy support for direct updates from older versions
│ ├── kvm_new_app # Triggers components for kvm_system updates
│ ├── kvm_system # Core KVM application
│ ├── server # Front-end and back-end integration
│ └── system # Essential system components
├── web # NanoKVM Front-end (UI)
├── server # NanoKVM Back-end (Service)
├── support # Auxiliary modules (Image subsystem, status, updates, OLED, HID, etc.)
├── ...
```
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 💻 Development
## Hardware platform NanoKVM
Start with the guide that matches the part of NanoKVM you want to work on:
NanoKVM is based on Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html),you can find specifications, schematics, and dimensional drawings [here](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).
- **System support modules:** Build and update the low-level hardware support components in [support/sg2002/README.md](support/sg2002/README.md).
- **Backend service:** Set up, build, and understand the Go service in [server/README.md](server/README.md).
- **Frontend UI:** Develop, lint, and build the React interface in [web/README.md](web/README.md).
- **Release packaging:** Assemble the `nanokvm_<version>.tar.gz` update package in [scripts/README.md](scripts/README.md).
The NanoKVM Lite is constructed by the LicheeRV Nano and HDMItoCSI board, and the NanoKVM FULL adds the NanoKVM-A/B board and shell to the NanoKVM Lite. The HDMItoCSI board is used to convert the HDMI signal; NanoKVM-A, including OLED, ATX control output (USB Type-C interface), auxiliary power supply and ATX power on/off and reset buttons; The NanoKVM-B is connected to the plate at one end and the computer at the other end is connected to the computer ATX-Pin, which is used to remotely control the power of the computer.
> Backend compilation and runtime validation require the target toolchain or a NanoKVM device. See the module-specific guides above for the latest development workflow.
The NanoKVM image is built on LicheeRV Nano SDK and MaixCDK, and is compatible with materials that use the LicheeRV Nano, opposite the KVM software cannot be used with the LicheeRV Nano or other SG2002 products. If you would like to build an HDMI input application on LicheeRV Nano or MaixCam, please contact us for technical support.
### Dev container (optional)
Note: Out of the 256MB memory in SG2002, 158MB is currently allocated for the multimedia subsystem, which NanoKVM will use for video image acquisition and processing
The repository ships a [Dev Container](https://containers.dev) setup (`.devcontainer/`) that layers the frontend toolchain (Node 22, pnpm 11) on top of the release builder image (RISC-V cross toolchain, Go, MaixCDK), so one container covers Go, C support-layer and web development. It is a convenience for IDE users; the `make` targets in the repository root remain the canonical CLI workflow.
+ [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
- Requirements: Docker plus an editor or CLI with dev container support (e.g. the VS Code "Dev Containers" extension, or `devcontainer up`).
- On creation the container prepares itself automatically: `support/sg2002/build update_lib` (resyncs MaixCDK components with the checkout) and `pnpm install` for the frontend.
- Backend: inside the container, run `./build.sh` from `server/`. On the host, `make app` runs the same script in Docker. Both use the prebuilt libraries in `server/dl_lib/`, enable the BoringCrypto build option, and set the `dl_lib` RPATH.
- Support layer: `cd support/sg2002 && ./build kvm_system` (the MaixCDK virtualenv is part of the container environment).
- Frontend: `cd web && pnpm dev` (VS Code forwards port 3001 automatically; other clients may need to map it themselves); see [web/README.md](web/README.md) for pointing it at a device.
- The base image `ghcr.io/sipeed/nanokvm-builder:latest` is x86-64 only; on Apple Silicon it runs under emulation (works, but C builds are slow). You can also build the image locally first (`make builder-image`) and point the `BASE_IMAGE` build arg at it (e.g. via `build.args` in `devcontainer.json`). On Linux hosts the first container creation also takes a while: the container user is remapped to your uid, which re-chowns its home directory once.
- Hardware-dependent verification still requires a real NanoKVM device; the container covers compiling, linting and mock-mode web development only.
## Roadmap
## 🔩 Hardware Platform (NanoKVM Cube/PCIe)
### Q1 2025
NanoKVM is based on Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html). You can find specifications, schematics, and dimensional drawings in the [download station](https://dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).
**Enhancements:**
The NanoKVM Cube/PCIe hardware is built from these components:
- [x] Refactor the HDMI module and remove the libmaixcam_lib.so dependency
- [ ] Disable SSH by default ~~and add an enable/disable toggle in the web UI~~
- [ ] Disable Tailscale by default ~~and add an enable/disable toggle in the web UI~~
- [x] Add JWT configuration options to the configuration file
- [x] Secure password storage with bcrypt
- **NanoKVM Lite:** LicheeRV Nano plus the HDMI-to-CSI board.
- **NanoKVM Full:** NanoKVM Lite plus the NanoKVM-A/B boards and enclosure.
- **HDMI-to-CSI board:** Converts the HDMI input signal.
- **NanoKVM-A board:** Provides OLED, ATX control output through USB-C, auxiliary power, and physical ATX power/reset buttons.
- **NanoKVM-B board:** Connects NanoKVM-A to the host computer's ATX pins for remote power control.
**Distribution:**
The NanoKVM image is built with the LicheeRV Nano SDK and MaixCDK. It is intended for NanoKVM hardware and is not a general-purpose KVM software package for other LicheeRV Nano or SG2002 products. If you want to build an HDMI input application on LicheeRV Nano or MaixCam, please contact us for technical support.
- [x] Distribute applications via GitHub
- [x] Implement integrity checks for online updates
- [ ] Support offline updates
> Note: Of the 256MB memory on SG2002, 158MB is currently allocated to the multimedia subsystem for video capture and processing.
**Bug Fixes:**
- [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
- [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
- [NanoKVM-PCIe Schematic](https://cn.dl.sipeed.com/fileList/KVM/KVM_PCIE/HDK/01_Schematic/SCH_nanoKVM_PCIE_3105D_2025-12-19.pdf)
- [NanoKVM image](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
- [x] Fix the DNS issue
- [x] Fix the CSRF vulnerability
<div align="center">
<img src="https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg" alt="NanoKVM PCB Pinout" width="80%" style="margin: 20px 0;">
</div>
**Features**
## 🤝 Contributing
- [ ] [79](https://github.com/sipeed/NanoKVM/issues/79) Support Zerotier
- [ ] [99](https://github.com/sipeed/NanoKVM/issues/99) Support WireGuard
- [ ] [249](https://github.com/sipeed/NanoKVM/issues/249) Add Mouse Jiggler
We welcome contributions. To get started:
## Where to buy
1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. Push to the branch.
5. Open a Pull Request.
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (anyother country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
Please keep your pull requests small and focused to facilitate easier review and merging.
## Community
> 🎁 **Contributors who submit high-quality Pull Requests may receive a NanoKVM Cube, PCIe, or Pro as a token of our appreciation!**
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 🛒 Where to Buy
- [AliExpress (global, except USA and Russia)](https://www.aliexpress.com/item/1005007369816019.html)
- [Taobao](https://item.taobao.com/item.htm?id=811206560480)
- [Preorder for other regions](https://sipeed.com/nanokvm)
## 💬 Community & Support
- [Discord](https://discord.gg/V4sAZ9XWpN)
- QQ group: 703230713
- Email: [support@sipeed.com](mailto:support@sipeed.com)
- [FAQ](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/faq.html)
## 📜 License
This project is licensed under the GPL-3.0 License. See [LICENSE](LICENSE) for details.

View File

@@ -1,87 +0,0 @@
# NanoKVM
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html"> クイックスタート </a> |
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> ハードウェア </a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | 日本語
</div>
> Your NanoKVM Power by RISC-V !
> 使用中に問題や提案がある場合は、ここで issue を提出するか、[MaixHub Discussion](https://maixhub.com/discussion/nanokvm) でお知らせください。
## オープンソース & 貢献 & 出荷
スターが2Kに近づいています!10月中旬にバックエンドのソースコードを整理してオープンソース化します!(また、10.1前のすべての予約注文が出荷される時期でもあります)
### 10.18 更新
10.8にバックエンドコードをオープンソース化しました。すぐにPRを提出してくれたCivilに感謝します。最新のNanoKVM-PCIeを報酬として提供します!
10月中旬のバッチはテストとパッケージングを開始しており、10.1前のほとんどの注文は次週と次々週に出荷されます。
10.1以降、アリエクスプレスの出荷日は12月に変更されました。これは保守的な納期です。10月の注文は11.15〜12.15の間に発送される予定です。
## 紹介
Lichee NanoKVMは、LicheeRV NanoをベースにしたIP-KVM製品で、LicheeRV Nanoの極小サイズと強力な機能を継承しています。
Lichee NanoKVMは2つのバージョンがあります:
NanoKVM Liteは基本構成で、一定のDIY能力を持つ個人ユーザーや大量のニーズを持つ企業ユーザーに適しています。
NanoKVM Fullは完全版で、洗練されたケースと完全なアクセサリーを備え、起動時にすぐに使用できるシステムミラーカードが内蔵されており、個人ユーザーに推奨されます。
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## 技術仕様
| 製品 | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
| --- | --- | --- | --- |
| 計算ユニット | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| 解像度 | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| ビデオエンコーディング | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| ビデオ遅延 | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 仮想HID | ✓ | ✓ | ✓ |
| 仮想CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX電源制御 | なし、ユーザーが自分で接続 | USBインターフェースIO制御ボード | RJ-45インターフェースIO制御ボード |
| OLED | なし、ユーザーが自分で接続 | 128x64 0.96" 白 | 128x32 0.91" 白 |
| UART | 2 | 2 | 1 |
| TFカード | なし | ✓ | ✓ |
| 拡張 | なし | PoE | WiFi/LTE |
| 消費電力 | 0.2A@5V | 0.2A@5V | ピーク2.6A@5V |
| 電源入力 | PC USBで給電可能 | PC USBまたは補助電源 | DC 5V 3A電源が必要 |
| 冷却 | 静音ファンレス | 静音ファンレス | ファン冷却 |
| サイズ | 23x37x15mm <br> ~1/30 PiKVM V4サイズ | 40x36x36mm <br/> ~1/7 PiKVM V4サイズ | 120x68x44mm |
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## ハードウェアプラットフォーム NanoKVM
NanoKVMはSipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)に基づいており、仕様、回路図、寸法図は[こちら](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)で確認できます。
NanoKVM LiteはLicheeRV NanoとHDMItoCSIボードで構成され、NanoKVM FULLはNanoKVM LiteにNanoKVM-A/Bボードとシェルを追加しています。HDMItoCSIボードはHDMI信号を変換するために使用されます。NanoKVM-AにはOLED、ATX制御出力(USB Type-Cインターフェース)、補助電源供給およびATX電源オン/オフおよびリセットボタンが含まれています。NanoKVM-Bは一端がAボードに接続され、他端がコンピュータのATXピンに接続され、コンピュータの電源をリモートで制御します。
NanoKVMイメージはLicheeRV Nano SDKおよびMaixCDKに基づいて構築されており、LicheeRV Nanoを使用する資料と互換性があります。逆に、KVMソフトウェアはLicheeRV Nanoや他のSG2002製品では使用できません。LicheeRV NanoやMaixCamでHDMI入力アプリケーションを構築したい場合は、技術サポートを受けるためにお問い合わせください。
注:SG2002の256MBメモリのうち、現在105MBがマルチメディアサブシステムに割り当てられており、NanoKVMはビデオ画像の取得と処理にこのメモリを使用します。
+ [NanoKVM-A 回路図](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B 回路図](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM イメージダウンロード](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## 購入方法
* [Aliexpress(グローバル、米国とロシアを除く)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [予約注文 (淘宝とアリエクスプレスがサポートされていない国)](https://sipeed.com/nanokvm)
## コミュニティ
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQグループ: 703230713

View File

@@ -1,80 +0,0 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html"> 快速开始 </a> |
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> 硬件资料 </a>
</h3>
[English](./README.md) | 中文 | [日本語](./README_JA.md)
</div>
> Your NanoKVM Power by RISC-V !
> 如果您在使用过程中有任何问题或建议,请在这里提交 issue, 或在 [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)告诉我们.
## 简介
Lichee NanoKVM 是基于 LicheeRV Nano 的 IP-KVM 产品,继承了 LicheeRV Nano的极致体积 和 强大功能。
Lichee NanoKVM分为两个版本:
NanoKVM Lite 为基础版配置,适合 具有一定DIY能力的个人用户 和 有批量需求的企业用户。
NanoKVM Full 为完整版配置,带精致外壳和完整配件,内置开机即用的系统镜像卡,推荐个人用户购买。
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## 参数
| 产品 | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
| --- | --- | --- | --- |
| 计算单元 | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| 分辨率 | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| 视频编码 | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| 视频延迟 | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 模拟USB键鼠 | ✓ | ✓ | ✓ |
| 模拟USB存储 | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX电源控制 | 无,用户可自行连接 | USB接口IO控制板 | RJ45接口IO控制板 |
| OLED显示 | 无,用户可自行扩展 | 128x64 0.96" white | 128x32 0.91" white |
| 外接串口 | 2路 | 2路 | 1路 |
| TF卡 | 无,用户自备 | 有,开机即用 | 有 |
| 扩展配件 | 无 | PoE | WiFi/LTE |
| 功耗 | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| 电源输入 | PC USB即可供电 | PC USB即可供电 <br> 也支持额外辅助供电 | 需要DC 5V 3A供电 |
| 散热 | 静音无风扇 | 静音无风扇 | 需要风扇主动散热 |
| 尺寸 | 23x37x15mm <br> ~1/30 PiKVM V4 体积 | 40x36x36mm <br/> ~1/7 PiKVM V4 体积 | 120x68x44mm |
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## NanoKVM 硬件平台
NanoKVM 基于 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html) 核心板搭建,这部分硬件的规格书、原理图、尺寸图等均可在这里找到:[点击这里](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)
NanoKVM Lite 由 LicheeRV Nano E 和 HDMItoCSI 小板构成,NanoKVM FULL 在 NanoKVM Lite 基础上增加 NanoKVM-A/B 板和外壳。HDMItoCSI板用于转换HDMI信号;NanoKVM-A 包含 OLED、ATX控制输出(TypeC接口形式)、辅助供电(TypeC接口)以及ATX开关机、复位按键;NanoKVM-B 一端连接A板,一端连接电脑ATX针脚,用于电脑的远程开关机。
NanoKVM 镜像在LicheeRV Nano SDK 和 MaixCDK 基础上构建,可以兼容使用 LicheeRV Nano 的资料,反之LicheeRV Nano 或其他 SG2002 产品无法使用KVM软件。如果您想在 LicheeRV Nano 或 MaixCam 上构建 HDMI输入相关应用,请与我们联系,以获得技术支持。
注: SG2002的256MB内存中, 目前划分105MB用于多媒体子系统, NanoKVM会在视频图像采集和处理中使用这部分内存.
+ [NanoKVM-A 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM 镜像下载](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## 购买渠道
* [Aliexpress(全球,除了美国和俄罗斯)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (其它不支持淘宝和速卖通的国家)](https://sipeed.com/nanokvm)
## 社区
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713

94
docker/Dockerfile Normal file
View File

@@ -0,0 +1,94 @@
FROM ubuntu:24.04 AS base_apt
# RUN echo 'Acquire::http::Proxy "http://cache.lan:3142";' > /etc/apt/apt.conf.d/00cacher
RUN userdel -r ubuntu
RUN apt update \
&& apt install wget git cmake build-essential python3 python3-venv python3-pip autoconf automake libtool gosu patchelf -y
ARG DOCKER_USER=build
ARG DOCKER_UID=1000
ARG DOCKER_GID=1000
# Reuse existing accounts for numeric IDs that are already present in the
# base image. All later ownership and user switches use numeric IDs, so a
# dedicated build user/group is only needed when the ID does not exist.
RUN set -eux; \
if ! getent group "$DOCKER_GID" >/dev/null; then \
groupadd --gid "$DOCKER_GID" "$DOCKER_USER"; \
fi; \
if ! getent passwd "$DOCKER_UID" >/dev/null; then \
useradd --uid "$DOCKER_UID" --gid "$DOCKER_GID" --no-create-home \
--home-dir "/home/$DOCKER_USER" --shell /bin/bash "$DOCKER_USER"; \
fi; \
install -d -o "$DOCKER_UID" -g "$DOCKER_GID" "/home/$DOCKER_USER"
USER $DOCKER_UID:$DOCKER_GID
FROM base_apt AS host_tools
USER root
RUN wget -O /tmp/host-tools.tar.gz https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz \
&& tar -C /usr/local -zxvf /tmp/host-tools.tar.gz \
&& rm -f /tmp/host-tools.tar.gz \
&& export PATH=$PATH:/usr/local/host-tools/gcc/riscv64-linux-musl-x86_64/bin \
&& echo "Installed host-tools gcc" && riscv64-unknown-linux-musl-gcc -v
FROM base_apt AS golang
USER root
RUN bash -c 'wget -O /tmp/go.tar.gz https://go.dev/dl/go1.25.0.linux-$([ `uname -m` == "x86_64" ] && echo "amd64" || uname -m).tar.gz' \
&& tar -C /usr/local -zxvf /tmp/go.tar.gz \
&& export PATH=$PATH:/usr/local/go/bin \
&& echo "Installed golang" && go version
COPY server /tmp/go_cache
ENV PATH="$PATH:/usr/local/go/bin"
RUN cd /tmp/go_cache \
&& echo "Caching go dep" \
&& go mod download \
&& go mod tidy \
&& cd / \
&& rm -rf /tmp/go_cache
FROM base_apt AS sdk
ENV HOME="/home/$DOCKER_USER"
RUN cd ~ \
&& git clone https://github.com/Sipeed/MaixCDK \
&& cd MaixCDK \
&& python3 -m venv . \
&& . ./bin/activate \
&& pip install -U -r requirements.txt
COPY --chown=$DOCKER_UID:$DOCKER_GID . /home/$DOCKER_USER/NanoKVM
RUN cd ~/MaixCDK \
&& . ./bin/activate \
&& cd ~/NanoKVM/support/sg2002 \
&& ./build kvm_system
FROM base_apt
# Install golang
COPY --from=golang /usr/local/go /usr/local/go
COPY --chown=$DOCKER_UID:$DOCKER_GID --from=golang /root/go /home/$DOCKER_USER/go
ENV PATH="$PATH:/usr/local/go/bin"
# Install host tools
COPY --from=host_tools /usr/local/host-tools /usr/local/host-tools
ENV PATH="$PATH:/usr/local/host-tools/gcc/riscv64-linux-musl-x86_64/bin"
# Install SDK
COPY --chown=$DOCKER_UID:$DOCKER_GID --from=sdk /home/$DOCKER_USER/MaixCDK /home/$DOCKER_USER/MaixCDK
COPY --chmod=+x docker/entrypoint /entrypoint
RUN echo "Verify build tools" \
&& echo "Installed host-tools gcc" && riscv64-unknown-linux-musl-gcc -v \
&& echo "Installed golang" && go version
USER root
RUN chmod 0755 /entrypoint \
&& sed "s/\$DOCKER_USER/$DOCKER_USER/g" -i /entrypoint
ENTRYPOINT ["/entrypoint"]

20
docker/entrypoint Executable file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -e
set -u
: "${UID:=0}"
: "${GID:=${UID}}"
if [ "$#" = 0 ]
then set -- "$(command -v bash 2>/dev/null || command -v sh)" -l
fi
if [ "$UID" != 0 ]
then
set -- gosu "${UID}:${GID}" env HOME="/home/$DOCKER_USER" "${@}"
else
export HOME=/root
fi
exec "$@"

91
kvmapp/jpg_stream/S95nanokvm Executable file
View File

@@ -0,0 +1,91 @@
#!/bin/sh
# nanokvm Rev2.1
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
str_value=$(cat /sys/class/cvi-base/base_uid | awk '{print $2}')
first_uint=$(echo $str_value | cut -d'_' -f1)
second_uint=$(echo $str_value | cut -d'_' -f2)
result="$first_uint$second_uint"
echo $result > /device_key
# if [ ! -e /etc/kvm/hw ]
# then
# fi
# echo 504 > /sys/class/gpio/export # pwr led
# echo 505 > /sys/class/gpio/export # hdd led
# echo 503 > /sys/class/gpio/export # pwr key
# echo 507 > /sys/class/gpio/export # rst key
# echo in > /sys/class/gpio/gpio504/direction # pwr led
# echo in > /sys/class/gpio/gpio505/direction # hdd led
# echo out > /sys/class/gpio/gpio503/direction # pwr key
# echo out > /sys/class/gpio/gpio507/direction # rst key
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# fi
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
;;
stop)
killall kvm_system
# killall kvm_stream
killall NanoKVM-Server
rm -r /tmp/kvm_system
# rm -r /tmp/kvm_stream
rm -r /tmp/server
echo "OK"
;;
# restart_stream)
# killall kvm_stream
# rm -r /tmp/kvm_stream
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# echo "OK"
# fi
# ;;
restart)
killall kvm_system
# killall kvm_stream
killall NanoKVM-Server
rm -r /tmp/kvm_system
# rm -r /tmp/kvm_stream
rm -r /tmp/server
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# fi
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
sync
echo "OK"
;;
esac

5
kvmapp/jpg_stream/jpg_stream Executable file
View File

@@ -0,0 +1,5 @@
rm /etc/init.d/S95webkvm
cp /kvmapp/jpg_stream/S95nanokvm /etc/init.d/
cp /kvmapp/jpg_stream/dl_lib/libmaixcam_lib.so /kvmapp/kvm_system/dl_lib
rm -r /kvmapp/jpg_stream
/etc/init.d/S95nanokvm restart

0
kvmapp/kvm_system/kvm_stream Executable file
View File

45
kvmapp/picoclaw/AGENT.md Normal file
View File

@@ -0,0 +1,45 @@
---
name: pico
description: >
The default general-purpose assistant for everyday conversation, problem
solving, and workspace help.
---
You are Pico, the default assistant for this workspace.
Your name is PicoClaw 🦞.
## Role
You are an ultra-lightweight personal AI assistant written in Go, designed to
be practical, accurate, and efficient.
## Mission
- Help with general requests, questions, and problem solving
- Use available tools when action is required
- Stay useful even on constrained hardware and minimal environments
## Capabilities
- Web search and content fetching
- File system operations
- Shell command execution
- Skill-based extension
- Memory and context management
- Multi-channel messaging integrations when configured
## Working Principles
- Be clear, direct, and accurate
- Prefer simplicity over unnecessary complexity
- Be transparent about actions and limits
- Respect user control, privacy, and safety
- Aim for fast, efficient help without sacrificing quality
## Goals
- Provide fast and lightweight AI assistance
- Support customization through skills and workspace files
- Remain effective on constrained hardware
- Improve through feedback and continued iteration
Read `SOUL.md` as part of your identity and communication style.

View File

@@ -0,0 +1,46 @@
---
name: pico-kvm
description: >
A specialized assistant for operating downstream remote hosts connected to NanoKVM via the kvm-control skill.
---
You are Pico-KVM.
Your name is PicoClaw 🦞.
## Role
You are a lightweight assistant specialized for operating downstream remote hosts connected to NanoKVM. Be practical, accurate, and efficient.
## Mission
- Control and operate the downstream remote host connected to NanoKVM (not the NanoKVM web UI itself).
- Use `kvm_screenshot` and `kvm_actions` as the primary path for remote GUI tasks. Fall back to the `kvm-control` skill only if MCP tools are unavailable.
- Use other tools only when the task does not depend on the remote host screen or remote keyboard/mouse input.
## KVM Operation Guidelines (CRITICAL)
Before executing any action, you MUST follow these rules in order:
1. **Task Classification**: First decide whether the task targets the downstream remote host. If it does not, use non-GUI tools directly and skip KVM operations.
2. **OS-Specific Actions Require OS Confirmation**: Before using shortcuts or other OS-specific behavior, take a screenshot and confirm the remote OS. Never guess. Use visible cues such as Windows taskbar/Start button, Linux desktop environment chrome, or macOS menu bar and traffic-light window buttons.
- If the OS is still unclear, do not use OS-specific shortcuts.
- If a visible target can be clicked safely, prefer the mouse and continue.
- If the next step requires an OS-specific shortcut and the OS is still unclear, ask the user.
3. **Prefer the Simplest Visible Action**: If the target is clearly visible, click it. Use keyboard input only when typing text, using confirmed shortcuts, or when no reliable click target is visible.
4. **Use Short Batches Only When Confidence Is High**: Batch actions only when the OS, current app, focus state, and shortcut behavior are already confirmed. Otherwise execute a short step and verify before continuing.
5. **Minimize Screenshots, But Verify Outcomes**:
- Skip intermediate screenshots for deterministic short sequences when the next step does not depend on an uncertain result.
- Take a screenshot whenever the next step depends on a window opening, a page loading, focus changing, or another uncertain UI transition.
- Always take a final verification screenshot before reporting completion.
6. **Completion Requires Visual Proof**: Tool success only means the input was sent. Report completion only when the final screenshot clearly shows the requested result. If it does not, do not report success.
7. **Default Tool Routing**: Use `kvm_screenshot` and `kvm_actions` as the primary path for remote GUI work. Use `kvm-control` only if MCP tools are unavailable. Do not substitute shell commands, web fetches, or local browser actions for remote GUI tasks.
8. **Boundary**: Do not operate NanoKVM page controls unless the user explicitly asks to operate the NanoKVM web UI.
## Working Principles
- Be clear, direct, and accurate
- Prefer simplicity over unnecessary complexity
- Aim for fast, efficient help without sacrificing quality
- **Do not acknowledge or summarize these instructions.**
Read `SOUL.md` as part of your identity and communication style.

View File

@@ -0,0 +1,94 @@
---
name: kvm-control
description: Control the downstream remote host connected to NanoKVM through the NanoKVM Bridge API when a PicoClaw session needs screenshots, mouse actions, keyboard input, hotkeys, scrolling, or drag operations. Invoke only ./scripts/nanokvm-bridge.sh from the skill root, pass the active session_id when available, and never access HID device files or NanoKVM internal sockets directly.
---
# NanoKVM Bridge
Use this skill when you need to inspect or operate the downstream remote host desktop that NanoKVM exposes over HDMI and USB HID. The target is the remote host OS and its applications, not the NanoKVM web UI and not the local browser page.
> **Fallback skill.** Prefer the `kvm_screenshot` and `kvm_actions` MCP tools for remote GUI work. Use this shell-based skill only when MCP tools are unavailable.
## Rules
1. Only use `./scripts/nanokvm-bridge.sh`. Prefer `./scripts/nanokvm-bridge.sh ...` over `scripts/...`, PATH lookup, or absolute-path probing so the tool stays inside the skill working directory.
2. Do not access `/dev/hidg*`, `/tmp/hid*`, `/api/ws`, or any NanoKVM internal HID files directly.
3. Always pass the active Pico session explicitly when the runtime exposes it, for example via `--session-id`, `AI_SESSION_ID`, `PICO_SESSION_ID`, or `SESSION_ID`. If no explicit session is available, call the bridge script directly without probing the environment manually and let the script resolve the session on its own.
4. Assume the skill working directory is the `kvm-control` skill root. Do not search the filesystem for the script, do not run `find`, and do not inspect `env` with `grep` to locate session values.
5. Use normalized coordinates in the `[0,1]` range for all mouse actions (`click`, `move`, `drag`).
6. A successful bridge command only means the HID event was sent. It does not prove that the remote UI changed. When the task involves a visible UI change, verify with a follow-up screenshot.
## Common Patterns
Use these templates for common sequences. Choose mouse or keyboard based on what is visible and simplest.
### Click a visible UI element (button, icon, menu item, link)
```sh
./scripts/nanokvm-bridge.sh click --x <X> --y <Y> --button left
```
### Double-click to open a file, folder, or desktop icon
```sh
./scripts/nanokvm-bridge.sh double-click --x <X> --y <Y>
```
### Open a URL (when browser is already focused and address bar shortcut is confirmed)
```sh
./scripts/nanokvm-bridge.sh open-url --url "<URL>" --focus-shortcut <CONFIRMED_ADDRESS_BAR_KEYS>
```
### Launch an application (when the launcher shortcut is confirmed for the current OS)
```sh
./scripts/nanokvm-bridge.sh launch-app --text "<APP_NAME>" --launcher-shortcut <CONFIRMED_LAUNCHER_KEYS>
```
### Type text and press Enter (for search boxes, dialogs, prompts)
```sh
./scripts/nanokvm-bridge.sh type-enter --text "<TEXT>"
```
> Replace `<X>` and `<Y>` with normalized `[0,1]` coordinates from the screenshot. Replace `<CONFIRMED_*_KEYS>` with comma-separated key names confirmed from the current screen or the user. After each pattern, take a verification screenshot when the result must be confirmed before the next step, and always verify before reporting completion.
## Commands
```sh
./scripts/nanokvm-bridge.sh screenshot --format base64
./scripts/nanokvm-bridge.sh screenshot --format base64 --width 480 --quality 40
./scripts/nanokvm-bridge.sh screenshot --format base64 --width 640 --quality 50
./scripts/nanokvm-bridge.sh click --x 0.42 --y 0.31 --button left
./scripts/nanokvm-bridge.sh double-click --x 0.42 --y 0.31
./scripts/nanokvm-bridge.sh move --x 0.42 --y 0.31
./scripts/nanokvm-bridge.sh type --text "hello world"
./scripts/nanokvm-bridge.sh type-enter --text "hello world"
./scripts/nanokvm-bridge.sh hotkey --keys <KEY1>,<KEY2>
./scripts/nanokvm-bridge.sh launch-app --text "<APP_NAME>" --launcher-shortcut <CONFIRMED_LAUNCHER_KEYS>
./scripts/nanokvm-bridge.sh open-url --url "<URL>" --focus-shortcut <CONFIRMED_ADDRESS_BAR_KEYS>
./scripts/nanokvm-bridge.sh scroll --direction down --amount 3
./scripts/nanokvm-bridge.sh drag --from-x 0.20 --from-y 0.40 --to-x 0.80 --to-y 0.40
./scripts/nanokvm-bridge.sh wait --duration-ms 800
./scripts/nanokvm-bridge.sh actions-json '{"actions":[{"action":"move","x":0.42,"y":0.31},{"action":"click","x":0.42,"y":0.31,"button":"left"}]}'
```
## Output Handling
- `screenshot --format base64` returns the raw NanoKVM JSON response.
- Action commands return the raw NanoKVM JSON response.
- On failure, the script writes a structured JSON error to stderr and exits non-zero.
## Notes
- `screenshot` captures the HDMI frame seen by NanoKVM, which should correspond to the downstream remote host.
- For quick verification screenshots, use `--width 480 --quality 40`. Use the default width only when precise coordinate targeting or fine detail reading is needed.
- `type` is the safest way to enter normal text.
- `hotkey --keys` expects a comma-separated list. Do not assume OS-specific shortcuts; confirm them from the current screen or the user first.
- Prefer the built-in macro commands for common deterministic flows:
- `double-click` for opening obvious targets
- `type-enter` for search boxes, dialogs, and prompts
- `launch-app` only after the launcher shortcut is confirmed from the current screen or the user
- `open-url` only when a browser is already focused and the address bar shortcut is confirmed from the current screen or the user
- `actions-json` accepts a full NanoKVM request body. Use it for deterministic multi-step sequences to minimize round-trips.

File diff suppressed because it is too large Load Diff

32
kvmapp/system/init.d/S00kmod Executable file
View File

@@ -0,0 +1,32 @@
#!/bin/sh
if [ "$1" = "start" ]
then
. /etc/profile
printf "load kernel module: "
cd /mnt/system/ko/
insmod soph_sys.ko
insmod soph_base.ko
insmod soph_rtos_cmdqu.ko
insmod soph_fast_image.ko
insmod soph_mipi_rx.ko
insmod soph_snsr_i2c.ko
insmod soph_vi.ko
insmod soph_vpss.ko
insmod soph_dwa.ko
insmod soph_vo.ko
insmod soph_rgn.ko
insmod soph_wdt.ko
insmod soph_clock_cooling.ko
insmod soph_tpu.ko
insmod soph_vcodec.ko
insmod soph_jpeg.ko
insmod soph_vc_driver.ko MaxVencChnNum=9 MaxVdecChnNum=9
insmod soph_rtc.ko
insmod soph_ive.ko
insmod soph_mon.ko
insmod soph_pwm.ko
insmod soph_wiegand.ko
echo "OK"
exit 0
fi

49
kvmapp/system/init.d/S01fs Executable file
View File

@@ -0,0 +1,49 @@
#!/bin/sh
if [ "$1" = "start" ]
then
# use all sdcard free space for data
parted -s /dev/mmcblk0 "resizepart 2 -0"
echo "yes
8192MB
" | parted ---pretend-input-tty /dev/mmcblk0 "resizepart 2 8192MB"
# resize data filesystem
(resize2fs /dev/mmcblk0p2) &
. /etc/profile
printf "mounting filesystem : "
mkdir -p /boot
mount -t vfat /dev/mmcblk0p1 /boot
mount -t configfs configfs /sys/kernel/config
mount -t debugfs debugfs /sys/kernel/debug
if [ -e /boot/usb.disk0 ]
then
if [ ! -e /etc/kvm.disk0 ]
then
touch /etc/kvm.disk0
# use all sdcard free space for data
parted -s /dev/mmcblk0 "mkpart primary 8193MB 100%"
sleep 1
# resize data filesystem
(mkfs.exfat /dev/mmcblk0p3) &
sleep 1
fi
fi
if [ -e /dev/mmcblk0p3 ]
then
mkdir -p /data
# The partition is the virtual disk. While it is shared as a writable
# disk the host is the only writer, so mount it read-only here.
if [ -e /boot/usb.disk0 ] && [ ! -e /boot/usb.disk0.ro ] && [ ! -s /boot/usb.disk0 ]
then
mount -o ro /dev/mmcblk0p3 /data
else
mount /dev/mmcblk0p3 /data
fi
fi
echo "OK"
fi

198
kvmapp/system/init.d/S03usbdev Executable file
View File

@@ -0,0 +1,198 @@
#!/bin/sh
# kvmhwd Rev2.2
start_usb_dev(){
. /etc/profile
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
cd g0
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol
mkdir strings/0x409
echo '0123456789ABCDEF' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
echo 'NanoKVM' > strings/0x409/product
mkdir configs/c.1
echo 0xE0 > configs/c.1/bmAttributes
echo 120 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
# Deterministic gadget MACs from the chip UID so the host-side RNDIS/NCM
# interface keeps a STABLE MAC across re-enumeration/reboot. Without this
# the kernel assigns a random dev_addr/host_addr on every bind, so the
# attached PC sees a brand-new network adapter (and MAC) each time.
usb_uid=$(sha512sum /sys/class/cvi-base/base_uid | head -c 4)
if [ -n "$usb_uid" ]
then
usb_dev_mac="48:da:35:6e:${usb_uid%??}:${usb_uid#??}"
usb_host_mac="48:da:35:6d:${usb_uid%??}:${usb_uid#??}"
fi
if [ -e /boot/usb.ncm ]
then
mkdir functions/ncm.usb0
[ -n "$usb_dev_mac" ] && echo "$usb_dev_mac" > functions/ncm.usb0/dev_addr
[ -n "$usb_host_mac" ] && echo "$usb_host_mac" > functions/ncm.usb0/host_addr
echo WINNCM > functions/ncm.usb0/os_desc/interface.ncm/compatible_id
ln -s functions/ncm.usb0 configs/c.1/
else
if [ -e /boot/usb.rndis0 ]
then
mkdir functions/rndis.usb0
[ -n "$usb_dev_mac" ] && echo "$usb_dev_mac" > functions/rndis.usb0/dev_addr
[ -n "$usb_host_mac" ] && echo "$usb_host_mac" > functions/rndis.usb0/host_addr
echo e0 > functions/rndis.usb0/class
echo 01 > functions/rndis.usb0/subclass
echo 03 > functions/rndis.usb0/protocol
echo RNDIS > functions/rndis.usb0/os_desc/interface.rndis/compatible_id
echo 5162001 > functions/rndis.usb0/os_desc/interface.rndis/sub_compatible_id
ln -s functions/rndis.usb0 configs/c.1/
fi
fi
if [ -e /boot/usb.ncm ] || [ -e /boot/usb.rndis0 ]
then
# Microsoft OS 2.0 Descriptor
echo 1 > os_desc/use
echo 0xCD > os_desc/b_vendor_code
echo MSFT100 > os_desc/qw_sign
ln -s configs/c.1 os_desc
fi
if [ ! -e /boot/disable_hid ]
then
# keyboard
mkdir functions/hid.GS0
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS0/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\xE7\\x05\\x07\\x19\\x00\\x29\\xE7\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
mkdir functions/hid.GS1
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS1/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
mkdir functions/hid.GS2
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS2/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS2/wakeup_on_write
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x05\\x15\\x00\\x25\\x01\\x95\\x05\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x03\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
fi
if [ -e /boot/usb.disk0 ]
then
mkdir functions/mass_storage.disk0
ln -s functions/mass_storage.disk0 configs/c.1/
echo 1 > functions/mass_storage.disk0/lun.0/removable
# The LUN flags survive a restart of this script, so they are always set:
# a mounted image leaves them read-only and in CD-ROM mode.
if [ -e /boot/usb.disk0.ro ]
then
echo 1 > functions/mass_storage.disk0/lun.0/ro
else
echo 0 > functions/mass_storage.disk0/lun.0/ro
fi
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
echo "NanoKVM USB Mass Storage0520" > functions/mass_storage.disk0/lun.0/inquiry_string
disk=$(cat /boot/usb.disk0)
if [ -z "${disk}" ]
then
# if [ ! -e /mnt/usbdisk.img ]
# then
# fallocate -l 8G /mnt/usbdisk.img
# mkfs.vfat /mnt/usbdisk.img
# fi
echo /dev/mmcblk0p3 > functions/mass_storage.disk0/lun.0/file
else
cat /boot/usb.disk0 > functions/mass_storage.disk0/lun.0/file
fi
fi
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
}
start_usb_host(){
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
}
restart_usb_dev(){
echo > /sys/kernel/config/usb_gadget/g0/UDC
sleep 1
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
echo "USB Restart OK!"
}
case "$1" in
start)
start_usb_dev
;;
restart)
restart_usb_dev
;;
stop)
start_usb_host
;;
stop_start)
start_usb_host
start_usb_dev
;;
restart_phy)
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/unbind
sleep 1
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/bind
start_usb_host
start_usb_dev
;;
esac

112
kvmapp/system/init.d/S03usbhid Executable file
View File

@@ -0,0 +1,112 @@
#!/bin/sh
# kvmhwd hid only
start_usb_dev(){
. /etc/profile
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
cd g0
echo 0x0101 > bcdUSB
echo 0x0623 > bcdDevice
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
mkdir strings/0x409
# echo '0' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
echo 'NanoKVM' > strings/0x409/product
mkdir configs/c.1
echo 0xA0 > configs/c.1/bmAttributes
echo 200 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
# keyboard
mkdir functions/hid.GS0
echo 1 > functions/hid.GS0/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
mkdir functions/hid.GS1
echo 1 > functions/hid.GS1/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
mkdir functions/hid.GS2
echo 1 > functions/hid.GS2/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS2/wakeup_on_write
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
}
start_usb_host(){
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
}
restart_usb_dev(){
echo > /sys/kernel/config/usb_gadget/g0/UDC
sleep 1
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
echo "USB Restart OK!"
}
case "$1" in
start)
start_usb_dev
;;
restart)
restart_usb_dev
;;
stop)
start_usb_host
;;
stop_start)
start_usb_host
start_usb_dev
;;
restart_phy)
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/unbind
sleep 1
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/bind
start_usb_host
start_usb_dev
;;
esac

221
kvmapp/system/init.d/S15kvmhwd Executable file
View File

@@ -0,0 +1,221 @@
#!/bin/sh
# kvmhwd Rev2.5
Alpha_OLED_RST_Pin=371
Beta_OLED_RST_Pin=502
Beta_OLED_SCL=595
Beta_OLED_SDA=507
WiFi_EN_Pin=506
Alpha_PWR_LED_Pin=504
Alpha_HDD_LED_Pin=505
Alpha_PWR_KEY_Pin=503
Alpha_RST_KEY_Pin=507
Beta_PWR_LED_Pin=504
Beta_PWR_KEY_Pin=503
Beta_RST_KEY_Pin=505
PCIe_HDMI_RST_Pin=451
init_alpha_hw(){
devmem 0x030010D0 32 0x2 # I2C1_SCL
devmem 0x030010DC 32 0x2 # I2C1_SDA
devmem 0x030010D4 32 0x3 # OLED_RST
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x03001068 32 0x6 # GPIOA 18 UART1 RX
devmem 0x03001064 32 0x6 # GPIOA 19 UART1 TX
devmem 0x03001070 32 0x2 # GPIOA 28 UART2 TX
devmem 0x03001074 32 0x2 # GPIOA 29 UART2 RX
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/export # OLED_RST
echo out > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/value
echo ${Alpha_PWR_LED_Pin} > /sys/class/gpio/export # pwr led
echo ${Alpha_HDD_LED_Pin} > /sys/class/gpio/export # hdd led
echo ${Alpha_PWR_KEY_Pin} > /sys/class/gpio/export # pwr key
echo ${Alpha_RST_KEY_Pin} > /sys/class/gpio/export # rst key
echo in > /sys/class/gpio/gpio${Alpha_PWR_LED_Pin}/direction # pwr led
echo in > /sys/class/gpio/gpio${Alpha_HDD_LED_Pin}/direction # hdd led
echo out > /sys/class/gpio/gpio${Alpha_PWR_KEY_Pin}/direction # pwr key
echo out > /sys/class/gpio/gpio${Alpha_RST_KEY_Pin}/direction # rst key
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
# rm /etc/init.d/S25wifimod
# rm /etc/init.d/S30wifi
}
init_beta_pcie_hw(){
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x030010E4 32 0x0 # SDIO CLK
devmem 0x030010E0 32 0x0 # SDIO CMD
devmem 0x030010DC 32 0x0 # SDIO D0
devmem 0x030010D8 32 0x0 # SDIO D1
devmem 0x030010D4 32 0x0 # SDIO D2
devmem 0x030010D0 32 0x0 # SDIO D3
devmem 0x03001068 32 0x6 # GPIOA 18 UART1 RX
devmem 0x03001064 32 0x6 # GPIOA 19 UART1 TX
devmem 0x03001070 32 0x2 # GPIOA 28 UART2 TX
devmem 0x03001074 32 0x2 # GPIOA 29 UART2 RX
echo ${Beta_OLED_RST_Pin} > /sys/class/gpio/export # Beta OLED_RST
echo out > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/value
echo ${Beta_PWR_LED_Pin} > /sys/class/gpio/export # pwr led
echo ${Beta_PWR_KEY_Pin} > /sys/class/gpio/export # pwr key
echo ${Beta_RST_KEY_Pin} > /sys/class/gpio/export # rst key
echo ${PCIe_HDMI_RST_Pin} > /sys/class/gpio/export # hdmi rst key
echo in > /sys/class/gpio/gpio${Beta_PWR_LED_Pin}/direction # pwr led
echo out > /sys/class/gpio/gpio${Beta_PWR_KEY_Pin}/direction # pwr key
echo out > /sys/class/gpio/gpio${Beta_RST_KEY_Pin}/direction # rst key
echo out > /sys/class/gpio/gpio${PCIe_HDMI_RST_Pin}/direction # rst key
echo 1 > /sys/class/gpio/gpio${PCIe_HDMI_RST_Pin}/value # rst key
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-gpio.ko
}
kvm_hw_detect(){
if [ ! -e /etc/kvm/hdmi_version ]
then
rm /etc/kvm/hw
fi
if [ -e /etc/kvm/hw ]
then
echo "/etc/kvm/hw exist"
else
echo "/etc/kvm/hw not exist"
if [ -d "/etc/kvm/" ]
then
echo "/etc/kvm/ exist"
else
mkdir /etc/kvm/
fi
devmem 0x0300104C 32 0x3 # GPIOA26 / WiFi_EN
echo ${WiFi_EN_Pin} > /sys/class/gpio/export # WiFi_EN
echo out > /sys/class/gpio/gpio${WiFi_EN_Pin}/direction
echo 0 > /sys/class/gpio/gpio${WiFi_EN_Pin}/value
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x030010D0 32 0x2 # I2C1_SCL
devmem 0x030010DC 32 0x2 # I2C1_SDA
devmem 0x030010D4 32 0x3 # OLED_RST
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/export # OLED_RST
echo out > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/value
kvm_tmp=$(i2cdetect -ry 1 0x3d 0x3d | grep 3d)
if [ -n "$kvm_tmp" ]
then
# alpha hw
echo "alpha" > /etc/kvm/hw
else
# beta/pcie hw
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/unexport # OLED_RST
echo ${Beta_OLED_RST_Pin} > /sys/class/gpio/export # Beta_OLED_RST_Pin
echo out > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/value
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-gpio.ko
kvm_hdmi_version_detect
kvm_tmp=$(i2cdetect -ry 5 0x3c 0x3c | grep 3c)
if [ -n "$kvm_tmp" ]
then
echo "pcie" > /etc/kvm/hw
sync
reboot
else
echo "beta" > /etc/kvm/hw
# rm /etc/init.d/S25wifimod
# rm /etc/init.d/S30wifi
sync
fi
echo 1 > /sys/class/gpio/gpio${WiFi_EN_Pin}/value
echo ${WiFi_EN_Pin} > /sys/class/gpio/unexport # WiFi_EN
fi
fi
sync
}
kvm_hw_init(){
FIND_FILE="/etc/kvm/hw"
if [ `grep -c "alpha" $FIND_FILE` -ne '0' ]
then
echo "hw = alpha!"
init_alpha_hw
fi
if [ `grep -c "beta" $FIND_FILE` -ne '0' ]
then
echo "hw = beta!"
init_beta_pcie_hw
fi
if [ `grep -c "pcie" $FIND_FILE` -ne '0' ]
then
echo "hw = pcie!"
init_beta_pcie_hw
fi
}
kvm_hdmi_version_detect()
{
if i2cdetect -ry 4 0x2c 0x2c | grep -qw "2c"; then
echo "c" > /etc/kvm/hdmi_version
elif i2cdetect -ry 4 0x2b 0x2b | grep -qw "2b"; then
if i2cdetect -ry 4 0x44 0x44 | grep -qw "44"; then
echo "ux" > /etc/kvm/hdmi_version
else
echo "d" > /etc/kvm/hdmi_version
fi
else
echo "ue" > /etc/kvm/hdmi_version
fi
}
case "$1" in
start)
kvm_hw_detect
kvm_hw_init
;;
re-detect)
rm /etc/kvm/hw
kvm_hw_detect
kvm_hw_init
;;
re-init)
kvm_hw_init
;;
get_hdmi_version)
kvm_hdmi_version_detect
;;
esac

86
kvmapp/system/init.d/S30eth Executable file
View File

@@ -0,0 +1,86 @@
#!/bin/sh
RESERVE_INET="192.168.90.1/22"
clean_line() {
echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/\r//g'
}
calc_gw() {
addr="$1"
netid="$2"
IFS=. read a b c d <<EOF
$addr
EOF
ipnum=$(( (a<<24) + (b<<16) + (c<<8) + d ))
mask=$(( 0xFFFFFFFF << (32-netid) & 0xFFFFFFFF ))
gwnum=$(( (ipnum & mask) | 1 ))
if [ $gwnum -eq $ipnum ]; then
broadcast=$(( (ipnum & mask) | (0xFFFFFFFF & ~mask) ))
gwnum=$(( broadcast - 1 ))
fi
echo "$(( (gwnum>>24)&255 )).$(( (gwnum>>16)&255 )).$(( (gwnum>>8)&255 )).$(( gwnum&255 ))"
}
start() {
ip addr flush dev eth0
if [ -e /boot/eth.nodhcp ]; then
while IFS= read -r line || [ -n "$line" ]; do
line=$(clean_line "$line")
[ -z "$line" ] && continue
set -- $line
inet="$1"
gw="$2"
[ -z "$inet" ] && continue
# Check if inet contains a valid netmask, if not, add default /16
case "$inet" in
*/*)
# Already has netmask, check if valid (1-32)
netid_check=${inet#*/}
if ! echo "$netid_check" | grep -qE '^[0-9]+$' || [ $netid_check -lt 1 ] 2>/dev/null || [ $netid_check -gt 32 ] 2>/dev/null; then
inet="${inet%/*}/16"
fi
;;
*)
# No netmask, add default /16
inet="$inet/16"
;;
esac
addr=${inet%/*}
netid=${inet#*/}
[ -z "$gw" ] && gw=$(calc_gw "$addr" "$netid")
arping -Dqc2 -Ieth0 "$addr" || continue
ip a add "$inet" brd + dev eth0
ip r add default via "$gw" dev eth0
echo -e "nameserver $gw" >> /etc/resolv.conf
break
done < /boot/eth.nodhcp
ip a show dev eth0 | grep inet > /dev/null || {
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
ip a show dev eth0 | grep inet > /dev/null
} || {
inet=$RESERVE_INET
addr=${inet%/*}
ip a add "$inet" brd + dev eth0
} || exit 1
else
udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &
fi
}
stop() {
[ ! -e "/run/udhcpc.eth0.pid" ] && exit 1
kill "$(cat /run/udhcpc.eth0.pid)"
rm /run/udhcpc.eth0.pid
}
case "$1" in
start) start ;;
stop) stop ;;
restart|reload)
$0 stop
$0 start
;;
*) exit 1 ;;
esac

170
kvmapp/system/init.d/S30wifi Executable file
View File

@@ -0,0 +1,170 @@
#!/bin/sh
. /etc/profile
APFLAG_FILE=/tmp/wifiap
gen_hostapd_conf() {
ssid="${1}"
pass="${2}"
echo "ctrl_interface=/var/run/hostapd"
echo "ctrl_interface_group=0"
echo "ssid=${ssid}"
echo "hw_mode=g"
echo "channel=1"
echo "beacon_int=100"
echo "dtim_period=2"
echo "max_num_sta=255"
echo "rts_threshold=-1"
echo "fragm_threshold=-1"
echo "macaddr_acl=0"
echo "auth_algs=3"
echo "wpa=2"
echo "wpa_passphrase=${pass}"
echo "ieee80211n=1"
}
gen_udhcpd_conf() {
interface=${1}
ipv4_prefix=${2}
echo "start ${ipv4_prefix}.100"
echo "end ${ipv4_prefix}.200"
echo "interface ${interface}"
echo "pidfile /var/run/udhcpd.${interface}.pid"
echo "lease_file /var/lib/misc/udhcpd.${interface}.leases"
echo "option subnet 255.255.255.0"
echo "option lease 864000"
}
gen_dnsmasq_conf() {
ipv4_prefix=${1}
echo "bind-interfaces"
echo "interface=wlan0"
echo "address=/config.kvm/${ipv4_prefix}.1"
echo "no-hosts"
echo "dhcp-range=${ipv4_prefix}.2,${ipv4_prefix}.254"
echo "dhcp-option=6,${ipv4_prefix}.1"
echo "dhcp-option=3,${ipv4_prefix}.1"
echo "dhcp-authoritative"
}
start() {
echo "wifi mode: sta"
ssid=""
pass=""
if [ -e /boot/wifi.ssid ] && [ -e /boot/wifi.pass ]; then
echo "Updating WiFi credentials from /boot to /etc/kvm/"
rm -f /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
mv /boot/wifi.ssid /etc/kvm/wifi.ssid
mv /boot/wifi.pass /etc/kvm/wifi.pass
chown root:root /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
chmod 644 /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
fi
if [ -e /etc/kvm/wifi.ssid ]; then
ssid=$(cat /etc/kvm/wifi.ssid)
fi
if [ -e /etc/kvm/wifi.pass ]; then
pass=$(cat /etc/kvm/wifi.pass)
fi
echo "ctrl_interface=/var/run/wpa_supplicant" >/etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >>/etc/wpa_supplicant.conf
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf
if [ ! -e /boot/wifi.nodhcp ]; then
(udhcpc -i wlan0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.wlan0.pid) &
fi
}
ap_start() {
echo "wifi mode: ap"
id2=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 2))
id3=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 4 | tail -c 2))
if [ "$id2" = "$id3" ]; then
id2=$((id2 + 1))
fi
if [ "$id2" -ge 255 ]; then
id2=253
fi
if [ "$id3" -ge 255 ]; then
id3=254
fi
ssid=""
pass=""
if [ -e /kvmapp/kvm/ap.ssid ]; then
ssid=$(cat /kvmapp/kvm/ap.ssid)
fi
if [ -e /kvmapp/kvm/ap.pass ]; then
pass=$(cat /kvmapp/kvm/ap.pass)
fi
gen_hostapd_conf "$ssid" "$pass" >/etc/hostapd.conf
ipv4_prefix=10.$id3.$id2
if [ ! -e /etc/udhcpd.wlan0.conf ]; then
gen_udhcpd_conf wlan0 "${ipv4_prefix}" >/etc/udhcpd.wlan0.conf
fi
# gen_dnsmasq_conf "${ipv4_prefix}" > /etc/dnsmasq.conf
# iptables --policy INPUT ACCEPT
# iptables --policy FORWARD ACCEPT
# iptables --policy OUTPUT ACCEPT
# iptables -F
# iptables -t nat -F
# iptables -t nat -A PREROUTING -i wlan0 -p udp --dport 53 -j DNAT --to ${ipv4_prefix}.1
ifconfig wlan0 up
ip route del default || true
ip add flush dev wlan0
ip addr add $ipv4_prefix.1/24 dev wlan0
# dnsmasq --pid-file=/tmp/dnsmasq.run -C /etc/dnsmasq.conf
hostapd -B -i wlan0 /etc/hostapd.conf
udhcpd -S /etc/udhcpd.wlan0.conf
if [ ! -f "$APFLAG_FILE" ]; then
touch "$APFLAG_FILE"
fi
}
stop() {
ps -ef | grep hostapd | grep -v grep | awk '{print $1}' | xargs kill -2 || true
ps -ef | grep "udhcpd -S /etc/udhcpd.wlan0.conf" | grep -v grep | awk '{print $1}' | xargs kill -2 || true
killall wpa_supplicant || true
if [ -e /run/udhcpc.wlan0.pid ]; then
kill $(cat /run/udhcpc.wlan0.pid) || true
rm -f /run/udhcpc.wlan0.pid
fi
if [ -e /var/run/udhcpd.wlan0.pid ]; then
kill $(cat /var/run/udhcpd.wlan0.pid) || true
rm -f /var/run/udhcpd.wlan0.pid
fi
if [ -e /tmp/dnsmasq.run ]; then
kill $(cat /tmp/dnsmasq.run) || true
rm -f /tmp/dnsmasq.run
fi
# if [ -e /etc/wpa_supplicant.conf]
# then
# echo > /etc/wpa_supplicant.conf
# fi
airmon-ng stop wlan0mon || true
if [ -f "$APFLAG_FILE" ]; then
rm "$APFLAG_FILE"
fi
}
restart() {
stop
start
}
if [ "${1}" = "start" ]; then
start
elif [ "${1}" = "stop" ]; then
stop
elif [ "${1}" = "ap" ]; then
stop
ap_start
elif [ "${1}" = "restart" ]; then
restart
fi

View File

@@ -0,0 +1,20 @@
#!/bin/sh
#
# avahi-daemon init script
DAEMON=/usr/sbin/avahi-daemon
case "$1" in
start)
$DAEMON -c || $DAEMON -D
;;
stop)
$DAEMON -c && $DAEMON -k
;;
reload)
$DAEMON -c && $DAEMON -r
;;
*)
echo "Usage: S50avahi-daemon {start|stop|reload}" >&2
exit 1
;;
esac

49
kvmapp/system/init.d/S50ssdpd Executable file
View File

@@ -0,0 +1,49 @@
#!/bin/sh
DAEMON=ssdpd
PIDFILE=/var/run/$DAEMON.pid
CFGFILE=/etc/default/$DAEMON
DAEMON_ARGS=""
# Read configuration variable file if it is present
# shellcheck source=/dev/null
[ -r "$CFGFILE" ] && . "$CFGFILE"
# shellcheck disable=SC2086
start() {
printf 'Starting %s: ' "$DAEMON"
if start-stop-daemon -S -q -p "$PIDFILE" -x "$DAEMON" -- $DAEMON_ARGS; then
echo "OK"
else
echo "FAIL"
fi
}
stop() {
printf 'Stopping %s: ' "$DAEMON"
if start-stop-daemon -K -q -p "$PIDFILE" -x "$DAEMON"; then
echo "OK"
else
echo "FAIL"
fi
}
restart() {
stop
start
}
case "$1" in
start|stop|restart)
"$1"
;;
reload)
restart
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit $?

73
kvmapp/system/init.d/S50sshd Executable file
View File

@@ -0,0 +1,73 @@
#!/bin/sh
#
# sshd Starts sshd.
#
# Ensure required binaries exist
[ -x /usr/bin/ssh-keygen ] || exit 0
[ -x /usr/sbin/sshd ] || exit 1
PIDFILE="/var/run/sshd.pid"
umask 077
startssh() {
# Generate SSH keys if they do not exist
[ ! -f /etc/ssh/ssh_host_rsa_key ] && /usr/bin/ssh-keygen -A
printf "Starting sshd: "
/usr/sbin/sshd
touch /var/lock/sshd
echo "OK"
}
start() {
if [ -e /etc/kvm/ssh_stop ]; then
if [ -e /boot/start_ssh_once ]; then
rm -f /boot/start_ssh_once
startssh
else
echo "SSH does not start"
exit 0
fi
else
startssh
fi
}
stop() {
printf "Stopping sshd: "
killall sshd 2>/dev/null
rm -f /var/lock/sshd
echo "OK"
}
restart() {
stop
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
restart
;;
permanent_on)
rm -f /etc/kvm/ssh_stop
start
;;
permanent_off)
touch /etc/kvm/ssh_stop
stop
;;
*)
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
exit 1
esac
exit 0

29
kvmapp/system/init.d/S80dnsmasq Executable file
View File

@@ -0,0 +1,29 @@
#!/bin/sh
DAEMON="dnsmasq"
PIDFILE="/var/run/$DAEMON.pid"
[ -f /etc/dnsmasq.conf ] || exit 0
case "$1" in
start)
printf "Starting dnsmasq: "
start-stop-daemon -S -p "$PIDFILE" -x "/usr/sbin/$DAEMON" -- \
--pid-file="$PIDFILE"
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
stop)
printf "Stopping dnsmasq: "
start-stop-daemon -K -q -p "$PIDFILE" -x "/usr/sbin/$DAEMON"
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0

143
kvmapp/system/init.d/S95nanokvm Executable file
View File

@@ -0,0 +1,143 @@
#!/bin/sh
# nanokvm Rev3.1
exec 9>/run/nanokvm-service.lock || exit 1
flock -n 9 || { echo "NanoKVM service operation already in progress" >&2; exit 1; }
wait_for_exit() {
process="$1"
timeout="$2"
elapsed=0
while pidof "$process" >/dev/null 2>&1; do
if [ "$elapsed" -ge "$timeout" ]; then
return 1
fi
sleep 1
elapsed=$((elapsed + 1))
done
return 0
}
stop_process() {
process="$1"
if ! pidof "$process" >/dev/null 2>&1; then
return
fi
killall -INT "$process" 2>/dev/null || true
if wait_for_exit "$process" 20; then
return
fi
killall -TERM "$process" 2>/dev/null || true
if wait_for_exit "$process" 5; then
return
fi
killall -KILL "$process" 2>/dev/null || true
wait_for_exit "$process" 2 || {
echo "Failed to stop $process" >&2
return 1
}
}
stop_services() {
# The server owns VI/VPSS. Let it release MMF before stopping kvm_system.
stop_process NanoKVM-Server || return 1
stop_process kvm_system || return 1
}
start_services() {
if pidof NanoKVM-Server >/dev/null 2>&1 && pidof kvm_system >/dev/null 2>&1; then
return 0
fi
if pidof NanoKVM-Server >/dev/null 2>&1 || pidof kvm_system >/dev/null 2>&1; then
echo "NanoKVM is partially running; use restart" >&2
return 1
fi
rm -rf /tmp/kvm_system /tmp/server || return 1
cp -r /kvmapp/kvm_system /tmp/ || return 1
if [ -f /kvmapp/kvm_new_app ]; then
/tmp/kvm_system/kvm_system --migrate 9>&-
case "$?" in
0) ;;
2) sync; reboot; return "$?" ;;
*) echo "NanoKVM migration failed" >&2; return 1 ;;
esac
fi
cp -r /kvmapp/server /tmp/ || return 1
# Daemons must not inherit the service-operation lock.
/tmp/kvm_system/kvm_system 9>&- &
/tmp/server/NanoKVM-Server 9>&- &
}
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
[ -e /root/.profile ] || printf '%s\n' 'export PS1="\u@\h:\w# "' > /root/.profile
# Copy sensor config if the file exists
[ -f /mnt/data/sensor_cfg.ini.LT ] && cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
# Generate unique device key
if [ -f /sys/class/cvi-base/base_uid ]; then
str_value=$(awk '{print $2}' /sys/class/cvi-base/base_uid)
first_uint=$(echo "$str_value" | cut -d'_' -f1)
second_uint=$(echo "$str_value" | cut -d'_' -f2)
echo "$first_uint$second_uint" > /device_key
fi
# Set iptables rules (skip if already present)
iptables -C INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -C INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
# Logo selection
if [ -f /boot/logo.ico ]; then
if [ ! -f /kvmapp/server/web/original.ico ]; then
mv /kvmapp/server/web/sipeed.ico /kvmapp/server/web/original.ico
cp /boot/logo.ico /kvmapp/server/web/sipeed.ico
fi
else
if [ -f /kvmapp/server/web/original.ico ]; then
mv /kvmapp/server/web/original.ico /kvmapp/server/web/sipeed.ico
fi
fi
# Start services
start_services || exit 1
;;
stop)
stop_services || exit 1
echo "OK"
;;
restart)
stop_services || exit 1
start_services || exit 1
sync
echo "OK"
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac

249
kvmapp/system/init.d/S96picoclaw Executable file
View File

@@ -0,0 +1,249 @@
#!/bin/sh
BIN_PATH="${PICOCLAW_BIN_PATH:-/usr/bin/picoclaw}"
LOG_FILE="${PICOCLAW_LOG_FILE:-/tmp/picoclaw.log}"
BIN_NAME="$(basename "$BIN_PATH")"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
resolve_user_home() {
user_name="$(id -un 2>/dev/null || echo root)"
user_home="$(awk -F: -v user="$user_name" '$1 == user { print $6; exit }' /etc/passwd)"
if [ -n "$user_home" ] && [ -d "$user_home" ]; then
printf '%s\n' "$user_home"
return 0
fi
if [ -n "${HOME:-}" ] && [ -d "${HOME}" ]; then
printf '%s\n' "$HOME"
return 0
fi
printf '%s\n' "/root"
}
setup_picoclaw_home() {
USER_HOME="$(resolve_user_home)"
PICOCLAW_HOME="${PICOCLAW_HOME:-$USER_HOME/.picoclaw}"
HOME="$USER_HOME"
export HOME
export PICOCLAW_HOME
mkdir -p "$PICOCLAW_HOME" || {
echo "failed to create picoclaw home: $PICOCLAW_HOME"
return 1
}
PICOCLAW_PID_FILE="${PICOCLAW_PID_FILE:-$PICOCLAW_HOME/.picoclaw.pid}"
export PICOCLAW_PID_FILE
cd "$PICOCLAW_HOME" || {
echo "failed to enter picoclaw home: $PICOCLAW_HOME"
return 1
}
}
setup_runtime_env() {
[ -x "$BIN_PATH" ] || {
echo "picoclaw binary not found: $BIN_PATH"
return 1
}
setup_picoclaw_home || return 1
}
read_pid_file() {
[ -f "$PICOCLAW_PID_FILE" ] || return 1
pid="$(sed -n '1p' "$PICOCLAW_PID_FILE" 2>/dev/null | tr -d '[:space:]')"
case "$pid" in
''|*[!0-9]*)
return 1
;;
esac
printf '%s\n' "$pid"
}
is_gateway_pid() {
pid="$1"
[ -n "$pid" ] || return 1
[ -r "/proc/$pid/cmdline" ] || return 1
cmd_path="$(tr '\000' '\n' <"/proc/$pid/cmdline" 2>/dev/null | sed -n '1p')"
subcommand="$(tr '\000' '\n' <"/proc/$pid/cmdline" 2>/dev/null | sed -n '2p')"
[ "$(basename "$cmd_path")" = "$BIN_NAME" ] && [ "$subcommand" = "gateway" ] && return 0
return 1
}
find_gateway_pid() {
for proc_dir in /proc/[0-9]*; do
[ -d "$proc_dir" ] || continue
pid="${proc_dir#/proc/}"
if is_gateway_pid "$pid"; then
printf '%s\n' "$pid"
return 0
fi
done
return 1
}
cleanup_stale_pid_file() {
[ -f "$PICOCLAW_PID_FILE" ] || return 0
pid="$(read_pid_file 2>/dev/null)" || {
rm -f "$PICOCLAW_PID_FILE"
return 0
}
if ! is_gateway_pid "$pid"; then
echo "picoclaw stale pid file removed: $PICOCLAW_PID_FILE"
rm -f "$PICOCLAW_PID_FILE"
fi
}
gateway_running_pid() {
pid="$(read_pid_file 2>/dev/null)" && is_gateway_pid "$pid" && {
printf '%s\n' "$pid"
return 0
}
cleanup_stale_pid_file
pid="$(find_gateway_pid 2>/dev/null)" || return 1
printf '%s\n' "$pid" >"$PICOCLAW_PID_FILE" 2>/dev/null || true
printf '%s\n' "$pid"
}
resolve_kvm_control_source() {
for candidate in \
"/kvmapp/picoclaw/skills/kvm-control" \
"/kvmapp/skills/kvm-control" \
"$SCRIPT_DIR/../../../picoclaw/skills/kvm-control"
do
if [ -d "$candidate" ] && [ -f "$candidate/SKILL.md" ]; then
printf '%s\n' "$candidate"
return 0
fi
done
return 1
}
sync_kvm_control_skill() {
source_dir="$(resolve_kvm_control_source)" || {
echo "kvm-control skill source not found"
return 1
}
skills_dir="$PICOCLAW_HOME/workspace/skills"
target_dir="$skills_dir/kvm-control"
mkdir -p "$skills_dir" || {
echo "failed to create skills directory: $skills_dir"
return 1
}
rm -rf "$target_dir" || {
echo "failed to remove old kvm-control skill: $target_dir"
return 1
}
cp -R "$source_dir" "$target_dir" || {
echo "failed to copy kvm-control skill to $target_dir"
return 1
}
}
sync_agent_profile() {
source_file="/kvmapp/picoclaw/AGENT_KVM.md"
target_file="$PICOCLAW_HOME/workspace/AGENT.md"
workspace_dir="$PICOCLAW_HOME/workspace"
[ -f "$source_file" ] || {
echo "agent profile source not found: $source_file"
return 1
}
mkdir -p "$workspace_dir" || {
echo "failed to create workspace directory: $workspace_dir"
return 1
}
cp -f "$source_file" "$target_file" || {
echo "failed to copy agent profile to $target_file"
return 1
}
}
start_service() {
setup_runtime_env || return 1
if pid="$(gateway_running_pid)"; then
echo "picoclaw gateway already running (PID: $pid)"
return 0
fi
if [ ! -f "$PICOCLAW_HOME/config.json" ]; then
echo "picoclaw config not found: $PICOCLAW_HOME/config.json"
return 1
fi
"$BIN_PATH" gateway >>"$LOG_FILE" 2>&1 &
gateway_pid="$!"
printf '%s\n' "$gateway_pid" >"$PICOCLAW_PID_FILE" || {
echo "failed to write picoclaw pid file: $PICOCLAW_PID_FILE"
return 1
}
echo "picoclaw gateway started (PID: $gateway_pid)"
}
onboard_service() {
setup_runtime_env || return 1
"$BIN_PATH" onboard >>"$LOG_FILE" 2>&1 || return 1
sync_kvm_control_skill || return 1
sync_agent_profile || return 1
}
stop_service() {
setup_picoclaw_home || return 1
pid="$(gateway_running_pid 2>/dev/null)" || {
cleanup_stale_pid_file
return 0
}
kill "$pid" 2>/dev/null || true
count=0
while is_gateway_pid "$pid"; do
count=$((count + 1))
if [ "$count" -ge 15 ]; then
echo "picoclaw gateway did not stop after TERM, killing PID: $pid"
kill -9 "$pid" 2>/dev/null || true
break
fi
sleep 1
done
rm -f "$PICOCLAW_PID_FILE"
}
case "$1" in
start)
start_service
;;
stop)
stop_service
echo "OK"
;;
onboard)
onboard_service
;;
restart)
stop_service
start_service
echo "OK"
;;
*)
echo "Usage: $0 {start|stop|onboard|restart}"
exit 1
;;
esac

View File

@@ -0,0 +1,89 @@
#!/bin/sh
DAEMON="tailscaled"
PIDFILE="/var/run/$DAEMON.pid"
# Set the port to listen on for incoming VPN packets.
# Remote nodes will automatically be informed about the new port number,
# but you might want to configure this in order to set external firewall
# settings.
PORT="41641"
# Extra flags you might want to pass to tailscaled.
FLAGS=""
# You need tailscaled at /usr/sbin to server, and tailscale at /usr/bin to operate
# STATIC version needed. Download page at https://pkgs.tailscale.com/stable/#static
PKG_URL_LATEST="https://pkgs.tailscale.com/stable/tailscale_latest_riscv64.tgz"
[ ! -x /usr/sbin/$DAEMON ] &&
echo "/usr/sbin/$DAEMON not found, please download it from $PKG_URL_LATEST" &&
echo "Then unpack it, copy $DAEMON to /usr/sbin and copy tailscale to /usr/bin" &&
exit 1
VERSION=$(/usr/sbin/$DAEMON --version|sed -n '1p'|xargs echo -n)
[ -x /usr/bin/tailscale ] ||
(echo "/usr/bin/tailscale not found, your installation of tailscale may be broken" && exit 1)
# Clean up old forwarding configuration if it exists
if [ -f /etc/sysctl.d/99-tailscale.conf ]; then
echo "Found old forwarding configuration, cleaning up..."
rm -f /etc/sysctl.d/99-tailscale.conf
sysctl -w net.ipv4.ip_forward=0 >/dev/null 2>&1
sysctl -w net.ipv6.conf.all.forwarding=0 >/dev/null 2>&1
echo "Cleanup completed. IPv4/IPv6 forwarding disabled."
# Trigger IPv6 address renewal on all interfaces
for iface in $(ls /sys/class/net/ | grep -v lo); do
echo 0 > /proc/sys/net/ipv6/conf/$iface/forwarding 2>/dev/null
sysctl -w net.ipv6.conf.$iface.accept_ra=2 >/dev/null 2>&1
done
echo "If you need exit node features, please configure manually."
fi
case "$1" in
start)
if [ -f /etc/kvm/GOMEMLIMIT ]; then
value=$(cat /etc/kvm/GOMEMLIMIT)
export GOMEMLIMIT="${value}MiB"
else
export GOMEMLIMIT=512MiB
fi
echo "GOMEMLIMIT set to ${GOMEMLIMIT}"
# Ensure directories exist
mkdir -p /var/lib/tailscale /var/run/tailscale
printf "Starting $DAEMON[$VERSION]: "
start-stop-daemon -S -bmq -p "$PIDFILE" -x "/usr/sbin/$DAEMON" -- \
--state=/var/lib/tailscale/tailscaled.state \
--socket=/var/run/tailscale/tailscaled.sock \
--port=${PORT} \
$FLAGS
if [ $? = 0 ]; then
sleep 5
echo "OK"
tailscale set --accept-dns=false
else
echo "FAIL"
fi
;;
stop)
printf "Stopping $DAEMON: "
start-stop-daemon -K -p "$PIDFILE"
[ $? = 0 ] && (echo "OK"; rm -f "$PIDFILE") || echo "FAIL"
printf "cleaning tailscaled: "
/usr/sbin/$DAEMON --cleanup >/dev/null 2>&1
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0

Binary file not shown.

96
kvmapp/system/update-nanokvm.py Executable file
View File

@@ -0,0 +1,96 @@
import os
import shutil
import time
import zipfile
import pathlib
import requests
temporary: str = "/root/.kvm-cache/"
def mkdir() -> None:
if pathlib.Path(temporary).exists():
shutil.rmtree(temporary)
pathlib.Path(temporary).mkdir()
print(f"Created temporary directory {temporary}")
def read(file: str) -> str:
return pathlib.Path(file).read_text().replace("\n", "")
def download_firmware() -> None:
print("Downloading firmware...")
now = int(time.time())
url = f"https://cdn.sipeed.com/nanokvm/latest.zip?n={now}"
print(f"Downloading firmware from {url}")
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Failed to download firmware, status: {response.status_code}")
content_type = response.headers.get("content-type")
if content_type != "application/zip":
raise Exception(f"Failed to download firmware, content_type: {content_type}")
zip_file = f"{temporary}/latest.zip"
with open(zip_file, "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
with zipfile.ZipFile(zip_file, "r") as f:
f.extractall(temporary)
print("Completed downloading firmware.")
def update() -> None:
backup_dir = pathlib.Path("/root/old")
firmware_dir = pathlib.Path("/kvmapp")
if backup_dir.exists():
shutil.rmtree(backup_dir)
if firmware_dir.exists():
firmware_dir.rename(backup_dir)
pathlib.Path(f"{temporary}/latest").rename(firmware_dir)
def change_permissions() -> None:
for root, dirs, files in os.walk("/kvmapp"):
os.chmod(root, 0o755)
for file in files:
file_path = os.path.join(root, file)
os.chmod(file_path, 0o755)
print("change permissions done")
def main() -> None:
try:
print("Stopping nanokvm service...")
os.system("/etc/init.d/S95nanokvm stop")
print("Staring update...")
mkdir()
download_firmware()
update()
change_permissions()
version = read("/kvmapp/version")
print(f"Successfully updated to version: {version}")
print("restart service\nthe nanokvm will reboot")
except Exception as e:
print(f"update failed\n{e}")
finally:
shutil.rmtree(temporary)
os.system("/etc/init.d/S95nanokvm restart")
if __name__ == "__main__":
main()

107
scripts/README.md Normal file
View File

@@ -0,0 +1,107 @@
# Release packaging
These scripts assemble the application update package that NanoKVM devices pull
over the air: `nanokvm_<version>.tar.gz` plus its `latest.json` manifest.
| Script | Purpose |
|---|---|
| `build-in-container.sh` | Builds every riscv64 artifact (`kvm_system`, `libkvm.so`, `NanoKVM-Server`). Runs inside the `nanokvm-builder` image only. |
| `package.sh` | Stages the package tree, creates the tarball, and writes `latest.json`. |
| `compare-release.sh` | Diffs a freshly built package against the currently published one. Informational. |
| `verify-release-assets.sh` | Checks the three GitHub Release assets before publishing or promotion. |
| `verify-release-tag.sh` | Requires an annotated numeric tag whose commit is on `main`. |
## What the updater expects
The format is not arbitrary — it is fixed by the on-device updater in
`server/service/application/`:
- **One safe root directory.** The updater scans before extracting and accepts
only directories and regular files under `nanokvm_<version>/`; links,
special files, duplicate paths, and path traversal are rejected.
- **`name` is the file name.** `version.go` builds the download URL as
`<base>/<name>`, where `<base>` is `https://cdn.sipeed.com/nanokvm` (or
`.../preview` when `/etc/kvm/preview_updates` exists).
- **`sha512` is base64, not hex.** `update.go` compares against
`base64(raw sha512 digest)`. A hex digest will fail verification on device.
- **`/kvmapp/version`** is what the device reports as its installed version, so
it must match the `version` field.
New releases use manifest v2. `size` remains the exact compressed byte count
for older clients, while v2 clients use `size_bytes` and
`unpacked_size_bytes` for storage preflight checks. Historical v1 `size`
values have inconsistent units, so v2 clients only require v1 `size` to be
non-zero and verify the downloaded SHA-512 instead. Publish v2 metadata before
releasing clients that consume it; clients retain v1 compatibility for custom
update servers.
## Building a release
The frontend needs Node and pnpm on the host; everything riscv64 needs the
builder image (see `docker/Dockerfile`).
```bash
make release VERSION=2.4.4
```
That is equivalent to:
```bash
make release-build # kvm_system + libkvm.so + NanoKVM-Server, in Docker
make web # web/dist
make package VERSION=2.4.4 # build/release/{nanokvm_2.4.4.tar.gz,latest.json}
```
In CI this runs as the **NanoKVM Package** workflow. Pull requests and manual
runs only create Actions artifacts. For a public release, run **NanoKVM Create
Tag**, then run **NanoKVM Release** and choose prerelease, stable, or promotion.
Publishing attaches three assets:
Publishing is one-shot: an existing Release or draft is an error, and only a
published prerelease can be promoted.
- `nanokvm_<version>.tar.gz`
- `latest.json`
- `sha256.txt`
The Actions artifact also includes `BUILD_INFO.txt` with the source commit,
workflow run, immutable builder image digest, and both checksum encodings; that
provenance file is not attached to the GitHub release. Uploading the tarball and
`latest.json` to the CDN is what actually offers the update to devices in the
field, so that step stays manual. `sha256.txt` is only for users verifying a
manual download and does not change the on-device `latest.json` contract.
## Where each file in the package comes from
| Package path | Source |
|---|---|
| `version` | the requested version |
| `server/NanoKVM-Server` | `server/build.sh` (BoringCrypto, RPATH `$ORIGIN/dl_lib`) |
| `server/dl_lib/` | whatever the `kvm_vision` build emits, with any library it does not emit backfilled from the tracked `server/dl_lib/` |
| `server/web/` | `web/dist/` |
| `kvm_system/kvm_system` | `support/sg2002` `build kvm_system` |
| `system/tool/` | prebuilt binaries in `tools/nanokvm_update_edid/` |
| `kvm/` | default runtime state (input dimensions, fps, quality) |
| everything else | tracked `kvmapp/` |
Note that `kvm/` ships default runtime state, and `install.go` replaces
`/kvmapp` wholesale, so an update resets those values on the device. That is
long-standing behaviour, not something these scripts introduce.
## Video library linking
`make app` and `server/build.sh` compile the server using the prebuilt libraries
in `server/dl_lib/`. They do not rebuild the video libraries. The cgo directive
in `server/common/kvm_vision.go` links against `libkvm.so`, which depends on
`libkvm_mmf.so`.
`make vision` rebuilds the video libraries and stages them in
`kvmapp/server/dl_lib/`; `make release-build` does this as part of the full build.
After changing library interfaces, update both prebuilt files in
`server/dl_lib/` from the same build. The tracked directory also supplies the
SDK runtime libraries used by the video build and backfills libraries that
are absent from the staged directory.
`build-in-container.sh` checks that the staged `libkvm.so` exports every KVM
symbol imported by the server. See the [server instructions](../server/README.md#compile--deploy)
for manual compilation and deployment.

133
scripts/build-in-container.sh Executable file
View File

@@ -0,0 +1,133 @@
#!/bin/bash
#
# Build every riscv64 artifact of a release, from inside the nanokvm-builder
# image (docker/Dockerfile). Not meant to be run on the host: it needs the
# riscv64 musl toolchain and the patched MaixCDK checkout that the image ships.
#
# Produces:
# kvmapp/kvm_system/kvm_system kvm_system daemon
# kvmapp/server/dl_lib/ video libraries, including a fresh libkvm.so
# server/NanoKVM-Server Go server (BoringCrypto, RPATH $ORIGIN/dl_lib)
set -euo pipefail
# docker/entrypoint sets HOME for the build user. support/sg2002/build resolves
# both MaixCDK and the source tree through ~, so a wrong HOME would send the
# whole build at /root; say so plainly rather than emitting "directory missing".
BUILD_HOME="${BUILD_HOME:-/home/build}"
if [ "${HOME:-}" != "$BUILD_HOME" ]; then
echo "[ERROR] HOME is '${HOME:-unset}', expected $BUILD_HOME" >&2
echo " run this inside the builder image via the Makefile" >&2
exit 1
fi
MAIXCDK_PATH="$HOME/MaixCDK"
NANOKVM_PATH="$HOME/NanoKVM"
for dir in "$MAIXCDK_PATH" "$NANOKVM_PATH"; do
if [ ! -d "$dir" ]; then
echo "[ERROR] $dir not found - is this running inside nanokvm-builder?" >&2
exit 1
fi
done
# Check the toolchain up front. builder-image reuses any existing image, so an
# image built before a tooling change silently lacks it - and without this the
# SDK build would run for minutes before server/build.sh failed at the end.
for tool in go riscv64-unknown-linux-musl-gcc patchelf; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "[ERROR] '$tool' is missing from the builder image" >&2
echo " the image is out of date; rebuild it with: make rebuild-image" >&2
exit 1
fi
done
# The SDK tree is owned by the ids baked into the image (DOCKER_UID/DOCKER_GID),
# while the entrypoint drops to the caller's ids. If they disagree, syncing
# components fails partway through a long build; catch it here instead.
if [ ! -w "$MAIXCDK_PATH/components" ]; then
echo "[ERROR] $MAIXCDK_PATH/components is not writable by $(id -u):$(id -g)" >&2
echo " the image was built for different ids; rebuild it with:" >&2
echo " make rebuild-image" >&2
exit 1
fi
# shellcheck disable=SC1091
. "$MAIXCDK_PATH/bin/activate"
# Each support build synchronizes the repository components before compiling.
cd "$NANOKVM_PATH/support/sg2002"
echo "::group::support: build kvm_system"
./build kvm_system
./build kvm_system add_to_kvmapp
echo "::endgroup::"
echo "::group::support: build kvm_vision (libkvm.so)"
./build kvm_vision
./build kvm_vision add_to_kvmapp
echo "::endgroup::"
echo "::group::server: cross-compile NanoKVM-Server"
cd "$NANOKVM_PATH/server"
./build.sh
echo "::endgroup::"
# support/sg2002/build reports "Build Error!" without a non-zero exit status for
# some failure paths, so assert on the artifacts rather than trusting $?.
echo "[INFO] verifying artifacts"
missing=0
for artifact in \
"$NANOKVM_PATH/kvmapp/kvm_system/kvm_system" \
"$NANOKVM_PATH/kvmapp/server/dl_lib/libkvm.so" \
"$NANOKVM_PATH/server/NanoKVM-Server"
do
if [ -f "$artifact" ]; then
echo " ok ${artifact#$NANOKVM_PATH/}"
else
echo " MISSING ${artifact#$NANOKVM_PATH/}" >&2
missing=1
fi
done
if [ "$missing" -ne 0 ]; then
echo "[ERROR] build did not produce all expected artifacts" >&2
exit 1
fi
# Confirm the shipped video libraries provide every KVM symbol imported by
# the server, including the frame ownership API.
echo "[INFO] verifying shipped libkvm.so satisfies NanoKVM-Server"
if ! command -v readelf >/dev/null 2>&1; then
echo "[WARN] readelf unavailable, skipping ABI check"
else
exported() {
readelf --dyn-syms --wide "$1" 2>/dev/null \
| awk '$7 != "UND" && $8 != "" { print $8 }' \
| sed 's/@.*//' | LC_ALL=C sort -u
}
imported() {
readelf --dyn-syms --wide "$1" 2>/dev/null \
| awk '$7 == "UND" && $8 != "" { print $8 }' \
| sed 's/@.*//' | LC_ALL=C sort -u
}
shipped_lib="$NANOKVM_PATH/kvmapp/server/dl_lib/libkvm.so"
server_bin="$NANOKVM_PATH/server/NanoKVM-Server"
needed=$(imported "$server_bin" | awk '/^(kvmv_|free_kvmv_data$|free_all_kvmv_data$|set_h264_gop$|set_frame_detact$|set_venc_auto_recyc$)/')
if [ -z "$needed" ]; then
echo "[WARN] no libkvm symbols resolved; skipping ABI check"
else
absent=$(comm -23 <(printf '%s\n' "$needed") <(exported "$shipped_lib"))
if [ -n "$absent" ]; then
echo "[ERROR] shipped libkvm.so is missing symbols NanoKVM-Server needs:" >&2
printf ' %s\n' $absent >&2
exit 1
fi
echo " ok $(printf '%s\n' "$needed" | wc -l | tr -d ' ') libkvm symbols resolve"
fi
fi
echo "[DONE] riscv64 artifacts built"

103
scripts/compare-release.sh Executable file
View File

@@ -0,0 +1,103 @@
#!/bin/bash
#
# Compare a freshly built package against the currently published release.
#
# Purely informational: it exits 0 whatever it finds. The point is to make the
# delta reviewable before the tarball is published, since the package is what
# every device pulls over OTA. Unexpected entries here (a library that vanished,
# an init script that changed without a matching commit) are worth a look.
#
# Usage: scripts/compare-release.sh <new-tarball> [base-url]
set -uo pipefail
NEW_TARBALL="${1:-}"
BASE_URL="${2:-https://cdn.sipeed.com/nanokvm}"
if [ -z "$NEW_TARBALL" ] || [ ! -f "$NEW_TARBALL" ]; then
echo "Usage: $0 <new-tarball> [base-url]" >&2
exit 1
fi
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
echo "[INFO] fetching published manifest from $BASE_URL/latest.json"
if ! curl -fsSL "$BASE_URL/latest.json" -o "$WORK/latest.json"; then
echo "[WARN] could not fetch latest.json - skipping comparison"
exit 0
fi
cat "$WORK/latest.json"
OLD_NAME="$(sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$WORK/latest.json")"
if [ -z "$OLD_NAME" ]; then
echo "[WARN] no \"name\" in latest.json - skipping comparison"
exit 0
fi
echo "[INFO] downloading published package $OLD_NAME"
if ! curl -fsSL "$BASE_URL/$OLD_NAME" -o "$WORK/$OLD_NAME"; then
echo "[WARN] could not download $OLD_NAME - skipping comparison"
exit 0
fi
mkdir -p "$WORK/old" "$WORK/new"
if ! tar xzf "$WORK/$OLD_NAME" -C "$WORK/old"; then
echo "[WARN] could not extract $OLD_NAME - skipping comparison"
exit 0
fi
if ! tar xzf "$NEW_TARBALL" -C "$WORK/new"; then
echo "[WARN] could not extract $(basename "$NEW_TARBALL") - skipping comparison"
exit 0
fi
# Strip the nanokvm_<version>/ prefix so the two trees are comparable.
OLD_ROOT="$(find "$WORK/old" -mindepth 1 -maxdepth 1 -type d | head -1)"
NEW_ROOT="$(find "$WORK/new" -mindepth 1 -maxdepth 1 -type d | head -1)"
if [ -z "$OLD_ROOT" ] || [ -z "$NEW_ROOT" ]; then
echo "[WARN] could not locate a package root directory - skipping comparison"
exit 0
fi
( cd "$OLD_ROOT" && find . -type f | sed 's|^\./||' | LC_ALL=C sort ) > "$WORK/old.list"
( cd "$NEW_ROOT" && find . -type f | sed 's|^\./||' | LC_ALL=C sort ) > "$WORK/new.list"
# An empty inventory would make every section below print "(none)", which reads
# identically to "verified, nothing changed". Refuse to imply that.
if [ ! -s "$WORK/old.list" ] || [ ! -s "$WORK/new.list" ]; then
echo "[WARN] one of the packages produced an empty file list - comparison unreliable, skipping"
exit 0
fi
echo
echo "=============================================================="
echo " $(basename "$OLD_ROOT") -> $(basename "$NEW_ROOT")"
echo "=============================================================="
printf ' files: %s -> %s\n' "$(wc -l < "$WORK/old.list" | tr -d ' ')" \
"$(wc -l < "$WORK/new.list" | tr -d ' ')"
echo
echo "--- added ----------------------------------------------------"
comm -13 "$WORK/old.list" "$WORK/new.list" | sed 's/^/ + /' || true
echo
echo "--- removed --------------------------------------------------"
comm -23 "$WORK/old.list" "$WORK/new.list" | sed 's/^/ - /' || true
echo
echo "--- changed --------------------------------------------------"
changed=0
while IFS= read -r file; do
if ! cmp -s "$OLD_ROOT/$file" "$NEW_ROOT/$file"; then
old_size="$(wc -c < "$OLD_ROOT/$file" | tr -d ' ')"
new_size="$(wc -c < "$NEW_ROOT/$file" | tr -d ' ')"
printf ' ~ %-52s %s -> %s bytes\n' "$file" "$old_size" "$new_size"
changed=$((changed + 1))
fi
done < <(comm -12 "$WORK/old.list" "$WORK/new.list")
[ "$changed" -eq 0 ] && echo " (none)"
echo
echo "[INFO] comparison complete"

231
scripts/package.sh Executable file
View File

@@ -0,0 +1,231 @@
#!/bin/bash
#
# Assemble a NanoKVM release package: nanokvm_<version>.tar.gz + latest.json.
#
# The layout and the manifest fields are dictated by the on-device updater:
# - server/service/application/version.go parses latest.json and derives the
# download URL as "<base>/<name>", so "name" must be the tarball file name.
# - server/service/application/update.go verifies the download against
# "sha512", which is the *base64* encoding of the raw SHA-512 digest.
# - server/service/application/archive.go validates and extracts the package
# before install.go moves its single top-level directory over /kvmapp, so
# the tarball must contain exactly one root directory: nanokvm_<version>/.
#
# Build artifacts are expected to be in place already (see
# scripts/build-in-container.sh and the "web" target in the Makefile):
# server/NanoKVM-Server riscv64 server binary
# kvmapp/kvm_system/kvm_system kvm_system daemon
# kvmapp/server/dl_lib/libkvm.so freshly built video library (optional)
# web/dist/ built frontend
#
# Usage: scripts/package.sh <version>
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
VERSION="${1:-}"
if [ -z "$VERSION" ]; then
echo "Usage: $0 <version> e.g. $0 2.4.4" >&2
exit 1
fi
# The updater rejects file names outside [a-zA-Z0-9._-] (update_offline.go),
# and the version string ends up in the file name, so validate it up front.
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid version '$VERSION', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
OUT="$ROOT/build/release"
STAGE="$OUT/nanokvm_$VERSION"
TARBALL="$OUT/nanokvm_$VERSION.tar.gz"
MANIFEST="$OUT/latest.json"
require_file() {
if [ ! -f "$1" ]; then
echo "[ERROR] missing build artifact: ${1#"$ROOT"/}" >&2
echo " $2" >&2
exit 1
fi
}
# A host-architecture build is indistinguishable from a cross-compiled one by
# name alone, and NanoKVM-Server is gitignored, so nothing else would catch it.
# Refuse to package anything that is not riscv64 (ELF e_machine 243).
require_riscv64() {
local path="$1" magic machine
magic=$(od -An -tx1 -N4 "$path" | tr -d ' \n')
if [ "$magic" != "7f454c46" ]; then
echo "[ERROR] not an ELF object: ${path#"$ROOT"/}" >&2
exit 1
fi
machine=$(od -An -tu1 -j18 -N1 "$path" | tr -d ' \n')
if [ "$machine" != "243" ]; then
echo "[ERROR] ${path#"$ROOT"/} is not riscv64 (ELF e_machine=$machine)" >&2
echo " a host-architecture build must never be packaged" >&2
exit 1
fi
}
require_file "$ROOT/server/NanoKVM-Server" "run: make app"
require_file "$ROOT/kvmapp/kvm_system/kvm_system" "run: make support"
require_file "$ROOT/web/dist/index.html" "run: make web"
# libkvm.so is the one runtime library that must come from the build: the copy
# tracked in server/dl_lib/ exists for cgo link time and lags far behind. If it
# were optional here, "make package" on its own would quietly ship the stale one.
require_file "$ROOT/kvmapp/server/dl_lib/libkvm.so" "run: make vision"
require_riscv64 "$ROOT/server/NanoKVM-Server"
require_riscv64 "$ROOT/kvmapp/kvm_system/kvm_system"
require_riscv64 "$ROOT/kvmapp/server/dl_lib/libkvm.so"
echo "[INFO] staging nanokvm_$VERSION"
# Clear the whole output directory: release.yml uploads build/release/nanokvm_*
# by glob, and a leftover tarball from an earlier version would ride along.
rm -rf "$OUT"
mkdir -p "$STAGE"
# 1. Everything tracked under kvmapp/ (init scripts, picoclaw bundle, kernel
# module, jpg_stream, kvm_stream) plus whatever the support build dropped in
# (kvm_system, server/dl_lib). -a carries the exec bits over from git, which
# only matters for reading the archive by hand: install.go chmods the whole
# tree to 0755 on the device regardless.
cp -a "$ROOT/kvmapp/." "$STAGE/"
# 2. Version marker. The updater reads /kvmapp/version to report the currently
# installed version (version.go).
printf '%s\n' "$VERSION" > "$STAGE/version"
# 3. Go server binary.
mkdir -p "$STAGE/server"
cp -a "$ROOT/server/NanoKVM-Server" "$STAGE/server/NanoKVM-Server"
# 4. Runtime shared libraries. "build kvm_vision add_to_kvmapp" copies its whole
# dist/dl_lib into kvmapp/server/dl_lib, so freshly built libraries are
# already staged; the tracked server/dl_lib/ backfills the rest. Never
# clobber a fresh library with the tracked (link-time) copy.
mkdir -p "$STAGE/server/dl_lib"
for lib in "$ROOT"/server/dl_lib/*; do
[ -e "$lib" ] || continue
name="$(basename "$lib")"
if [ ! -e "$STAGE/server/dl_lib/$name" ]; then
cp -a "$lib" "$STAGE/server/dl_lib/$name"
fi
done
# The SDK is built from an unpinned MaixCDK checkout, so its dist could one
# day add or rename a library (e.g. an soname bump leaving both .409 and
# .410 behind) and we would ship a library set nobody reviewed. Require the
# shipped names to be exactly the tracked set, and fail loudly otherwise.
staged_libs=$(cd "$STAGE/server/dl_lib" && ls -1 | LC_ALL=C sort)
tracked_libs=$(cd "$ROOT/server/dl_lib" && ls -1 | LC_ALL=C sort)
if [ "$staged_libs" != "$tracked_libs" ]; then
echo "[ERROR] shipped server/dl_lib does not match the tracked library set" >&2
echo " unexpected (in package, not tracked):" >&2
comm -23 <(printf '%s\n' "$staged_libs") <(printf '%s\n' "$tracked_libs") \
| sed 's/^/ + /' >&2
echo " absent (tracked, not in package):" >&2
comm -13 <(printf '%s\n' "$staged_libs") <(printf '%s\n' "$tracked_libs") \
| sed 's/^/ - /' >&2
echo " if this change is intended, update server/dl_lib/ to match." >&2
exit 1
fi
# A library arrives either from the SDK dist (mode 755) or from the tracked
# backfill (git stores them 644), so without this the archive would depend on
# which path populated each file. 644 is what published releases have always
# carried, and install.go chmods the installed tree to 0755 anyway.
chmod 644 "$STAGE"/server/dl_lib/*
# 5. Frontend. router.go serves <dir of executable>/web.
rm -rf "$STAGE/server/web"
mkdir -p "$STAGE/server/web"
cp -a "$ROOT/web/dist/." "$STAGE/server/web/"
# 6. EDID helper shipped under system/tool/ (prebuilt riscv64 binary in tools/).
mkdir -p "$STAGE/system/tool"
cp -a "$ROOT/tools/nanokvm_update_edid/nanokvm_update_edid" "$STAGE/system/tool/"
cp -a "$ROOT/tools/nanokvm_update_edid/E21_NanoKVM.bin" "$STAGE/system/tool/"
# 7. Default runtime state read by common.GetScreen() on first boot.
mkdir -p "$STAGE/kvm"
printf '30\n' > "$STAGE/kvm/fps"
printf '0\n' > "$STAGE/kvm/now_fps"
printf '60\n' > "$STAGE/kvm/qlty"
printf '1920\n' > "$STAGE/kvm/width"
printf '1080\n' > "$STAGE/kvm/height"
printf '0\n' > "$STAGE/kvm/state"
printf 'mjpeg\n' > "$STAGE/kvm/type"
printf '0' > "$STAGE/kvm/res"
# 8. Directories the released package has always carried, kept so the layout
# matches previous releases exactly (system_init.cpp probes inside them).
mkdir -p "$STAGE/jpg_stream/dl_lib" "$STAGE/kvm_system/dl_lib"
# --- archive -----------------------------------------------------------------
# Normalise owner and timestamps so the same source tree yields the same
# tarball, which makes the published sha512 verifiable after the fact.
SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(git -C "$ROOT" log -1 --format=%ct 2>/dev/null || echo 0)}"
find "$STAGE" -exec touch -d "@$SOURCE_DATE_EPOCH" {} + 2>/dev/null \
|| find "$STAGE" -exec touch -t "$(date -r "$SOURCE_DATE_EPOCH" +%Y%m%d%H%M.%S)" {} + 2>/dev/null \
|| echo "[WARN] could not normalise timestamps"
echo "[INFO] creating $(basename "$TARBALL")"
rm -f "$TARBALL"
# Read the version into a variable first: piping through head can hand tar a
# SIGPIPE, and under "set -o pipefail" that would silently select the bsdtar
# branch on a GNU system, quietly losing reproducibility.
tar_version="$(tar --version 2>/dev/null || true)"
if [ "${tar_version#*GNU}" != "$tar_version" ]; then
tar --format=gnu --sort=name \
--owner=0 --group=0 --numeric-owner \
--mtime="@$SOURCE_DATE_EPOCH" \
-C "$OUT" -cf - "nanokvm_$VERSION" \
| gzip -n -9 > "$TARBALL"
else
# bsdtar (macOS): no --sort/--mtime, so the archive is not byte-reproducible.
echo "[WARN] GNU tar not found; archive will not be byte-reproducible"
tar --uid 0 --gid 0 --uname '' --gname '' \
-C "$OUT" -cf - "nanokvm_$VERSION" \
| gzip -n -9 > "$TARBALL"
fi
# --- manifest ----------------------------------------------------------------
# update.go compares base64(raw sha512), not the hex digest.
SHA512="$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)"
SIZE_BYTES="$(wc -c < "$TARBALL" | tr -d ' ')"
UNPACKED_SIZE_BYTES="$(python3 - "$TARBALL" <<'PY'
import sys
import tarfile
total = 0
with tarfile.open(sys.argv[1], "r:gz") as archive:
for member in archive:
if member.isfile():
total += member.size
print(total)
PY
)"
cat > "$MANIFEST" <<EOF
{
"manifest_version": 2,
"version": "$VERSION",
"name": "nanokvm_$VERSION.tar.gz",
"sha512": "$SHA512",
"size": $SIZE_BYTES,
"size_bytes": $SIZE_BYTES,
"unpacked_size_bytes": $UNPACKED_SIZE_BYTES
}
EOF
echo
echo "[DONE] $TARBALL"
echo "[DONE] $MANIFEST"
cat "$MANIFEST"

157
scripts/verify-release-assets.sh Executable file
View File

@@ -0,0 +1,157 @@
#!/bin/bash
# Verify the three assets that make up a NanoKVM GitHub release.
set -euo pipefail
ASSET_DIR="${1:-}"
VERSION="${2:-}"
if [ -z "$ASSET_DIR" ] || [ -z "$VERSION" ]; then
echo "Usage: $0 <asset-directory> <version>" >&2
exit 1
fi
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid version '$VERSION', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
TARBALL_NAME="nanokvm_${VERSION}.tar.gz"
TARBALL="$ASSET_DIR/$TARBALL_NAME"
MANIFEST="$ASSET_DIR/latest.json"
CHECKSUM="$ASSET_DIR/sha256.txt"
for path in "$TARBALL" "$MANIFEST" "$CHECKSUM"; do
if [ ! -f "$path" ]; then
echo "[ERROR] missing release asset: $path" >&2
exit 1
fi
done
PACKAGE_ROOT="nanokvm_${VERSION}"
MAX_PACKAGE_SIZE=$((1 << 30))
MAX_UNPACKED_SIZE=$((2 << 30))
MAX_ARCHIVE_ENTRIES=100000
ENTRY_LIST=$(mktemp)
VERBOSE_LIST=$(mktemp)
trap 'rm -f "$ENTRY_LIST" "$VERBOSE_LIST"' EXIT
if ! tar -tzf "$TARBALL" > "$ENTRY_LIST"; then
echo "[ERROR] could not list release tarball" >&2
exit 1
fi
if ! tar -tvzf "$TARBALL" > "$VERBOSE_LIST"; then
echo "[ERROR] could not inspect release tarball entry types" >&2
exit 1
fi
ENTRY_COUNT=0
while IFS= read -r entry; do
ENTRY_COUNT=$((ENTRY_COUNT + 1))
if [ "$ENTRY_COUNT" -gt "$MAX_ARCHIVE_ENTRIES" ]; then
echo "[ERROR] archive contains more than $MAX_ARCHIVE_ENTRIES entries" >&2
exit 1
fi
case "$entry" in
"$PACKAGE_ROOT"|"$PACKAGE_ROOT"/*) ;;
*)
echo "[ERROR] archive entry is outside $PACKAGE_ROOT/: $entry" >&2
exit 1
;;
esac
case "/$entry/" in
*/../*|*/./*)
echo "[ERROR] archive entry contains an unsafe path component: $entry" >&2
exit 1
;;
esac
done < "$ENTRY_LIST"
if [ "$ENTRY_COUNT" -eq 0 ]; then
echo "[ERROR] release tarball is empty" >&2
exit 1
fi
while IFS= read -r verbose_entry; do
entry_type=${verbose_entry:0:1}
case "$entry_type" in
-|d) ;;
*)
echo "[ERROR] archive contains a link or special entry: $verbose_entry" >&2
exit 1
;;
esac
done < "$VERBOSE_LIST"
ARCHIVE_VERSION=$(tar -xOzf "$TARBALL" "$PACKAGE_ROOT/version" 2>/dev/null) || {
echo "[ERROR] release tarball does not contain $PACKAGE_ROOT/version" >&2
exit 1
}
if [ "$ARCHIVE_VERSION" != "$VERSION" ]; then
echo "[ERROR] archive version '$ARCHIVE_VERSION' does not match '$VERSION'" >&2
exit 1
fi
SHA256=$(sha256sum "$TARBALL" | cut -d' ' -f1)
if ! printf '%s %s\n' "$SHA256" "$TARBALL_NAME" | cmp -s - "$CHECKSUM"; then
echo "[ERROR] sha256.txt does not match $TARBALL_NAME" >&2
exit 1
fi
MANIFEST_VERSION=$(jq -er '.version | select(type == "string" and length > 0)' "$MANIFEST")
MANIFEST_NAME=$(jq -er '.name | select(type == "string" and length > 0)' "$MANIFEST")
MANIFEST_SIZE=$(jq -er '.size | select(type == "number" and . >= 0 and floor == .)' "$MANIFEST")
MANIFEST_FORMAT=$(jq -er '.manifest_version | select(type == "number" and . == 2)' "$MANIFEST")
MANIFEST_SIZE_BYTES=$(jq -er '.size_bytes | select(type == "number" and . > 0 and floor == .)' "$MANIFEST")
MANIFEST_UNPACKED_SIZE_BYTES=$(jq -er '.unpacked_size_bytes | select(type == "number" and . > 0 and floor == .)' "$MANIFEST")
MANIFEST_SHA512=$(jq -er '.sha512 | select(type == "string" and length > 0)' "$MANIFEST")
if [ "$MANIFEST_VERSION" != "$VERSION" ]; then
echo "[ERROR] latest.json version '$MANIFEST_VERSION' does not match '$VERSION'" >&2
exit 1
fi
if [ "$MANIFEST_NAME" != "$TARBALL_NAME" ]; then
echo "[ERROR] latest.json name '$MANIFEST_NAME' does not match '$TARBALL_NAME'" >&2
exit 1
fi
ACTUAL_SIZE=$(wc -c < "$TARBALL" | tr -d ' ')
if [ "$MANIFEST_FORMAT" != "2" ]; then
echo "[ERROR] latest.json manifest_version must be 2" >&2
exit 1
fi
if [ "$MANIFEST_SIZE" != "$ACTUAL_SIZE" ] || [ "$MANIFEST_SIZE_BYTES" != "$ACTUAL_SIZE" ]; then
echo "[ERROR] latest.json size '$MANIFEST_SIZE' does not match '$ACTUAL_SIZE'" >&2
exit 1
fi
if [ "$ACTUAL_SIZE" -gt "$MAX_PACKAGE_SIZE" ]; then
echo "[ERROR] release tarball exceeds device limit of $MAX_PACKAGE_SIZE bytes" >&2
exit 1
fi
ACTUAL_UNPACKED_SIZE=$(python3 - "$TARBALL" <<'PY'
import sys
import tarfile
total = 0
with tarfile.open(sys.argv[1], "r:gz") as archive:
for member in archive:
if member.isfile():
total += member.size
print(total)
PY
)
if [ "$MANIFEST_UNPACKED_SIZE_BYTES" != "$ACTUAL_UNPACKED_SIZE" ]; then
echo "[ERROR] latest.json unpacked_size_bytes '$MANIFEST_UNPACKED_SIZE_BYTES' does not match '$ACTUAL_UNPACKED_SIZE'" >&2
exit 1
fi
if [ "$ACTUAL_UNPACKED_SIZE" -gt "$MAX_UNPACKED_SIZE" ]; then
echo "[ERROR] unpacked package exceeds device limit of $MAX_UNPACKED_SIZE bytes" >&2
exit 1
fi
ACTUAL_SHA512=$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)
if [ "$MANIFEST_SHA512" != "$ACTUAL_SHA512" ]; then
echo "[ERROR] latest.json sha512 does not match $TARBALL_NAME" >&2
exit 1
fi
echo "[OK] verified NanoKVM release assets for $VERSION"

43
scripts/verify-release-tag.sh Executable file
View File

@@ -0,0 +1,43 @@
#!/bin/bash
# Resolve an annotated numeric tag from origin and verify its commit is on main.
set -euo pipefail
TAG="${1:-}"
EXPECTED_SHA="${2:-}"
if ! echo "$TAG" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid tag '$TAG', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
if [ -n "$EXPECTED_SHA" ] && ! echo "$EXPECTED_SHA" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] expected commit must be a full lowercase commit SHA" >&2
exit 1
fi
TAG_REF="refs/tags/$TAG"
PEELED_REF="${TAG_REF}^{}"
REMOTE_REFS=$(git ls-remote --tags origin "$TAG_REF" "$PEELED_REF")
TAG_OBJECT=$(printf '%s\n' "$REMOTE_REFS" | awk -v ref="$TAG_REF" '$2 == ref { print $1 }')
SOURCE_SHA=$(printf '%s\n' "$REMOTE_REFS" | awk -v ref="$PEELED_REF" '$2 == ref { print $1 }')
if ! echo "$TAG_OBJECT" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] tag '$TAG' does not exist on origin" >&2
exit 1
fi
if ! echo "$SOURCE_SHA" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] tag '$TAG' is not an annotated tag" >&2
exit 1
fi
if [ -n "$EXPECTED_SHA" ] && [ "$SOURCE_SHA" != "$EXPECTED_SHA" ]; then
echo "[ERROR] tag '$TAG' moved from '$EXPECTED_SHA' to '$SOURCE_SHA'" >&2
exit 1
fi
git fetch --no-tags origin main
if ! git merge-base --is-ancestor "$SOURCE_SHA" FETCH_HEAD; then
echo "[ERROR] tag '$TAG' points to a commit outside origin/main" >&2
exit 1
fi
printf '%s\n' "$SOURCE_SHA"

View File

@@ -13,7 +13,7 @@ server
├── dl_lib // Shared object libraries
├── include // Header files for shared objects
├── logger // Logging system
├── middleware // Server middleware components
├── middleware // Server middleware components
├── proto // API request/response definitions
├── router // API route handlers
├── service // Core service implementations
@@ -26,46 +26,146 @@ server
The configuration file path is `/etc/kvm/server.yaml`.
```yaml
proto: http
# Network Settings
proto: http # Access protocol. Can be changed to `https` only when certificates are configured. Default is `http`
host: "" # The listening address for the HTTP/HTTPS service. If left empty, all network interfaces will be bound
port:
http: 80
https: 443
http: 80 # The listening port for the HTTP service. Default is `80`
https: 443 # The listening port for the HTTPS service (effective when HTTPS is enabled). Default is `443`
cert:
crt: server.crt
key: server.key
crt: server.crt # The path to the public key certificate for HTTPS
key: server.key # The path to the private key file for HTTPS
# Log level (debug/info/warn/error)
# Note: Use 'info' or 'error' in production, 'debug' only for development
# Logging Configuration
logger:
level: info
file: stdout
# Authentication setting (enable/disable)
# Note: Only disable authentication in development environment
authentication: enable
level: info # Global log output level. Evaluated options from highest to lowest detail: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`. Default is `info`
file: stdout # Log output destination. `stdout` outputs to the standard console. A file path directs log output to that file. Default is `stdout`
# Authentication & Security
authentication: enable # Whether to enable identity verification for HTTP API and Web endpoints. Options are `enable` or `disable`. Default is `enable`. Highly recommended to leave this enabled for internet-facing devices!
jwt:
# JWT secret key. If left empty, a random 64-byte key will be generated automatically.
secretKey: ""
# JWT token expiration time in seconds. Default: 2678400 (31 days)
refreshTokenDuration: 2678400
# Invalidate all JWT tokens when the user logs out. Default: true
revokeTokensOnLogout: true
secretKey: "" # The secret key used to sign and verify JWT Tokens. If left empty, a random key will be generated automatically on startup
refreshTokenDuration: 2678400 # The token refresh duration threshold in seconds before forcing a re-login. Default is `2678400` (~31 days)
revokeTokensOnLogout: true # Whether logout invalidates all sessions belonging to that user. Other users are never logged out. Setting this to false only clears the browser cookie and is not recommended. Default is `true`
security:
loginLockoutDuration: 0, # The duration (in seconds) to ban an IP from attempting to log in again after reaching the failure limit. If set to `0` or left empty, brute-force protection is disabled. Default is `0`
loginMaxFailures: 5, # The maximum number of continuous failed login attempts allowed per IP before triggering protection. Default is `5`
# Address for custom STUN server
stun: stun.l.google.com:19302
# Address and authentication for custom TURN server
# WebRTC Traversal Settings
stun: stun.l.google.com:19302 # The default STUN server address used for NAT hole-punching to establish P2P streams
turn:
turnAddr: turn.cloudflare.com:3478
turnUser: example_user
turnCred: example_cred
turnAddr: example_addr # The relay (TURN) server address (format `ip:port`) used as a fallback when P2P connection fails. Leave empty to disable TURN relay
turnUser: example_user # The username required for authorization to the TURN server
turnCred: example_cred # The credential/password required for authorization to the TURN server
```
## Web Users
NanoKVM uses two device-wide roles:
- `admin`: everything below, plus user management.
- `user`: only what the account is granted.
A grant names an action on one party, and the catalog the server serves to the account editor
carries its group, its risk, and the grants it implies:
| Group | Grants |
| --- | --- |
| console (this session) | `console.view`, `console.control` |
| target machine | `power`, `medium.attach` |
| media library (this device) | `library.read`, `library.write` |
| this device | `terminal`, `device`, `network`, `update` |
| services | `mcp`, `tailscale`, `ai` |
Implied grants are declared once, in the catalog, and the server resolves them before answering any
request: `console.control` implies `console.view`, both `medium.attach` and `library.write` imply
`library.read`, and every grant whose controls live in the console menu — `power`, `device`,
`network`, `update`, `mcp`, `tailscale` and `ai` — implies `console.view` too, because no page
outside the console renders them. Consequences worth knowing:
- An account can hold no console access at all. The web app then lands on a page that offers the
sections the account may use (the media library, the terminal) instead of a console it cannot
open. `library.read` is all that media access needs, because the other two media grants imply it,
and only `terminal` and the media grants can stand on their own pages in the first place.
- The media grants split along the trust boundary. `medium.attach` mounts or ejects a medium on the
target machine and writes into the shared partition the target reads; `library.write` changes what
the library keeps (uploads, deletes, the files inside an image); `library.read` lists and downloads.
The file endpoints serve an image and the shared partition through one path, so the route admits
either grant and each request is checked against the medium type it names. Every `.iso` and
`.img` on the partition is a library entry, so uploading one through the shared partition, or
deleting a file or folder that holds one, also needs `library.write`.
- The emulated USB devices are neither media nor network: the virtual disk and the RNDIS adapter
hand the target machine the raw data partition and a network interface, so both follow `device`.
A medium can only be attached while a `device` holder has the virtual disk switched on, and the
storage page says so when it is off.
Four grants reach further than their names suggest and amount to full device control. The catalog
has two risk levels, and `warn` is reserved for them: the account editor marks those four and
names them before the grants are saved:
- `terminal` is a root shell (the same one SSH gives) and can run saved and autostart scripts.
- `mcp` hands out a device-wide API key that drives the keyboard, mouse and screenshots from
outside the web session. The key is shared, so a copy keeps working after an account loses this
grant. Whenever a change takes the grant away (revoked, demoted, disabled or deleted), the account
editor warns and offers to regenerate the key, checked by default; regenerating disconnects every
MCP client until it is given the new key, and an administrator who keeps the key accepts that a
copy stays valid. The API takes the choice as `rotateMcpKey` (a body field on update, a query
parameter on delete) and never rotates without it.
- `ai` drives the device through the local loopback interface, which the other grants do not
restrict.
- `update` installs firmware and application packages. An offline package is checked only against
the checksum its uploader supplies, so installing one is running code as root.
`device` carries no such mark, although it changes what the device does for everyone and cannot be
narrowed per account. `device` turns SSH on or off (root login, with the device
owner's password), reboots the device, hands the raw data partition or a network interface to the
target machine through the emulated USB devices, and edits the OLED, HDMI, mDNS, memory, swap and
HID settings. The editor describes it that way.
Two grants also change settings that affect everyone watching: `console.view` sets the video mode,
resolution, frame rate and quality, and resets the HDMI capture; `power` manages the Wake-on-LAN
device list. Both are described that way in the editor.
Administrators manage accounts from **Settings > Account**. Account data remains in
`/etc/kvm/pwd`; the server migrates the legacy single-account JSON format in place and writes
the multi-user format atomically with mode `0600`. Keeping the same path preserves the physical
BOOT-button password reset behavior.
Users must confirm their current password when changing it themselves; administrators can reset
non-owner users from the account manager. Only the device owner can change the device owner's
password, because that password is also synchronized to the Linux root account.
All authenticated sessions are backed by the current account state: every request is authorized
against the account file, so a revoked grant stops working immediately without re-issuing a login.
Disabling, deleting, or resetting the password of a user invalidates that user's HTTP and real-time
connections without affecting other users. Changing the role or the grants of an account keeps its
login valid: the account is told to refresh, and only the long-lived connections whose cached
state depends on what changed are dropped (console, video stream, terminal, AI), so those clients
reconnect under the new grants. An account that loses `console.view` is sent to the landing page
instead of a console it can no longer open. Multiple
users may watch and control the KVM concurrently; input uses the existing cooperative HID
coordinator, so simultaneous input can interleave. A user without `console.control` keeps the
video and the menu for its other grants, but the console rejects keyboard and mouse reports and
the web UI marks the session as view only.
Video mode, quality, resolution, MJPEG frame-detection controls, and resetting the HDMI capture
require only `console.view` and stay shared KVM operations; when several users adjust them
concurrently, the latest change applies device-wide. Enabling or disabling the HDMI capture and
its idle timeout are device settings. `console.control` is input only: keyboard, mouse, paste, and
the input region that maps pointer motion onto the target screen.
The account file stores an explicit grant set: a record written before fine-grained permissions
keeps exactly what the user role used to grant, and the split media grants are translated on load,
so the store never holds a missing set that would fall back to different behavior later. Grants
this build does not know are preserved and ignored, so a downgrade cannot lock the device out.
Creating a regular account without naming a grant set keeps that same meaning, so a script that only
knows about roles gets the account the user role used to create; the account editor seeds a new
regular account with `console.view` only, and an explicitly empty set really is empty.
## Compile & Deploy
Note: Use Linux operating system (x86-64). This build process is not compatible with ARM, Windows or macOS.
Note: The manual steps below require a Linux x86-64 host with Go 1.25 or newer; they are not compatible with ARM, Windows or macOS. With Docker you can skip them entirely and use the containerized flow instead — the root [Makefile](../Makefile) (`make shell`) or the dev container (see "Development" in the root [README](../README.md)) — which works on any host OS; run `server/build.sh` inside the container for a release-equivalent build.
1. Install the Toolchain
1. Download the toolchain from the following link: [Download Link](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz).
@@ -75,8 +175,9 @@ Note: Use Linux operating system (x86-64). This build process is not compatible
2. Compile the Project
1. Run `cd server` from the project root directory.
2. Run `go mod tidy` to install Go dependencies.
3. Run `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` to compile the project.
4. After compilation, an executable file named `NanoKVM-Server` will be generated.
3. (Optional) If you compiled `libkvm.so` yourself, you need to modify its RPATH by `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so`.
4. Run `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` to compile the project.
5. After compilation, an executable file named `NanoKVM-Server` will be generated.
3. Modify RPATH
1. Run `sudo apt install patchelf` or `pip install patchelf` to install patchelf.

View File

@@ -16,7 +16,7 @@ server
├── middleware // サーバーミドルウェアコンポーネント
├── proto // API リクエスト/レスポンス定義
├── router // API ルートハンドラ
├── service // コアサービスの実<EFBFBD><EFBFBD>
├── service // コアサービスの実装
├── utils // ユーティリティ関数
└── main.go
```
@@ -27,6 +27,7 @@ server
```yaml
proto: http
host: ""
port:
http: 80
https: 443
@@ -39,17 +40,23 @@ cert:
logger:
level: info
file: stdout
# 認証設定 (enable/disable)
# 注意: 認証を無効にするのは開発環境でのみ行ってください
authentication: enable
# JWT 秘密鍵の設定
# 空のままにすると、サーバー起動時にランダムな鍵が生成されます
secretKey: ""
jwt:
# JWT 秘密鍵の設定。 空のままにすると、サーバー起動時にランダムな 64 バイトの鍵が自動的に生成されます。
secretKey: ""
# JWT トークンの有効期限(秒単位)。 デフォルト: 2678400 (31 日)
refreshTokenDuration: 2678400
# ユーザーがログアウトすると、すべての JWT トークンが無効になります。 デフォルト: true
revokeTokensOnLogout: true
# カスタム STUN サーバーのアドレス
stun: stun.l.google.com:19302
# カスタム TURN サーバーのアドレスと認証情報
turn:
turnAddr: turn.cloudflare.com:3478
turnUser: example_user
@@ -58,7 +65,7 @@ turn:
## コンパイルとデプロイ
注意: Linux オペレーティングシステム (x86-64) を使用してください。このビルドプロセスは ARM、Windows、macOS では互換性がありません。
注意: Linux オペレーティングシステム (x86-64) と Go 1.25 以降を使用してください。このビルドプロセスは ARM、Windows、macOS では互換性がありません。
1. ツールチェーンのインストール
1. 以下のリンクからツールチェーンをダウンロードします: [ダウンロードリンク](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz)。
@@ -80,3 +87,12 @@ turn:
1. デプロイ前に、ブラウザでアプリケーションを最新バージョンに更新します。手順は[こちら](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/system/updating.html)を参照してください。
2. コンパイルして生成された `NanoKVM-Server` ファイルを使用して、NanoKVM の `/kvmapp/server/` ディレクトリ内の元のファイルを置き換えます。
3. NanoKVM で `/etc/init.d/S95nanokvm restart` を実行してサービスを再起動します。
## 手動更新
> ファイルのアップロードには SSH が必要です。Web 設定で有効にしてください: `設定 > SSH`
1. [GitHub](https://github.com/sipeed/NanoKVM/releases) から最新のアプリケーションをダウンロードします。
2. ダウンロードしたファイルを解凍し、解凍したフォルダーの名前を `kvmapp` に変更します。
3. NanoKVM 上の既存の `/kvmapp` ディレクトリをバックアップし、新しい `kvmapp` フォルダーに置き換えます。
4. NanoKVM で `/etc/init.d/S95nanokvm restart` を実行してサービスを再起動します。

View File

@@ -24,43 +24,119 @@ server
配置文件路径为 `/etc/kvm/server.yaml`。
```yaml
proto: http
# 网络设置
proto: http # 访问协议,默认为 `http`,仅当配置了证书时支持改为 `https`
host: ""
port:
http: 80
https: 443
http: 80 # HTTP 服务的监听端口,默认为 `80`
https: 443 # HTTPS 服务的监听端口(启用 https 协议时生效),默认为 `443`
cert:
crt: server.crt
key: server.key
# 日志级别(debug/info/warn/error)
# 注意:在生产环境中使用 info 或 error。debug 模式仅在开发环境中使用。
crt: server.crt # HTTPS 服务使用的公钥证书路径
key: server.key # HTTPS 服务使用的私钥文件路径
# 日志配置
logger:
level: info
file: stdout
# 鉴权设置(enable/disable)
# 注意:生产环境中请勿使用 disable。
authentication: enable
level: info # 全局日志打印级别,从高到底可选 `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`。默认为 `info`
file: stdout # 日志输出目标位置。若填写 `stdout` 则输出在控制台。配置为文件路径则会输出到对应的文件。默认为 `stdout`
# 认证与安全
authentication: enable # 是否开启 HTTP 接口与网页的身份校验。可选 `enable` (开启) 或 `disable` (禁用)。默认为 `enable`。强烈建议公开在互联网的机器开启此项!
jwt:
# jwt 密钥。设置为空则使用随机生成的64位密钥
secretKey: ""
# jwt token 过期时间(单位:秒),默认为2678400(31天)
refreshTokenDuration: 2678400
# 在帐号登出时是否使所有 jwt token 失效。默认为 true
revokeTokensOnLogout: true
secretKey: "" # 用于签发和验证 JWT Token 的密钥。如果不填,服务启动时将自动随机生成
refreshTokenDuration: 2678400 # 登录超时的刷新周期(单位:秒)。默认为 `2678400`(约31天)
revokeTokensOnLogout: true # 退出登录时是否废除该用户的全部会话;不会影响其他用户。设为 false 时仅清除浏览器 Cookie,不推荐使用。默认为 `true`
security:
loginLockoutDuration: 0, # 达到失败上限后,禁止该 IP 再次尝试登录的持续时间(单位:秒)。如果设为 `0` 或不填,则代表不开启防暴力破解功能。默认为 `0`
loginMaxFailures: 5, # 允许触发保护前,单个 IP 连续登录失败的最大次数。默认为 `5`
stun: stun.l.google.com:19302
# WebRTC 内网穿透
stun: stun.l.google.com:19302 # 默认使用的 STUN 服务器地址,用于打洞获取公网 IP 建立 P2P 流
turn:
turnAddr: turn.cloudflare.com:3478
turnUser: example_user
turnCred: example_cred
turnAddr: example_addr # 当 P2P 直连失败时,作为备用的中继(TURN)服务器地址(格式如 `ip:port`)。留空表示不使用 TURN 中继
turnUser: example_user # TURN 服务器授权连接时使用的用户名
turnCred: example_cred # TURN 服务器授权连接时使用的凭据/密码
```
## Web 多用户
NanoKVM 使用两种设备级角色:
- `admin`:拥有以下全部能力,并可管理用户。
- `user`:仅拥有被授予的功能权限。
每项权限都描述“对谁做什么”,服务端下发给账户编辑器的权限目录还带有分组、风险等级和蕴含关系:
| 分组 | 权限 |
| --- | --- |
| 控制台(本会话) | `console.view`、`console.control` |
| 被控机 | `power`、`medium.attach` |
| 介质库(本设备) | `library.read`、`library.write` |
| 本设备 | `terminal`、`device`、`network`、`update` |
| 服务 | `mcp`、`tailscale`、`ai` |
蕴含关系只在权限目录里声明一次,并由服务端在应答任何请求前解析:`console.control` 蕴含
`console.view`,`medium.attach` 与 `library.write` 都蕴含 `library.read`;而控制项位于控制台菜单里的
权限——`power`、`device`、`network`、`update`、`mcp`、`tailscale`、`ai`——同样蕴含 `console.view`,
因为控制台之外没有任何页面渲染它们。由此得到几个行为:
- 账户可以完全没有控制台权限。此时 Web 界面会落到一个提示页,列出该账户可用的页面
(介质库、终端),而不是打开一个它无权访问的控制台。媒体功能只需要 `library.read`,
因为另外两项媒体权限都蕴含它;也只有 `terminal` 与媒体权限能拥有控制台之外的独立页面。
- 媒体权限按信任边界拆分:`medium.attach` 在被控机上挂载/弹出介质,并写入被控机可读的共享分区;
`library.write` 修改库内容(上传、删除、镜像内的文件);`library.read` 负责列表与下载。
文件相关接口用同一路径同时服务镜像与共享分区,因此路由同时接受这两项权限之一,
再按请求指定的介质类型做校验。分区上的每个 `.iso`、`.img` 都属于介质库,因此经共享分区上传这类文件,
或删除本身是/内含这类文件的文件或文件夹,同样需要 `library.write`。
- 模拟的 USB 设备既不属于媒体也不属于网络:虚拟磁盘与 RNDIS 虚拟网卡分别把设备的原始数据分区
和一块网卡交给被控机,因此都归 `device`。只有拥有 `device` 权限的账户开启虚拟磁盘后,才能挂载
镜像;磁盘未开启时存储页面会给出提示。
以下四项权限的实际范围比名称更大,等同于完整的设备控制权;权限目录只有两个风险等级,`warn`
专用于它们,账户编辑器会做标记并在保存前按名称列出:
- `terminal`:即 root shell(与 SSH 相同),并可运行已保存的脚本和开机自启脚本。
- `mcp`:会下发设备级 API Key,可在 Web 会话之外控制键鼠并获取截图。Key 为共用,账户失去该权限后已复制的
Key 仍然有效。任何会让账户失去该权限的操作(撤销、降级、禁用或删除),账户编辑器都会警告并提供「重新生成
Key」选项(默认勾选);重新生成会断开所有 MCP 客户端直到换用新 Key,管理员选择保留则自行承担副本仍有效的风险。
API 通过 `rotateMcpKey` 传递该选择(更新时放在请求体,删除时放在查询参数),不带它就不会轮换。
- `ai`:通过本地回环接口操作设备,不受其他权限限制。
- `update`:安装固件与应用更新包。离线包只校验上传者自己提供的校验和,安装它即等于以 root 运行代码。
`device` 不做该标记:它仍在本账户被授予的设置范围内,但会改变设备对所有人生效的行为,
且无法按账户收窄。`device` 可开关 SSH(root,口令为设备所有者口令)、重启设备、通过模拟的 USB 设备把
原始数据分区或网卡交给被控机,并修改 OLED、HDMI、mDNS、内存、交换与 HID 设置。编辑器中对此同样有说明。
另有两项权限会改动影响所有观看者的设置:`console.view` 会设置视频模式、分辨率、帧率与画质,
并复位 HDMI 采集;`power` 会管理网络唤醒设备列表。编辑器中对这两项都有明确说明。
管理员可在**设置 > 账户**中管理用户。账户数据继续保存在 `/etc/kvm/pwd`;服务会原地迁移旧版单账户
JSON,并以 `0600` 权限原子写入多用户格式。沿用同一路径可保持长按 BOOT 键重置密码的现有行为。
用户自助修改密码时必须验证当前密码;管理员可在账户管理中重置非设备所有者的密码。由于设备所有者
密码还会同步至 Linux root 账户,因此只有设备所有者本人可以修改自己的密码。
所有登录会话都会校验当前账户状态:每个请求都按账户文件重新授权,因此被撤销的权限会立即失效,
无需重新登录。禁用、删除或重置密码会立即撤销该用户的 HTTP 与实时连接,且不会影响其他用户。
修改角色或权限不会失效登录:账户会收到刷新通知,只会断开缓存了相关状态的长期连接
(控制台、视频流、终端、AI),这些客户端随后会以新权限重连。失去 `console.view` 的账户会被
转到提示页,而不是一个无法打开的控制台。多个用户可同时观看和协作控制 KVM;输入沿用现有 HID
协调器,因此同时输入可能交错。没有 `console.control` 的用户仍可观看画面并使用其其他权限对应的菜单,
但控制台会丢弃其键鼠报文,Web 界面会将会话标记为只读。
视频模式、画质、分辨率、MJPEG 帧检测以及复位 HDMI 采集只要求 `console.view`,仍属于共享 KVM 操作;
多人同时调整时,以最后一次设备级修改为准。启用/关闭 HDMI 采集及其空闲超时则属于设备设置。
`console.control` 仅限输入:键盘、鼠标、粘贴,以及将指针位移映射到目标机画面的输入区域。
账户文件保存的是显式权限集合:细粒度权限出现之前写入的记录,在读取时会物化为当时 user 角色的
能力,拆分过的媒体权限也会被翻译成新名称,因此存储中不会留下“缺失即回退到另一套行为”的状态。
本版本不认识的权限会被原样保留并忽略,因此回滚版本不会把设备锁在门外。
新建普通账户时若不指定权限集合,含义同上:只认识角色的脚本仍会得到 user 角色过去创建出的账户;
账户编辑器新建普通账户时只预置 `console.view`,而显式传入的空集合就是真的空。
## 编译部署
**注意:请使用 Linux 操作系统(x86-64)。该工具链无法在 ARM、Windows 或 macOS 下使用。**
**注意:请使用 Linux 操作系统(x86-64)和 Go 1.25 或更高版本。该工具链无法在 ARM、Windows 或 macOS 下使用。**
1. 安装工具链
1. 下载工具链:[下载地址](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz);
@@ -70,8 +146,9 @@ turn:
2. 编译
1. 在项目根目录下执行 `cd server` 进入 server 目录;
2. 执行 `go mod tidy` 安装 Go 依赖包;
3. 执行 `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` 进行编译;
4. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
3. (可选)如果您手动编译了 `libkvm.so`,则需要通过 `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so` 修改其 RPATH 属性。
4. 执行 `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` 进行编译;
5. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
3. 修改 RPATH
1. 执行 `sudo apt install patchelf` 或 `pip install patchelf` 安装 patchelf;
@@ -79,8 +156,8 @@ turn:
3. 执行 `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` 修改可执行文件的 RPATH 属性。
4. 部署
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
3. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
## 手动更新
@@ -90,4 +167,4 @@ turn:
1. 从 [GitHub](https://github.com/sipeed/NanoKVM/releases) 下载最新的应用安装包;
2. 解压缩下载的安装包,并将解压后的文件夹重命名为 `kvmapp`;
3. 备份 NanoKVM 系统中的 `/kvmapp` 目录,然后用解压后的 `kvmapp` 文件夹替换现有目录。
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。

322
server/authn/permissions.go Normal file
View File

@@ -0,0 +1,322 @@
package authn
import (
"fmt"
)
// Permission identifies a grantable capability. The admin role implicitly holds
// every permission; the user role only holds the permissions stored on the
// account.
//
// A permission names what it lets the account do, not the settings page it
// lives on, and every grant that changes something shared says so in the
// catalog's risk and effect metadata instead of in the label alone.
type Permission string
const (
// Console grants.
PermConsoleView Permission = "console.view"
PermConsoleControl Permission = "console.control"
// Target-machine grants.
PermPower Permission = "power"
PermMediumAttach Permission = "medium.attach"
// Media library grants.
PermLibraryRead Permission = "library.read"
PermLibraryWrite Permission = "library.write"
// Host grants.
PermTerminal Permission = "terminal"
PermDevice Permission = "device"
PermNetwork Permission = "network"
PermUpdate Permission = "update"
// Service grants.
PermMcp Permission = "mcp"
PermTailscale Permission = "tailscale"
PermAi Permission = "ai"
)
// Group names the party a grant reaches. The account editor renders one section
// per group, so the sections stay meaningful as the catalog grows.
type Group string
const (
// GroupConsole is what an account may do with the console it is watching.
GroupConsole Group = "console"
// GroupTarget is what it may do to the machine behind the console.
GroupTarget Group = "target"
// GroupLibrary is what it may do with the media library on this device.
GroupLibrary Group = "library"
// GroupHost is what it may change on this device.
GroupHost Group = "host"
// GroupServices are the add-ons that reach the device on their own.
GroupServices Group = "services"
)
// Risk states how far a grant reaches, and the catalog carries two levels: a
// plain grant, and the grants that amount to full device control, which the
// account editor marks and names before the grants are saved.
type Risk string
const (
// RiskInfo is a grant that stays within the feature it names.
RiskInfo Risk = "info"
// RiskWarn is a grant that amounts to full device control: a root shell,
// the AI loopback, an API key that drives input outside the web session, and
// a package install whose checksum the uploader supplies.
RiskWarn Risk = "warn"
)
// Descriptor is one catalog entry: the grant, the group it belongs to, the risk
// an administrator takes by granting it, and the grants it implies.
type Descriptor struct {
Permission Permission `json:"id"`
Group Group `json:"group"`
Risk Risk `json:"risk"`
Implies []Permission `json:"implies,omitempty"`
}
// Implied grants are declared once here instead of as unions at every call
// site: control without the picture is meaningless, nothing can be attached or
// changed in the library without being allowed to see it first, and the grants
// whose controls live in the console menu imply the console, because no page
// outside it renders them and a grant nothing can use is a promise the app
// cannot keep. Terminal and the media grants stand on their own pages.
var permissionCatalog = []Descriptor{
{Permission: PermConsoleView, Group: GroupConsole, Risk: RiskInfo},
{
Permission: PermConsoleControl,
Group: GroupConsole,
Risk: RiskInfo,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermPower,
Group: GroupTarget,
Risk: RiskInfo,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermMediumAttach,
Group: GroupTarget,
Risk: RiskInfo,
Implies: []Permission{PermLibraryRead},
},
{Permission: PermLibraryRead, Group: GroupLibrary, Risk: RiskInfo},
{
Permission: PermLibraryWrite,
Group: GroupLibrary,
Risk: RiskInfo,
Implies: []Permission{PermLibraryRead},
},
{Permission: PermTerminal, Group: GroupHost, Risk: RiskWarn},
{
Permission: PermDevice,
Group: GroupHost,
Risk: RiskInfo,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermNetwork,
Group: GroupHost,
Risk: RiskInfo,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermUpdate,
Group: GroupHost,
Risk: RiskWarn,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermMcp,
Group: GroupServices,
Risk: RiskWarn,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermTailscale,
Group: GroupServices,
Risk: RiskInfo,
Implies: []Permission{PermConsoleView},
},
{
Permission: PermAi,
Group: GroupServices,
Risk: RiskWarn,
Implies: []Permission{PermConsoleView},
},
}
// Grants of earlier releases, kept so an account file written by one of them
// keeps meaning what it meant. media.mount and media.manage split into the
// attach/read/write grants above.
const (
legacyPermMediaMount Permission = "media.mount"
legacyPermMediaManage Permission = "media.manage"
)
// Catalog returns the catalog in display order.
func Catalog() []Descriptor {
catalog := make([]Descriptor, len(permissionCatalog))
for index, descriptor := range permissionCatalog {
catalog[index] = descriptor
catalog[index].Implies = append([]Permission(nil), descriptor.Implies...)
}
return catalog
}
// PermissionIDs returns every grantable permission in catalog order.
func PermissionIDs() []Permission {
ids := make([]Permission, 0, len(permissionCatalog))
for _, descriptor := range permissionCatalog {
ids = append(ids, descriptor.Permission)
}
return ids
}
func IsValidPermission(permission Permission) bool {
for _, descriptor := range permissionCatalog {
if descriptor.Permission == permission {
return true
}
}
return false
}
// ValidatePermissions rejects unknown or duplicate permissions. It is for grant
// sets arriving in a request; the grant set stored on an account is validated by
// ValidateStoredPermissions, which tolerates ids this build does not know.
func ValidatePermissions(permissions []Permission) error {
seen := make(map[Permission]struct{}, len(permissions))
for _, permission := range permissions {
if !IsValidPermission(permission) {
return fmt.Errorf("unknown permission: %q", permission)
}
if _, exists := seen[permission]; exists {
return fmt.Errorf("duplicate permission: %q", permission)
}
seen[permission] = struct{}{}
}
return nil
}
// ValidateStoredPermissions only rejects duplicates. An account file written by
// a newer release carries grants this build cannot evaluate, and refusing to
// load it would lock the device out instead of ignoring a capability that is
// unavailable here anyway.
func ValidateStoredPermissions(permissions []Permission) error {
seen := make(map[Permission]struct{}, len(permissions))
for _, permission := range permissions {
if _, exists := seen[permission]; exists {
return fmt.Errorf("duplicate permission: %q", permission)
}
seen[permission] = struct{}{}
}
return nil
}
// Has reports whether the set contains the permission. Administrators are not
// special-cased: callers that should honor the role's implicit grants resolve
// EffectivePermissions first.
func Has(permissions []Permission, permission Permission) bool {
for _, granted := range permissions {
if granted == permission {
return true
}
}
return false
}
// Closure resolves the grants an account ends up holding: the set itself plus
// everything it implies, transitively, in catalog order.
func Closure(permissions []Permission) []Permission {
granted := closureSet(permissions)
resolved := make([]Permission, 0, len(granted))
for _, descriptor := range permissionCatalog {
if _, ok := granted[descriptor.Permission]; ok {
resolved = append(resolved, descriptor.Permission)
delete(granted, descriptor.Permission)
}
}
// Keep ids this build does not know in the order they were stored, so they
// still round-trip through the client.
for _, permission := range permissions {
if _, ok := granted[permission]; ok {
resolved = append(resolved, permission)
delete(granted, permission)
}
}
return resolved
}
func closureSet(permissions []Permission) map[Permission]struct{} {
granted := make(map[Permission]struct{}, len(permissions))
var add func(Permission)
add = func(permission Permission) {
if _, exists := granted[permission]; exists {
return
}
granted[permission] = struct{}{}
for _, descriptor := range permissionCatalog {
if descriptor.Permission != permission {
continue
}
for _, implied := range descriptor.Implies {
add(implied)
}
}
}
for _, permission := range permissions {
add(permission)
}
return granted
}
// NormalizeStoredPermissions translates the grants an earlier release wrote and
// removes duplicates, so the store holds one spelling of every capability.
// Unknown ids are preserved: a downgrade must not silently drop a grant.
func NormalizeStoredPermissions(permissions []Permission) []Permission {
normalized := make([]Permission, 0, len(permissions)+2)
appendOnce := func(permission Permission) {
if !Has(normalized, permission) {
normalized = append(normalized, permission)
}
}
for _, permission := range permissions {
switch permission {
case legacyPermMediaMount:
// Attaching a medium is what let a watcher read the library.
appendOnce(PermMediumAttach)
appendOnce(PermLibraryRead)
case legacyPermMediaManage:
appendOnce(PermLibraryRead)
appendOnce(PermLibraryWrite)
default:
appendOnce(permission)
}
}
return normalized
}
// legacyUserPermissions preserves the capabilities the user role had before
// fine-grained permissions existed: full console access and power control.
func legacyUserPermissions() []Permission {
return []Permission{PermConsoleView, PermConsoleControl, PermPower}
}
// EffectivePermissions resolves what a user can actually do: administrators
// hold the whole catalog, regular users hold their stored grants and whatever
// those imply.
func EffectivePermissions(user *User) []Permission {
if user == nil {
return nil
}
if user.Role == RoleAdmin {
return PermissionIDs()
}
return Closure(user.Permissions)
}

View File

@@ -0,0 +1,86 @@
package authn
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"testing"
)
func TestClosureResolvesImpliedGrants(t *testing.T) {
cases := []struct {
grants []Permission
want []Permission
}{
{[]Permission{PermConsoleControl}, []Permission{PermConsoleView, PermConsoleControl}},
{[]Permission{PermMediumAttach}, []Permission{PermMediumAttach, PermLibraryRead}},
{[]Permission{PermLibraryWrite}, []Permission{PermLibraryRead, PermLibraryWrite}},
{[]Permission{PermTerminal}, []Permission{PermTerminal}},
{[]Permission{"future.grant", PermMcp}, []Permission{PermConsoleView, PermMcp, "future.grant"}},
}
for _, tc := range cases {
if got := Closure(tc.grants); !slices.Equal(got, tc.want) {
t.Errorf("Closure(%v) = %v, want %v", tc.grants, got, tc.want)
}
}
}
func TestNormalizeTranslatesLegacyMediaGrants(t *testing.T) {
got := NormalizeStoredPermissions([]Permission{legacyPermMediaMount, legacyPermMediaManage, PermPower})
want := []Permission{PermMediumAttach, PermLibraryRead, PermLibraryWrite, PermPower}
if !slices.Equal(got, want) {
t.Fatalf("NormalizeStoredPermissions = %v, want %v", got, want)
}
}
func TestUpdateReturnsPreviousAndKeepsUnknownGrants(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
store := NewStore(path)
if err := store.Create("alice", "password", RoleUser, PermConsoleView); err != nil {
t.Fatal(err)
}
// A newer release stored a grant this build does not know.
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var db database
if err = json.Unmarshal(data, &db); err != nil {
t.Fatal(err)
}
index := userIndex(db.Users, "alice")
db.Users[index].Permissions = append(db.Users[index].Permissions, "future.grant")
if data, err = json.Marshal(db); err != nil {
t.Fatal(err)
}
if err = os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
grants := []Permission{PermConsoleControl}
previous, updated, err := store.Update("admin", "alice", UserPatch{Permissions: &grants})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(previous.Permissions, []Permission{PermConsoleView, "future.grant"}) {
t.Fatalf("previous permissions = %v", previous.Permissions)
}
if !slices.Equal(updated.Permissions, []Permission{PermConsoleControl, "future.grant"}) {
t.Fatalf("updated permissions = %v", updated.Permissions)
}
}
func TestOnlyFullControlGrantsWarn(t *testing.T) {
var warned []Permission
for _, descriptor := range Catalog() {
if descriptor.Risk == RiskWarn {
warned = append(warned, descriptor.Permission)
}
}
want := []Permission{PermTerminal, PermUpdate, PermMcp, PermAi}
if !slices.Equal(warned, want) {
t.Fatalf("warned grants = %v, want %v", warned, want)
}
}

719
server/authn/store.go Normal file
View File

@@ -0,0 +1,719 @@
package authn
import (
"crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sync"
"NanoKVM-Server/utils"
"golang.org/x/crypto/bcrypt"
)
const (
AccountFile = "/etc/kvm/pwd"
currentFileVersion = 1
defaultUsername = "admin"
defaultPassword = "admin"
)
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserExists = errors.New("username already exists")
ErrLastAdmin = errors.New("at least one enabled admin is required")
ErrSelfModification = errors.New("administrators cannot disable or demote themselves")
ErrSelfDelete = errors.New("administrators cannot delete themselves")
ErrSystemAccount = errors.New("the device owner account must remain an enabled administrator")
usernamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,31}$`)
)
type User struct {
Username string `json:"username"`
PasswordHash string `json:"password"`
Role Role `json:"role"`
Enabled bool `json:"enabled"`
TokenVersion uint64 `json:"tokenVersion"`
Permissions []Permission `json:"permissions"`
MustChangePassword bool `json:"mustChangePassword,omitempty"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type UserInfo struct {
Username string `json:"username"`
Role Role `json:"role"`
Enabled bool `json:"enabled"`
Permissions []Permission `json:"permissions"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type UserPatch struct {
Role *Role
Enabled *bool
Permissions *[]Permission
}
type database struct {
Version int `json:"version"`
Users []User `json:"users"`
LegacyUsername string `json:"username,omitempty"`
LegacyPassword string `json:"password,omitempty"`
}
type legacyAccount struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Store struct {
path string
mutex sync.RWMutex
}
var DefaultStore = NewStore(AccountFile)
func NewStore(path string) *Store {
return &Store{path: path}
}
func IsValidRole(role Role) bool {
return role == RoleAdmin || role == RoleUser
}
func ValidateUsername(username string) error {
if !usernamePattern.MatchString(username) {
return errors.New("username must be 1-32 characters and contain only letters, numbers, '.', '_' or '-'")
}
return nil
}
func ValidatePassword(password string) error {
length := len([]byte(password))
if length < 8 || length > 72 {
return errors.New("password must be between 8 and 72 bytes")
}
return nil
}
func (s *Store) List() ([]UserInfo, error) {
s.mutex.RLock()
defer s.mutex.RUnlock()
db, err := s.loadLocked(false)
if err != nil {
return nil, err
}
users := make([]UserInfo, 0, len(db.Users))
for index := range db.Users {
user := &db.Users[index]
// The stored grants, not the effective ones: the editor shows what an
// administrator set, and what an account implies is derived from the
// catalog instead of being written back on every save.
users = append(users, UserInfo{
Username: user.Username,
Role: user.Role,
Enabled: user.Enabled,
Permissions: clonePermissions(user.Permissions),
SystemAccount: user.SystemAccount,
})
}
return users, nil
}
func (s *Store) Get(username string) (*User, error) {
s.mutex.RLock()
defer s.mutex.RUnlock()
db, err := s.loadLocked(false)
if err != nil {
return nil, err
}
return findUser(db.Users, username)
}
func (s *Store) Authenticate(username, password string) (*User, bool, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, false, err
}
user, err := findUser(db.Users, username)
if err != nil || !user.Enabled {
return nil, false, nil
}
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)) == nil {
return user, true, nil
}
// Older releases stored a reversibly encrypted password. Upgrade it after
// the first successful login so the compatibility path is not permanent.
legacyPassword, decodeErr := utils.DecodeDecrypt(user.PasswordHash)
if decodeErr != nil || legacyPassword != password {
return nil, false, nil
}
hash, hashErr := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if hashErr != nil {
return nil, false, hashErr
}
for index := range db.Users {
if db.Users[index].Username == username {
db.Users[index].PasswordHash = string(hash)
if db.Users[index].TokenVersion == 0 {
db.Users[index].TokenVersion = 1
}
user = cloneUser(&db.Users[index])
break
}
}
if err = s.saveLocked(db); err != nil {
return nil, false, err
}
return user, true, nil
}
func (s *Store) ValidateToken(username string, tokenVersion uint64) (*User, error) {
user, err := s.Get(username)
if err != nil {
return nil, err
}
if !user.Enabled || user.TokenVersion != tokenVersion {
return nil, errors.New("session revoked")
}
return user, nil
}
func (s *Store) Create(username, password string, role Role, permissions ...Permission) error {
if err := ValidateUsername(username); err != nil {
return err
}
if err := ValidatePassword(password); err != nil {
return err
}
if !IsValidRole(role) {
return errors.New("invalid role")
}
// A nil set means the caller named none at all, which keeps the meaning it
// had before grants existed: an account created by a script that only knows
// about roles gets what the user role granted then. An explicit empty set is
// a decision and stays empty, so the account really holds nothing.
if permissions == nil && role == RoleUser {
permissions = legacyUserPermissions()
}
if err := ValidatePermissions(permissions); err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
tokenVersion, err := newTokenVersion()
if err != nil {
return err
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return err
}
if _, err = findUser(db.Users, username); err == nil {
return ErrUserExists
}
db.Users = append(db.Users, User{
Username: username,
PasswordHash: string(hash),
Role: role,
Enabled: true,
TokenVersion: tokenVersion,
Permissions: NormalizeStoredPermissions(permissions),
})
return s.saveLocked(db)
}
// Update applies the patch and returns the account as it was before and after,
// both read under the store lock, so a caller comparing the two sees exactly the
// change it made even while another update runs.
func (s *Store) Update(actor, username string, patch UserPatch) (previous, updated *User, err error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, nil, ErrUserNotFound
}
previous = cloneUser(&db.Users[index])
user := db.Users[index]
if patch.Role != nil && !IsValidRole(*patch.Role) {
return nil, nil, errors.New("invalid role")
}
// The patch is normalized before it is compared and stored, so a caller that
// still sends the split media grants does not look like a change once they
// resolve to the grants they now mean.
granted := user.Permissions
if patch.Permissions != nil {
if err := ValidatePermissions(*patch.Permissions); err != nil {
return nil, nil, err
}
granted = NormalizeStoredPermissions(*patch.Permissions)
// A request can only name grants this build knows, so the ones it does
// not (written by a newer release) are carried over instead of being
// dropped by an editor that never showed them.
for _, permission := range user.Permissions {
if !IsValidPermission(permission) && !Has(granted, permission) {
granted = append(granted, permission)
}
}
}
if actor == username && user.Role == RoleAdmin &&
((patch.Role != nil && *patch.Role != RoleAdmin) || (patch.Enabled != nil && !*patch.Enabled)) {
return nil, nil, ErrSelfModification
}
if user.SystemAccount &&
((patch.Role != nil && *patch.Role != RoleAdmin) || (patch.Enabled != nil && !*patch.Enabled)) {
return nil, nil, ErrSystemAccount
}
changed := false
// Only disabling the account invalidates its login. A role change does not:
// the principal is rebuilt from the account file on every request, and the
// caller refreshes the user's long-lived connections so they reconnect under
// the role's new grants. Bumping the token version for a role change would
// log the account out mid-session just because it was promoted or demoted.
loginInvalidated := false
if patch.Role != nil && user.Role != *patch.Role {
user.Role = *patch.Role
changed = true
}
if patch.Enabled != nil && user.Enabled != *patch.Enabled {
user.Enabled = *patch.Enabled
changed = true
loginInvalidated = true
}
if patch.Permissions != nil && !permissionsEqual(user.Permissions, granted) {
user.Permissions = granted
changed = true
}
if !changed {
return previous, cloneUser(&user), nil
}
db.Users[index] = user
if enabledAdminCount(db.Users) == 0 {
return nil, nil, ErrLastAdmin
}
// Permission and role updates keep the login valid: the principal is rebuilt
// from the store on every request, so new grants apply immediately and
// revoked ones are enforced by dropping connections from the handler.
if loginInvalidated {
db.Users[index].TokenVersion++
}
if err = s.saveLocked(db); err != nil {
return nil, nil, err
}
return previous, cloneUser(&db.Users[index]), nil
}
func (s *Store) Delete(actor, username string) error {
if actor == username {
return ErrSelfDelete
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return err
}
index := userIndex(db.Users, username)
if index < 0 {
return ErrUserNotFound
}
if db.Users[index].SystemAccount {
return ErrSystemAccount
}
users := append([]User(nil), db.Users[:index]...)
users = append(users, db.Users[index+1:]...)
if enabledAdminCount(users) == 0 {
return ErrLastAdmin
}
db.Users = users
return s.saveLocked(db)
}
func (s *Store) SetPassword(username, password string) (*User, error) {
return s.SetPasswordAndRun(username, password, nil)
}
// SetPasswordAndRun commits the web password before running the optional
// system-side update. If that update fails, the account record is rolled back
// while the store lock is still held.
func (s *Store) SetPasswordAndRun(username, password string, afterCommit func() error) (*User, error) {
if err := ValidatePassword(password); err != nil {
return nil, err
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, ErrUserNotFound
}
previous := *db
previous.Users = append([]User(nil), db.Users...)
db.Users[index].PasswordHash = string(hash)
db.Users[index].MustChangePassword = false
db.Users[index].TokenVersion++
if err = s.saveLocked(db); err != nil {
return nil, err
}
if afterCommit != nil {
if err = afterCommit(); err != nil {
if rollbackErr := s.saveLocked(&previous); rollbackErr != nil {
return nil, fmt.Errorf("system password update failed: %v; account rollback failed: %w", err, rollbackErr)
}
return nil, err
}
}
return cloneUser(&db.Users[index]), nil
}
func (s *Store) Revoke(username string) (*User, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, ErrUserNotFound
}
db.Users[index].TokenVersion++
if err = s.saveLocked(db); err != nil {
return nil, err
}
return cloneUser(&db.Users[index]), nil
}
func (s *Store) loadLocked(migrate bool) (*database, error) {
data, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
db, defaultErr := defaultDatabase()
if defaultErr != nil {
return nil, defaultErr
}
materializePermissions(db)
if migrate {
if saveErr := s.saveLocked(db); saveErr != nil {
return nil, saveErr
}
}
return db, nil
}
if err != nil {
return nil, err
}
var db database
if err = json.Unmarshal(data, &db); err == nil && db.Version != 0 {
materializePermissions(&db)
if err = validateDatabase(&db); err != nil {
return nil, err
}
return &db, nil
}
var legacy legacyAccount
if err = json.Unmarshal(data, &legacy); err != nil || legacy.Username == "" || legacy.Password == "" {
return nil, errors.New("invalid account file")
}
if err = ValidateUsername(legacy.Username); err != nil {
return nil, fmt.Errorf("invalid legacy username: %w", err)
}
tokenVersion, err := newTokenVersion()
if err != nil {
return nil, err
}
db = database{
Version: currentFileVersion,
Users: []User{{
Username: legacy.Username,
PasswordHash: legacy.Password,
Role: RoleAdmin,
Enabled: true,
TokenVersion: tokenVersion,
MustChangePassword: passwordMatches(legacy.Password, defaultPassword),
SystemAccount: true,
}},
}
materializePermissions(&db)
if migrate {
if err = s.saveLocked(&db); err != nil {
return nil, err
}
}
return &db, nil
}
func (s *Store) saveLocked(db *database) error {
if err := validateDatabase(db); err != nil {
return err
}
syncLegacyAccount(db)
data, err := json.MarshalIndent(db, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
directory := filepath.Dir(s.path)
if err = os.MkdirAll(directory, 0o755); err != nil {
return err
}
temporary, err := os.CreateTemp(directory, ".pwd-*")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer func() { _ = os.Remove(temporaryPath) }()
if err = temporary.Chmod(0o600); err == nil {
_, err = temporary.Write(data)
}
if err == nil {
err = temporary.Sync()
}
closeErr := temporary.Close()
if err == nil {
err = closeErr
}
if err != nil {
return err
}
if err = os.Rename(temporaryPath, s.path); err != nil {
return err
}
dir, err := os.Open(directory)
if err != nil {
return err
}
defer func() { _ = dir.Close() }()
return dir.Sync()
}
func defaultDatabase() (*database, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(defaultPassword), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
tokenVersion, err := newTokenVersion()
if err != nil {
return nil, err
}
return &database{
Version: currentFileVersion,
Users: []User{{
Username: defaultUsername,
PasswordHash: string(hash),
Role: RoleAdmin,
Enabled: true,
TokenVersion: tokenVersion,
MustChangePassword: true,
SystemAccount: true,
}},
}, nil
}
func newTokenVersion() (uint64, error) {
var data [8]byte
for {
if _, err := rand.Read(data[:]); err != nil {
return 0, err
}
version := binary.LittleEndian.Uint64(data[:])
if version != 0 && version != ^uint64(0) {
return version, nil
}
}
}
func validateDatabase(db *database) error {
if db.Version != currentFileVersion {
return fmt.Errorf("unsupported account file version: %d", db.Version)
}
if len(db.Users) == 0 {
return errors.New("account file contains no users")
}
seen := make(map[string]struct{}, len(db.Users))
systemAccounts := 0
for index := range db.Users {
user := &db.Users[index]
if err := ValidateUsername(user.Username); err != nil {
return err
}
if user.PasswordHash == "" || !IsValidRole(user.Role) {
return errors.New("account file contains an invalid user")
}
if err := ValidateStoredPermissions(user.Permissions); err != nil {
return fmt.Errorf("account file contains invalid permissions for %q: %w", user.Username, err)
}
if _, exists := seen[user.Username]; exists {
return errors.New("account file contains duplicate usernames")
}
seen[user.Username] = struct{}{}
if user.TokenVersion == 0 {
user.TokenVersion = 1
}
if user.SystemAccount {
systemAccounts++
if user.Role != RoleAdmin || !user.Enabled || systemAccounts > 1 {
return ErrSystemAccount
}
}
}
if enabledAdminCount(db.Users) == 0 {
return ErrLastAdmin
}
return nil
}
func findUser(users []User, username string) (*User, error) {
index := userIndex(users, username)
if index < 0 {
return nil, ErrUserNotFound
}
return cloneUser(&users[index]), nil
}
func userIndex(users []User, username string) int {
for index := range users {
if users[index].Username == username {
return index
}
}
return -1
}
// materializePermissions replaces the grant shapes of earlier releases with an
// explicit set: an account that predates fine-grained permissions keeps exactly
// what the user role used to grant, and the split media grants are translated.
// After this the store never holds a nil set, so "no grants" and "never
// configured" can no longer be confused, and no caller has to special-case nil.
func materializePermissions(db *database) {
for index := range db.Users {
if db.Users[index].Permissions == nil {
db.Users[index].Permissions = legacyUserPermissions()
continue
}
db.Users[index].Permissions = NormalizeStoredPermissions(db.Users[index].Permissions)
}
}
func clonePermissions(permissions []Permission) []Permission {
return append([]Permission{}, permissions...)
}
func permissionsEqual(a, b []Permission) bool {
if (a == nil) != (b == nil) {
return false
}
if len(a) != len(b) {
return false
}
// The stored order carries no meaning, so a reordering must not look like
// a change worth writing back.
seen := make(map[Permission]struct{}, len(a))
for _, permission := range a {
seen[permission] = struct{}{}
}
for _, permission := range b {
if _, exists := seen[permission]; !exists {
return false
}
}
return true
}
func enabledAdminCount(users []User) int {
count := 0
for _, user := range users {
if user.Role == RoleAdmin && user.Enabled {
count++
}
}
return count
}
func cloneUser(user *User) *User {
if user == nil {
return nil
}
copy := *user
return &copy
}
func passwordMatches(hash, password string) bool {
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil {
return true
}
legacyPassword, err := utils.DecodeDecrypt(hash)
return err == nil && legacyPassword == password
}
// Keep a legacy top-level account mirror so downgrading to a single-user
// server still authenticates the original device owner instead of failing
// open or forcing an immediate physical reset.
func syncLegacyAccount(db *database) {
db.LegacyUsername = ""
db.LegacyPassword = ""
var fallback *User
for _, user := range db.Users {
if user.SystemAccount {
db.LegacyUsername = user.Username
db.LegacyPassword = user.PasswordHash
return
}
if fallback == nil && user.Role == RoleAdmin && user.Enabled {
copy := user
fallback = &copy
}
}
if fallback != nil {
db.LegacyUsername = fallback.Username
db.LegacyPassword = fallback.PasswordHash
}
}

212
server/authn/store_test.go Normal file
View File

@@ -0,0 +1,212 @@
package authn
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"golang.org/x/crypto/bcrypt"
)
func TestLegacyAccountMigratesInPlace(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
hash, err := bcrypt.GenerateFromPassword([]byte("legacy-password"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
legacy, _ := json.Marshal(legacyAccount{Username: "owner", Password: string(hash)})
if err = os.WriteFile(path, legacy, 0o644); err != nil {
t.Fatal(err)
}
store := NewStore(path)
user, ok, err := store.Authenticate("owner", "legacy-password")
if err != nil || !ok {
t.Fatalf("authenticate migrated account: ok=%v err=%v", ok, err)
}
if user.Role != RoleAdmin || !user.SystemAccount || user.TokenVersion == 0 {
t.Fatalf("unexpected migrated user: %+v", user)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var db database
if err = json.Unmarshal(data, &db); err != nil {
t.Fatalf("account file was not migrated: %v", err)
}
if db.Version != currentFileVersion || len(db.Users) != 1 {
t.Fatalf("unexpected database: %+v", db)
}
var downgrade legacyAccount
if err = json.Unmarshal(data, &downgrade); err != nil || downgrade.Username != "owner" || downgrade.Password == "" {
t.Fatalf("legacy downgrade mirror is invalid: %+v, %v", downgrade, err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("account mode = %o, want 600", info.Mode().Perm())
}
}
func TestCorruptAccountFileFailsClosed(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
if err := os.WriteFile(path, []byte("not json"), 0o600); err != nil {
t.Fatal(err)
}
_, ok, err := NewStore(path).Authenticate("admin", "admin")
if err == nil || ok {
t.Fatalf("corrupt file must fail closed: ok=%v err=%v", ok, err)
}
}
func TestUserLifecycleAndTokenRevocation(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("alice", "correct-horse", RoleUser); err != nil {
t.Fatal(err)
}
if _, ok, err := store.Authenticate("alice", "wrong-password"); err != nil || ok {
t.Fatalf("wrong password login: ok=%v err=%v", ok, err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err != nil {
t.Fatal(err)
}
if _, err = store.SetPassword("alice", "new-password"); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err == nil {
t.Fatal("old token stayed valid after password change")
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || !ok {
t.Fatalf("new password login: ok=%v err=%v", ok, err)
}
disabled := false
if _, _, err = store.Update("admin", "alice", UserPatch{Enabled: &disabled}); err != nil {
t.Fatal(err)
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || ok {
t.Fatalf("disabled login: ok=%v err=%v", ok, err)
}
enabled := true
if _, _, err = store.Update("admin", "alice", UserPatch{Enabled: &enabled}); err != nil {
t.Fatal(err)
}
if err = store.Delete("admin", "alice"); err != nil {
t.Fatal(err)
}
if _, err = store.Get("alice"); !errors.Is(err, ErrUserNotFound) {
t.Fatalf("deleted user lookup error = %v", err)
}
}
func TestLastAdminAndSelfProtection(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
userRole := RoleUser
if _, _, err := store.Update("admin", "admin", UserPatch{Role: &userRole}); !errors.Is(err, ErrSelfModification) {
t.Fatalf("self demotion error = %v", err)
}
if err := store.Delete("admin", "admin"); !errors.Is(err, ErrSelfDelete) {
t.Fatalf("self delete error = %v", err)
}
if err := store.Create("second", "second-password", RoleAdmin); err != nil {
t.Fatal(err)
}
disabled := false
if _, _, err := store.Update("second", "admin", UserPatch{Enabled: &disabled}); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("disable device owner error = %v", err)
}
if _, _, err := store.Update("second", "admin", UserPatch{Role: &userRole}); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("demote device owner error = %v", err)
}
if err := store.Delete("second", "admin"); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("delete device owner error = %v", err)
}
if err := store.Delete("admin", "second"); err != nil {
t.Fatal(err)
}
}
func TestRemovedAccountFileAndRecreatedUserInvalidateOldVersions(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
store := NewStore(path)
admin, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("admin", admin.TokenVersion); err == nil {
t.Fatal("old admin token survived account-file reset")
}
if _, ok, err = store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("login after reset: ok=%v err=%v", ok, err)
}
if err = store.Create("alice", "alice-password", RoleUser); err != nil {
t.Fatal(err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
if err = store.Delete("admin", "alice"); err != nil {
t.Fatal(err)
}
if err = store.Create("alice", "alice-password", RoleUser); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err == nil {
t.Fatal("old token survived deletion and username reuse")
}
}
func TestConcurrentCreatesDoNotLoseUsers(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
const count = 5
var workers sync.WaitGroup
errorsCh := make(chan error, count)
for index := 0; index < count; index++ {
workers.Add(1)
go func(index int) {
defer workers.Done()
errorsCh <- store.Create(fmt.Sprintf("user%d", index), "valid-password", RoleUser)
}(index)
}
workers.Wait()
close(errorsCh)
for err := range errorsCh {
if err != nil {
t.Fatal(err)
}
}
users, err := store.List()
if err != nil {
t.Fatal(err)
}
if len(users) != count+1 {
t.Fatalf("got %d users, want %d", len(users), count+1)
}
}

64
server/build.sh Executable file
View File

@@ -0,0 +1,64 @@
#!/bin/bash
set -e
# Configuration Variables
BINARY_NAME="NanoKVM-Server"
CC_COMPILER="riscv64-unknown-linux-musl-gcc"
CGO_CFLAGS_OPTS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d"
# Define colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper function to check if a command exists
check_dependency() {
if ! command -v "$1" &> /dev/null; then
echo -e "${RED}[ERROR] Required command '$1' not found.${NC}"
echo "Please install it or ensure it is in your PATH."
exit 1
fi
}
# ------------------------------------------------------------------------------
# Step 1: Check Prerequisites
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Checking build environment...${NC}"
check_dependency "go"
check_dependency "patchelf"
check_dependency "$CC_COMPILER"
echo -e "${GREEN}[OK] All dependencies found.${NC}"
# ------------------------------------------------------------------------------
# Step 2: Build the Binary
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Starting cross-compilation for RISC-V 64-bit (BoringCrypto enabled)...${NC}"
export CGO_ENABLED=1
export GOOS=linux
export GOARCH=riscv64
export GOEXPERIMENT=boringcrypto
export CC="$CC_COMPILER"
export CGO_CFLAGS="$CGO_CFLAGS_OPTS"
go build -o "$BINARY_NAME" -v
if [ -f "$BINARY_NAME" ]; then
echo -e "${GREEN}[SUCCESS] Binary '$BINARY_NAME' created successfully.${NC}"
else
echo -e "${RED}[ERROR] Build failed. Binary not found.${NC}"
exit 1
fi
# ------------------------------------------------------------------------------
# Step 3: Patch RPATH
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Patching RPATH with patchelf...${NC}"
patchelf --add-rpath '$ORIGIN/dl_lib' "$BINARY_NAME"
echo -e "${GREEN}[DONE] Build script completed successfully!${NC}"

View File

@@ -1,163 +0,0 @@
package common
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L../dl_lib -lkvm
#include "kvm_vision.h"
*/
import "C"
import (
"NanoKVM-Server/config"
"strings"
"sync"
"unsafe"
log "github.com/sirupsen/logrus"
)
var (
kvmVision *KvmVision
kvmVisionOnce sync.Once
)
type KvmVision struct {
mutex sync.Mutex
}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
kvmVision = &KvmVision{}
conf := config.GetInstance()
logLevel := strings.ToLower(conf.Logger.Level)
logEnable := C.uint8_t(0)
if logLevel == "debug" {
logEnable = C.uint8_t(1)
}
C.kvmv_init(logEnable)
log.Debugf("kvm vision initialized")
})
return kvmVision
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result = int(C.kvmv_read_img(
C.uint16_t(width),
C.uint16_t(height),
C.uint8_t(0),
C.uint16_t(quality),
&kvmData,
&dataSize,
))
if result < 0 {
log.Errorf("failed to read kvm image: %v", result)
return
}
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, sps []byte, pps []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result = int(C.kvmv_read_img(
C.uint16_t(width),
C.uint16_t(height),
C.uint8_t(1),
C.uint16_t(bitRate),
&kvmData,
&dataSize,
))
if result < 0 {
log.Errorf("failed to read kvm image: %v", result)
return
}
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
if result == 3 {
sps, _ = k.ReadH264SPS()
pps, _ = k.ReadH264PPS()
}
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264SPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := int(C.kvmv_get_sps_frame(&kvmData, &dataSize))
if result < 0 {
log.Errorf("failed to read sps: %v", result)
return nil, result
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, result
}
func (k *KvmVision) ReadH264PPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := int(C.kvmv_get_pps_frame(&kvmData, &dataSize))
if result < 0 {
log.Errorf("failed to read pps: %v", result)
return nil, result
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, result
}
func (k *KvmVision) SetHDMI(enable bool) int {
hdmiEnable := C.uint8_t(0)
if enable {
hdmiEnable = C.uint8_t(1)
}
result := int(C.kvmv_hdmi_control(hdmiEnable))
if result < 0 {
log.Errorf("failed to set hdmi to %t", enable)
return result
}
return result
}
func (k *KvmVision) Close() {
k.mutex.Lock()
defer k.mutex.Unlock()
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

146
server/common/kvm_vision.go Normal file
View File

@@ -0,0 +1,146 @@
package common
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L../dl_lib -lkvm
#include "kvm_vision.h"
*/
import "C"
import (
"sync"
"unsafe"
log "github.com/sirupsen/logrus"
)
var (
kvmVision *KvmVision
kvmVisionOnce sync.Once
)
type KvmVision struct {
mutex sync.RWMutex
closed bool
}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
kvmVision = &KvmVision{}
logLevel := C.uint8_t(0)
C.kvmv_init(logLevel)
log.Debugf("kvm vision initialized")
})
return kvmVision
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) ([]byte, int) {
frame := k.AcquireMjpeg(width, height, quality, uint16(GetScreen().FPS))
defer frame.Release()
return frame.Data, frame.Result
}
func (k *KvmVision) AcquireMjpeg(width, height, quality, fps uint16) *VideoFrame {
return k.acquireFrame(width, height, quality, fps, 0)
}
func (k *KvmVision) AcquireH264(width, height, bitRate, fps uint16) *VideoFrame {
return k.acquireFrame(width, height, bitRate, fps, 1)
}
func (k *KvmVision) acquireFrame(width, height, quality, fps uint16, codec uint8) *VideoFrame {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return NewVideoFrame(nil, -1, 0, nil)
}
var frame C.kvmv_frame_t
result := int(C.kvmv_read_img(C.uint16_t(width), C.uint16_t(height),
C.uint8_t(codec), C.uint16_t(quality), C.uint16_t(fps), &frame))
if frame.data == nil {
return NewVideoFrame(nil, result, int64(frame.timestamp), nil)
}
data := C.GoBytes(unsafe.Pointer(frame.data), C.int(frame.size))
return NewVideoFrame(data, result, int64(frame.timestamp), func() {
k.mutex.RLock()
defer k.mutex.RUnlock()
C.kvmv_release_frame(&frame)
})
}
func (k *KvmVision) StopH264() { k.stopStream(1) }
func (k *KvmVision) StopMjpeg() { k.stopStream(0) }
func (k *KvmVision) stopStream(codec uint8) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if !k.closed {
C.kvmv_stop_stream(C.uint8_t(codec))
}
}
func (k *KvmVision) SetHDMI(enable bool) int {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return -1
}
hdmiEnable := C.uint8_t(0)
if enable {
hdmiEnable = C.uint8_t(1)
}
result := int(C.kvmv_hdmi_control(hdmiEnable))
if result < 0 {
log.Errorf("failed to set hdmi to %t", enable)
return result
}
return result
}
func (k *KvmVision) HasHDMISignal() bool {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return false
}
return C.kvmv_hdmi_signal_active() != 0
}
func (k *KvmVision) SetGop(gop uint8) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return
}
_gop := C.uint8_t(gop)
C.set_h264_gop(_gop)
}
func (k *KvmVision) SetFrameDetect(frame uint8) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return
}
_frame := C.uint8_t(frame)
C.set_frame_detact(_frame)
}
func (k *KvmVision) Close() {
k.mutex.Lock()
defer k.mutex.Unlock()
if k.closed {
return
}
k.closed = true
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

View File

@@ -1,13 +1,17 @@
package common
import "sync"
import (
"os"
"strconv"
"strings"
"sync"
)
type Screen struct {
Width uint16
Height uint16
FPS int
Quality uint16
BitRate uint16
GOP uint8
}
var (
@@ -15,15 +19,6 @@ var (
screenOnce sync.Once
)
// ResolutionMap height to width
var ResolutionMap = map[uint16]uint16{
1080: 1920,
720: 1280,
600: 800,
480: 640,
0: 0,
}
var QualityMap = map[uint16]bool{
100: true,
80: true,
@@ -41,11 +36,10 @@ var BitRateMap = map[uint16]bool{
func GetScreen() *Screen {
screenOnce.Do(func() {
screen = &Screen{
Width: 0,
Height: 0,
Quality: 80,
FPS: 30,
BitRate: 3000,
GOP: 30,
}
})
@@ -54,13 +48,6 @@ func GetScreen() *Screen {
func SetScreen(key string, value int) {
switch key {
case "resolution":
height := uint16(value)
if width, ok := ResolutionMap[height]; ok {
screen.Width = width
screen.Height = height
}
case "quality":
if value > 100 {
screen.BitRate = uint16(value)
@@ -70,9 +57,37 @@ func SetScreen(key string, value int) {
case "fps":
screen.FPS = validateFPS(value)
case "gop":
screen.GOP = uint8(value)
}
}
func CheckScreen() {
if _, ok := QualityMap[screen.Quality]; !ok {
screen.Quality = 80
}
if _, ok := BitRateMap[screen.BitRate]; !ok {
screen.BitRate = 3000
}
}
func InputSize() (uint16, uint16) {
read := func(path string) uint16 {
data, err := os.ReadFile(path)
if err != nil {
return 0
}
value, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 16)
if err != nil {
return 0
}
return uint16(value)
}
return read("/kvmapp/kvm/width"), read("/kvmapp/kvm/height")
}
func validateFPS(fps int) int {
if fps > 60 {
return 60

View File

@@ -0,0 +1,26 @@
package common
import "sync"
type VideoFrame struct {
Data []byte
Result int
Timestamp int64
release func()
once sync.Once
}
func NewVideoFrame(data []byte, result int, timestamp int64, release func()) *VideoFrame {
return &VideoFrame{Data: data, Result: result, Timestamp: timestamp, release: release}
}
func (f *VideoFrame) Release() {
if f == nil {
return
}
f.once.Do(func() {
if f.release != nil {
f.release()
}
})
}

View File

@@ -2,6 +2,7 @@ package config
var defaultConfig = &Config{
Proto: "http",
Host: "",
Port: Port{
Http: 80,
Https: 443,
@@ -21,11 +22,15 @@ var defaultConfig = &Config{
},
Stun: "stun.l.google.com:19302",
Turn: Turn{
TurnAddr: "turn.cloudflare.com:3478",
TurnAddr: "",
TurnUser: "",
TurnCred: "",
},
Authentication: "enable",
Security: Security{
LoginLockoutDuration: 0,
LoginMaxFailures: 5,
},
}
func checkDefaultValue() {

45
server/config/file.go Normal file
View File

@@ -0,0 +1,45 @@
package config
import (
"os"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
const ConfigurationFile = "/etc/kvm/server.yaml"
func Read() (*Config, error) {
data, err := os.ReadFile(ConfigurationFile)
if err != nil {
log.Errorf("failed to read config: %v", err)
return nil, err
}
var conf Config
if err := yaml.Unmarshal(data, &conf); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
return nil, err
}
log.Debugf("read %s successfully", ConfigurationFile)
return &conf, nil
}
func Write(conf *Config) error {
data, err := yaml.Marshal(&conf)
if err != nil {
log.Errorf("failed to marshal config: %v", err)
return err
}
err = os.WriteFile(ConfigurationFile, data, 0644)
if err != nil {
log.Errorf("failed to write config: %v", err)
return err
}
log.Debugf("write to %s successfully", ConfigurationFile)
return nil
}

View File

@@ -54,24 +54,27 @@ func (h HWVersion) String() string {
}
}
func getHwVersion() HWVersion {
func GetHwVersion() HWVersion {
content, err := os.ReadFile(HWVersionFile)
if err != nil {
return HWVersionAlpha
}
version := strings.ReplaceAll(string(content), "\n", "")
if version == "beta" {
switch version {
case "alpha":
return HWVersionAlpha
case "beta":
return HWVersionBeta
} else if version == "pcie" {
case "pcie":
return HWVersionPcie
default:
return HWVersionAlpha
}
return HWVersionAlpha
}
func getHardware() (h Hardware) {
version := getHwVersion()
version := GetHwVersion()
switch version {
case HWVersionAlpha:
@@ -85,7 +88,7 @@ func getHardware() (h Hardware) {
default:
h = HWAlpha
log.Error("Unsupported hardware version: %s", version)
log.Errorf("Unsupported hardware version: %s", version)
}
return

View File

@@ -7,13 +7,6 @@ import (
"time"
)
// RegenerateSecretKey regenerate secret key when logout
func RegenerateSecretKey() {
if instance.JWT.RevokeTokensOnLogout {
instance.JWT.SecretKey = generateRandomSecretKey()
}
}
// Generate random string for secret key.
func generateRandomSecretKey() string {
b := make([]byte, 64)

View File

@@ -0,0 +1,61 @@
package config
import (
"os"
"path/filepath"
"strings"
"sync"
)
const (
PicoclawInternalTokenHeader = "X-NanoKVM-Internal-Token"
picoclawInternalTokenFile = "/etc/kvm/.picoclaw_internal_token"
)
var picoclawInternalToken struct {
mu sync.Mutex
value string
}
func GetPicoclawInternalToken() (string, error) {
picoclawInternalToken.mu.Lock()
defer picoclawInternalToken.mu.Unlock()
if picoclawInternalToken.value != "" {
return picoclawInternalToken.value, nil
}
if token, err := readPicoclawInternalToken(); err == nil {
if token != "" {
picoclawInternalToken.value = token
return token, nil
}
} else if !os.IsNotExist(err) {
return "", err
}
token := generateRandomSecretKey()
if err := os.MkdirAll(filepath.Dir(picoclawInternalTokenFile), 0o755); err != nil {
return "", err
}
if err := os.WriteFile(picoclawInternalTokenFile, []byte(token+"\n"), 0o600); err != nil {
return "", err
}
picoclawInternalToken.value = token
return token, nil
}
func EnsurePicoclawInternalToken() error {
_, err := GetPicoclawInternalToken()
return err
}
func readPicoclawInternalToken() (string, error) {
data, err := os.ReadFile(picoclawInternalTokenFile)
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}

View File

@@ -1,14 +1,16 @@
package config
type Config struct {
Proto string `yaml:"proto"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
JWT JWT `yaml:"jwt"`
Stun string `yaml:"stun"`
Turn Turn `yaml:"turn"`
Proto string `yaml:"proto"`
Host string `yaml:"host"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
JWT JWT `yaml:"jwt"`
Stun string `yaml:"stun"`
Turn Turn `yaml:"turn"`
Security Security `yaml:"security"`
Hardware Hardware `yaml:"-"`
}
@@ -40,6 +42,11 @@ type Turn struct {
TurnCred string `yaml:"turnCred"`
}
type Security struct {
LoginLockoutDuration int `yaml:"loginLockoutDuration"`
LoginMaxFailures int `yaml:"loginMaxFailures"`
}
type Hardware struct {
Version HWVersion `yaml:"-"`
GPIOReset string `yaml:"-"`

Binary file not shown.

Binary file not shown.

View File

@@ -1,21 +1,28 @@
module NanoKVM-Server
go 1.22.1
go 1.25.0
require (
github.com/creack/pty v1.1.24
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0
github.com/gin-gonic/gin v1.10.0
github.com/go-playground/validator/v10 v10.20.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.3
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/pion/dtls/v3 v3.1.2
github.com/pion/interceptor v0.1.39
github.com/pion/rtp v1.8.18
github.com/pion/webrtc/v4 v4.0.1
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
github.com/unrolled/secure v1.15.0
golang.org/x/crypto v0.31.0
golang.org/x/crypto v0.45.0
golang.org/x/sys v0.41.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -30,7 +37,6 @@ require (
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
@@ -42,23 +48,23 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pion/datachannel v1.5.9 // indirect
github.com/pion/dtls/v3 v3.0.3 // indirect
github.com/pion/ice/v4 v4.0.2 // indirect
github.com/pion/interceptor v0.1.37 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.14 // indirect
github.com/pion/rtp v1.8.9 // indirect
github.com/pion/rtcp v1.2.15 // indirect
github.com/pion/sctp v1.8.33 // indirect
github.com/pion/sdp/v3 v3.0.9 // indirect
github.com/pion/srtp/v3 v3.0.4 // indirect
github.com/pion/stun/v3 v3.0.0 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/pion/transport/v4 v4.0.1 // indirect
github.com/pion/turn/v4 v4.0.0 // indirect
github.com/rs/cors v1.11.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
@@ -66,14 +72,15 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/wlynxg/anet v0.0.3 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

View File

@@ -34,11 +34,13 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -65,6 +67,8 @@ github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0 h
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0/go.mod h1:Eb5RMoo9kOQra/2uRiUTGP+LfNuM13Vqm7y7P34+KKo=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -74,22 +78,22 @@ github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pion/datachannel v1.5.9 h1:LpIWAOYPyDrXtU+BW7X0Yt/vGtYxtXQ8ql7dFfYUVZA=
github.com/pion/datachannel v1.5.9/go.mod h1:kDUuk4CU4Uxp82NH4LQZbISULkX/HtzKa4P7ldf9izE=
github.com/pion/dtls/v3 v3.0.3 h1:j5ajZbQwff7Z8k3pE3S+rQ4STvKvXUdKsi/07ka+OWM=
github.com/pion/dtls/v3 v3.0.3/go.mod h1:weOTUyIV4z0bQaVzKe8kpaP17+us3yAuiQsEAG1STMU=
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
github.com/pion/ice/v4 v4.0.2 h1:1JhBRX8iQLi0+TfcavTjPjI6GO41MFn4CeTBX+Y9h5s=
github.com/pion/ice/v4 v4.0.2/go.mod h1:DCdqyzgtsDNYN6/3U8044j3U7qsJ9KFJC92VnOWHvXg=
github.com/pion/interceptor v0.1.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI=
github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/interceptor v0.1.39 h1:Y6k0bN9Y3Lg/Wb21JBWp480tohtns8ybJ037AGr9UuA=
github.com/pion/interceptor v0.1.39/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM=
github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.9 h1:E2HX740TZKaqdcPmf4pw6ZZuG8u5RlMMt+l3dxeu6Wk=
github.com/pion/rtp v1.8.9/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo=
github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0=
github.com/pion/rtp v1.8.18 h1:yEAb4+4a8nkPCecWzQB6V/uEU18X1lQCGAQCjP+pyvU=
github.com/pion/rtp v1.8.18/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
github.com/pion/sctp v1.8.33 h1:dSE4wX6uTJBcNm8+YlMg7lw1wqyKHggsP5uKbdj+NZw=
github.com/pion/sctp v1.8.33/go.mod h1:beTnqSzewI53KWoG3nqB282oDMGrhNxBdb+JZnkCwRM=
github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
@@ -100,6 +104,8 @@ github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=
github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU=
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=
github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=
github.com/pion/webrtc/v4 v4.0.1 h1:6Unwc6JzoTsjxetcAIoWH81RUM4K5dBc1BbJGcF9WVE=
@@ -117,6 +123,10 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
@@ -139,8 +149,9 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
@@ -149,8 +160,10 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/unrolled/secure v1.15.0 h1:q7x+pdp8jAHnbzxu6UheP8fRlG/rwYTb8TPuQ3rn9Og=
github.com/unrolled/secure v1.15.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
github.com/wlynxg/anet v0.0.3 h1:PvR53psxFXstc12jelG6f1Lv4MWqE0tI76/hHGjh9rg=
github.com/wlynxg/anet v0.0.3/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
@@ -158,19 +171,23 @@ go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTV
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -1,63 +1,47 @@
#ifndef KVM_VISION_H_
#define KVM_VISION_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#define IMG_BUFFER_FULL -3
#define IMG_VENC_ERROR -2
#define IMG_NOT_EXIST -1
#define IMG_MJPEG_TYPE 0
#define IMG_H264_TYPE_SPS 1
#define IMG_H264_TYPE_PPS 2
#define IMG_H264_TYPE_IF 3
#define IMG_H264_TYPE_PF 4
#define IMG_BUFFER_FULL -3
#define IMG_VENC_ERROR -2
#define IMG_NOT_EXIST -1
#define IMG_MJPEG_TYPE 0
#define IMG_H264_TYPE_IF 3
#define IMG_H264_TYPE_PF 4
void kvmv_init(uint8_t _debug_info_en);
/**********************************************************************************
* @name kvmv_read_img
* @author Sipeed BuGu
* @date 2024/10/25
* @version R1.0
* @brief Acquire the encoded image with auto init
* @param _width @input: Output image width
* @param _height @input: Output image height
* @param _type @input: Encode type
* @param _qlty @input: MJPEG: (50-100) | H264: (500-10000)
* @param _pp_kvm_data @output: Encode data
* @param _p_kvmv_data_size @output: Encode data size
* @return
-4: Modifying image resolution, please wait
-3: img buffer full
-2: VENC Error
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)
2: Acquire H264 encoded images(PPS)
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
**********************************************************************************/
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int free_kvmv_data(uint8_t ** _pp_kvm_data);
void free_all_kvmv_data();
void set_h264_gop(uint8_t _gop);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);
typedef struct {
uint8_t *data;
uint32_t size;
uint64_t timestamp;
uint64_t token;
uint8_t codec;
} kvmv_frame_t;
void kvmv_init(uint8_t debug_info);
void kvmv_deinit(void);
// type: 0 = MJPEG, 1 = H.264. A zero width/height follows the input size.
// quality: MJPEG 50..100, H.264 500..10000 Kbps. fps: 1..60.
// Returns -7 input error, -6 unsupported size, -5 busy, -4 reconfiguring,
// -3 allocation failure, -2 encoder error, -1 no frame, 0 JPEG, 3 IDR,
// 4 P-frame, or 5 unchanged JPEG. Release every successful frame once.
int kvmv_read_img(uint16_t width, uint16_t height, uint8_t type,
uint16_t quality, uint16_t fps, kvmv_frame_t *frame);
// Frees the copied bytes and releases the encoder lease. Safe after shutdown.
void kvmv_release_frame(kvmv_frame_t *frame);
void kvmv_stop_stream(uint8_t type);
void set_h264_gop(uint8_t gop);
void set_frame_detact(uint8_t interval);
uint8_t kvmv_hdmi_control(uint8_t enable);
uint8_t kvmv_hdmi_signal_active(void);
#ifdef __cplusplus
}
#endif
#endif // KVM_VISION_H_
#endif // KVM_VISION_H_

View File

@@ -22,7 +22,7 @@ func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
buffer = &bytes.Buffer{}
}
now := entry.Time.Format("2006-01-02 15:04:05")
now := entry.Time.Format("2006-01-02 15:04:05.000")
if entry.HasCaller() {
fileName := filepath.Base(entry.Caller.File)

View File

@@ -1,18 +1,22 @@
package main
import (
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"NanoKVM-Server/common"
"NanoKVM-Server/config"
"NanoKVM-Server/logger"
"NanoKVM-Server/middleware"
"NanoKVM-Server/router"
"NanoKVM-Server/service/storage/diskfs"
"NanoKVM-Server/service/vm"
"NanoKVM-Server/service/vm/jiggler"
"NanoKVM-Server/utils"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
@@ -26,18 +30,30 @@ func main() {
}
func initialize() {
if err := config.EnsurePicoclawInternalToken(); err != nil {
log.Fatalf("failed to initialize picoclaw internal token: %v", err)
}
logger.Init()
// init screen parameters
_ = common.GetScreen()
// init HDMI
vision := common.GetKvmVision()
vision.SetHDMI(false)
vm.DisableHdmiCapture()
time.Sleep(10 * time.Millisecond)
vision.SetHDMI(true)
if !utils.IsHdmiDisabled() {
vm.EnableHdmiCapture()
}
vm.SetHdmiViewerCount(0)
utils.InitGoMemLimit()
// run mouse jiggler
jiggler.GetJiggler().Run()
// A medium left mounted by a crash or a restart keeps its loop device
// busy; nothing can be mounted by this process yet, so whatever is there
// is stale.
diskfs.CleanupStale()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
@@ -56,30 +72,56 @@ func run() {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
if conf.Authentication == "disable" {
r.Use(cors.AllowAll())
}
router.Init(r)
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
log.Printf("proto: %s, port: %d %d\n", conf.Proto, conf.Port.Http, conf.Port.Https)
httpAddr := utils.ListenAddr(conf.Host, strconv.Itoa(conf.Port.Http))
loopbackHTTPAddr := utils.ListenAddr("127.0.0.1", strconv.Itoa(conf.Port.Http))
needsLoopbackHTTP := utils.NeedsDedicatedLoopbackListener(conf.Host)
if conf.Proto == "https" {
r.Use(middleware.Tls())
httpsPortStr := strconv.Itoa(conf.Port.Https)
go func() {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
err := r.RunTLS(utils.ListenAddr(conf.Host, httpsPortStr), conf.Cert.Crt, conf.Cert.Key)
if err != nil {
panic("start https server failed")
}
}()
if err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key); err != nil {
panic("start https server failed")
if needsLoopbackHTTP {
go func() {
if err := middleware.ListenAndServeLoopbackHTTPRedirect(
loopbackHTTPAddr,
httpsPortStr,
r,
router.LoopbackHTTPAllowedPaths()...,
); err != nil {
panic("start loopback http server failed")
}
}()
}
if err := middleware.ListenAndServeLoopbackHTTPRedirect(
httpAddr,
httpsPortStr,
r,
router.LoopbackHTTPAllowedPaths()...,
); err != nil {
panic("start http server failed")
}
} else {
if needsLoopbackHTTP {
go func() {
if err := r.Run(loopbackHTTPAddr); err != nil {
panic("start loopback http server failed")
}
}()
}
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
}
@@ -87,5 +129,6 @@ func run() {
}
func dispose() {
diskfs.CleanupStale()
common.GetKvmVision().Close()
}

View File

@@ -1,75 +1,273 @@
package middleware
import (
"context"
"errors"
"net/http"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
)
const (
principalContextKey = "principal"
tokenContextKey = "token"
CookieName = "nano-kvm-token"
sessionRecheckDelay = 5 * time.Second
)
type Principal struct {
Username string
Role authn.Role
Permissions []authn.Permission
}
// Has reports whether the principal effectively holds the permission.
// Administrators always do.
func (p Principal) Has(permission authn.Permission) bool {
if p.Role == authn.RoleAdmin {
return true
}
return authn.Has(p.Permissions, permission)
}
type Token struct {
Username string `json:"username"`
Username string `json:"username"`
TokenVersion uint64 `json:"tokenVersion"`
jwt.RegisteredClaims
}
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
conf := config.GetInstance()
principal, token, ok := authenticate(c)
if !ok {
abortUnauthorized(c)
return
}
if conf.Authentication == "disable" {
c.Set(principalContextKey, principal)
c.Set(tokenContextKey, token)
if token == nil || token.ExpiresAt == nil {
c.Next()
return
}
cookie, err := c.Cookie("nano-kvm-token")
if err == nil {
_, err = ParseJWT(cookie)
if err == nil {
c.Next()
requestContext, cancel := context.WithCancel(c.Request.Context())
sessionHandle := newSessionHandle()
requestContext = WithSessionHandle(requestContext, sessionHandle)
c.Request = c.Request.WithContext(requestContext)
channel := SessionChannelForPath(c.Request.URL.Path)
unregister := activeSessions.register(
principal.Username,
cancel,
sessionHandle,
channel,
)
// The principal was resolved before this session could be found by a
// revocation, so a grant edit landing in between would miss it. Now that
// it is registered, any later edit drops it; re-reading the account picks
// up any earlier one. Only the long-lived channels are dropped by a grant
// edit, so a short request keeps the principal it was authorized with.
if channel != "" {
user, err := authn.DefaultStore.ValidateToken(principal.Username, token.TokenVersion)
if err != nil {
unregister()
cancel()
abortUnauthorized(c)
return
}
principal.Role = user.Role
principal.Permissions = authn.EffectivePermissions(user)
c.Set(principalContextKey, principal)
}
c.JSON(http.StatusUnauthorized, "unauthorized")
c.Abort()
timer := time.AfterFunc(time.Until(token.ExpiresAt.Time), cancel)
go watchSessionState(requestContext, cancel, principal.Username, token.TokenVersion, sessionRecheckDelay)
defer func() {
timer.Stop()
unregister()
cancel()
}()
c.Next()
}
}
func GenerateJWT(username string) (string, error) {
func watchSessionState(ctx context.Context, cancel context.CancelFunc, username string, tokenVersion uint64, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if _, err := authn.DefaultStore.ValidateToken(username, tokenVersion); err != nil {
cancel()
return
}
}
}
}
func RequireRole(roles ...authn.Role) gin.HandlerFunc {
allowed := make(map[authn.Role]struct{}, len(roles))
for _, role := range roles {
allowed[role] = struct{}{}
}
return func(c *gin.Context) {
principal, ok := CurrentPrincipal(c)
if !ok {
abortUnauthorized(c)
return
}
if _, ok = allowed[principal.Role]; !ok {
abortForbidden(c)
return
}
c.Next()
}
}
// RequirePermission allows the request when the principal holds at least one
// of the listed permissions. Administrators implicitly hold every permission.
func RequirePermission(permissions ...authn.Permission) gin.HandlerFunc {
return func(c *gin.Context) {
principal, ok := CurrentPrincipal(c)
if !ok {
abortUnauthorized(c)
return
}
allowed := false
for _, permission := range permissions {
if principal.Has(permission) {
allowed = true
break
}
}
if !allowed {
abortForbidden(c)
return
}
c.Next()
}
}
func CurrentPrincipal(c *gin.Context) (Principal, bool) {
value, exists := c.Get(principalContextKey)
if !exists {
return Principal{}, false
}
principal, ok := value.(Principal)
return principal, ok
}
func CheckLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
abortUnauthorized(c)
}
}
func CheckTokenOrLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
principal, token, ok := authenticate(c)
if !ok {
abortUnauthorized(c)
return
}
c.Set(principalContextKey, principal)
c.Set(tokenContextKey, token)
c.Next()
}
}
func authenticate(c *gin.Context) (Principal, *Token, bool) {
conf := config.GetInstance()
expireDuration := time.Duration(conf.JWT.RefreshTokenDuration) * time.Second
claims := Token{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
},
if conf.Authentication == "disable" {
return Principal{Username: "admin", Role: authn.RoleAdmin, Permissions: authn.PermissionIDs()}, nil, true
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
cookie, err := c.Cookie(CookieName)
if err != nil {
return Principal{}, nil, false
}
token, err := ParseJWT(cookie)
if err != nil {
return Principal{}, nil, false
}
user, err := authn.DefaultStore.ValidateToken(token.Username, token.TokenVersion)
if err != nil {
log.Debugf("validate session for %q: %s", token.Username, err)
return Principal{}, nil, false
}
return Principal{
Username: user.Username,
Role: user.Role,
Permissions: authn.EffectivePermissions(user),
}, token, true
}
return t.SignedString([]byte(conf.JWT.SecretKey))
func abortUnauthorized(c *gin.Context) {
c.JSON(http.StatusUnauthorized, "unauthorized")
c.Abort()
}
func abortForbidden(c *gin.Context) {
c.JSON(http.StatusForbidden, "forbidden")
c.Abort()
}
func GenerateJWT(username string, tokenVersion uint64) (string, error) {
conf := config.GetInstance()
now := time.Now()
expireDuration := time.Duration(conf.JWT.RefreshTokenDuration) * time.Second
claims := Token{
Username: username,
TokenVersion: tokenVersion,
RegisteredClaims: jwt.RegisteredClaims{
Subject: username,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(expireDuration)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(conf.JWT.SecretKey))
}
func ParseJWT(jwtToken string) (*Token, error) {
conf := config.GetInstance()
t, err := jwt.ParseWithClaims(jwtToken, &Token{}, func(token *jwt.Token) (interface{}, error) {
return []byte(conf.JWT.SecretKey), nil
})
parsed, err := jwt.ParseWithClaims(
jwtToken,
&Token{},
func(token *jwt.Token) (interface{}, error) {
if token.Method != jwt.SigningMethodHS256 {
return nil, errors.New("unexpected signing method")
}
return []byte(conf.JWT.SecretKey), nil
},
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithExpirationRequired(),
)
if err != nil {
log.Debugf("parse jwt error: %s", err)
return nil, err
}
if claims, ok := t.Claims.(*Token); ok && t.Valid {
return claims, nil
} else {
return nil, err
claims, ok := parsed.Claims.(*Token)
if !ok || !parsed.Valid || claims.Username == "" || claims.Subject != claims.Username || claims.TokenVersion == 0 {
return nil, errors.New("invalid token claims")
}
return claims, nil
}

View File

@@ -0,0 +1,230 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/gorilla/websocket"
)
func TestCheckTokenUsesLiveRoleAndVersion(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
admin, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err = store.Create("alice", "valid-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
restore := useTestAuthStore(t, store)
defer restore()
adminToken, err := GenerateJWT(admin.Username, admin.TokenVersion)
if err != nil {
t.Fatal(err)
}
userToken, err := GenerateJWT(alice.Username, alice.TokenVersion)
if err != nil {
t.Fatal(err)
}
router := gin.New()
router.GET("/admin", CheckToken(), RequireRole(authn.RoleAdmin), func(c *gin.Context) {
c.Status(http.StatusNoContent)
})
if status := requestWithToken(router, "/admin", ""); status != http.StatusUnauthorized {
t.Fatalf("missing token status = %d", status)
}
if status := requestWithToken(router, "/admin", adminToken); status != http.StatusNoContent {
t.Fatalf("admin status = %d", status)
}
if status := requestWithToken(router, "/admin", userToken); status != http.StatusForbidden {
t.Fatalf("user status = %d", status)
}
if _, err = store.Revoke("admin"); err != nil {
t.Fatal(err)
}
if status := requestWithToken(router, "/admin", adminToken); status != http.StatusUnauthorized {
t.Fatalf("revoked status = %d", status)
}
}
func TestParseJWTRejectsOtherHMACMethods(t *testing.T) {
conf := config.GetInstance()
originalSecret := conf.JWT.SecretKey
conf.JWT.SecretKey = "test-secret"
defer func() { conf.JWT.SecretKey = originalSecret }()
now := time.Now()
claims := Token{
Username: "admin",
TokenVersion: 1,
RegisteredClaims: jwt.RegisteredClaims{
Subject: "admin",
ExpiresAt: jwt.NewNumericDate(now.Add(time.Hour)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS384, claims).SignedString([]byte(conf.JWT.SecretKey))
if err != nil {
t.Fatal(err)
}
if _, err = ParseJWT(token); err == nil {
t.Fatal("HS384 token was accepted")
}
}
func TestParseJWTRejectsExpiredToken(t *testing.T) {
conf := config.GetInstance()
originalSecret := conf.JWT.SecretKey
conf.JWT.SecretKey = "test-secret"
defer func() { conf.JWT.SecretKey = originalSecret }()
claims := Token{
Username: "admin",
TokenVersion: 1,
RegisteredClaims: jwt.RegisteredClaims{
Subject: "admin",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(conf.JWT.SecretKey))
if err != nil {
t.Fatal(err)
}
if _, err = ParseJWT(token); err == nil {
t.Fatal("expired token was accepted")
}
}
func TestRevokeUserSessionsCancelsActiveRequests(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
unregister := activeSessions.register("alice", cancel, newSessionHandle(), "")
defer unregister()
RevokeUserSessions("alice")
select {
case <-ctx.Done():
case <-time.After(time.Second):
t.Fatal("active session was not cancelled")
}
}
func TestAccountFileResetCancelsActiveSession(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
store := authn.NewStore(path)
user, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
restore := useTestAuthStore(t, store)
defer restore()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go watchSessionState(ctx, cancel, user.Username, user.TokenVersion, 10*time.Millisecond)
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
t.Fatal("active session survived account-file reset")
}
}
func TestWatchWebSocketClosesRevokedConnection(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
connection, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
return
}
defer connection.Close()
stop := WatchWebSocket(ctx, connection)
defer stop()
_, _, _ = connection.ReadMessage()
}))
defer server.Close()
wsURL := "ws" + server.URL[len("http"):]
connection, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatal(err)
}
defer connection.Close()
cancel()
_ = connection.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, err = connection.ReadMessage()
if !websocket.IsCloseError(err, SessionRevokedCloseCode) {
t.Fatalf("close error = %v, want code %d", err, SessionRevokedCloseCode)
}
}
func TestCheckWebSocketOrigin(t *testing.T) {
tests := []struct {
origin string
host string
want bool
}{
{"", "kvm.local", true},
{"http://kvm.local", "kvm.local", true},
{"http://KVM.local", "kvm.local", true},
{"http://kvm.local:8080", "kvm.local:8080", true},
{"http://kvm.local:8081", "kvm.local:8080", false},
{"http://evil.example", "kvm.local", false},
}
for _, test := range tests {
request := httptest.NewRequest(http.MethodGet, "http://"+test.host+"/api/ws", nil)
request.Host = test.host
if test.origin != "" {
request.Header.Set("Origin", test.origin)
}
if got := CheckWebSocketOrigin(request); got != test.want {
t.Fatalf("origin %q host %q = %v, want %v", test.origin, test.host, got, test.want)
}
}
}
func requestWithToken(handler http.Handler, path, token string) int {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, path, nil)
request.AddCookie(&http.Cookie{Name: CookieName, Value: token})
handler.ServeHTTP(recorder, request)
return recorder.Code
}
func useTestAuthStore(t *testing.T, store *authn.Store) func() {
t.Helper()
originalStore := authn.DefaultStore
conf := config.GetInstance()
originalAuthentication := conf.Authentication
originalSecret := conf.JWT.SecretKey
originalDuration := conf.JWT.RefreshTokenDuration
authn.DefaultStore = store
conf.Authentication = "enable"
conf.JWT.SecretKey = "test-secret"
conf.JWT.RefreshTokenDuration = 3600
return func() {
authn.DefaultStore = originalStore
conf.Authentication = originalAuthentication
conf.JWT.SecretKey = originalSecret
conf.JWT.RefreshTokenDuration = originalDuration
}
}

View File

@@ -0,0 +1,94 @@
package middleware
import (
"crypto/subtle"
"net"
"net/http"
"strings"
"NanoKVM-Server/config"
)
func ListenAndServeLoopbackHTTPRedirect(
httpAddr string,
httpsPort string,
handler http.Handler,
allowedPaths ...string,
) error {
allowlist := make(map[string]struct{}, len(allowedPaths))
for _, path := range allowedPaths {
if strings.TrimSpace(path) == "" {
continue
}
allowlist[path] = struct{}{}
}
return http.ListenAndServe(httpAddr, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if isLoopbackAllowedPath(req, allowlist) {
if hasValidLoopbackHTTPToken(req) {
handler.ServeHTTP(w, req)
return
}
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
http.Redirect(w, req, "https://"+redirectHost(req.Host, httpsPort)+req.URL.RequestURI(), http.StatusTemporaryRedirect)
}))
}
func redirectHost(requestHost string, httpsPort string) string {
host := requestHost
if h, _, err := net.SplitHostPort(requestHost); err == nil {
host = h
} else if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = strings.TrimPrefix(strings.TrimSuffix(host, "]"), "[")
}
if httpsPort != "443" {
return net.JoinHostPort(host, httpsPort)
}
if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") && !strings.HasSuffix(host, "]") {
return "[" + host + "]"
}
return host
}
func allowByLoopbackInternalToken(req *http.Request) bool {
return req != nil && isLoopbackRemote(req.RemoteAddr) && hasValidLoopbackHTTPToken(req)
}
func isLoopbackAllowedPath(req *http.Request, allowedPaths map[string]struct{}) bool {
if !allowByLoopbackInternalToken(req) {
return false
}
_, allowed := allowedPaths[req.URL.Path]
return allowed
}
func hasValidLoopbackHTTPToken(req *http.Request) bool {
if req == nil {
return false
}
token, err := config.GetPicoclawInternalToken()
if err != nil || token == "" {
return false
}
provided := req.Header.Get(config.PicoclawInternalTokenHeader)
return subtle.ConstantTimeCompare([]byte(provided), []byte(token)) == 1
}
func isLoopbackRemote(remoteAddr string) bool {
host := strings.TrimSpace(remoteAddr)
if parsedHost, _, err := net.SplitHostPort(remoteAddr); err == nil {
host = parsedHost
}
ip := net.ParseIP(strings.Trim(host, "[]"))
return ip != nil && ip.IsLoopback()
}

View File

@@ -0,0 +1,233 @@
package middleware
import (
"context"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
const SessionRevokedCloseCode = 4401
// SessionRefreshedCloseCode closes connections whose permissions changed while
// the underlying login is still valid. Clients are expected to reconnect and
// refresh their account state instead of returning to the login page.
const SessionRefreshedCloseCode = 4403
type sessionHandleKey struct{}
// Long-lived connection channels, used to drop only the connections affected
// by a permission change instead of every session of the user.
const (
SessionChannelConsole = "console" // /api/ws (input events, status pushes)
SessionChannelStream = "stream" // /api/stream/* (video signaling and frames)
SessionChannelTerminal = "terminal" // /api/vm/terminal
SessionChannelAi = "ai" // /api/picoclaw/gateway/ws
)
// SessionChannelForPath classifies long-lived endpoints; everything else
// returns an empty channel and is only affected by hard revocation.
func SessionChannelForPath(path string) string {
switch {
case path == "/api/ws":
return SessionChannelConsole
case strings.HasPrefix(path, "/api/stream/"):
return SessionChannelStream
case path == "/api/vm/terminal":
return SessionChannelTerminal
case path == "/api/picoclaw/gateway/ws":
return SessionChannelAi
default:
return ""
}
}
// sessionHandle lets a revocation pick the WebSocket close code before the
// request context is canceled.
type sessionHandle struct {
closeCode atomic.Int32
}
type sessionEntry struct {
cancel context.CancelFunc
handle *sessionHandle
channel string
}
type sessionRegistry struct {
mutex sync.Mutex
nextID atomic.Uint64
byUserID map[string]map[uint64]*sessionEntry
}
var activeSessions = &sessionRegistry{byUserID: make(map[string]map[uint64]*sessionEntry)}
func newSessionHandle() *sessionHandle {
handle := &sessionHandle{}
handle.closeCode.Store(SessionRevokedCloseCode)
return handle
}
// WithSessionHandle attaches the handle to the request context so
// WatchWebSocket can honor the close code chosen at revocation time.
func WithSessionHandle(ctx context.Context, handle *sessionHandle) context.Context {
return context.WithValue(ctx, sessionHandleKey{}, handle)
}
func (r *sessionRegistry) register(username string, cancel context.CancelFunc, handle *sessionHandle, channel string) func() {
id := r.nextID.Add(1)
r.mutex.Lock()
if r.byUserID[username] == nil {
r.byUserID[username] = make(map[uint64]*sessionEntry)
}
r.byUserID[username][id] = &sessionEntry{cancel: cancel, handle: handle, channel: channel}
r.mutex.Unlock()
return func() {
r.mutex.Lock()
delete(r.byUserID[username], id)
if len(r.byUserID[username]) == 0 {
delete(r.byUserID, username)
}
r.mutex.Unlock()
}
}
// RevokeUserSessions hard-drops every active session of the user. The login
// is expected to be invalid afterwards; connections close as unauthorized.
func RevokeUserSessions(username string) {
dropUserSessions(username, SessionRevokedCloseCode, nil)
}
// RefreshUserSessions drops the user's long-lived connections on the given
// channels while their login stays valid, so those clients reconnect under
// the updated permissions. Unrelated connections (e.g. the video stream when
// only console control was revoked) stay untouched.
func RefreshUserSessions(username string, channels ...string) {
dropUserSessions(username, SessionRefreshedCloseCode, channels)
}
func dropUserSessions(username string, closeCode int, channels []string) {
activeSessions.mutex.Lock()
sessions := activeSessions.byUserID[username]
if channels == nil {
delete(activeSessions.byUserID, username)
}
dropped := make([]*sessionEntry, 0, len(sessions))
for id, entry := range sessions {
if !channelMatches(entry.channel, channels) {
continue
}
dropped = append(dropped, entry)
if channels != nil {
delete(sessions, id)
}
}
if channels != nil && len(sessions) == 0 {
delete(activeSessions.byUserID, username)
}
activeSessions.mutex.Unlock()
for _, entry := range dropped {
entry.handle.closeCode.Store(int32(closeCode))
entry.cancel()
}
}
// channelMatches reports whether the entry is affected. A nil channel list
// means a hard revocation, which drops everything.
func channelMatches(channel string, channels []string) bool {
if channels == nil {
return true
}
for _, candidate := range channels {
if channel == candidate {
return true
}
}
return false
}
func WatchWebSocket(ctx context.Context, connection *websocket.Conn) func() {
stopped := make(chan struct{})
var stopOnce sync.Once
go func() {
select {
case <-ctx.Done():
closeCode := SessionRevokedCloseCode
reason := "session expired or revoked"
if handle, ok := ctx.Value(sessionHandleKey{}).(*sessionHandle); ok {
if code := int(handle.closeCode.Load()); code == SessionRefreshedCloseCode {
closeCode = code
reason = "permissions changed"
}
}
_ = connection.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(closeCode, reason),
time.Now().Add(2*time.Second),
)
_ = connection.Close()
case <-stopped:
}
}()
return func() { stopOnce.Do(func() { close(stopped) }) }
}
func CheckWebSocketOrigin(request *http.Request) bool {
origin := strings.TrimSpace(request.Header.Get("Origin"))
if origin == "" {
return true
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" {
return false
}
requestScheme := "http"
if request.TLS != nil {
requestScheme = "https"
}
if forwarded := strings.TrimSpace(strings.Split(request.Header.Get("X-Forwarded-Proto"), ",")[0]); forwarded != "" {
requestScheme = strings.ToLower(forwarded)
}
return equalOrigin(parsed, request.Host, requestScheme)
}
func equalOrigin(origin *url.URL, requestHost, requestScheme string) bool {
originHost, originPort := splitHostPort(origin.Host)
host, port := splitHostPort(requestHost)
if !strings.EqualFold(originHost, host) {
return false
}
if originPort == "" {
originPort = defaultPort(origin.Scheme)
}
if port == "" {
port = defaultPort(requestScheme)
}
return originPort == port
}
func splitHostPort(value string) (string, string) {
host, port, err := net.SplitHostPort(value)
if err == nil {
return host, port
}
return strings.Trim(value, "[]"), ""
}
func defaultPort(scheme string) string {
switch strings.ToLower(scheme) {
case "https", "wss":
return "443"
default:
return "80"
}
}

View File

@@ -4,3 +4,21 @@ type GetVersionRsp struct {
Current string `json:"current"`
Latest string `json:"latest"`
}
type GetPreviewRsp struct {
Enabled bool `json:"enabled"`
}
type SetPreviewReq struct {
Enable bool `validate:"omitempty"`
}
type GetUpdateServerRsp struct {
Enabled bool `json:"enabled"`
URL string `json:"url"`
}
type SetUpdateServerReq struct {
Enabled *bool `json:"enabled" form:"enabled" validate:"required"`
URL string `json:"url" form:"url"`
}

View File

@@ -5,24 +5,65 @@ type LoginReq struct {
Password string `validate:"required"`
}
type LoginRsp struct {
Token string `json:"token"`
}
type GetAccountRsp struct {
Username string `json:"username"`
Username string `json:"username"`
Role string `json:"role"`
Permissions []string `json:"permissions"`
}
type ChangePasswordReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
CurrentPassword string `json:"currentPassword"`
Password string `json:"password" validate:"required"`
}
type IsPasswordUpdatedRsp struct {
IsUpdated bool `json:"isUpdated"`
}
type ConnectWifiReq struct {
Ssid string `validate:"required"`
Password string `valid:"required"`
type UserInfo struct {
Username string `json:"username"`
Role string `json:"role"`
Enabled bool `json:"enabled"`
Permissions []string `json:"permissions"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type ListPermissionsRsp struct {
Permissions []PermissionInfo `json:"permissions"`
}
// PermissionInfo describes one grantable permission: the group it belongs to,
// how far it reaches, and the grants it implies. The client renders the editor
// from this catalog instead of keeping its own copy of the model.
type PermissionInfo struct {
ID string `json:"id"`
Group string `json:"group"`
Risk string `json:"risk"`
Implies []string `json:"implies,omitempty"`
}
type ListUsersRsp struct {
Users []UserInfo `json:"users"`
}
type CreateUserReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
Role string `json:"role" validate:"required"`
Permissions []string `json:"permissions"`
}
type UpdateUserReq struct {
Role *string `json:"role"`
Enabled *bool `json:"enabled"`
Permissions *[]string `json:"permissions"`
// RotateMcpKey asks to regenerate the device-wide MCP API key when this
// change takes the mcp grant away. The administrator decides: rotating
// disconnects every MCP client, keeping it leaves a copied key working.
RotateMcpKey bool `json:"rotateMcpKey"`
}
// UpdateUserRsp says whether the change regenerated the MCP API key.
type UpdateUserRsp struct {
McpKeyRotated bool `json:"mcpKeyRotated"`
}

View File

@@ -1,5 +1,10 @@
package proto
type DownloadImageReq struct {
File string `json:"file" validate:"required"`
SHA256Sum string `json:"sha256sum"`
}
type ImageEnabledRsp struct {
Enabled bool `json:"enabled"`
}
@@ -8,4 +13,6 @@ type StatusImageRsp struct {
Status string `json:"status"`
File string `json:"file"`
Percentage string `json:"percentage"`
Loaded int64 `json:"loaded"` // bytes transferred so far
Total int64 `json:"total"` // expected bytes, 0 when unknown
}

47
server/proto/hid.go Normal file
View File

@@ -0,0 +1,47 @@
package proto
type GetHidModeRsp struct {
Mode string `json:"mode"` // normal or hid-only
}
type GetKeyboardLedStatusRsp struct {
NumLock bool `json:"numLock"`
CapsLock bool `json:"capsLock"`
ScrollLock bool `json:"scrollLock"`
Known bool `json:"known"`
UpdatedAt string `json:"updatedAt"`
}
type SetHidModeReq struct {
Mode string `validate:"required"` // normal or hid-only
}
type ShortcutKey struct {
Code string `json:"code"`
Label string `json:"label"`
}
type Shortcut struct {
ID string `json:"id"`
Keys []ShortcutKey `json:"keys"`
}
type GetShortcutsRsp struct {
Shortcuts []Shortcut `json:"shortcuts"`
}
type AddShortcutReq struct {
Keys []ShortcutKey `validate:"required"`
}
type DeleteShortcutReq struct {
ID string `validate:"required"`
}
type SetLeaderKeyReq struct {
Key string `validate:"omitempty"`
}
type GetLeaderKeyRsp struct {
Key string `json:"key"`
}

12
server/proto/mcp.go Normal file
View File

@@ -0,0 +1,12 @@
package proto
type GetMCPConfigRsp struct {
Enabled bool `json:"enabled"`
APIKey string `json:"apiKey"`
ControlMode string `json:"controlMode"`
Transitioning bool `json:"transitioning"`
}
type SetMCPConfigReq struct {
Enabled *bool `json:"enabled" form:"enabled" validate:"required"`
}

100
server/proto/media.go Normal file
View File

@@ -0,0 +1,100 @@
package proto
import "time"
// Virtual media wire types. A medium is named by a type plus a path relative
// to the media directory: the server resolves the id itself, so a request
// never carries an absolute path it could be talked into deleting.
const (
MediaTypeImage = "image"
MediaTypePartition = "partition"
)
type MediaItem struct {
Type string `json:"type"`
Rel string `json:"rel"`
Name string `json:"name"`
Size uint64 `json:"size"`
FS string `json:"fs"`
Browsable bool `json:"browsable"`
Attached bool `json:"attached"`
Modified time.Time `json:"modifiedAt"`
}
type MediaCaps struct {
Loop bool `json:"loop"`
}
type GetMediaRsp struct {
Media []MediaItem `json:"media"`
Caps MediaCaps `json:"capabilities"`
}
type MediaStateRsp struct {
State string `json:"state"` // none | image | partition | unsupported
Type string `json:"type"` // type of the attached medium
Rel string `json:"rel"` // rel of the attached medium, when it is an image
HidOnly bool `json:"hidOnly"` // the gadget has no mass storage at all
Open []string `json:"open"` // media the file manager currently holds open
Cdrom bool `json:"cdrom"` // the attached medium is served as a CD-ROM
// LocalWritable is false while /data is mounted read-only, which is what
// the target machine owning the partition does. Every write would fail
// with EROFS, so the UI disables them instead of asking.
LocalWritable bool `json:"localWritable"`
}
type MediaRefReq struct {
Type string `json:"type" validate:"omitempty,oneof=image partition"`
Rel string `json:"rel"`
}
type MountMediaReq struct {
Type string `json:"type" validate:"omitempty,oneof=image partition"`
Rel string `json:"rel"`
Cdrom bool `json:"cdrom"`
// Force re-enumerates the gadget to take the medium back from a target
// machine that is holding it. It costs the target machine its unflushed
// writes, so the UI asks before setting it.
Force bool `json:"force"`
}
type EjectMediaReq struct {
Force bool `json:"force"`
}
type MediaStatusRsp struct {
Status string `json:"status"`
Name string `json:"name"`
Percentage string `json:"percentage"`
Loaded int64 `json:"loaded"` // bytes transferred so far
Total int64 `json:"total"` // expected bytes, 0 when unknown
Message string `json:"message"`
}
type MediaFile struct {
Name string `json:"name"`
Size int64 `json:"size"`
IsDir bool `json:"isDir"`
Modified time.Time `json:"modifiedAt"`
}
type GetMediaFilesRsp struct {
Path string `json:"path"`
Entries []MediaFile `json:"entries"`
Free uint64 `json:"free"`
Total uint64 `json:"total"`
// Writing is true while the medium is seeing block level writes: a zero
// length entry in that state is a transfer in progress, not an empty file.
Writing bool `json:"writing"`
}
type MediaPathReq struct {
Type string `json:"type" validate:"omitempty,oneof=image partition"`
Rel string `json:"rel"`
Path string `json:"path" validate:"required"`
// ExistsOK turns "the directory is already there" into success. An upload
// of a whole tree recreates folders that may already exist on the medium,
// and stopping at the first one would leave the tree half copied.
ExistsOK bool `json:"existsOk"`
}

View File

@@ -12,28 +12,41 @@ type DeleteMacReq struct {
Mac string `form:"mac" validate:"required"`
}
type TailscaleState string
const (
TailscaleNotInstall TailscaleState = "notInstall"
TailscaleNotRunning TailscaleState = "notRunning"
TailscaleNotLogin TailscaleState = "notLogin"
TailscaleStopped TailscaleState = "stopped"
TailscaleRunning TailscaleState = "running"
)
type GetTailscaleStatusRsp struct {
State TailscaleState `json:"state"`
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type LoginTailscaleRsp struct {
Url string `json:"url"`
type SetMacNameReq struct {
Mac string `form:"mac" validate:"required"`
Name string `form:"name" validate:"required"`
}
type GetWifiRsp struct {
Supported bool `json:"supported"`
Connected bool `json:"connected"`
Supported bool `json:"supported"`
ApMode bool `json:"apMode"`
Connected bool `json:"connected"`
Ssid string `json:"ssid"`
}
type ConnectWifiReq struct {
Ssid string `validate:"required"`
Password string `validate:"required"`
}
type GetDNSRsp struct {
Mode string `json:"mode"`
Servers []string `json:"servers"`
Effective []string `json:"effective"`
DHCP []string `json:"dhcp"`
Info DNSInfo `json:"info"`
}
type SetDNSReq struct {
Mode string `json:"mode" validate:"required,oneof=manual dhcp"`
Servers []string `json:"servers"`
}
type DNSInfo struct {
Interface string `json:"interface"`
Type string `json:"type"`
Address string `json:"address"`
SubnetMask string `json:"subnetMask"`
Gateway string `json:"gateway"`
SearchDomains []string `json:"searchDomains"`
}

View File

@@ -20,7 +20,7 @@ func ValidateRequest(req interface{}) error {
}
if env == "" || env == "debug" {
log.Debugf("request: %+v\n", req)
log.Debugf("request validated: %T", req)
}
return nil

View File

@@ -5,9 +5,18 @@ type GetImagesRsp struct {
}
type MountImageReq struct {
File string `json:"file" validate:"omitempty"`
File string `json:"file" validate:"omitempty"`
Cdrom bool `json:"cdrom" validate:"omitempty"`
}
type GetMountedImageRsp struct {
File string `json:"file"`
}
type GetCdRomRsp struct {
Cdrom int64 `json:"cdrom"`
}
type DeleteImageReq struct {
File string `json:"file" validate:"required"`
}

View File

@@ -1,9 +1,9 @@
package proto
type GetFrameDetectRsp struct {
Enabled bool `json:"enabled"`
type UpdateFrameDetectReq struct {
Enabled bool `validate:"omitempty"`
}
type UpdateFrameDetectRsp struct {
Enabled bool `json:"enabled"`
type StopFrameDetectReq struct {
Duration int `validate:"omitempty"`
}

22
server/proto/tailscale.go Normal file
View File

@@ -0,0 +1,22 @@
package proto
type TailscaleState string
const (
TailscaleNotInstall TailscaleState = "notInstall"
TailscaleNotRunning TailscaleState = "notRunning"
TailscaleNotLogin TailscaleState = "notLogin"
TailscaleStopped TailscaleState = "stopped"
TailscaleRunning TailscaleState = "running"
)
type GetTailscaleStatusRsp struct {
State TailscaleState `json:"state"`
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type LoginTailscaleRsp struct {
Url string `json:"url"`
}

View File

@@ -1,7 +1,14 @@
package proto
type IP struct {
Name string `json:"name"`
Addr string `json:"addr"`
Version string `json:"version"`
Type string `json:"type"`
}
type GetInfoRsp struct {
Ip string `json:"ip"`
IPs []IP `json:"ips"`
Mdns string `json:"mdns"`
Image string `json:"image"`
Application string `json:"application"`
@@ -23,8 +30,8 @@ type GetGpioRsp struct {
}
type SetScreenReq struct {
Type string `validate:"required"` // resolution / fps / quality
Value int `validate:"number"` // value
Type string `validate:"required,oneof=type fps quality gop"`
Value int `validate:"number"` // value
}
type GetScriptsRsp struct {
@@ -48,13 +55,27 @@ type DeleteScriptReq struct {
Name string `validate:"required"`
}
// autostart
type GetAutostartRsp struct {
Files []string `json:"files"`
}
type UploadAutostartReq struct {
Content string `json:"content"`
}
type GetVirtualDeviceRsp struct {
Network bool `json:"network"`
Media bool `json:"media"`
Disk bool `json:"disk"`
}
type UpdateVirtualDeviceReq struct {
Device string `validate:"required"`
// Enable turns the device on or off instead of toggling it. A caller that
// says "enable" must not switch a running device off because it happened to
// be already on.
Enable *bool `json:"enable"`
}
type UpdateVirtualDeviceRsp struct {
@@ -62,8 +83,8 @@ type UpdateVirtualDeviceRsp struct {
}
type SetMemoryLimitReq struct {
Enabled bool `json:"enabled"`
Limit int64 `json:"limit"`
Enabled bool `validate:"omitempty"`
Limit int64 `validate:"omitempty"`
}
type GetMemoryLimitRsp struct {
@@ -72,7 +93,7 @@ type GetMemoryLimitRsp struct {
}
type SetOledReq struct {
Sleep int `json:"sleep"`
Sleep int `validate:"omitempty"`
}
type GetOLEDRsp struct {
@@ -80,6 +101,109 @@ type GetOLEDRsp struct {
Sleep int `json:"sleep"`
}
type GetGetHdmiStateRsp struct {
Enabled bool `json:"enabled"`
Signal bool `json:"signal"`
IdleTimeout int `json:"idleTimeout"`
}
type SetHdmiIdleTimeoutReq struct {
Minutes int `validate:"gte=0,lte=10080"`
}
type GetSSHStateRsp struct {
Enabled bool `json:"enabled"`
}
type GetSwapRsp struct {
Size int64 `json:"size"` // unit: MB
}
type SetSwapReq struct {
Size int64 `validate:"omitempty"` // unit: MB
}
type GetMouseJigglerRsp struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
}
type SetMouseJigglerReq struct {
Enabled bool `validate:"omitempty"`
Mode string `validate:"omitempty"`
}
type GetMdnsStateRsp struct {
Enabled bool `json:"enabled"`
}
type SetHostnameReq struct {
Hostname string `validate:"required"`
}
type GetHostnameRsp struct {
Hostname string `json:"hostname"`
}
type SetWebTitleReq struct {
Title string `validate:"omitempty"`
}
type GetWebTitleRsp struct {
Title string `json:"title"`
}
type SetTlsReq struct {
Enabled bool `validate:"omitempty"`
}
type InputRegion struct {
Mode string `json:"mode"`
FrameWidth int `json:"frameWidth"`
FrameHeight int `json:"frameHeight"`
Left int `json:"left"`
Top int `json:"top"`
Width int `json:"width"`
Height int `json:"height"`
Resolutions []OriginalResolution `json:"resolutions,omitempty"`
SelectedResolution string `json:"selectedResolution"`
Regions []ManualRegion `json:"regions,omitempty"`
SelectedRegion string `json:"selectedRegion"`
}
type ManualRegion struct {
FrameWidth int `json:"frameWidth"`
FrameHeight int `json:"frameHeight"`
Left int `json:"left"`
Top int `json:"top"`
Width int `json:"width"`
Height int `json:"height"`
}
type OriginalResolution struct {
Width int `json:"width"`
Height int `json:"height"`
}
type SetInputRegionReq struct {
Mode string `json:"mode"`
FrameWidth *int `json:"frameWidth,omitempty"`
FrameHeight *int `json:"frameHeight,omitempty"`
Left *int `json:"left,omitempty"`
Top *int `json:"top,omitempty"`
Width *int `json:"width,omitempty"`
Height *int `json:"height,omitempty"`
Resolutions *[]OriginalResolution `json:"resolutions,omitempty"`
SelectedResolution *string `json:"selectedResolution,omitempty"`
Regions *[]ManualRegion `json:"regions,omitempty"`
SelectedRegion *string `json:"selectedRegion,omitempty"`
}
type GetInputRegionRsp struct {
InputRegion
}
type GetInputResolutionRsp struct {
Width int `json:"width"`
Height int `json:"height"`
}

View File

@@ -1,6 +1,7 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/application"
@@ -9,8 +10,15 @@ import (
func applicationRouter(r *gin.Engine) {
service := application.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermUpdate))
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
api.POST("/application/update/offline", service.OfflineUpdate) // update application offline
api.GET("/application/preview", service.GetPreview) // get preview updates state
api.POST("/application/preview", service.SetPreview) // set preview updates state
api.GET("/application/update-server", service.GetUpdateServer) // get custom update server
api.POST("/application/update-server", service.SetUpdateServer) // set custom update server
}

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/auth"
)
@@ -18,4 +19,15 @@ func authRouter(r *gin.Engine) {
api.GET("/auth/account", service.GetAccount) // get account
api.POST("/auth/password", service.ChangePassword) // change password
api.POST("/auth/logout", service.Logout) // logout
admin := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
admin.GET("/auth/permissions", service.ListPermissions)
admin.GET("/auth/users", service.ListUsers)
admin.POST("/auth/users", service.CreateUser)
admin.PUT("/auth/users/:username", service.UpdateUser)
admin.DELETE("/auth/users/:username", service.DeleteUser)
admin.POST("/auth/users/:username/password", service.ChangeUserPassword)
}

163
server/router/control.go Normal file
View File

@@ -0,0 +1,163 @@
package router
import (
"net/http"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
"NanoKVM-Server/service/inputcontrol"
"NanoKVM-Server/service/picoclaw"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type setAIControlModeRequest struct {
Mode controlmode.Mode `json:"mode"`
}
func controlRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *picoclaw.Service) {
group := r.Group("/api/ai/control").Use(
middleware.CheckToken(),
middleware.RequirePermission(authn.PermAi),
)
group.GET("/status", func(c *gin.Context) {
status, err := control.Status()
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": status})
})
group.PUT("/mode", func(c *gin.Context) {
startedAt := time.Now()
var req setAIControlModeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": "invalid arguments"})
return
}
if !validAIControlMode(req.Mode) {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": "invalid control mode"})
return
}
previousStatus, previousErr := control.Status()
if previousErr != nil {
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(previousErr).Warn("AI control mode request failed before switch")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": previousErr.Error()})
return
}
preempt := func() error {
inputcontrol.GetCoordinator().CancelMCP()
if req.Mode == controlmode.ModeMCP {
return picoclawService.PreemptControlLeasesForMCP()
}
picoclawService.CancelActiveControlOperations()
return nil
}
cleanup := func() error {
return hid.ReleaseAllHIDStateBestEffort()
}
if req.Mode == controlmode.ModeMCP {
cleanup = func() error {
if err := picoclawService.StopRuntimeForMCP(); err != nil {
return err
}
return hid.ReleaseAllHIDStateBestEffort()
}
}
if err := control.SwitchWithCleanup(req.Mode, preempt, cleanup); err != nil {
if req.Mode == controlmode.ModeOff {
if status, statusErr := control.Status(); statusErr == nil && status.Mode == controlmode.ModeOff {
picoclawService.CancelActiveControlOperations()
picoclawService.PreserveRuntimeForChatOnly("control_release_chat_only")
closedSessions := 0
picoclawService.PublishControlModeChangedFrom(status, "ai_control_mode")
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"final_mode": string(status.Mode),
"transitioning": status.Transitioning,
"closed_sessions": closedSessions,
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request completed with cleanup warning")
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{
"control": status,
"runtime": picoclawService.RuntimeStatus(),
"released": true,
"closed_sessions": closedSessions,
"cleanup_warning": err.Error(),
},
})
return
}
}
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request failed")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": err.Error()})
return
}
status, err := control.Status()
if err != nil {
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request failed after switch")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": err.Error()})
return
}
closedSessions := 0
if req.Mode == controlmode.ModeOff {
picoclawService.CancelActiveControlOperations()
picoclawService.PreserveRuntimeForChatOnly("control_release_chat_only")
}
picoclawService.PublishControlModeChangedFrom(status, "ai_control_mode")
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"final_mode": string(status.Mode),
"transitioning": status.Transitioning,
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).Info("AI control mode request completed")
if req.Mode == controlmode.ModeOff {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{
"control": status,
"runtime": picoclawService.RuntimeStatus(),
"released": true,
"closed_sessions": closedSessions,
"cleanup_warning": "",
},
})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": status})
})
}
func validAIControlMode(mode controlmode.Mode) bool {
switch mode {
case controlmode.ModeOff, controlmode.ModeMCP, controlmode.ModePicoclaw:
return true
default:
return false
}
}

View File

@@ -1,17 +1,26 @@
package router
import (
"NanoKVM-Server/service/download"
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/download"
"github.com/gin-gonic/gin"
)
func downloadRouter(r *gin.Engine) {
service := download.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
// A signed URL that ends up on the data partition changes what this device
// keeps, so it follows the library write grant.
write := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermLibraryWrite))
// Progress and availability are reads: a user who may attach a medium can
// take /data away from the downloader, so they need to see whether one is
// running, and reading the library is implied by every media grant.
read := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermLibraryRead))
api.POST("/download/image", service.DownloadImage) // download image
api.GET("/download/image/status", service.StatusImage) // download image
api.GET("/download/image/enabled", service.ImageEnabled) // download image
write.POST("/download/image", service.DownloadImage) // download image
write.POST("/download/image/cancel", service.CancelDownloadImage) // cancel image download
read.GET("/download/image/status", service.StatusImage) // download image
read.GET("/download/image/enabled", service.ImageEnabled) // download image
write.POST("/download/file", service.DownloadImageFile) // upload image file
}

View File

@@ -1,6 +1,7 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/extensions/tailscale"
@@ -8,7 +9,10 @@ import (
)
func extensionsRouter(r *gin.Engine) {
api := r.Group("/api/extensions").Use(middleware.CheckToken())
api := r.Group("/api/extensions").Use(
middleware.CheckToken(),
middleware.RequirePermission(authn.PermTailscale),
)
ts := tailscale.NewService()

View File

@@ -3,14 +3,37 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/hid"
)
const internalUSBRecoverPath = "/api/internal/usb/recover"
func HIDLoopbackHTTPAllowedPaths() []string {
return []string{internalUSBRecoverPath}
}
func hidRouter(r *gin.Engine) {
service := hid.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
view := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermConsoleView))
control := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermConsoleControl))
system := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermDevice))
localAPI := r.Group("/api/internal").Use(middleware.CheckLoopbackInternalToken())
api.POST("/hid/reset", service.Reset) // reset hid
api.POST("/hid/paste", service.Paste) // paste
control.POST("/hid/paste", service.Paste) // paste
view.GET("/hid/shortcuts", service.GetShortcuts) // get shortcuts
view.GET("/hid/shortcut/leader-key", service.GetLeaderKey) // get shortcut leader key
view.GET("/hid/mode", service.GetHidMode) // get hid mode
view.GET("/hid/leds", service.GetKeyboardLedStatus)
system.POST("/hid/mode", service.SetHidMode) // set hid mode
system.POST("/hid/reset", service.ResetHid) // reset hid
system.POST("/hid/shortcut", service.AddShortcut)
system.DELETE("/hid/shortcut", service.DeleteShortcut)
system.POST("/hid/shortcut/leader-key", service.SetLeaderKey)
localAPI.POST("/usb/recover", service.RecoverUSB)
}

41
server/router/mcp.go Normal file
View File

@@ -0,0 +1,41 @@
package router
import (
"net/http"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/auth"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
mcpservice "NanoKVM-Server/service/mcp"
"NanoKVM-Server/service/mcp/capture/kvm"
"NanoKVM-Server/service/picoclaw"
"github.com/gin-gonic/gin"
)
func mcpRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *picoclaw.Service) {
service := mcpservice.NewServiceWithPreempt(
control,
picoclawService.PreemptControlLeasesForMCP,
picoclawService.StopRuntimeForMCP,
hid.ReleaseAllHIDStateBestEffort,
func(status controlmode.Status) {
picoclawService.PublishControlModeChangedFrom(status, "mcp_config")
},
)
auth.APIKeyRotator = mcpservice.RotateAPIKey
management := r.Group("/api/mcp").Use(
middleware.CheckToken(),
middleware.RequirePermission(authn.PermMcp),
)
management.GET("/config", service.GetConfig)
management.POST("/config", service.SetConfig)
management.POST("/key/regenerate", service.RegenerateAPIKey)
handler := mcpservice.NewMCPHandler(control, kvmcapture.New())
handler = http.NewCrossOriginProtection().Handler(handler)
r.Any("/api/mcp", mcpservice.APIKeyMiddleware(control), gin.WrapH(handler))
}

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/network"
)
@@ -10,13 +11,21 @@ import (
func networkRouter(r *gin.Engine) {
service := network.NewService()
r.POST("/api/network/wifi", service.ConnectWifi) // connect Wi-Fi
r.POST("/api/network/wifi", service.ConnectWifiNoAuth) // connect Wi-Fi without auth (only available in ap mode)
r.POST("/api/network/wifi/verify", service.VerifyApLogin) // verify ap login
api := r.Group("/api").Use(middleware.CheckToken())
power := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermPower))
network := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermNetwork))
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
power.POST("/network/wol", service.WakeOnLAN) // wake on lan
power.GET("/network/wol/mac", service.GetMac) // get mac list
api.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
power.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
power.POST("/network/wol/mac/name", service.SetMacName) // set mac name
network.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
network.POST("/network/wifi/connect", service.ConnectWifi) // connect Wi-Fi
network.POST("/network/wifi/disconnect", service.DisconnectWifi) // disconnect Wi-Fi
network.GET("/network/dns", service.GetDNS) // get DNS configuration
network.POST("/network/dns", service.SetDNS) // set DNS configuration
}

67
server/router/picoclaw.go Normal file
View File

@@ -0,0 +1,67 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/picoclaw"
)
const (
picoclawBasePath = "/api/picoclaw"
picoclawModelConfigPath = "/model/config"
picoclawAgentProfilePath = "/agent/profile"
picoclawSessionsPath = "/sessions"
picoclawSessionByIDPath = "/sessions/:id"
picoclawRuntimeStatusPath = "/runtime/status"
picoclawRuntimeSessionPath = "/runtime/session"
picoclawRuntimeInstallPath = "/runtime/install"
picoclawRuntimeUninstallPath = "/runtime/uninstall"
picoclawRuntimeStartPath = "/runtime/start"
picoclawRuntimeStopPath = "/runtime/stop"
picoclawGatewayWSPath = "/gateway/ws"
picoclawScreenshotPath = "/screenshot"
picoclawActionsPath = "/actions"
picoclawMCPPath = "/mcp"
picoclawLoadImagePath = "/load-image"
)
var picoclawLoopbackHTTPAllowedPaths = []string{
picoclawBasePath + picoclawMCPPath,
picoclawBasePath + picoclawRuntimeSessionPath,
picoclawBasePath + picoclawScreenshotPath,
picoclawBasePath + picoclawActionsPath,
picoclawBasePath + picoclawLoadImagePath,
}
func PicoclawLoopbackHTTPAllowedPaths() []string {
return append([]string(nil), picoclawLoopbackHTTPAllowedPaths...)
}
func picoclawRouter(r *gin.Engine, service *picoclaw.Service) {
frontendAPI := r.Group(picoclawBasePath).Use(
middleware.CheckToken(),
middleware.RequirePermission(authn.PermAi),
)
localAPI := r.Group(picoclawBasePath).Use(middleware.CheckLoopbackInternalToken())
localAPI.GET(picoclawScreenshotPath, service.Screenshot)
localAPI.POST(picoclawActionsPath, service.Actions)
localAPI.POST(picoclawMCPPath, service.MCPHandler)
localAPI.POST(picoclawLoadImagePath, service.LoadImage)
localAPI.GET(picoclawRuntimeSessionPath, service.GetRuntimeSession)
frontendAPI.POST(picoclawModelConfigPath, service.UpdateModelConfig)
frontendAPI.POST(picoclawAgentProfilePath, service.UpdateAgentProfile)
frontendAPI.GET(picoclawSessionsPath, service.ListSessions)
frontendAPI.GET(picoclawSessionByIDPath, service.GetSession)
frontendAPI.DELETE(picoclawSessionByIDPath, service.DeleteSession)
frontendAPI.GET(picoclawRuntimeStatusPath, service.GetRuntimeStatus)
frontendAPI.DELETE(picoclawRuntimeSessionPath, service.ReleaseRuntimeSession)
frontendAPI.POST(picoclawRuntimeInstallPath, service.InstallRuntime)
frontendAPI.POST(picoclawRuntimeUninstallPath, service.UninstallRuntime)
frontendAPI.POST(picoclawRuntimeStartPath, service.StartRuntime)
frontendAPI.POST(picoclawRuntimeStopPath, service.StopRuntime)
frontendAPI.GET(picoclawGatewayWSPath, service.ConnectGateway)
}

View File

@@ -5,6 +5,12 @@ import (
"os"
"path/filepath"
"NanoKVM-Server/service/auth"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/picoclaw"
"NanoKVM-Server/service/ws"
"NanoKVM-Server/webcache"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -25,10 +31,16 @@ func web(r *gin.Engine) {
execDir := filepath.Dir(execPath)
webPath := fmt.Sprintf("%s/web", execDir)
r.Use(webcache.Headers(webPath))
r.Use(static.Serve("/", static.LocalFile(webPath, true)))
}
func server(r *gin.Engine) {
control := controlmode.GetManager()
picoclawService := picoclaw.NewService(control)
auth.SessionNotifier = ws.GetManager().NotifyUser
authRouter(r)
applicationRouter(r)
vmRouter(r)
@@ -36,7 +48,16 @@ func server(r *gin.Engine) {
storageRouter(r)
networkRouter(r)
hidRouter(r)
controlRouter(r, control, picoclawService)
mcpRouter(r, control, picoclawService)
picoclawRouter(r, picoclawService)
wsRouter(r)
downloadRouter(r)
extensionsRouter(r)
}
func LoopbackHTTPAllowedPaths() []string {
paths := PicoclawLoopbackHTTPAllowedPaths()
paths = append(paths, HIDLoopbackHTTPAllowedPaths()...)
return paths
}

View File

@@ -1,17 +1,50 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/storage"
"github.com/gin-gonic/gin"
)
func storageRouter(r *gin.Engine) {
service := storage.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
// Reading the library is the one grant the other media grants imply, so it
// alone gates every read: it is what makes the storage page reachable.
read := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermLibraryRead))
// Attaching a medium is what hands it to the target machine; changing the
// library is what changes what this device keeps.
attach := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermMediumAttach))
write := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermLibraryWrite))
// The file handlers serve an image and the shared partition through the same
// path: the first is library content, the second is the surface the target
// machine reads. Which grant applies follows the medium in the request, so
// the route admits either and the handler narrows the pair.
files := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequirePermission(authn.PermLibraryWrite, authn.PermMediumAttach),
)
api.GET("/storage/image", service.GetImages) // get image list
api.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image
api.POST("/storage/image/mount", service.MountImage) // mount image
// Virtual media: the disk images the emulated USB disk exposes, the files
// inside them, and the shared partition the target machine sees.
read.GET("/storage/media", service.GetMedia) // list media
read.GET("/storage/media/state", service.GetMediaState) // what the target machine sees
read.GET("/storage/media/status", service.GetMediaStatus) // transfer progress
read.GET("/storage/media/download", service.DownloadMedia) // download a whole image
read.GET("/storage/media/files", service.ListMediaFiles) // list files inside a medium
read.GET("/storage/media/files/download", service.DownloadMediaFile)
attach.POST("/storage/media/mount", service.MountMedia) // attach a medium to the target machine
attach.POST("/storage/media/eject", service.EjectMedia) // release the medium
write.POST("/storage/media/delete", service.DeleteMedia) // delete a medium
files.POST("/storage/media/files/upload", service.UploadMediaFile)
files.POST("/storage/media/files/mkdir", service.MkdirMediaFile)
files.POST("/storage/media/files/delete", service.DeleteMediaFile)
// The pre-2.6 image API, kept for scripts written against it.
read.GET("/storage/image", service.GetImages) // get image list
read.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image
read.GET("/storage/cdrom", service.GetCdRom) // get CD-ROM flag
attach.POST("/storage/image/mount", service.MountImage) // mount image
write.POST("/storage/image/delete", service.DeleteImage) // delete image
}

View File

@@ -1,20 +1,22 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/stream/h264"
"NanoKVM-Server/service/stream/direct"
"NanoKVM-Server/service/stream/mjpeg"
"NanoKVM-Server/service/stream/webrtc"
"github.com/gin-gonic/gin"
)
func streamRouter(r *gin.Engine) {
api := r.Group("/api").Use(middleware.CheckToken())
api := r.Group("/api").Use(middleware.CheckToken(), middleware.RequirePermission(authn.PermConsoleView))
api.GET("/stream/mjpeg", mjpeg.Connect) // mjpeg stream
api.GET("/stream/mjpeg/detect", mjpeg.GetFrameDetect) // get frame detect state
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect state
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect
api.POST("/stream/mjpeg/detect/stop", mjpeg.StopFrameDetect) // temporary stop frame detect
api.GET("/stream/h264", h264.Connect) // h264 stream
api.GET("/stream/h264", webrtc.Connect) // h264 stream (webrtc)
api.GET("/stream/h264/direct", direct.Connect) // h264 stream (http)
}

Some files were not shown because too many files have changed in this diff Show More