Files
openchamber-android-native/internal/storage/storage.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

150 lines
3.6 KiB
Go

// Package storage keeps saved servers in the app's data directory and
// their device tokens in the platform's secure storage.
package storage
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"os"
"path/filepath"
"sort"
"sync"
"github.com/egoist/mygo"
)
// Connection is one saved server.
type Connection struct {
ID string `json:"id"`
Label string `json:"label"`
URL string `json:"url"`
Proxy string `json:"proxy,omitempty"`
Insecure bool `json:"insecure,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
ServerID string `json:"serverId,omitempty"`
Passwordless bool `json:"passwordless,omitempty"`
LastUsedAt int64 `json:"lastUsedAt,omitempty"`
}
// Store is the persistence the UI needs. Tests use a memory store.
type Store interface {
Connections() []Connection
SaveConnections([]Connection)
InstallID() string
LoadToken(c Connection) (string, bool, error)
SaveToken(id, token string) error
ClearToken(c Connection) error
}
// Persistent is the app's store: servers in connections.json, tokens in
// the platform's secure store (the Android Keystore / iOS Keychain).
type Persistent struct {
mu sync.Mutex
path string
conns []Connection
installID string
}
// New makes the persistent store. It reads the servers file once; call it
// on startup, before any window shows.
func New() *Persistent {
p := &Persistent{}
dir, err := mygo.App.Path(mygo.PathUserData)
if err == nil {
p.path = filepath.Join(dir, "connections.json")
}
p.load()
return p
}
func (p *Persistent) load() {
if p.path == "" {
return
}
data, err := os.ReadFile(p.path)
if err != nil {
return
}
var list []Connection
if json.Unmarshal(data, &list) == nil {
p.conns = list
}
}
func (p *Persistent) save() {
if p.path == "" {
return
}
if err := os.MkdirAll(filepath.Dir(p.path), 0o700); err != nil {
return
}
data, _ := json.Marshal(p.conns)
_ = os.WriteFile(p.path, data, 0o600)
}
// migrateLegacy is gone: the earlier Asuka builds kept their data in
// Asuka's own stores, which this app cannot read.
func (p *Persistent) Connections() []Connection {
p.mu.Lock()
defer p.mu.Unlock()
out := make([]Connection, len(p.conns))
copy(out, p.conns)
return out
}
func (p *Persistent) SaveConnections(list []Connection) {
sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt })
p.mu.Lock()
p.conns = list
p.mu.Unlock()
p.save()
}
// InstallID is a stable random id for this installation. It names the
// device when logging in, so repeated logins reuse one device record.
func (p *Persistent) InstallID() string {
p.mu.Lock()
defer p.mu.Unlock()
if p.installID != "" {
return p.installID
}
p.installID = NewID()
return p.installID
}
func (p *Persistent) tokenKey(id string) string {
sum := sha256.Sum256([]byte(id))
return "openchamber.token." + hex.EncodeToString(sum[:12])
}
func (p *Persistent) LoadToken(c Connection) (string, bool, error) {
tok, err := mygo.Secrets.Get(p.tokenKey(c.ID))
if errors.Is(err, mygo.ErrSecretNotFound) {
return "", false, nil
}
if err != nil {
return "", false, err
}
return string(tok), true, nil
}
func (p *Persistent) SaveToken(id, token string) error {
return mygo.Secrets.Set(p.tokenKey(id), []byte(token))
}
func (p *Persistent) ClearToken(c Connection) error {
return mygo.Secrets.Delete(p.tokenKey(c.ID))
}
func NewID() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "srv_" + hex.EncodeToString(b[:4])
}
return "srv_" + hex.EncodeToString(b[:])
}