Add configuration files, database migrations, and authentication implementation scaffolding
This commit is contained in:
51
internal/db/db.go
Normal file
51
internal/db/db.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
// Connect initializes a standard sql.DB connection with retries.
|
||||
func Connect(dsn string) (*sql.DB, error) {
|
||||
var db *sql.DB
|
||||
var err error
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
db, err = sql.Open("postgres", dsn)
|
||||
if err == nil {
|
||||
err = db.Ping()
|
||||
if err == nil {
|
||||
return db, nil
|
||||
}
|
||||
}
|
||||
fmt.Printf("Failed to connect to database, retrying in 2s... (%d/10)\n", i+1)
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to connect to database after retries: %w", err)
|
||||
}
|
||||
|
||||
// RunMigrations runs the SQL migrations from internal/db/migrations.
|
||||
func RunMigrations(dsn string) error {
|
||||
m, err := migrate.New(
|
||||
"file://internal/db/migrations",
|
||||
dsn,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create migrate instance: %w", err)
|
||||
}
|
||||
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
return fmt.Errorf("could not run up migrations: %w", err)
|
||||
}
|
||||
|
||||
log.Println("Migrations completed successfully")
|
||||
return nil
|
||||
}
|
||||
25
internal/db/migrations/000001_init.up.sql
Normal file
25
internal/db/migrations/000001_init.up.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
-- Migration: 000001_init.up.sql
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
|
||||
CREATE TABLE IF NOT EXISTS encrypted_logs (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
log_type TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
encrypted_payload BYTEA NOT NULL,
|
||||
blind_index_hash TEXT,
|
||||
server_id TEXT NOT NULL,
|
||||
session_id TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_logs_created_at ON encrypted_logs(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_logs_blind_hash ON encrypted_logs(blind_index_hash);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS telemetry (
|
||||
timestamp TIMESTAMP WITH TIME ZONE PRIMARY KEY DEFAULT CURRENT_TIMESTAMP,
|
||||
community_id TEXT NOT NULL,
|
||||
server_fps DOUBLE PRECISION NOT NULL,
|
||||
player_count INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_telemetry_community_id ON telemetry(community_id);
|
||||
77
internal/db/migrations/000002_webauthn.up.sql
Normal file
77
internal/db/migrations/000002_webauthn.up.sql
Normal file
@@ -0,0 +1,77 @@
|
||||
-- Migration: 000002_webauthn.up.sql
|
||||
-- WebAuthn-based Authentication for Zero-Knowledge Admin Access
|
||||
|
||||
-- Communities table (represents each gaming community using the platform)
|
||||
CREATE TABLE IF NOT EXISTS communities (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
name TEXT NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
master_key_salt BYTEA NOT NULL, -- Used for key wrapping/unwrapping
|
||||
storage_node_id TEXT, -- Which storage node handles this community's data
|
||||
retention_days INTEGER DEFAULT 30 -- Auto-deletion policy (DSGVO)
|
||||
);
|
||||
|
||||
-- Admin users (co-owners of a community)
|
||||
CREATE TABLE IF NOT EXISTS admin_users (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
|
||||
username TEXT NOT NULL,
|
||||
email TEXT,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
is_primary_owner BOOLEAN DEFAULT false,
|
||||
UNIQUE(community_id, username)
|
||||
);
|
||||
|
||||
-- WebAuthn credentials (hardware-bound authentication)
|
||||
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
||||
id BYTEA PRIMARY KEY, -- Credential ID from WebAuthn
|
||||
admin_user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
|
||||
public_key BYTEA NOT NULL,
|
||||
sign_count BIGINT NOT NULL DEFAULT 0,
|
||||
aaguid BYTEA, -- Authenticator AAGUID
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
last_used_at TIMESTAMP WITH TIME ZONE,
|
||||
device_name TEXT -- e.g., "YubiKey 5C", "Windows Hello"
|
||||
);
|
||||
|
||||
-- Wrapped master keys (encrypted with WebAuthn public key)
|
||||
CREATE TABLE IF NOT EXISTS wrapped_master_keys (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
admin_user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
|
||||
community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
|
||||
wrapped_key_data BYTEA NOT NULL, -- Master key encrypted for this admin
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(admin_user_id, community_id)
|
||||
);
|
||||
|
||||
-- Managed Trust Vault (for Discord Bot & external API integrations)
|
||||
CREATE TABLE IF NOT EXISTS managed_trust_vault (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
|
||||
service_name TEXT NOT NULL, -- e.g., "discord_bot", "external_api"
|
||||
encrypted_master_key BYTEA NOT NULL, -- Encrypted with provider's key
|
||||
granted_by UUID NOT NULL REFERENCES admin_users(id),
|
||||
expires_at TIMESTAMP WITH TIME ZONE, -- NULL = permanent, else temporary
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(community_id, service_name)
|
||||
);
|
||||
|
||||
-- Player roster for fast blind-index searching
|
||||
CREATE TABLE IF NOT EXISTS player_roster (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
|
||||
player_name_hash TEXT NOT NULL, -- HMAC hash for blind searching
|
||||
encrypted_player_data BYTEA NOT NULL, -- Contains name, Steam ID, etc.
|
||||
first_seen TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
last_seen TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(community_id, player_name_hash)
|
||||
);
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_admin_users_community ON admin_users(community_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_webauthn_admin_user ON webauthn_credentials(admin_user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_wrapped_keys_admin ON wrapped_master_keys(admin_user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_managed_trust_community ON managed_trust_vault(community_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_player_roster_community ON player_roster(community_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_player_roster_hash ON player_roster(player_name_hash);
|
||||
25
internal/db/migrations/000003_password_auth.up.sql
Normal file
25
internal/db/migrations/000003_password_auth.up.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
-- Migration: 000003_password_auth.up.sql
|
||||
-- Add password authentication as optional fallback
|
||||
|
||||
-- Add password hash column to admin_users (nullable for Passkey-only accounts)
|
||||
ALTER TABLE admin_users ADD COLUMN password_hash TEXT;
|
||||
|
||||
-- Sessions table for JWT token management
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
admin_user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE, -- SHA256 hash of JWT
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
last_activity TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
ip_address TEXT,
|
||||
user_agent TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(admin_user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
|
||||
|
||||
-- Add auth_method to track how user logged in
|
||||
ALTER TABLE admin_users ADD COLUMN preferred_auth_method TEXT DEFAULT 'password';
|
||||
-- Options: 'password', 'passkey', 'both'
|
||||
19
internal/db/queries.sql
Normal file
19
internal/db/queries.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- name: CreateEncryptedLog :one
|
||||
INSERT INTO encrypted_logs (
|
||||
log_type, encrypted_payload, blind_index_hash, server_id, session_id
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5
|
||||
) RETURNING *;
|
||||
|
||||
-- name: CreateTelemetry :one
|
||||
INSERT INTO telemetry (
|
||||
community_id, server_fps, player_count
|
||||
) VALUES (
|
||||
$1, $2, $3
|
||||
) RETURNING *;
|
||||
|
||||
-- name: GetRecentLogs :many
|
||||
SELECT * FROM encrypted_logs
|
||||
WHERE server_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2;
|
||||
31
internal/db/sqlc/db.go
Normal file
31
internal/db/sqlc/db.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
|
||||
PrepareContext(context.Context, string) (*sql.Stmt, error)
|
||||
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
|
||||
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
29
internal/db/sqlc/models.go
Normal file
29
internal/db/sqlc/models.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type EncryptedLog struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
LogType string `json:"log_type"`
|
||||
CreatedAt sql.NullTime `json:"created_at"`
|
||||
EncryptedPayload []byte `json:"encrypted_payload"`
|
||||
BlindIndexHash sql.NullString `json:"blind_index_hash"`
|
||||
ServerID string `json:"server_id"`
|
||||
SessionID sql.NullString `json:"session_id"`
|
||||
}
|
||||
|
||||
type Telemetry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
CommunityID string `json:"community_id"`
|
||||
ServerFps float64 `json:"server_fps"`
|
||||
PlayerCount int32 `json:"player_count"`
|
||||
}
|
||||
17
internal/db/sqlc/querier.go
Normal file
17
internal/db/sqlc/querier.go
Normal file
@@ -0,0 +1,17 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
CreateEncryptedLog(ctx context.Context, arg CreateEncryptedLogParams) (EncryptedLog, error)
|
||||
CreateTelemetry(ctx context.Context, arg CreateTelemetryParams) (Telemetry, error)
|
||||
GetRecentLogs(ctx context.Context, arg GetRecentLogsParams) ([]EncryptedLog, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
117
internal/db/sqlc/queries.sql.go
Normal file
117
internal/db/sqlc/queries.sql.go
Normal file
@@ -0,0 +1,117 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: queries.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
const createEncryptedLog = `-- name: CreateEncryptedLog :one
|
||||
INSERT INTO encrypted_logs (
|
||||
log_type, encrypted_payload, blind_index_hash, server_id, session_id
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5
|
||||
) RETURNING id, log_type, created_at, encrypted_payload, blind_index_hash, server_id, session_id
|
||||
`
|
||||
|
||||
type CreateEncryptedLogParams struct {
|
||||
LogType string `json:"log_type"`
|
||||
EncryptedPayload []byte `json:"encrypted_payload"`
|
||||
BlindIndexHash sql.NullString `json:"blind_index_hash"`
|
||||
ServerID string `json:"server_id"`
|
||||
SessionID sql.NullString `json:"session_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) CreateEncryptedLog(ctx context.Context, arg CreateEncryptedLogParams) (EncryptedLog, error) {
|
||||
row := q.db.QueryRowContext(ctx, createEncryptedLog,
|
||||
arg.LogType,
|
||||
arg.EncryptedPayload,
|
||||
arg.BlindIndexHash,
|
||||
arg.ServerID,
|
||||
arg.SessionID,
|
||||
)
|
||||
var i EncryptedLog
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.LogType,
|
||||
&i.CreatedAt,
|
||||
&i.EncryptedPayload,
|
||||
&i.BlindIndexHash,
|
||||
&i.ServerID,
|
||||
&i.SessionID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const createTelemetry = `-- name: CreateTelemetry :one
|
||||
INSERT INTO telemetry (
|
||||
community_id, server_fps, player_count
|
||||
) VALUES (
|
||||
$1, $2, $3
|
||||
) RETURNING timestamp, community_id, server_fps, player_count
|
||||
`
|
||||
|
||||
type CreateTelemetryParams struct {
|
||||
CommunityID string `json:"community_id"`
|
||||
ServerFps float64 `json:"server_fps"`
|
||||
PlayerCount int32 `json:"player_count"`
|
||||
}
|
||||
|
||||
func (q *Queries) CreateTelemetry(ctx context.Context, arg CreateTelemetryParams) (Telemetry, error) {
|
||||
row := q.db.QueryRowContext(ctx, createTelemetry, arg.CommunityID, arg.ServerFps, arg.PlayerCount)
|
||||
var i Telemetry
|
||||
err := row.Scan(
|
||||
&i.Timestamp,
|
||||
&i.CommunityID,
|
||||
&i.ServerFps,
|
||||
&i.PlayerCount,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getRecentLogs = `-- name: GetRecentLogs :many
|
||||
SELECT id, log_type, created_at, encrypted_payload, blind_index_hash, server_id, session_id FROM encrypted_logs
|
||||
WHERE server_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type GetRecentLogsParams struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
func (q *Queries) GetRecentLogs(ctx context.Context, arg GetRecentLogsParams) ([]EncryptedLog, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getRecentLogs, arg.ServerID, arg.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []EncryptedLog
|
||||
for rows.Next() {
|
||||
var i EncryptedLog
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.LogType,
|
||||
&i.CreatedAt,
|
||||
&i.EncryptedPayload,
|
||||
&i.BlindIndexHash,
|
||||
&i.ServerID,
|
||||
&i.SessionID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
Reference in New Issue
Block a user