Files
pages/internal/store/profile_contact.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

186 lines
6.7 KiB
Go

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 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=? AND principal_uuid=?`, 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, error) {
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
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=? AND m.state='active' JOIN principal_identities i ON i.principal_uuid=p.uuid AND i.provider_type='password' WHERE p.uuid=? 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=? AND m.principal_uuid=? 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 := loadProfileContact(ctx, tx, domain, owner)
if err != nil {
return ProfileContact{}, err
}
if viewer != owner {
policy, err := 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) error {
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, nil)
if err != nil {
return err
}
defer tx.Rollback()
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=? AND m.state='active' JOIN principal_identities i ON i.principal_uuid=p.uuid AND i.provider_type='password' WHERE p.uuid=? AND p.state='active'`, domain, actor).Scan(&username); err != nil {
return err
}
current, err := 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 := 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(?,?,?,?,?,1,?) 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()
}