carlos / platform Public

console: saved domain contacts, registrant snapshot, app-less purchases

domain_saved_contacts holds an account's registrant contacts; an edit
bumps the version and clears the handle, and a minted handle is written
back only for the version it was minted for. Registrations store their
registrant. migrateDomains backfills saved contacts from domain_contacts
once (marker in domain_meta) and registrants from the newest purchase
with a contact. domain_purchases is FreeWhenNoApp so a "Not yet"
purchase (app '') needs no permit. Spec 11.7 gains the storage note.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d0d1cb727c7b6866fa47956252e9c7afce05afba parent ca0da60
4 files changed, +727 −5
  • docs/superpowers/specs/2026-11-01-domain-registration-design.md +21 −0
  • internal/console/domainstore.go +381 −2
  • internal/console/domainstore_test.go +320 −0
  • internal/console/store_gate.go +5 −3
diff --git a/docs/superpowers/specs/2026-11-01-domain-registration-design.md b/docs/superpowers/specs/2026-11-01-domain-registration-design.md
index 0387e211f..cabb00ec3 100644
--- a/docs/superpowers/specs/2026-11-01-domain-registration-design.md
+++ b/docs/superpowers/specs/2026-11-01-domain-registration-design.md
@@ -574,6 +574,27 @@ Renewal, Registered to or Transfer out.
the registration it becomes are stored per account, not in an app's
database, so renewals, the reconcile and transfer out read one list. The
storage mechanism is the builder's.
+- **Storage as built (builder's note, Plan 2a):** purchases and
+ registrations already live in console.db keyed by account
+ (`domain_purchases`, `domain_registrations`), so the move is a no-op:
+ existing purchase rows keep their ID, state and URL. A "Not yet"
+ purchase stores app `''`; under the HostClaim gate `domain_purchases`
+ is `FreeWhenNoApp`, like user CLI tokens. Saved contacts live in
+ `domain_saved_contacts`, keyed by account. A purchase is bound to one
+ frozen contact (R12): at start it copies the saved contact's Contact,
+ Version and Handle into its details, and later steps read only the
+ frozen copy. A saved contact's handle is never passed to the
+ registrar's ensure-contact call again. An edit bumps Version and clears
+ the handle; a minted handle is written back only when Version still
+ matches and the handle is still empty. Each registration stores its
+ registrant (the purchase's frozen contact), which no contact edit
+ changes. One-time backfills: Plan 1's single contact per account
+ becomes a saved contact with the same handle (once, recorded in
+ `domain_meta`, so a contact removed later never returns), and each
+ registration without a registrant takes the contact of the newest
+ purchase for the same account and domain. Existing purchases are not
+ rewritten: one with no saved-contact ID keeps using its own frozen
+ contact and handle.
- **Migration:** every existing purchase record (dev witnesses, and any
flagship purchase made before this ships) moves to the account store
once, idempotently, keeping its ID and state. The purchase card URLs keep
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go
index 10bf0d61f..f0a46b9da 100644
--- a/internal/console/domainstore.go
+++ b/internal/console/domainstore.go
@@ -1,6 +1,7 @@
package console
import (
+ "context"
"crypto/rand"
"database/sql"
"encoding/hex"
@@ -31,6 +32,9 @@ const (
var (
ErrDomainPurchaseLive = errors.New("console: live domain purchase exists")
ErrPurchaseStateMoved = errors.New("console: domain purchase state moved")
+ // ErrSavedContactNotFound is an edit or removal of a saved contact that
+ // does not exist or belongs to another account.
+ ErrSavedContactNotFound = errors.New("console: saved contact not found")
)
type purchaseDetails struct {
@@ -43,6 +47,11 @@ type purchaseDetails struct {
RegisterAlerted bool
SetupStartedAt time.Time
SetupAlerted bool
+ // ContactID and ContactVersion name the saved contact the purchase froze
+ // at start. ContactID is "" on purchases made before saved contacts: such
+ // a legacy purchase uses its own Contact and OwnerHandle.
+ ContactID string
+ ContactVersion int64
}
type DomainPurchase struct {
@@ -66,6 +75,21 @@ type DomainRegistration struct {
Expires time.Time
AutoRenew bool
CreatedAt time.Time
+ // Registrant is the purchase's frozen contact; a saved-contact edit
+ // never changes it.
+ Registrant registrar.Contact
+}
+
+// SavedContact is one of an account's registrant contacts. Every edit bumps
+// Version and clears Handle, so a registrar handle minted for one version is
+// never used for another.
+type SavedContact struct {
+ ID string // "dc_" + 12 random hex
+ AccountID int64
+ Contact registrar.Contact
+ Version int64 // 1 on add, +1 on every edit
+ Handle string // registrar handle for this Version; "" until a purchase mints one
+ LastUsed, CreatedAt time.Time
}
const liveDomainPurchaseSQL = `state NOT IN ('done','failed','expired','unpaid')`
@@ -106,6 +130,20 @@ CREATE TABLE IF NOT EXISTS domain_registrations (
expires_at INTEGER NOT NULL,
auto_renew INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL
+);
+CREATE TABLE IF NOT EXISTS domain_saved_contacts (
+ id TEXT PRIMARY KEY,
+ account_id INTEGER NOT NULL,
+ contact TEXT NOT NULL,
+ version INTEGER NOT NULL DEFAULT 1,
+ handle TEXT NOT NULL DEFAULT '',
+ last_used INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS domain_saved_contacts_account ON domain_saved_contacts(account_id);
+CREATE TABLE IF NOT EXISTS domain_meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
);`)
if err != nil {
return err
@@ -113,14 +151,113 @@ CREATE TABLE IF NOT EXISTS domain_registrations (
for _, stmt := range []string{
`ALTER TABLE domain_purchases ADD COLUMN details TEXT NOT NULL DEFAULT '{}'`,
`ALTER TABLE domain_purchases ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE domain_registrations ADD COLUMN registrant TEXT NOT NULL DEFAULT '{}'`,
} {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
}
+ ctx := context.Background() // boot migration: there is no request to inherit
+ if err := s.backfillSavedContacts(ctx); err != nil {
+ return err
+ }
+ return s.backfillRegistrants(ctx)
+}
+
+// backfillSavedContacts copies each domain_contacts row into a saved contact
+// once. The domain_meta marker commits with the copies, so a contact edited
+// or removed afterwards never comes back on a restart.
+func (s *Store) backfillSavedContacts(ctx context.Context) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var done int
+ if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM domain_meta WHERE key = 'saved_contacts_backfilled'`).Scan(&done); err != nil {
+ return err
+ }
+ if done != 0 {
+ return nil
+ }
+ if _, err := tx.ExecContext(ctx, `INSERT INTO domain_saved_contacts (id, account_id, contact, version, handle, last_used, created_at)
+ SELECT 'dc_' || lower(hex(randomblob(6))), account_id, contact, 1, handle, updated_at, updated_at FROM domain_contacts`); err != nil {
+ return err
+ }
+ if _, err := tx.ExecContext(ctx, `INSERT INTO domain_meta (key, value) VALUES ('saved_contacts_backfilled', '1')`); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// backfillRegistrants gives each registration with no registrant the
+// contact of the newest purchase for the same account and domain whose
+// details carry one, whatever that purchase's state. Purchases are not
+// rewritten.
+func (s *Store) backfillRegistrants(ctx context.Context) error {
+ rows, err := s.db.QueryContext(ctx, `SELECT domain, account_id FROM domain_registrations WHERE registrant = '{}'`)
+ if err != nil {
+ return err
+ }
+ type reg struct {
+ domain string
+ account int64
+ }
+ var regs []reg
+ for rows.Next() {
+ var r reg
+ if err := rows.Scan(&r.domain, &r.account); err != nil {
+ rows.Close()
+ return err
+ }
+ regs = append(regs, r)
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return err
+ }
+ for _, r := range regs {
+ c, err := s.newestPurchaseContact(ctx, r.account, r.domain)
+ if err != nil {
+ return err
+ }
+ if c == (registrar.Contact{}) {
+ continue
+ }
+ registrant, err := json.Marshal(c)
+ if err != nil {
+ return err
+ }
+ if _, err := s.db.ExecContext(ctx, `UPDATE domain_registrations SET registrant = ? WHERE domain = ? AND account_id = ? AND registrant = '{}'`,
+ string(registrant), r.domain, r.account); err != nil {
+ return err
+ }
+ }
return nil
}
+func (s *Store) newestPurchaseContact(ctx context.Context, accountID int64, domain string) (registrar.Contact, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT details FROM domain_purchases WHERE account_id = ? AND domain = ? ORDER BY created_at DESC, rowid DESC`, accountID, domain)
+ if err != nil {
+ return registrar.Contact{}, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var details string
+ if err := rows.Scan(&details); err != nil {
+ return registrar.Contact{}, err
+ }
+ var d purchaseDetails
+ if err := json.Unmarshal([]byte(details), &d); err != nil {
+ return registrar.Contact{}, err
+ }
+ if d.Contact != (registrar.Contact{}) {
+ return d.Contact, nil
+ }
+ }
+ return registrar.Contact{}, rows.Err()
+}
+
func newDomainPurchaseID() string {
var b [8]byte
_, _ = rand.Read(b[:])
@@ -292,8 +429,250 @@ func (s *Store) AddDomainRegistration(r DomainRegistration) error {
if r.CreatedAt.IsZero() {
r.CreatedAt = time.Now().UTC()
}
- _, err := s.db.Exec(`INSERT INTO domain_registrations (domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`, r.Domain, r.AccountID, r.RegistrarID, r.ZoneID, domainUnix(r.Expires), r.AutoRenew, r.CreatedAt.Unix())
+ registrant, err := registrantJSON(r.Registrant)
+ if err != nil {
+ return err
+ }
+ _, err = s.db.Exec(`INSERT INTO domain_registrations (domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at, registrant)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, r.Domain, r.AccountID, r.RegistrarID, r.ZoneID, domainUnix(r.Expires), r.AutoRenew, r.CreatedAt.Unix(), registrant)
+ return err
+}
+
+// registrantJSON stores an empty registrant as '{}', the marker the
+// registrant backfill looks for.
+func registrantJSON(c registrar.Contact) (string, error) {
+ if c == (registrar.Contact{}) {
+ return "{}", nil
+ }
+ b, err := json.Marshal(c)
+ return string(b), err
+}
+
+const domainRegistrationColumns = `domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at, registrant`
+
+func scanDomainRegistration(sc interface{ Scan(...any) error }) (*DomainRegistration, error) {
+ var r DomainRegistration
+ var expires, created int64
+ var registrant string
+ if err := sc.Scan(&r.Domain, &r.AccountID, &r.RegistrarID, &r.ZoneID, &expires, &r.AutoRenew, &created, &registrant); err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(registrant), &r.Registrant); err != nil {
+ return nil, err
+ }
+ if expires != 0 {
+ r.Expires = time.Unix(expires, 0).UTC()
+ }
+ r.CreatedAt = time.Unix(created, 0).UTC()
+ return &r, nil
+}
+
+// DomainRegistrations lists an account's registrations by domain.
+func (s *Store) DomainRegistrations(accountID int64) ([]DomainRegistration, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ rows, err := s.db.QueryContext(ctx, `SELECT `+domainRegistrationColumns+` FROM domain_registrations WHERE account_id = ? ORDER BY domain`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []DomainRegistration
+ for rows.Next() {
+ r, err := scanDomainRegistration(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *r)
+ }
+ return out, rows.Err()
+}
+
+// DomainRegistrationFor is nil, nil when the domain is not registered to
+// this account.
+func (s *Store) DomainRegistrationFor(accountID int64, domain string) (*DomainRegistration, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ r, err := scanDomainRegistration(s.db.QueryRowContext(ctx, `SELECT `+domainRegistrationColumns+` FROM domain_registrations WHERE domain = ? AND account_id = ?`, domain, accountID))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return r, err
+}
+
+// AccountDomainPurchases lists an account's purchases still in flight,
+// newest first.
+func (s *Store) AccountDomainPurchases(accountID int64) ([]DomainPurchase, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ rows, err := s.db.QueryContext(ctx, `SELECT `+domainPurchaseColumns+` FROM domain_purchases WHERE account_id = ? AND `+liveDomainPurchaseSQL+` ORDER BY created_at DESC, rowid DESC`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []DomainPurchase
+ for rows.Next() {
+ p, err := scanDomainPurchase(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *p)
+ }
+ return out, rows.Err()
+}
+
+// DomainObligations lists, sorted, the domains an account holds a
+// registration for or is still buying.
+func (s *Store) DomainObligations(accountID int64) ([]string, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ rows, err := s.db.QueryContext(ctx, `SELECT domain FROM domain_registrations WHERE account_id = ?
+ UNION SELECT domain FROM domain_purchases WHERE account_id = ? AND `+liveDomainPurchaseSQL+`
+ ORDER BY domain`, accountID, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var d string
+ if err := rows.Scan(&d); err != nil {
+ return nil, err
+ }
+ out = append(out, d)
+ }
+ return out, rows.Err()
+}
+
+func newSavedContactID() string {
+ var b [6]byte
+ _, _ = rand.Read(b[:])
+ return "dc_" + hex.EncodeToString(b[:])
+}
+
+const savedContactColumns = `id, account_id, contact, version, handle, last_used, created_at`
+
+func scanSavedContact(sc interface{ Scan(...any) error }) (*SavedContact, error) {
+ var id, contact, handle string
+ var account, version, used, created int64
+ if err := sc.Scan(&id, &account, &contact, &version, &handle, &used, &created); err != nil {
+ return nil, err
+ }
+ // A selector named Handle, on any receiver, trips the route census
+ // (TestClaimConsoleMuxHasOneRegistrar), so the field is set by key.
+ c := SavedContact{ID: id, AccountID: account, Version: version, Handle: handle}
+ if err := json.Unmarshal([]byte(contact), &c.Contact); err != nil {
+ return nil, err
+ }
+ if used != 0 {
+ c.LastUsed = time.Unix(used, 0).UTC()
+ }
+ c.CreatedAt = time.Unix(created, 0).UTC()
+ return &c, nil
+}
+
+// SavedContacts lists an account's saved contacts, most recently used
+// first, then newest first.
+func (s *Store) SavedContacts(accountID int64) ([]SavedContact, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ rows, err := s.db.QueryContext(ctx, `SELECT `+savedContactColumns+` FROM domain_saved_contacts WHERE account_id = ?
+ ORDER BY last_used DESC, created_at DESC, rowid DESC`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []SavedContact
+ for rows.Next() {
+ c, err := scanSavedContact(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *c)
+ }
+ return out, rows.Err()
+}
+
+// SavedContact is nil, nil when the contact is missing or another account's.
+func (s *Store) SavedContact(accountID int64, id string) (*SavedContact, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ c, err := scanSavedContact(s.db.QueryRowContext(ctx, `SELECT `+savedContactColumns+` FROM domain_saved_contacts WHERE account_id = ? AND id = ?`, accountID, id))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return c, err
+}
+
+func (s *Store) AddSavedContact(accountID int64, c registrar.Contact, now time.Time) (SavedContact, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ if err := c.Validate(); err != nil {
+ return SavedContact{}, err
+ }
+ contact, err := json.Marshal(c)
+ if err != nil {
+ return SavedContact{}, err
+ }
+ sc := SavedContact{ID: newSavedContactID(), AccountID: accountID, Contact: c, Version: 1, CreatedAt: time.Unix(now.Unix(), 0).UTC()}
+ _, err = s.db.ExecContext(ctx, `INSERT INTO domain_saved_contacts (`+savedContactColumns+`) VALUES (?, ?, ?, 1, '', 0, ?)`,
+ sc.ID, accountID, string(contact), sc.CreatedAt.Unix())
+ if err != nil {
+ return SavedContact{}, err
+ }
+ return sc, nil
+}
+
+// EditSavedContact replaces the contact, bumps Version and clears Handle:
+// the registrar handle of the old version is never used for the new one.
+// Registrations and purchases keep their frozen copies.
+func (s *Store) EditSavedContact(accountID int64, id string, c registrar.Contact) error {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ if err := c.Validate(); err != nil {
+ return err
+ }
+ contact, err := json.Marshal(c)
+ if err != nil {
+ return err
+ }
+ res, err := s.db.ExecContext(ctx, `UPDATE domain_saved_contacts SET contact = ?, version = version + 1, handle = '' WHERE account_id = ? AND id = ?`,
+ string(contact), accountID, id)
+ return savedContactAffected(res, err)
+}
+
+// RemoveSavedContact removes the contact from the list only; purchases and
+// registrations keep their frozen copy.
+func (s *Store) RemoveSavedContact(accountID int64, id string) error {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ res, err := s.db.ExecContext(ctx, `DELETE FROM domain_saved_contacts WHERE account_id = ? AND id = ?`, accountID, id)
+ return savedContactAffected(res, err)
+}
+
+func savedContactAffected(res sql.Result, err error) error {
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return ErrSavedContactNotFound
+ }
+ return nil
+}
+
+// SetSavedContactHandle records a handle minted for one version of a saved
+// contact. It is false, and changes nothing, when the contact has been
+// edited since (version moved) or already has a handle.
+func (s *Store) SetSavedContactHandle(accountID int64, id string, version int64, handle string) (bool, error) {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ res, err := s.db.ExecContext(ctx, `UPDATE domain_saved_contacts SET handle = ? WHERE account_id = ? AND id = ? AND version = ? AND handle = ''`,
+ handle, accountID, id, version)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
+}
+
+// TouchSavedContact sets LastUsed only. A contact removed meanwhile is not
+// an error.
+func (s *Store) TouchSavedContact(accountID int64, id string, now time.Time) error {
+ ctx := context.Background() // the domain store API takes no ctx yet; there is none to inherit
+ _, err := s.db.ExecContext(ctx, `UPDATE domain_saved_contacts SET last_used = ? WHERE account_id = ? AND id = ?`, now.Unix(), accountID, id)
return err
}
diff --git a/internal/console/domainstore_test.go b/internal/console/domainstore_test.go
index ccc3e6bf9..361c13cf0 100644
--- a/internal/console/domainstore_test.go
+++ b/internal/console/domainstore_test.go
@@ -278,3 +278,323 @@ func TestDomainPurchaseClaimGate(t *testing.T) {
t.Fatalf("gated purchase: %+v, %v", row, err)
}
}
+
+func savedTestContact(first string) registrar.Contact {
+ return registrar.Contact{FirstName: first, LastName: "Doe", Email: first + "@example.com", PhoneCountryCode: "353", Phone: "123456789",
+ Street: "Main Street", HouseNumber: "12", City: "Dublin", PostalCode: "D01TEST", Country: "IE"}
+}
+
+func TestSavedContactsOrderAndAccountScope(t *testing.T) {
+ s := openTestStore(t)
+ base := time.Date(2026, 11, 19, 10, 0, 0, 0, time.UTC)
+ if _, err := s.AddSavedContact(1, registrar.Contact{FirstName: "Half"}, base); err == nil {
+ t.Fatal("invalid contact saved")
+ }
+ var ids []string
+ for i, name := range []string{"alpha", "bravo", "charlie", "delta"} {
+ c, err := s.AddSavedContact(1, savedTestContact(name), base.Add(time.Duration(i)*time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !regexp.MustCompile(`^dc_[0-9a-f]{12}$`).MatchString(c.ID) || c.AccountID != 1 || c.Version != 1 || c.Handle != "" ||
+ !c.LastUsed.IsZero() || !c.CreatedAt.Equal(base.Add(time.Duration(i)*time.Minute)) || c.Contact != savedTestContact(name) {
+ t.Fatalf("added: %+v", c)
+ }
+ ids = append(ids, c.ID)
+ }
+ other, err := s.AddSavedContact(2, savedTestContact("other"), base.Add(time.Hour))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // bravo used last, alpha before it; charlie and delta never used: newest first.
+ if err := s.TouchSavedContact(1, ids[0], base.Add(2*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.TouchSavedContact(1, ids[1], base.Add(3*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.TouchSavedContact(1, other.ID, base.Add(4*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ list, err := s.SavedContacts(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, c := range list {
+ got = append(got, c.Contact.FirstName)
+ }
+ if want := []string{"bravo", "alpha", "delta", "charlie"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("order = %v, want %v", got, want)
+ }
+ if !list[0].LastUsed.Equal(base.Add(3 * time.Hour)) {
+ t.Fatalf("last used: %+v", list[0])
+ }
+ if c, err := s.SavedContact(1, other.ID); err != nil || c != nil {
+ t.Fatalf("another account's contact: %+v, %v", c, err)
+ }
+ if c, err := s.SavedContact(1, "dc_000000000000"); err != nil || c != nil {
+ t.Fatalf("missing contact: %+v, %v", c, err)
+ }
+ if c, err := s.SavedContact(2, other.ID); err != nil || c == nil || !c.LastUsed.IsZero() || c.Contact.FirstName != "other" {
+ t.Fatalf("other account touched across accounts or missing: %+v, %v", c, err)
+ }
+ if err := s.EditSavedContact(1, other.ID, savedTestContact("stolen")); !errors.Is(err, ErrSavedContactNotFound) {
+ t.Fatalf("cross-account edit: %v", err)
+ }
+ if err := s.RemoveSavedContact(1, other.ID); !errors.Is(err, ErrSavedContactNotFound) {
+ t.Fatalf("cross-account remove: %v", err)
+ }
+ if list, err := s.SavedContacts(2); err != nil || len(list) != 1 || list[0].Contact.FirstName != "other" {
+ t.Fatalf("other account list: %+v, %v", list, err)
+ }
+ if err := s.RemoveSavedContact(1, ids[0]); err != nil {
+ t.Fatal(err)
+ }
+ if list, err := s.SavedContacts(1); err != nil || len(list) != 3 {
+ t.Fatalf("after remove: %+v, %v", list, err)
+ }
+}
+
+func TestEditSavedContactBumpsVersionClearsHandle(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Date(2026, 11, 19, 10, 0, 0, 0, time.UTC)
+ c, err := s.AddSavedContact(1, savedTestContact("jane"), now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := s.SetSavedContactHandle(1, c.ID, 1, "handle-1"); err != nil || !ok {
+ t.Fatalf("set handle: %v, %v", ok, err)
+ }
+ if err := s.TouchSavedContact(1, c.ID, now.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.EditSavedContact(1, c.ID, registrar.Contact{FirstName: "Half"}); err == nil {
+ t.Fatal("invalid edit accepted")
+ }
+ edited := savedTestContact("janet")
+ if err := s.EditSavedContact(1, c.ID, edited); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.SavedContact(1, c.ID)
+ if err != nil || got == nil {
+ t.Fatalf("after edit: %+v, %v", got, err)
+ }
+ if got.Version != 2 || got.Handle != "" || got.Contact != edited || !got.CreatedAt.Equal(now) || !got.LastUsed.Equal(now.Add(time.Hour)) {
+ t.Fatalf("after edit: %+v", got)
+ }
+ if err := s.EditSavedContact(1, c.ID, edited); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := s.SavedContact(1, c.ID); err != nil || got.Version != 3 {
+ t.Fatalf("second edit: %+v, %v", got, err)
+ }
+ if err := s.EditSavedContact(1, "dc_000000000000", edited); !errors.Is(err, ErrSavedContactNotFound) {
+ t.Fatalf("missing edit: %v", err)
+ }
+}
+
+func TestSetSavedContactHandleIsConditional(t *testing.T) {
+ s := openTestStore(t)
+ c, err := s.AddSavedContact(1, savedTestContact("jane"), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.EditSavedContact(1, c.ID, savedTestContact("janet")); err != nil {
+ t.Fatal(err)
+ }
+ // A purchase that froze version 1 mints a handle after the edit: refused.
+ if ok, err := s.SetSavedContactHandle(1, c.ID, 1, "stale"); err != nil || ok {
+ t.Fatalf("stale version: %v, %v", ok, err)
+ }
+ if got, _ := s.SavedContact(1, c.ID); got.Handle != "" || got.Version != 2 {
+ t.Fatalf("stale write changed row: %+v", got)
+ }
+ if ok, err := s.SetSavedContactHandle(2, c.ID, 2, "cross"); err != nil || ok {
+ t.Fatalf("other account: %v, %v", ok, err)
+ }
+ if ok, err := s.SetSavedContactHandle(1, c.ID, 2, "first"); err != nil || !ok {
+ t.Fatalf("matching version: %v, %v", ok, err)
+ }
+ if ok, err := s.SetSavedContactHandle(1, c.ID, 2, "second"); err != nil || ok {
+ t.Fatalf("existing handle: %v, %v", ok, err)
+ }
+ if got, _ := s.SavedContact(1, c.ID); got.Handle != "first" || got.Version != 2 {
+ t.Fatalf("handle: %+v", got)
+ }
+}
+
+// seedLegacyDomainState writes what a console.db from before saved contacts
+// holds: a domain_contacts row, registrations with no registrant, and the
+// purchases they came from. It clears the backfill marker the open just wrote.
+func seedLegacyDomainState(t *testing.T, s *Store) (registered, done registrar.Contact) {
+ t.Helper()
+ if err := s.SetDomainContact(123, savedTestContact("legacy"), "contact-1"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`DELETE FROM domain_meta WHERE key = 'saved_contacts_backfilled'`); err != nil {
+ t.Fatal(err)
+ }
+ registered, done = savedTestContact("registered"), savedTestContact("done")
+ t0 := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
+ purchases := []DomainPurchase{
+ {ID: "dp_0000000000000001", AccountID: 123, Domain: "one.example", State: PurchaseRegistered, CreatedAt: t0, purchaseDetails: purchaseDetails{Contact: registered, OwnerHandle: "contact-1"}},
+ {ID: "dp_0000000000000002", AccountID: 123, Domain: "two.example", State: PurchaseFailed, CreatedAt: t0, purchaseDetails: purchaseDetails{Contact: savedTestContact("older")}},
+ {ID: "dp_0000000000000003", AccountID: 123, Domain: "two.example", State: PurchaseDone, CreatedAt: t0.Add(time.Hour), purchaseDetails: purchaseDetails{Contact: done}},
+ {ID: "dp_0000000000000004", AccountID: 123, Domain: "two.example", State: PurchaseExpired, CreatedAt: t0.Add(2 * time.Hour)},
+ {ID: "dp_0000000000000005", AccountID: 456, Domain: "two.example", State: PurchaseFailed, CreatedAt: t0.Add(3 * time.Hour), purchaseDetails: purchaseDetails{Contact: savedTestContact("stranger")}},
+ }
+ for _, p := range purchases {
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, d := range []string{"one.example", "two.example", "three.example"} {
+ if err := s.AddDomainRegistration(DomainRegistration{Domain: d, AccountID: 123, RegistrarID: "reg_" + d, ZoneID: "zone", Expires: t0.AddDate(1, 0, 0)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if n := countWhere(t, s, "domain_registrations", "registrant = '{}'"); n != 3 {
+ t.Fatalf("registrations without registrant = %d, want 3", n)
+ }
+ return registered, done
+}
+
+func TestMigrateDomainsBackfillsContactsAndRegistrant(t *testing.T) {
+ s := openTestStore(t)
+ before, err := s.SavedContacts(123)
+ if err != nil || len(before) != 0 {
+ t.Fatalf("fresh store: %+v, %v", before, err)
+ }
+ registered, done := seedLegacyDomainState(t, s)
+ for i := 0; i < 2; i++ {
+ if err := s.migrateDomains(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ list, err := s.SavedContacts(123)
+ if err != nil || len(list) != 1 {
+ t.Fatalf("saved contacts: %+v, %v", list, err)
+ }
+ c := list[0]
+ if c.Handle != "contact-1" || c.Version != 1 || c.Contact != savedTestContact("legacy") || c.LastUsed.IsZero() || c.AccountID != 123 {
+ t.Fatalf("backfilled contact: %+v", c)
+ }
+ for domain, want := range map[string]registrar.Contact{"one.example": registered, "two.example": done, "three.example": {}} {
+ r, err := s.DomainRegistrationFor(123, domain)
+ if err != nil || r == nil || r.Registrant != want {
+ t.Fatalf("%s registrant: %+v, %v; want %+v", domain, r, err, want)
+ }
+ }
+ // Purchases are not rewritten: a legacy purchase keeps its own frozen copy.
+ if p, err := s.DomainPurchase("dp_0000000000000001"); err != nil || p.ContactID != "" || p.ContactVersion != 0 || p.OwnerHandle != "contact-1" || p.Contact != registered {
+ t.Fatalf("legacy purchase: %+v, %v", p, err)
+ }
+ if c, h, err := s.DomainContact(123); err != nil || h != "contact-1" || c.FirstName != "legacy" {
+ t.Fatalf("domain_contacts stays: %+v %q %v", c, h, err)
+ }
+}
+
+func TestMigratedContactRemovalSurvivesReopen(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ seedLegacyDomainState(t, s)
+ if err := s.migrateDomains(); err != nil {
+ t.Fatal(err)
+ }
+ list, err := s.SavedContacts(123)
+ if err != nil || len(list) != 1 {
+ t.Fatalf("saved contacts: %+v, %v", list, err)
+ }
+ if err := s.RemoveSavedContact(123, list[0].ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if s, err = Open(path); err != nil {
+ t.Fatal(err)
+ }
+ if list, err := s.SavedContacts(123); err != nil || len(list) != 0 {
+ t.Fatalf("removed contact came back: %+v, %v", list, err)
+ }
+}
+
+func TestDomainObligations(t *testing.T) {
+ s := openTestStore(t)
+ t0 := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
+ jane := savedTestContact("jane")
+ for _, r := range []DomainRegistration{
+ {Domain: "zed.example", AccountID: 1, Registrant: jane},
+ {Domain: "alpha.example", AccountID: 1},
+ {Domain: "dup.example", AccountID: 1},
+ {Domain: "theirs.example", AccountID: 2},
+ } {
+ if err := s.AddDomainRegistration(r); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, p := range []DomainPurchase{
+ {Domain: "live.example", AccountID: 1, State: PurchaseAwaitingPayment, CreatedAt: t0, purchaseDetails: purchaseDetails{ContactID: "dc_000000000001", ContactVersion: 3}},
+ {Domain: "dup.example", AccountID: 1, State: PurchaseRegistered, CreatedAt: t0.Add(time.Hour)},
+ {Domain: "gone.example", AccountID: 1, State: PurchaseFailed, CreatedAt: t0.Add(2 * time.Hour)},
+ {Domain: "finished.example", AccountID: 1, State: PurchaseDone, CreatedAt: t0.Add(3 * time.Hour)},
+ {Domain: "other.example", AccountID: 2, State: PurchaseAuthorised, CreatedAt: t0.Add(4 * time.Hour)},
+ } {
+ p.ID = fmt.Sprintf("dp_%016x", i+1)
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ }
+ got, err := s.DomainObligations(1)
+ if want := []string{"alpha.example", "dup.example", "live.example", "zed.example"}; err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("obligations = %v, %v; want %v", got, err, want)
+ }
+ if got, err := s.DomainObligations(3); err != nil || len(got) != 0 {
+ t.Fatalf("empty account: %v, %v", got, err)
+ }
+ regs, err := s.DomainRegistrations(1)
+ if err != nil || len(regs) != 3 || regs[0].Domain != "alpha.example" || regs[1].Domain != "dup.example" || regs[2].Domain != "zed.example" || regs[2].Registrant != jane || regs[0].Registrant != (registrar.Contact{}) {
+ t.Fatalf("registrations: %+v, %v", regs, err)
+ }
+ if r, err := s.DomainRegistrationFor(1, "theirs.example"); err != nil || r != nil {
+ t.Fatalf("another account's registration: %+v, %v", r, err)
+ }
+ if r, err := s.DomainRegistrationFor(1, "missing.example"); err != nil || r != nil {
+ t.Fatalf("missing registration: %+v, %v", r, err)
+ }
+ purchases, err := s.AccountDomainPurchases(1)
+ if err != nil || len(purchases) != 2 || purchases[0].Domain != "dup.example" || purchases[1].Domain != "live.example" {
+ t.Fatalf("account purchases: %+v, %v", purchases, err)
+ }
+ if purchases[1].ContactID != "dc_000000000001" || purchases[1].ContactVersion != 3 {
+ t.Fatalf("frozen contact reference: %+v", purchases[1])
+ }
+}
+
+func TestAppLessPurchaseRowAllowedByGate(t *testing.T) {
+ if !claimSQLTables["domain_purchases"].FreeWhenNoApp {
+ t.Fatal("domain_purchases must be FreeWhenNoApp")
+ }
+ s := openGatedStore(t)
+ seedGateApp(t, s)
+ // A "Not yet" purchase names no app: it is not app-scoped, so no permit is needed.
+ p := DomainPurchase{ID: "dp_0000000000000001", AccountID: gateAcct, Domain: "shop.example", State: PurchaseAwaitingPayment}
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatalf("app-less purchase: %v", err)
+ }
+ if err := s.AdvanceDomainPurchase(p.ID, p.State, PurchaseAuthorised, func(row *DomainPurchase) { row.PaymentIntent = "pi_1" }); err != nil {
+ t.Fatalf("app-less advance: %v", err)
+ }
+ requireDenied(t, "pointing a purchase at an app without a permit",
+ s.AdvanceDomainPurchase(p.ID, PurchaseAuthorised, PurchaseZoneReady, func(row *DomainPurchase) { row.App = gateScope.App }))
+ withApp := DomainPurchase{ID: "dp_0000000000000002", AccountID: gateAcct, App: gateScope.App, Domain: "blog.example", State: PurchaseAwaitingPayment}
+ requireDenied(t, "app purchase without permit", s.CreateDomainPurchase(withApp))
+ if row, err := s.DomainPurchase(p.ID); err != nil || row == nil || row.App != "" || row.State != PurchaseAuthorised {
+ t.Fatalf("app-less row: %+v, %v", row, err)
+ }
+}
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index f9032badb..1c6269a0e 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -228,7 +228,7 @@ var claimSQLTables = map[string]claimSQLTable{
"app_policy_revisions": {Account: "account_id", App: "app"}, // apppolicy_store.go; the purge never writes it (revisions only rise)
"plan_lapse_items": {Account: "account_id", App: "app"},
"pending_changes": {Account: "account_id", App: "app"},
- "domain_purchases": {Account: "account_id", App: "app"},
+ "domain_purchases": {Account: "account_id", App: "app", FreeWhenNoApp: true}, // "Not yet" purchases carry app ''
"pending_confirms": {Account: "account_id", App: "app", Via: &claimSQLVia{Parent: "pending_changes", ChildCol: "change_id", ParentCol: "id"}},
"mail_counts": {Sqid: "account", App: "app"},
"mail_sender_counts": {Sqid: "account", App: "app"},
@@ -274,8 +274,10 @@ var claimSQLTables = map[string]claimSQLTable{
"email_challenges": {NonApp: "emailed sign-in and step-up links and codes in flight, keyed by id hash; carries no app column"},
"pending_actions": {NonApp: "replay-by-token actions, keyed by token hash; carries no app column and re-enters the ordinary handlers"},
- "domain_contacts": {NonApp: "registrant contact details and handle, keyed by account; names no app"},
- "domain_registrations": {NonApp: "domain ownership and renewal records, keyed by domain and account; names no app"},
+ "domain_contacts": {NonApp: "registrant contact details and handle, keyed by account; names no app"},
+ "domain_registrations": {NonApp: "domain ownership and renewal records, keyed by domain and account; names no app"},
+ "domain_saved_contacts": {NonApp: "saved registrant contacts and handles, keyed by account; names no app"},
+ "domain_meta": {NonApp: "domain migration bookkeeping, keyed by name; names no account or app"},
// Plans 6b's billing tables.
"billing_checkout_intents": {NonApp: "an account's Checkout intent and its prepared provider requests, keyed by account; names no app"},