feat(identity): add browser setup and user accounts

This commit is contained in:
sam committed 2026-10-16 02:41:24 +11:00
1 parent cf3455ef2e
commit aa012a7c6e
91 files changed
+6823 -636

No files matched your search

@@ -0,0 +1,97 @@
package postgres
import (
"context"
"crypto/rand"
"errors"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *Store) OpenAccountSession(ctx context.Context, expires time.Time) (identity.AccountSession, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
row, err := s.queries().GetIdentity(ctx, string(p.IdentityID))
if err != nil {
return identity.AccountSession{}, err
}
value := identityFromRow(row)
if value.Kind != identity.KindUser || !value.CanAct() {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
result := identity.AccountSession{Identity: value, Token: rand.Text(), Expires: time.Now().UTC().Add(identity.AccountSessionLifetime)}
if expires.IsZero() || !expires.After(time.Now()) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if expires.Before(result.Expires) {
result.Expires = expires
}
_, err = s.pool.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), string(p.IdentityID), result.Expires)
return result, err
}
func (s *Store) RequireFreshAccountSession(ctx context.Context, token string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
var fresh bool
err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM account_sessions WHERE token_hash=$1 AND identity_id=$2 AND expires_at>now() AND issued_at>now()-interval '10 minutes')`, sessionHash(token), string(p.IdentityID)).Scan(&fresh)
if err != nil {
return err
}
if !fresh {
return identity.ErrCredentialRejected
}
return nil
}
func (s *Store) CreateAccountRecovery(ctx context.Context) (string, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return "", identity.ErrCredentialRejected
}
code := rand.Text() + rand.Text()
result, err := s.pool.Exec(ctx, `UPDATE accounts SET recovery_hash=$2 WHERE identity_id=$1`, string(p.IdentityID), sessionHash(code))
if err != nil {
return "", err
}
if result.RowsAffected() != 1 {
return "", identity.ErrNotFound
}
return code, nil
}
func (s *Store) RecoverAccount(ctx context.Context, email, code, password string) error {
if len(code) < 52 || len(code) > 128 {
return identity.ErrCredentialRejected
}
hash, err := identity.HashPassword(password)
if err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
var id string
err = tx.QueryRow(ctx, `UPDATE accounts a SET password_hash=$3,recovery_hash=NULL,failed_attempts=0,locked_until=NULL FROM identities i WHERE a.identity_id=i.id AND i.lifecycle='active' AND a.email=$1 AND a.recovery_hash=$2 RETURNING a.identity_id`, strings.ToLower(strings.TrimSpace(email)), sessionHash(code), hash).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrCredentialRejected
}
if err != nil {
return err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
@@ -0,0 +1,286 @@
package postgres
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
func (s *Store) AccountSetupRequired(ctx context.Context) (bool, error) {
var required bool
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT 1 FROM accounts)`).Scan(&required)
return required, err
}
func (s *Store) RegisterAccount(ctx context.Context, r identity.AccountRegistration, bootstrap bool) (identity.Identity, error) {
role, orgID, err := accountRegistrationScope(ctx, &r, bootstrap)
if err != nil {
return identity.Identity{}, err
}
hash, err := identity.HashPassword(r.Password)
if err != nil {
return identity.Identity{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
// Every registration shares this lock so only one transaction can bootstrap.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(484726231)`); err != nil {
return identity.Identity{}, err
}
var anyAccounts bool
if err = tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM accounts)`).Scan(&anyAccounts); err != nil {
return identity.Identity{}, err
}
if bootstrap && anyAccounts {
return identity.Identity{}, identity.ErrSetupComplete
}
if !bootstrap && !anyAccounts {
return identity.Identity{}, identity.ErrCredentialRejected
}
value, err := writeAccount(ctx, tx, r, bootstrap, orgID, role, hash)
if err != nil {
return identity.Identity{}, err
}
if err = tx.Commit(ctx); err != nil {
return identity.Identity{}, err
}
return value, nil
}
func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, bootstrap bool, orgID org.OrgID, role org.Role, hash string) (identity.Identity, error) {
id := identity.IdentityID(rand.Text())
if bootstrap {
id = identity.OperatorID()
}
value, err := identity.New(id, identity.KindUser, r.DisplayName)
if err != nil {
return identity.Identity{}, err
}
now := time.Now().UTC()
value.CreatedAt, value.UpdatedAt = now, now
if bootstrap {
if err := setupAccountOrganisation(ctx, tx, r, orgID, now); err != nil {
return identity.Identity{}, err
}
}
_, err = tx.Exec(ctx, `INSERT INTO identities (id,kind,display_name,lifecycle,version,created_at,updated_at) VALUES ($1,'user',$2,'active',1,$3,$3)
ON CONFLICT (id) DO UPDATE SET display_name=EXCLUDED.display_name, lifecycle='active',version=identities.version+1,updated_at=EXCLUDED.updated_at`, string(id), r.DisplayName, now)
if err != nil {
return identity.Identity{}, err
}
_, err = tx.Exec(ctx, `INSERT INTO accounts (identity_id,email,password_hash) VALUES ($1,$2,$3)`, string(id), r.Email, hash)
if err != nil {
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
return identity.Identity{}, identity.ErrConflict
}
return identity.Identity{}, err
}
_, err = tx.Exec(ctx, `INSERT INTO memberships (identity_id,org_id,role) VALUES ($1,$2,$3) ON CONFLICT (identity_id,org_id,(COALESCE(workspace_id,''))) DO UPDATE SET role=EXCLUDED.role`, string(id), string(orgID), string(role))
if err != nil {
return identity.Identity{}, err
}
actor := id
if p, ok := access.PrincipalFromContext(ctx); ok {
actor = p.IdentityID
}
err = insertIdentityEvent(ctx, postgresdb.New(tx), id, identity.Event{Type: "create", To: identity.LifecycleActive, DisplayName: r.DisplayName}, identity.Audit{ActorID: actor, Source: "accounts", RequestID: "account:" + rand.Text()}, now)
if err != nil {
return identity.Identity{}, err
}
return value, nil
}
func sessionHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (s *Store) SignInAccount(ctx context.Context, email, password string) (identity.AccountSession, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.AccountSession{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
var id, hash string
var attempts int
var locked *time.Time
err = tx.QueryRow(ctx, `SELECT identity_id,password_hash,failed_attempts,locked_until FROM accounts WHERE email=$1 FOR UPDATE`, strings.ToLower(strings.TrimSpace(email))).Scan(&id, &hash, &attempts, &locked)
if errors.Is(err, pgx.ErrNoRows) {
// An unknown email still pays the password hashing cost.
_, hashErr := identity.HashPassword("unknown account dummy password")
if hashErr != nil {
return identity.AccountSession{}, hashErr
}
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.AccountSession{}, err
}
valid := identity.VerifyPassword(password, hash)
if locked != nil && time.Now().Before(*locked) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if !valid {
return identity.AccountSession{}, recordFailedAccountLogin(ctx, tx, id, attempts, locked)
}
row, err := postgresdb.New(tx).GetIdentity(ctx, id)
if err != nil {
return identity.AccountSession{}, err
}
value := identityFromRow(row)
if !value.CanAct() {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
token := rand.Text()
expires := time.Now().UTC().Add(identity.AccountSessionLifetime)
if _, err = tx.Exec(ctx, `UPDATE accounts SET failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, id); err != nil {
return identity.AccountSession{}, err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE expires_at<=now()`); err != nil {
return identity.AccountSession{}, err
}
if _, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(token), id, expires); err != nil {
return identity.AccountSession{}, err
}
if err = tx.Commit(ctx); err != nil {
return identity.AccountSession{}, err
}
return identity.AccountSession{Identity: value, Token: token, Expires: expires}, nil
}
func (s *Store) ResolveAccountSession(ctx context.Context, token string) (identity.Identity, error) {
if len(token) < 26 || len(token) > 128 {
return identity.Identity{}, identity.ErrCredentialRejected
}
var id string
err := s.pool.QueryRow(ctx, `SELECT s.identity_id FROM account_sessions s JOIN identities i ON i.id=s.identity_id WHERE s.token_hash=$1 AND s.expires_at>now() AND i.lifecycle='active'`, sessionHash(token)).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.Identity{}, err
}
row, err := s.queries().GetIdentity(ctx, id)
return identityFromRow(row), err
}
func (s *Store) SignOutAccount(ctx context.Context, token string) error {
_, err := s.pool.Exec(ctx, `DELETE FROM account_sessions WHERE token_hash=$1`, sessionHash(token))
return err
}
func (s *Store) ChangeAccountPassword(ctx context.Context, current, next string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
hash, err := identity.HashPassword(next)
if err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
var old string
err = tx.QueryRow(ctx, `SELECT password_hash FROM accounts WHERE identity_id=$1 FOR UPDATE`, string(p.IdentityID)).Scan(&old)
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrCredentialRejected
}
if err != nil {
return err
}
if !identity.VerifyPassword(current, old) {
return identity.ErrCredentialRejected
}
if _, err = tx.Exec(ctx, `UPDATE accounts SET password_hash=$2,failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, string(p.IdentityID), hash); err != nil {
return err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(p.IdentityID)); err != nil {
return err
}
return tx.Commit(ctx)
}
func accountRegistrationScope(ctx context.Context, r *identity.AccountRegistration, bootstrap bool) (org.Role, org.OrgID, error) {
if err := r.Validate(); err != nil {
return "", "", err
}
role := org.Role(r.Role)
orgID := org.OrgFromContext(ctx)
if bootstrap {
if err := validateAccountSetup(r); err != nil {
return "", "", err
}
return org.RoleOwner, org.DefaultOrgID, nil
}
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.Org != orgID {
return "", "", identity.ErrCredentialRejected
}
if role != org.RoleAdmin && role != org.RoleDeveloper && role != org.RoleViewer {
return "", "", identity.ErrInvalid
}
return role, orgID, nil
}
func recordFailedAccountLogin(ctx context.Context, tx pgx.Tx, id string, attempts int, locked *time.Time) error {
if locked != nil {
attempts = 0
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET failed_attempts=$2,locked_until=CASE WHEN $2>=5 THEN now()+interval '15 minutes' ELSE NULL END WHERE identity_id=$1`, id, attempts+1); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return err
}
return identity.ErrCredentialRejected
}
func setupAccountOrganisation(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, orgID org.OrgID, now time.Time) error {
_, err := tx.Exec(ctx, `UPDATE orgs SET name=$1, updated_at=$2 WHERE id=$3`, r.OrganisationName, now, string(orgID))
if err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE workspaces SET name=$1,updated_at=$2 WHERE org_id=$3 AND id=$4`, r.WorkspaceName, now, string(orgID), string(org.DefaultWorkspaceID)); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil {
return err
}
return nil
}
func validateAccountSetup(r *identity.AccountRegistration) error {
r.OrganisationName = strings.TrimSpace(r.OrganisationName)
r.WorkspaceName = strings.TrimSpace(r.WorkspaceName)
r.PublicURL = strings.TrimRight(r.PublicURL, "/")
if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 {
return identity.ErrInvalid
}
if r.OrganisationName == "" || len(r.OrganisationName) > 200 {
return fmt.Errorf("%w: organisation name is required", identity.ErrInvalid)
}
return (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate()
}
@@ -0,0 +1,41 @@
package postgres
import (
"context"
"errors"
"strings"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *Store) AuthenticationSettings(ctx context.Context) (identity.AuthenticationSettings, error) {
var value identity.AuthenticationSettings
err := s.pool.QueryRow(ctx, `SELECT public_url,oidc_issuer,oidc_audience,oidc_client_id FROM authentication_settings WHERE singleton`).Scan(&value.PublicURL, &value.OIDCIssuer, &value.OIDCAudience, &value.OIDCClientID)
if errors.Is(err, pgx.ErrNoRows) {
return value, nil
}
return value, err
}
func (s *Store) SaveAuthenticationSettings(ctx context.Context, value identity.AuthenticationSettings) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok || !p.InstanceAdmin() {
return identity.ErrCredentialRejected
}
value.PublicURL = strings.TrimRight(value.PublicURL, "/")
if err := value.Validate(); err != nil {
return err
}
// The relying-party origin cannot silently change and orphan enrolled keys.
command, err := s.pool.Exec(ctx, `UPDATE authentication_settings SET public_url=$1,oidc_issuer=$2,oidc_audience=$3,oidc_client_id=$4 WHERE singleton AND (public_url=$1 OR NOT EXISTS (SELECT 1 FROM passkeys))`, value.PublicURL, value.OIDCIssuer, value.OIDCAudience, value.OIDCClientID)
if err != nil {
return err
}
if command.RowsAffected() != 1 {
return identity.ErrInvalid
}
return nil
}
@@ -185,6 +185,11 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
if n != 1 {
return identity.Identity{}, identity.ErrConflict
}
if next.Lifecycle != identity.LifecycleActive {
if _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)); err != nil {
return identity.Identity{}, err
}
}
if command.Type == identity.CommandRename {
if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
Alias: next.DisplayName, IdentityID: string(id),
@@ -0,0 +1,49 @@
-- +goose Up
CREATE TABLE accounts (
identity_id text PRIMARY KEY REFERENCES identities(id),
email text NOT NULL UNIQUE CHECK (email = lower(email)),
password_hash text NOT NULL,
recovery_hash text,
failed_attempts integer NOT NULL DEFAULT 0,
locked_until timestamptz
);
CREATE TABLE account_sessions (
token_hash text PRIMARY KEY,
identity_id text NOT NULL REFERENCES identities(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
issued_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX account_sessions_identity ON account_sessions(identity_id);
CREATE INDEX account_sessions_expiry ON account_sessions(expires_at);
CREATE TABLE authentication_settings (
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
public_url text NOT NULL,
oidc_issuer text NOT NULL DEFAULT '',
oidc_audience text NOT NULL DEFAULT '',
oidc_client_id text NOT NULL DEFAULT ''
);
CREATE TABLE passkeys (
credential_id text PRIMARY KEY,
identity_id text NOT NULL REFERENCES identities(id),
name text NOT NULL,
credential jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX passkeys_identity ON passkeys(identity_id);
CREATE TABLE passkey_ceremonies (
token_hash text PRIMARY KEY,
identity_id text NOT NULL,
registration boolean NOT NULL,
session_data jsonb NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX passkey_ceremonies_expiry ON passkey_ceremonies(expires_at);
-- +goose Down
DROP TABLE passkey_ceremonies;
DROP TABLE passkeys;
DROP TABLE authentication_settings;
DROP TABLE account_sessions;
DROP TABLE accounts;
@@ -0,0 +1,264 @@
package postgres
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"net"
"net/url"
"strings"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
type passkeyUser struct {
value identity.Identity
credentials []webauthn.Credential
}
func (u passkeyUser) WebAuthnID() []byte { return []byte(u.value.ID) }
func (u passkeyUser) WebAuthnName() string { return u.value.DisplayName }
func (u passkeyUser) WebAuthnDisplayName() string { return u.value.DisplayName }
func (u passkeyUser) WebAuthnCredentials() []webauthn.Credential { return u.credentials }
func (s *Store) webAuthn(ctx context.Context) (*webauthn.WebAuthn, error) {
settings, err := s.AuthenticationSettings(ctx)
if err != nil {
return nil, err
}
u, err := url.Parse(settings.PublicURL)
secure := err == nil && (u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost"))
if !secure || u.Hostname() == "" || net.ParseIP(u.Hostname()) != nil {
return nil, identity.ErrInvalid
}
return webauthn.New(&webauthn.Config{RPDisplayName: "Archie", RPID: u.Hostname(), RPOrigins: []string{strings.TrimRight(settings.PublicURL, "/")}, AuthenticatorSelection: protocol.AuthenticatorSelection{UserVerification: protocol.VerificationRequired, ResidentKey: protocol.ResidentKeyRequirementRequired}})
}
func loadPasskeyUser(ctx context.Context, q *postgresdb.Queries, db interface {
Query(context.Context, string, ...any) (pgx.Rows, error)
}, id string,
) (passkeyUser, error) {
row, err := q.GetIdentity(ctx, id)
if err != nil {
return passkeyUser{}, err
}
user := passkeyUser{value: identityFromRow(row)}
if user.value.Kind != identity.KindUser || !user.value.CanAct() {
return passkeyUser{}, identity.ErrCredentialRejected
}
rows, err := db.Query(ctx, `SELECT credential FROM passkeys WHERE identity_id=$1`, id)
if err != nil {
return passkeyUser{}, err
}
defer rows.Close()
for rows.Next() {
var data []byte
if err = rows.Scan(&data); err != nil {
return passkeyUser{}, err
}
var credential webauthn.Credential
if err = json.Unmarshal(data, &credential); err != nil {
return passkeyUser{}, err
}
user.credentials = append(user.credentials, credential)
}
return user, rows.Err()
}
func (s *Store) BeginPasskey(ctx context.Context, registration bool) (identity.PasskeyCeremony, error) {
wa, err := s.webAuthn(ctx)
if err != nil {
return identity.PasskeyCeremony{}, err
}
var options any
var session *webauthn.SessionData
var owner string
if registration {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.PasskeyCeremony{}, identity.ErrCredentialRejected
}
owner = string(p.IdentityID)
user, loadErr := loadPasskeyUser(ctx, s.queries(), s.pool, owner)
if loadErr != nil {
return identity.PasskeyCeremony{}, loadErr
}
options, session, err = wa.BeginRegistration(user)
} else {
options, session, err = wa.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
}
if err != nil {
return identity.PasskeyCeremony{}, err
}
data, err := json.Marshal(session)
if err != nil {
return identity.PasskeyCeremony{}, err
}
encoded, err := json.Marshal(options)
if err != nil {
return identity.PasskeyCeremony{}, err
}
token := rand.Text()
if _, err = s.pool.Exec(ctx, `DELETE FROM passkey_ceremonies WHERE expires_at<=now()`); err != nil {
return identity.PasskeyCeremony{}, err
}
_, err = s.pool.Exec(ctx, `INSERT INTO passkey_ceremonies (token_hash,identity_id,registration,session_data,expires_at) VALUES ($1,$2,$3,$4,now()+interval '5 minutes')`, sessionHash(token), owner, registration, data)
return identity.PasskeyCeremony{Token: token, Options: encoded}, err
}
func (s *Store) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (identity.AccountSession, error) {
wa, err := s.webAuthn(ctx)
if err != nil {
return identity.AccountSession{}, err
}
var owner string
var data []byte
// Consume before verification: failed and successful attempts are single-use.
err = s.pool.QueryRow(ctx, `DELETE FROM passkey_ceremonies WHERE token_hash=$1 AND registration=$2 AND expires_at>now() RETURNING identity_id,session_data`, sessionHash(token), registration).Scan(&owner, &data)
if errors.Is(err, pgx.ErrNoRows) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.AccountSession{}, err
}
var session webauthn.SessionData
if err = json.Unmarshal(data, &session); err != nil {
return identity.AccountSession{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.AccountSession{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
credential, user, err := verifyPasskey(ctx, tx, wa, owner, session, response, registration)
if err != nil || credential == nil || credential.Authenticator.CloneWarning {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
owner = string(user.value.ID)
if err := persistPasskey(ctx, tx, credential, owner, name, registration); err != nil {
return identity.AccountSession{}, err
}
result := identity.AccountSession{Identity: user.value}
if !registration {
result.Token = rand.Text()
result.Expires = time.Now().UTC().Add(identity.AccountSessionLifetime)
_, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), owner, result.Expires)
if err != nil {
return identity.AccountSession{}, err
}
}
if err = tx.Commit(ctx); err != nil {
return identity.AccountSession{}, err
}
return result, nil
}
func (s *Store) ListPasskeys(ctx context.Context) ([]identity.Passkey, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return nil, identity.ErrCredentialRejected
}
rows, err := s.pool.Query(ctx, `SELECT credential_id,name FROM passkeys WHERE identity_id=$1 ORDER BY created_at`, string(p.IdentityID))
if err != nil {
return nil, err
}
defer rows.Close()
out := []identity.Passkey{}
for rows.Next() {
var value identity.Passkey
if err = rows.Scan(&value.ID, &value.Name); err != nil {
return nil, err
}
out = append(out, value)
}
return out, rows.Err()
}
func (s *Store) DeletePasskey(ctx context.Context, id string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
result, err := s.pool.Exec(ctx, `DELETE FROM passkeys WHERE credential_id=$1 AND identity_id=$2`, id, string(p.IdentityID))
if err != nil {
return err
}
if result.RowsAffected() != 1 {
return identity.ErrNotFound
}
return nil
}
func verifyPasskey(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte, registration bool) (*webauthn.Credential, passkeyUser, error) {
if registration {
return verifyPasskeyRegistration(ctx, tx, wa, owner, session, response)
}
var user passkeyUser
parsed, err := protocol.ParseCredentialRequestResponseBytes(response)
if err != nil {
return nil, user, identity.ErrCredentialRejected
}
credential, err := wa.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) {
if err = tx.QueryRow(ctx, `SELECT identity_id FROM passkeys WHERE credential_id=$1 FOR UPDATE`, base64.RawURLEncoding.EncodeToString(rawID)).Scan(&owner); err != nil {
return nil, identity.ErrCredentialRejected
}
if owner != string(userHandle) {
return nil, identity.ErrCredentialRejected
}
user, err = loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
return user, err
}, session, parsed)
return credential, user, err
}
func verifyPasskeyRegistration(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte) (*webauthn.Credential, passkeyUser, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok || string(p.IdentityID) != owner {
return nil, passkeyUser{}, identity.ErrCredentialRejected
}
user, err := loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
if err != nil {
return nil, user, err
}
parsed, err := protocol.ParseCredentialCreationResponseBytes(response)
if err != nil {
return nil, user, identity.ErrCredentialRejected
}
credential, err := wa.CreateCredential(user, session, parsed)
return credential, user, err
}
func persistPasskey(ctx context.Context, tx pgx.Tx, credential *webauthn.Credential, owner, name string, registration bool) error {
encoded, err := json.Marshal(credential)
if err != nil {
return err
}
credentialID := base64.RawURLEncoding.EncodeToString(credential.ID)
if registration {
name = strings.TrimSpace(name)
if name == "" {
name = "Passkey"
}
if len(name) > 200 {
return identity.ErrInvalid
}
_, err = tx.Exec(ctx, `INSERT INTO passkeys (credential_id,identity_id,name,credential) VALUES ($1,$2,$3,$4)`, credentialID, owner, name, encoded)
} else {
_, err = tx.Exec(ctx, `UPDATE passkeys SET credential=$2 WHERE credential_id=$1`, credentialID, encoded)
}
if err != nil {
return err
}
return nil
}
@@ -558,6 +558,11 @@ ON CONFLICT (session_id) DO UPDATE SET
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id
AND (
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
)
`
type SaveSessionParams struct {
@@ -577,8 +582,9 @@ type SaveSessionParams struct {
// Gateway conversation queries: sessions, messages, turns, full-text search.
// These back internal/gateway's PostgreSQL SessionStore.
// ── Sessions ────────────────────────────────────────────────────────────────
// Updates only a session the writing org owns: another org's session of the
// same id is left untouched and the zero row count refuses the write.
// A saved session keeps its organization and conversation identity. Empty
// placeholder rows may be completed; an existing conversation cannot be claimed
// by overwriting its source with another person's thread.
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) (int64, error) {
result, err := q.db.Exec(ctx, saveSession,
arg.SessionID,
@@ -44,6 +44,22 @@ type AccessPolicyVersion struct {
UpdatedAt time.Time
}
type Account struct {
IdentityID string
Email string
PasswordHash string
RecoveryHash pgtype.Text
FailedAttempts int32
LockedUntil pgtype.Timestamptz
}
type AccountSession struct {
TokenHash string
IdentityID string
ExpiresAt time.Time
IssuedAt time.Time
}
type Alert struct {
ID int64
OrgID string
@@ -89,6 +105,14 @@ type ApplyStatus struct {
ReportedAt time.Time
}
type AuthenticationSetting struct {
Singleton bool
PublicUrl string
OidcIssuer string
OidcAudience string
OidcClientID string
}
type Binding struct {
ID string
Name string
@@ -344,6 +368,22 @@ type OrgUpgrade struct {
CompletedAt time.Time
}
type Passkey struct {
CredentialID string
IdentityID string
Name string
Credential []byte
CreatedAt time.Time
}
type PasskeyCeremony struct {
TokenHash string
IdentityID string
Registration bool
SessionData []byte
ExpiresAt time.Time
}
type PlaybookDispatch struct {
PlaybookID string
PlaybookVersion string
@@ -4,8 +4,9 @@
-- ── Sessions ────────────────────────────────────────────────────────────────
-- name: SaveSession :execrows
-- Updates only a session the writing org owns: another org's session of the
-- same id is left untouched and the zero row count refuses the write.
-- A saved session keeps its organization and conversation identity. Empty
-- placeholder rows may be completed; an existing conversation cannot be claimed
-- by overwriting its source with another person's thread.
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
@@ -19,7 +20,12 @@ ON CONFLICT (session_id) DO UPDATE SET
branch_name = EXCLUDED.branch_name,
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id;
WHERE sessions.org_id = EXCLUDED.org_id
AND (
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
);
-- name: ClaimSession :exec
-- A write to a session no row names yet makes the writing org its owner.