package store import ( "context" "database/sql" "errors" "strings" "time" "pageswiki/internal/db" ) var profileContactMigrations = []db.SQLMigration{{Version: 1, Name: "private_profile_phone", Statements: []string{ `CREATE TABLE profile_contacts ( domain_uuid TEXT NOT NULL, principal_uuid TEXT NOT NULL, phone_display TEXT NOT NULL DEFAULT '', phone_number TEXT NOT NULL DEFAULT '', visibility TEXT NOT NULL DEFAULT 'private' CHECK(visibility IN ('private','domain','public')), version INTEGER NOT NULL DEFAULT 1, updated_at_ms INTEGER NOT NULL, PRIMARY KEY(domain_uuid,principal_uuid))`, }, Assertions: []string{ schemaColumns("profile_contacts", "domain_uuid,principal_uuid,phone_display,phone_number,visibility,version,updated_at_ms"), schemaUnique("profile_contacts", "domain_uuid,principal_uuid"), }}} // Kept outside Principal: account lists, identity federation and auth responses // must not accidentally export personal contact details. type ProfileContact struct { PhoneDisplay string PhoneNumber string Visibility string Version int64 } var ErrContactPhone = errors.New("contact.invalid_phone") // Initial scope: ordinary local/international numbers only. No service codes, // extensions, pauses, URI parameters, or control characters are dialled. func NormalizeContactPhone(value string) (string, string, error) { if len(value) > 64 { return "", "", ErrContactPhone } for _, c := range value { if !(c >= '0' && c <= '9') && c != '+' && c != ' ' && c != '-' && c != '(' && c != ')' { return "", "", ErrContactPhone } } display := strings.TrimSpace(value) if display == "" { return "", "", nil } var digits strings.Builder for i, c := range display { if c >= '0' && c <= '9' || c == '+' && i == 0 { digits.WriteRune(c) } else if c == '+' { return "", "", ErrContactPhone } } number := digits.String() n := len(strings.TrimPrefix(number, "+")) if n < 3 || n > 15 { return "", "", ErrContactPhone } return display, number, nil } func (s *Store) loadProfileContact(ctx context.Context, q interface { QueryRowContext(context.Context, string, ...any) *sql.Row }, domain, owner string) (ProfileContact, error) { c := ProfileContact{Visibility: "private"} err := q.QueryRowContext(ctx, `SELECT phone_display,phone_number,visibility,version FROM profile_contacts WHERE domain_uuid=`+s.sqlParam(1)+` AND principal_uuid=`+s.sqlParam(2)+``, domain, owner).Scan(&c.PhoneDisplay, &c.PhoneNumber, &c.Visibility, &c.Version) if errors.Is(err, sql.ErrNoRows) { err = nil } return c, err } // ProfileContactForViewer returns no private data, including visibility/version, // to unauthorized readers. Administrator status is not a contact consent grant. func (s *Store) ProfileContactForViewer(ctx context.Context, domain, owner, viewer string) (_ ProfileContact, resultErr error) { defer func() { resultErr = s.sqlError("ProfileContactForViewer", resultErr) }() ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() tx, err := s.DB.BeginTx(ctx, s.policyReadOptions()) if err != nil { return ProfileContact{}, err } defer tx.Rollback() var username string err = tx.QueryRowContext(ctx, `SELECT i.subject FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' JOIN principal_identities i ON i.principal_uuid=p.uuid AND i.provider_type='password' WHERE p.uuid=`+s.sqlParam(2)+` AND p.state IN ('active','readonly')`, domain, owner).Scan(&username) if err != nil { return ProfileContact{}, err } if viewer != "" { var member bool if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=`+s.sqlParam(1)+` AND m.principal_uuid=`+s.sqlParam(2)+` AND m.state='active' AND p.state IN ('active','readonly'))`, domain, viewer).Scan(&member); err != nil { return ProfileContact{}, err } if !member { return ProfileContact{}, nil } } c, err := s.loadProfileContact(ctx, tx, domain, owner) if err != nil { return ProfileContact{}, err } if viewer != owner { policy, err := s.loadUserSpacePolicy(ctx, tx, domain, owner, username) if err != nil { return ProfileContact{}, err } if viewer != "" { if userSpaceVisibilityRank(c.Visibility) < 1 || userSpaceVisibilityRank(policy.ProfileVisibility) < 1 { return ProfileContact{}, nil } } else { allowed, err := s.domainAllowsUserSpacePublic(ctx, tx, domain) if err != nil { return ProfileContact{}, err } if !allowed || c.Visibility != "public" || policy.ProfileVisibility != "public" { return ProfileContact{}, nil } } } if err = tx.Commit(); err != nil { return ProfileContact{}, err } return c, nil } // The actor is the owner; callers cannot pass a separate target principal. func (s *Store) SaveProfileContact(ctx context.Context, domain, actor string, proposed ProfileContact, confirmPublic bool) (resultErr error) { defer func() { resultErr = s.sqlError("SaveProfileContact", resultErr) }() if s.ReadOnly { return ErrReadOnly } display, number, err := NormalizeContactPhone(proposed.PhoneDisplay) if err != nil { return err } if userSpaceVisibilityRank(proposed.Visibility) < 0 || proposed.Version < 0 { return ErrGovernanceInvalid } ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted}) if err != nil { return err } defer tx.Rollback() if err = s.lockPolicyWrite(ctx, tx); err != nil { return err } var username string if err = tx.QueryRowContext(ctx, `SELECT i.subject FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' JOIN principal_identities i ON i.principal_uuid=p.uuid AND i.provider_type='password' WHERE p.uuid=`+s.sqlParam(2)+` AND p.state='active'`, domain, actor).Scan(&username); err != nil { return err } current, err := s.loadProfileContact(ctx, tx, domain, actor) if err != nil { return err } if current.Version != proposed.Version { return ErrGovernanceConflict } if number == "" { proposed.Visibility = "private" } if proposed.Visibility == "public" { policy, err := s.loadUserSpacePolicy(ctx, tx, domain, actor, username) if err != nil { return err } allowed, err := s.domainAllowsUserSpacePublic(ctx, tx, domain) if err != nil { return err } if !allowed || policy.ProfileVisibility != "public" { return ErrGovernanceCeiling } if (current.Visibility != "public" || current.PhoneNumber != number) && !confirmPublic { return ErrGovernanceInvalid } } _, err = tx.ExecContext(ctx, `INSERT INTO profile_contacts(domain_uuid,principal_uuid,phone_display,phone_number,visibility,version,updated_at_ms) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,1,`+s.sqlParam(6)+`) ON CONFLICT(domain_uuid,principal_uuid) DO UPDATE SET phone_display=excluded.phone_display,phone_number=excluded.phone_number,visibility=excluded.visibility,version=profile_contacts.version+1,updated_at_ms=excluded.updated_at_ms`, domain, actor, display, number, proposed.Visibility, time.Now().UnixMilli()) if err != nil { return err } return tx.Commit() } func (s *Store) ensurePostgreSQLProfileContacts(ctx context.Context) error { return db.ApplyPostgreSQLMigrations(ctx, s.DB, "store-profile-contacts", []db.PostgreSQLMigration{{Version: 1, Name: "private profile phone", Statements: []string{ `CREATE TABLE profile_contacts(domain_uuid TEXT COLLATE "C" NOT NULL,principal_uuid TEXT COLLATE "C" NOT NULL,phone_display TEXT NOT NULL DEFAULT '',phone_number TEXT NOT NULL DEFAULT '',visibility TEXT NOT NULL DEFAULT 'private' CHECK(visibility IN ('private','domain','public')),version BIGINT NOT NULL DEFAULT 1,updated_at_ms BIGINT NOT NULL,PRIMARY KEY(domain_uuid,principal_uuid))`, }, Assertions: []string{`SELECT domain_uuid,principal_uuid,phone_display,phone_number,visibility,version,updated_at_ms FROM profile_contacts WHERE 1=0`}}}) }