Files
arca/cmd/init.go
Kyle Isom c835358829 Initial implementation of arca, a LUKS volume manager.
Go CLI using cobra with mount, unmount, status, and init subcommands.
Unlocks via udisks2 D-Bus (passphrase/keyfile) or cryptsetup (FIDO2/TPM2)
with ordered method fallback. Includes NixOS-specific LD_LIBRARY_PATH
injection for systemd cryptsetup token plugins.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 07:42:38 -07:00

109 lines
2.5 KiB
Go

package cmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"git.wntrmute.dev/kyle/arca/internal/config"
"git.wntrmute.dev/kyle/arca/internal/udisks"
"github.com/godbus/dbus/v5"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
var forceInit bool
var initCmd = &cobra.Command{
Use: "init",
Short: "Generate config from detected LUKS devices",
Long: "Scans for LUKS-encrypted devices, excludes the root filesystem, and writes a config file with passphrase as the default unlock method.",
RunE: runInit,
}
func init() {
initCmd.Flags().BoolVarP(&forceInit, "force", "f", false, "overwrite existing config file")
rootCmd.AddCommand(initCmd)
}
func runInit(cmd *cobra.Command, args []string) error {
cfgPath := config.Path()
if !forceInit {
if _, err := os.Stat(cfgPath); err == nil {
return fmt.Errorf("config already exists at %s (use --force to overwrite)", cfgPath)
}
}
client, err := udisks.NewClient()
if err != nil {
return fmt.Errorf("connecting to udisks2: %w", err)
}
defer client.Close()
encrypted, err := client.ListEncryptedDevices()
if err != nil {
return err
}
rootBacking, err := client.RootBackingDevices()
if err != nil {
return fmt.Errorf("detecting root device: %w", err)
}
cfg := config.Config{
Devices: make(map[string]config.DeviceConfig),
}
for _, dev := range encrypted {
if isRootBacking(dev.ObjectPath, rootBacking) {
fmt.Fprintf(os.Stderr, "Skipping %s (root filesystem)\n", dev.DevicePath)
continue
}
alias := aliasFromPath(dev.DevicePath)
cfg.Devices[alias] = config.DeviceConfig{
UUID: dev.UUID,
Methods: []string{"passphrase"},
}
fmt.Fprintf(os.Stderr, "Found %s (UUID %s) -> alias %q\n", dev.DevicePath, dev.UUID, alias)
}
if len(cfg.Devices) == 0 {
fmt.Println("No non-root LUKS devices found.")
return nil
}
data, err := yaml.Marshal(&cfg)
if err != nil {
return fmt.Errorf("marshaling config: %w", err)
}
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
return fmt.Errorf("creating config directory: %w", err)
}
if err := os.WriteFile(cfgPath, data, 0o644); err != nil {
return fmt.Errorf("writing config: %w", err)
}
fmt.Printf("Config written to %s\n", cfgPath)
return nil
}
func isRootBacking(path dbus.ObjectPath, rootDevices []dbus.ObjectPath) bool {
for _, r := range rootDevices {
if path == r {
return true
}
}
return false
}
func aliasFromPath(devPath string) string {
// "/dev/sda1" -> "sda1", "/dev/nvme0n1p2" -> "nvme0n1p2"
base := filepath.Base(devPath)
return strings.TrimPrefix(base, "dm-")
}