// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Package seal keeps a bridge's account secrets sealed in its database (QA-289). With // XESSENGER_SEAL_KEY_FILE set, each secret is stored as AES-256-GCM under a key only the bridge's // enclave holds, bound by its associated data to the bridge, table, login and field it belongs to, // and opened when read. Without the variable nothing is sealed and stored values are read as they // are, as before. Started with XESSENGER_SEAL_UNSEAL=1 as well, a bridge rewrites what its key // sealed in the form it had before and exits, so that it can run without the key again. Keys the // bridge needs beyond sealing (the Matrix pickle key, the ghost ID hash key) are derived from its // key (Derive) and never stored while it has the key (DerivedKeys). // // The same file is built into every bridge: infra/matrix//seal (a module of its own, which // the patched mautrix-go and whatsmeow import) and services/email/internal/seal (the copy whose // tests run, which the email bridge's patched mautrix-go imports as a module of its own too, // services/email/xessenger-mautrix.sh). infra/matrix/check-no-replay.sh fails when a copy differs. package seal import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/hkdf" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "os" "path/filepath" "slices" "strings" "sync" ) // EnvKeyFile names the variable holding the path of the bridge's key: 32 raw bytes in a file named // after the bridge, /run/xessenger/seal/.key. const EnvKeyFile = "XESSENGER_SEAL_KEY_FILE" // EnvUnseal names the variable that starts a bridge to unseal: with XESSENGER_SEAL_UNSEAL=1 and its // key, the bridge rewrites every value its key sealed in the form the value had before sealing, // and exits without connecting anywhere. 1 is its only value. const EnvUnseal = "XESSENGER_SEAL_UNSEAL" // Prefix starts every sealed value. A sealed value is Prefix, a 12-byte nonce and the AES-GCM // ciphertext with its tag: as raw bytes in binary columns, base64 after Prefix in text ones. const Prefix = "xs1:" const ( nonceSize = 12 tagSize = 16 ) // Bridges are the bridges a key file may be named after. var Bridges = []string{"whatsapp", "telegram", "instagram", "facebook", "line", "email"} // LoginSecrets lists, per bridge, the user_login.metadata fields holding what would let whoever // reads them sign in, read or send as the account. The other fields stay as they are: the API // reads some of them in SQL (backfill_completed, history_sync_portals_need_creating) and so does // scripts/reset-local-gmail.mjs (gmail_history_id). var LoginSecrets = map[string][]string{ // Web push and APNs keys decrypt the notifications WhatsApp pushes for the account. "whatsapp": {"push_keys", "apns_enc_privkey"}, // The Meta session cookies sign in as the account; the native session holds its access token. "instagram": {"cookies", "push_keys", "native_session", "native_push_keys"}, "facebook": {"cookies", "push_keys", "native_session", "native_push_keys"}, // session holds the MTProto auth key, which is the whole Telegram session. "telegram": {"session", "push_encryption_key"}, // Tokens, the certificate that skips the PIN, and the E2EE key chain and exported keys. "line": {"access_token", "refresh_token", "password", "certificate", "encrypted_key_chain", "exported_key_map"}, // What network.encryption_key encrypted ("v1:", services/email/pkg/connector/secrets.go), as // the email bridge stores them without the key and after unsealing. "email": {"gmail_refresh_token", "gmail_app_password"}, } // DerivedKey is a key a bridge derives from its key (Derive), and KV the kv_store key that may hold // a copy of it in hex. type DerivedKey struct{ KV, Label string } // DerivedKeys are the keys derived from a bridge's key that it uses beyond sealing. With its key a // bridge always uses what Derive gives, never a stored copy: at start a copy must be that same key // and is removed, or the bridge does not start, so that a key planted in its database is never // used. Only a bridge started to unseal stores them, in plaintext, for the bridge started without // its key afterwards, which reads them from there (mautrix-seal.patch). var DerivedKeys = []DerivedKey{ {"xessenger_pickle_key", "pickle-key"}, // the Matrix crypto store's pickle key {"xessenger_ghost_hmac_key", "ghost-hmac"}, // the ghost ID hash key (services/bridgekit) {"xessenger_bridgekit_store_key", "bridgekit-store"}, // bridgekit's store key } var ( // ErrNoKey is a sealed value read without a key: the bridge runs without XESSENGER_SEAL_KEY_FILE // against a database a sealing bridge has written. ErrNoKey = errors.New("sealed value found, but " + EnvKeyFile + " is not set") // ErrOpen is a sealed value that does not open: another key, or a value moved from another // bridge, table, login or field. ErrOpen = errors.New("sealed value does not open with this bridge's key at this place") ) // Sealer seals and opens one bridge's secrets. A nil *Sealer is sealing turned off: Seal returns // values as they are, and Open returns plaintext and refuses sealed values with ErrNoKey. type Sealer struct { bridge string key []byte aead cipher.AEAD unseal bool } // New makes the sealer of bridge from its 32-byte key. The cipher key is derived from it with // HKDF-SHA256 for its purpose and bridge, like the keys Derive gives. func New(bridge string, key []byte) (*Sealer, error) { if !slices.Contains(Bridges, bridge) { return nil, fmt.Errorf("seal: unknown bridge %q", bridge) } else if len(key) != 32 { return nil, fmt.Errorf("seal: the key must be 32 bytes, not %d", len(key)) } cipherKey, err := hkdf.Key(sha256.New, key, nil, "xessenger/seal/v1/aes-256-gcm/"+bridge, 32) if err != nil { return nil, err } block, err := aes.NewCipher(cipherKey) if err != nil { return nil, err } aead, err := cipher.NewGCM(block) if err != nil { return nil, err } return &Sealer{bridge: bridge, key: bytes.Clone(key), aead: aead}, nil } // Load reads a key file. Its name, .key, says whose key it is. func Load(path string) (*Sealer, error) { bridge, ok := strings.CutSuffix(filepath.Base(path), ".key") if !ok || !slices.Contains(Bridges, bridge) { return nil, fmt.Errorf("%s=%q: the key file must be named .key, the bridge one of %s", EnvKeyFile, path, strings.Join(Bridges, ", ")) } key, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("%s: %w", EnvKeyFile, err) } defer clear(key) if len(key) != 32 { return nil, fmt.Errorf("%s=%q: the key must be 32 raw bytes, not %d", EnvKeyFile, path, len(key)) } return New(bridge, key) } var ( defaultOnce sync.Once defaultSealer *Sealer defaultErr error overrideLock sync.RWMutex overridden bool overrideSealer *Sealer ) // Default is the sealer XESSENGER_SEAL_KEY_FILE configures, read once; nil when the variable is // unset. A set variable whose file cannot be used is an error, never plaintext, and so is // XESSENGER_SEAL_UNSEAL with any value but 1, or without a key to open what it sealed. func Default() (*Sealer, error) { overrideLock.RLock() if overridden { defer overrideLock.RUnlock() return overrideSealer, nil } overrideLock.RUnlock() defaultOnce.Do(func() { defaultSealer, defaultErr = fromEnv() }) return defaultSealer, defaultErr } func fromEnv() (*Sealer, error) { unseal := false switch value := os.Getenv(EnvUnseal); value { case "": case "1": unseal = true default: return nil, fmt.Errorf("%s=%q: its only value is 1", EnvUnseal, value) } path, ok := os.LookupEnv(EnvKeyFile) if !ok { if unseal { return nil, fmt.Errorf("%s=1 needs %s: only the bridge's key opens what it sealed", EnvUnseal, EnvKeyFile) } return nil, nil } sealer, err := Load(path) if err != nil { return nil, err } sealer.unseal = unseal return sealer, nil } // MustDefault is Default for code that cannot return its error. A bridge calls Default when it // starts and stops there on an error, before anything reaches this. func MustDefault() *Sealer { sealer, err := Default() if err != nil { panic(err) } return sealer } // SetDefault makes Default return sealer until restore is called; for tests. func SetDefault(sealer *Sealer) (restore func()) { overrideLock.Lock() defer overrideLock.Unlock() wasOverridden, previous := overridden, overrideSealer overridden, overrideSealer = true, sealer return func() { overrideLock.Lock() defer overrideLock.Unlock() overridden, overrideSealer = wasOverridden, previous } } // Bridge is the bridge the key belongs to, "" without one. func (s *Sealer) Bridge() string { if s == nil { return "" } return s.bridge } // Unsealing reports whether the bridge was started to unseal (XESSENGER_SEAL_UNSEAL=1). func (s *Sealer) Unsealing() bool { return s != nil && s.unseal } // Derive is a 32-byte key of the bridge for the purpose label names, derived from the bridge's key // with HKDF-SHA256 (info "xessenger/seal/v1/derive/