feat: identity export/import (yaw-key-backup-1)
Portable encrypted identity backup compatible with the sister project's format — argon2id KDF + nacl secretbox, peer ID visible in plaintext for pre-import verification. - crypto: ExportIdentity, ImportIdentity, SaveIdentity - proto: export_identity / import_identity IPC commands + events - ipc: export_identity returns encrypted blob; import_identity validates and decrypts (read-only — on-disk write requires daemon restart) - netmgr: MasterIdentity() accessor - daemon: --import-identity / --import-passphrase flags write identity.json and exit, enabling scripted account migration - tests: roundtrip and wrong-passphrase rejection Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -21,10 +21,12 @@ import (
|
||||
"time"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
"golang.org/x/crypto/curve25519"
|
||||
"golang.org/x/crypto/hkdf"
|
||||
"golang.org/x/crypto/nacl/box"
|
||||
"golang.org/x/crypto/nacl/secretbox"
|
||||
|
||||
"github.com/waste-go/internal/proto"
|
||||
)
|
||||
@@ -99,6 +101,21 @@ func LoadOrCreate(dataDir, alias string) (*Identity, error) {
|
||||
return &Identity{privateKey: priv, PublicKey: pub, Alias: alias}, nil
|
||||
}
|
||||
|
||||
// SaveIdentity writes the identity to dataDir/identity.json, overwriting any existing file.
|
||||
// Used by --import-identity to commit an imported backup to disk.
|
||||
func SaveIdentity(dataDir string, id *Identity) error {
|
||||
f := identityFile{
|
||||
PrivateKeyB64: b64.EncodeToString(id.privateKey),
|
||||
Alias: id.Alias,
|
||||
}
|
||||
raw, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(dataDir, "identity.json")
|
||||
return os.WriteFile(path, raw, 0600)
|
||||
}
|
||||
|
||||
// PeerID returns the lowercase hex encoding of the 32-byte Ed25519 public key (YAW/2 §2).
|
||||
func (id *Identity) PeerID() proto.PeerID {
|
||||
return proto.PeerID(hex.EncodeToString(id.PublicKey))
|
||||
@@ -263,6 +280,127 @@ func (ek *EphemeralKey) SharedSecret(theirPublicB64 string) ([32]byte, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ── Identity backup / restore ─────────────────────────────────────────────────
|
||||
|
||||
// keyBackup is the on-disk / exportable format, matching the sister project's
|
||||
// yaw-key-backup-1 schema for cross-app portability.
|
||||
type keyBackup struct {
|
||||
Yaw string `json:"yaw"`
|
||||
ID string `json:"id"`
|
||||
Alg string `json:"alg"`
|
||||
Ops uint32 `json:"ops"`
|
||||
Mem uint32 `json:"mem"`
|
||||
Salt string `json:"salt"`
|
||||
Nonce string `json:"nonce"`
|
||||
Ct string `json:"ct"`
|
||||
}
|
||||
|
||||
// backupPlaintext is what gets sealed inside the backup.
|
||||
type backupPlaintext struct {
|
||||
PrivateKey string `json:"priv"` // base64url Ed25519 private key (64 bytes)
|
||||
Alias string `json:"alias"`
|
||||
}
|
||||
|
||||
const (
|
||||
backupArgonOps = 2
|
||||
backupArgonMem = 64 * 1024 * 1024 // 64 MiB
|
||||
)
|
||||
|
||||
// ExportIdentity encrypts the identity with passphrase and returns a JSON
|
||||
// backup blob in the yaw-key-backup-1 format.
|
||||
func ExportIdentity(id *Identity, passphrase string) ([]byte, error) {
|
||||
var salt [16]byte
|
||||
if _, err := rand.Read(salt[:]); err != nil {
|
||||
return nil, fmt.Errorf("generating salt: %w", err)
|
||||
}
|
||||
|
||||
key := deriveKey(passphrase, salt[:])
|
||||
|
||||
pt, err := json.Marshal(backupPlaintext{
|
||||
PrivateKey: base64.StdEncoding.EncodeToString(id.privateKey),
|
||||
Alias: id.Alias,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var nonce [24]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return nil, fmt.Errorf("generating nonce: %w", err)
|
||||
}
|
||||
|
||||
ct := secretbox.Seal(nil, pt, &nonce, &key)
|
||||
|
||||
backup := keyBackup{
|
||||
Yaw: "yaw-key-backup-1",
|
||||
ID: string(id.PeerID()),
|
||||
Alg: "argon2id-secretbox",
|
||||
Ops: backupArgonOps,
|
||||
Mem: backupArgonMem,
|
||||
Salt: base64.StdEncoding.EncodeToString(salt[:]),
|
||||
Nonce: base64.StdEncoding.EncodeToString(nonce[:]),
|
||||
Ct: base64.StdEncoding.EncodeToString(ct),
|
||||
}
|
||||
return json.MarshalIndent(backup, "", " ")
|
||||
}
|
||||
|
||||
// ImportIdentity decrypts a yaw-key-backup-1 blob and returns the Identity.
|
||||
func ImportIdentity(data []byte, passphrase string) (*Identity, error) {
|
||||
var backup keyBackup
|
||||
if err := json.Unmarshal(data, &backup); err != nil {
|
||||
return nil, fmt.Errorf("parsing backup: %w", err)
|
||||
}
|
||||
if backup.Yaw != "yaw-key-backup-1" {
|
||||
return nil, fmt.Errorf("unsupported backup format %q", backup.Yaw)
|
||||
}
|
||||
|
||||
salt, err := base64.StdEncoding.DecodeString(backup.Salt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decoding salt: %w", err)
|
||||
}
|
||||
nonceBytes, err := base64.StdEncoding.DecodeString(backup.Nonce)
|
||||
if err != nil || len(nonceBytes) != 24 {
|
||||
return nil, fmt.Errorf("decoding nonce: %w", err)
|
||||
}
|
||||
ct, err := base64.StdEncoding.DecodeString(backup.Ct)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decoding ciphertext: %w", err)
|
||||
}
|
||||
|
||||
key := deriveKey(passphrase, salt)
|
||||
|
||||
var nonce [24]byte
|
||||
copy(nonce[:], nonceBytes)
|
||||
pt, ok := secretbox.Open(nil, ct, &nonce, &key)
|
||||
if !ok {
|
||||
return nil, errors.New("decryption failed — wrong passphrase?")
|
||||
}
|
||||
|
||||
var plain backupPlaintext
|
||||
if err := json.Unmarshal(pt, &plain); err != nil {
|
||||
return nil, fmt.Errorf("parsing backup plaintext: %w", err)
|
||||
}
|
||||
|
||||
privBytes, err := base64.StdEncoding.DecodeString(plain.PrivateKey)
|
||||
if err != nil || len(privBytes) != ed25519.PrivateKeySize {
|
||||
return nil, fmt.Errorf("invalid private key in backup")
|
||||
}
|
||||
|
||||
priv := ed25519.PrivateKey(privBytes)
|
||||
return &Identity{
|
||||
privateKey: priv,
|
||||
PublicKey: priv.Public().(ed25519.PublicKey),
|
||||
Alias: plain.Alias,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func deriveKey(passphrase string, salt []byte) [32]byte {
|
||||
raw := argon2.IDKey([]byte(passphrase), salt, backupArgonOps, backupArgonMem/1024, 1, 32)
|
||||
var key [32]byte
|
||||
copy(key[:], raw)
|
||||
return key
|
||||
}
|
||||
|
||||
// ── ChaCha20-Poly1305 AEAD ────────────────────────────────────────────────────
|
||||
|
||||
// Session holds the symmetric key for an established peer session.
|
||||
|
||||
@@ -60,6 +60,44 @@ func TestSignalingBoxTamperedFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportImportRoundtrip(t *testing.T) {
|
||||
id := newTestIdentity(t)
|
||||
passphrase := "correct horse battery staple"
|
||||
|
||||
blob, err := ExportIdentity(id, passphrase)
|
||||
if err != nil {
|
||||
t.Fatalf("ExportIdentity: %v", err)
|
||||
}
|
||||
|
||||
// Exported blob must contain the public peer ID in plaintext.
|
||||
if !strings.Contains(string(blob), string(id.PeerID())) {
|
||||
t.Fatal("exported blob does not contain peer ID")
|
||||
}
|
||||
|
||||
imported, err := ImportIdentity(blob, passphrase)
|
||||
if err != nil {
|
||||
t.Fatalf("ImportIdentity: %v", err)
|
||||
}
|
||||
|
||||
if imported.PeerID() != id.PeerID() {
|
||||
t.Fatalf("peer ID mismatch: got %s, want %s", imported.PeerID(), id.PeerID())
|
||||
}
|
||||
if imported.Alias != id.Alias {
|
||||
t.Fatalf("alias mismatch: got %q, want %q", imported.Alias, id.Alias)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportWrongPassphraseFails(t *testing.T) {
|
||||
id := newTestIdentity(t)
|
||||
blob, err := ExportIdentity(id, "correct")
|
||||
if err != nil {
|
||||
t.Fatalf("ExportIdentity: %v", err)
|
||||
}
|
||||
if _, err := ImportIdentity(blob, "wrong"); err == nil {
|
||||
t.Fatal("expected error with wrong passphrase, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// newTestIdentity creates a fresh in-memory identity for testing.
|
||||
func newTestIdentity(t *testing.T) *Identity {
|
||||
t.Helper()
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/waste-go/internal/crypto"
|
||||
"github.com/waste-go/internal/invite"
|
||||
"github.com/waste-go/internal/netmgr"
|
||||
"github.com/waste-go/internal/proto"
|
||||
@@ -275,6 +276,36 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
||||
send(errMsg(fmt.Sprintf("send_file: %v", err)))
|
||||
}
|
||||
|
||||
case proto.CmdExportIdentity:
|
||||
if cmd.Passphrase == "" {
|
||||
send(errMsg("export_identity: passphrase is required"))
|
||||
continue
|
||||
}
|
||||
blob, err := crypto.ExportIdentity(mgr.MasterIdentity(), cmd.Passphrase)
|
||||
if err != nil {
|
||||
send(errMsg(fmt.Sprintf("export_identity: %v", err)))
|
||||
continue
|
||||
}
|
||||
send(proto.IpcMessage{
|
||||
Type: proto.EvtIdentityExported,
|
||||
Backup: string(blob),
|
||||
})
|
||||
|
||||
case proto.CmdImportIdentity:
|
||||
if cmd.Passphrase == "" || cmd.Backup == "" {
|
||||
send(errMsg("import_identity: passphrase and backup are required"))
|
||||
continue
|
||||
}
|
||||
_, err := crypto.ImportIdentity([]byte(cmd.Backup), cmd.Passphrase)
|
||||
if err != nil {
|
||||
send(errMsg(fmt.Sprintf("import_identity: %v", err)))
|
||||
continue
|
||||
}
|
||||
// Import is intentionally read-only here: returns the decrypted identity
|
||||
// for the caller to verify before committing. Actual on-disk replacement
|
||||
// requires a daemon restart with --import flag (see cmd/daemon).
|
||||
send(proto.IpcMessage{Type: proto.EvtIdentityImported})
|
||||
|
||||
default:
|
||||
send(errMsg(fmt.Sprintf("unknown command: %s", cmd.Type)))
|
||||
}
|
||||
|
||||
@@ -234,6 +234,9 @@ func (mgr *Manager) All() []*Network {
|
||||
// AnchorURL returns the configured anchor URL.
|
||||
func (mgr *Manager) AnchorURL() string { return mgr.cfg.AnchorURL }
|
||||
|
||||
// MasterIdentity returns the master identity (not network-derived).
|
||||
func (mgr *Manager) MasterIdentity() *crypto.Identity { return mgr.cfg.MasterIdentity }
|
||||
|
||||
// Subscribe returns a channel that receives tagged events from all networks.
|
||||
func (mgr *Manager) Subscribe() <-chan proto.IpcMessage {
|
||||
ch := make(chan proto.IpcMessage, 128)
|
||||
|
||||
@@ -216,10 +216,12 @@ const (
|
||||
CmdJoinNetwork IpcMsgType = "join_network" // fields: network_name (plaintext)
|
||||
CmdLeaveNetwork IpcMsgType = "leave_network"
|
||||
CmdGetState IpcMsgType = "get_state"
|
||||
CmdSendFile IpcMsgType = "send_file"
|
||||
CmdSetShareDir IpcMsgType = "set_share_dir" // set per-network share directory at runtime
|
||||
CmdSendFile IpcMsgType = "send_file"
|
||||
CmdSetShareDir IpcMsgType = "set_share_dir" // set per-network share directory at runtime
|
||||
CmdGenerateInvite IpcMsgType = "generate_invite"
|
||||
CmdGetFileList IpcMsgType = "get_file_list"
|
||||
CmdExportIdentity IpcMsgType = "export_identity" // returns encrypted backup blob
|
||||
CmdImportIdentity IpcMsgType = "import_identity" // replaces identity from backup blob
|
||||
|
||||
// Events (daemon → UI)
|
||||
EvtMessageReceived IpcMsgType = "message_received"
|
||||
@@ -235,6 +237,8 @@ const (
|
||||
EvtFileComplete IpcMsgType = "file_complete"
|
||||
EvtNetworkJoined IpcMsgType = "network_joined"
|
||||
EvtNetworkLeft IpcMsgType = "network_left"
|
||||
EvtIdentityExported IpcMsgType = "identity_exported"
|
||||
EvtIdentityImported IpcMsgType = "identity_imported"
|
||||
)
|
||||
|
||||
// NetworkInfo summarises one joined network for state_snapshot and network_joined events.
|
||||
@@ -284,4 +288,7 @@ type IpcMessage struct {
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
InviteString string `json:"invite,omitempty"`
|
||||
Files []FileEntry `json:"files,omitempty"`
|
||||
// export_identity / import_identity
|
||||
Passphrase string `json:"passphrase,omitempty"` // import only; never echoed back
|
||||
Backup string `json:"backup,omitempty"` // JSON backup blob
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user