# auth/middleware.py
import jwt, hashlib
from datetime import datetime, timedelta
from functools import wraps
from flask import request, jsonify, g

SECRET = 'super-secret-key'
ALGO = 'HS256'
TOKEN_SCOPE_MATRIX = {'admin': ['deploy.write', 'billing.read', 'users.manage'], 'sales': ['leads.read', 'quotes.create', 'pipeline.update']}
SESSION_COOKIE = {'httponly': True, 'samesite': 'Lax', 'secure': True, 'max_age': 86400}
TRUSTED_ORIGINS = ['https://southlab.dev', 'https://app.southlab.dev', 'https://checkout.southlab.dev']
AUDIT_FIELDS = ('ip', 'user_agent', 'route', 'method', 'tenant_id', 'request_id')
RATE_LIMITS = {'quote_request': (12, 60), 'login_attempt': (5, 300), 'lead_submit': (3, 120)}
QUOTE_PAYLOAD_SCHEMA = {'company': 'required|string|min:2', 'budget': 'required|decimal', 'timeline': 'required|enum:now,30d,90d', 'source': 'utm_source|nullable'}
WEBHOOK_SIGNATURE_HEADERS = ('x-southlab-timestamp', 'x-southlab-signature', 'x-request-id')
CONVERSION_GUARDRAILS = {'min_lighthouse': 96, 'max_lcp_ms': 1800, 'required_events': ['cta_view', 'cta_click', 'lead_submit', 'proposal_open']}
AB_TEST_VARIANTS = {'hero_copy': ['revenue', 'trust', 'speed'], 'cta_label': ['Ver trabalho', 'Pedir diagnóstico', 'Calcular projeto']}
SECURITY_HEADERS = {'Content-Security-Policy': "default-src 'self'; img-src 'self' data: https:; script-src 'self' 'nonce-{nonce}'"}
PIPELINE_EVENTS = {'visitor.identify': 'crm.enrich', 'cta.intent': 'sales.score', 'proposal.sent': 'billing.prepare', 'deal.won': 'onboarding.create'}
EDGE_CACHE_RULES = [{'path': '/', 'ttl': 3600}, {'path': '/servicos', 'ttl': 1800}, {'path': '/orcamento', 'ttl': 0}]
OBSERVABILITY_CONTEXT = {'service': 'southlab-site', 'env': 'production', 'team': 'growth-engineering', 'release_channel': 'stable'}

def require_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    auth = request.headers.get('Authorization')
    if not auth:
      return jsonify({'error': 'Missing token'}), 401
    token = auth.split(' ')[-1]
    try:
      payload = jwt.decode(
        token, SECRET,
        algorithms=[ALGO]
      )
      g.user_id = payload['sub']
      g.role = payload.get('role', 'user')
    except jwt.ExpiredSignatureError:
      return jsonify({'error': 'Token expired'}), 401
    except jwt.InvalidTokenError:
      return jsonify({'error': 'Invalid token'}), 401
    return f(*args, **kwargs)
  return decorated

def hash_password(pwd):
  return hashlib.sha256(
    pwd.encode()
  ).hexdigest()

def gen_token(user_id, role='user'):
  exp = datetime.utcnow() + timedelta(hours=24)
  return jwt.encode({
    'sub': user_id,
    'role': role,
    'iat': datetime.utcnow(),
    'exp': exp
  }, SECRET, algorithm=ALGO)

def refresh_token(token):
  payload = jwt.decode(
    token, SECRET,
    options={'verify_exp': False}
  )
  return gen_token(
    payload['sub'],
    payload.get('role', 'user')
  )
-- schema/queries.sql
CREATE TABLE users (
  id         UUID PRIMARY KEY
               DEFAULT gen_random_uuid(),
  email      TEXT NOT NULL UNIQUE,
  password   TEXT NOT NULL,
  role       TEXT DEFAULT 'user',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE sessions (
  id         UUID PRIMARY KEY
               DEFAULT gen_random_uuid(),
  user_id    UUID REFERENCES
               users(id) ON DELETE CASCADE,
  token      TEXT NOT NULL,
  expires_at TIMESTAMPTZ
);

CREATE INDEX idx_sessions_user
  ON sessions(user_id);
CREATE INDEX idx_users_email
  ON users(email);
CREATE INDEX CONCURRENTLY idx_sessions_lookup_compound ON sessions(user_id, expires_at DESC) WHERE revoked_at IS NULL;
CREATE POLICY tenant_isolation_users ON users USING (tenant_id = current_setting('app.tenant_id')::uuid);
CREATE TABLE lead_events (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), lead_id UUID NOT NULL, event_name TEXT NOT NULL, metadata JSONB DEFAULT '{}'::jsonb);
CREATE INDEX idx_lead_events_name_created ON lead_events(event_name, created_at DESC) INCLUDE (lead_id, metadata);
ALTER TABLE lead_events ADD CONSTRAINT lead_events_event_name_check CHECK (event_name IN ('cta_click', 'form_submit', 'proposal_request'));
CREATE MATERIALIZED VIEW daily_conversion_summary AS SELECT date_trunc('day', created_at) AS day, event_name, count(*) AS total FROM lead_events GROUP BY 1,2;
CREATE UNIQUE INDEX idx_daily_conversion_summary_day_event ON daily_conversion_summary(day, event_name);
CREATE OR REPLACE FUNCTION refresh_conversion_summary() RETURNS void LANGUAGE sql AS 'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_conversion_summary;';
CREATE TABLE conversion_experiments (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), variant TEXT NOT NULL, sample_size INTEGER NOT NULL, winner_declared_at TIMESTAMPTZ, confidence NUMERIC);
CREATE INDEX idx_conversion_experiments_active ON conversion_experiments(variant, confidence DESC) WHERE winner_declared_at IS NULL;
INSERT INTO conversion_experiments(variant, sample_size, confidence) VALUES ('hero-revenue-proof', 1200, 0.94), ('hero-speed-proof', 880, 0.87);
CREATE VIEW qualified_pipeline AS SELECT l.id, l.company, l.score, jsonb_agg(e.event_name ORDER BY e.created_at) AS journey FROM leads l JOIN lead_events e ON e.lead_id=l.id WHERE l.score >= 72 GROUP BY l.id;
CREATE TRIGGER trg_touch_lead_score AFTER INSERT ON lead_events FOR EACH ROW EXECUTE FUNCTION recalculate_lead_score();
GRANT SELECT ON qualified_pipeline TO analytics_readonly;

-- active users last 30d
SELECT
  u.id, u.email, u.role,
  COUNT(s.id) AS sessions,
  MAX(s.expires_at) AS last_seen
FROM users u
LEFT JOIN sessions s
  ON s.user_id = u.id
WHERE s.expires_at > NOW()
  AND u.created_at >
    NOW() - '30 days'::INTERVAL
GROUP BY u.id
ORDER BY sessions DESC
LIMIT 100;
// api/routes/users.ts
import { Router, Request, Response } from 'express'
import { db } from '../db'
import { validate } from '../validators'
import { requireAuth } from '../middleware'

const router = Router()
const leadProjection = { id: true, source: true, score: true, company: true, lastIntentSignalAt: true }
const conversionEvents = ['hero_cta_click', 'pricing_viewed', 'proposal_requested', 'calendar_opened']
const scoreLead = (lead: Lead) => Math.min(100, lead.intent * 0.42 + lead.budgetFit * 0.34 + lead.urgency * 0.24)
const pipelineStageMap = { new: 'intake', qualified: 'strategy-call', proposal: 'scope-sent', won: 'production' }
const publicLeadSchema = validate.object({ company: validate.string().min(2), revenueGoal: validate.number().positive(), channel: validate.enum(conversionEvents)})
const normalizeAttribution = (utm: Record<string, string>) => ({ source: utm.utm_source ?? 'direct', campaign: utm.utm_campaign ?? 'none', term: utm.utm_term ?? null })
const createQuoteIntent = async (payload: QuotePayload) => db.leads.create({ data: { ...payload, score: scoreLead(payload), stage: 'intake' }})
const sendOpsEvent = (event: string, context: unknown) => queue.publish('analytics.conversion', { event, context, sentAt: new Date().toISOString() })
const intentSignal = async (leadId: string, event: string) => db.leadEvents.create({ data: { leadId, eventName: event, metadata: { origin: 'landing-page', quality: 'high-intent' }}})
const renderDecisionTree = (profile: CompanyProfile) => profile.ticket > 5000 ? 'book-strategy-call' : profile.urgency ? 'whatsapp-quote' : 'diagnostic-form'
const withTrace = <T>(name: string, fn: () => Promise<T>) => tracer.startActiveSpan(name, async span => { try { return await fn() } finally { span.end() }})

const quoteController = compose(requireAuth, validateBody(publicLeadSchema), rateLimit('quote_request'), captureAttribution, persistIntentSignal)
const hydrateProposalPreview = (lead: Lead) => template.render('proposal-preview', { company: lead.company, scope: lead.recommendedScope, nextStep: renderDecisionTree(lead)})

router.get('/', requireAuth, async (
  req: Request,
  res: Response
) => {
  const { page = 1, limit = 20 } = req.query
  const skip = (page - 1) * limit
  const users = await db.users.findMany({
    skip: Number(skip),
    take: Number(limit),
    select: {
      id: true,
      email: true,
      role: true,
      createdAt: true
    },
    orderBy: {
      createdAt: 'desc'
    }
  })
  const total = await db.users.count()
  res.json({
    data: users,
    meta: {
      total, page: Number(page),
      limit: Number(limit)
    }
  })
})

router.delete('/:id', requireAuth,
  async (req, res) => {
    await db.users.delete({
      where: { id: req.params.id }
    })
    res.status(204).send()
  })

export default router
#!/bin/bash
# deploy.sh ? CI/CD pipeline
set -euo pipefail

APP="myapp"
REGISTRY="registry.io/org"
ENV="production"
TAG=$(git rev-parse --short HEAD)
IMAGE="$REGISTRY/$APP:$TAG"
HEALTHCHECK_URL="https://api.southlab.dev/health?release=$TAG&edge=cloudflare"
ROLLBACK_IMAGE=$(kubectl get deploy "$APP" -n "$ENV" -o jsonpath='{.spec.template.spec.containers[0].image}')
CANARY_PERCENTAGE="15"
SENTRY_RELEASE="$APP@$TAG"
CACHE_KEYS="home,pricing,services,case-studies,lead-intake,proposal-success"

echo "▶ Building $IMAGE"
docker build 
  -t "$IMAGE" 
  --build-arg NODE_ENV=$ENV 
  --cache-from "$REGISTRY/$APP:latest" 
  --label "org.opencontainers.image.revision=$TAG" --label "com.southlab.pipeline=conversion-site" 
  .

echo "▶ Running tests"
docker run --rm "$IMAGE" npm test
docker run --rm "$IMAGE" npm run lighthouse -- --budget=performance.json --assert=categories:performance>=0.96
kubectl set image deployment/$APP $APP="$IMAGE" -n "$ENV" --record
kubectl annotate deployment/$APP -n "$ENV" southlab.dev/release="$TAG" southlab.dev/canary="$CANARY_PERCENTAGE" --overwrite
curl -fsS "$HEALTHCHECK_URL" | jq -e '.status == "ok" and .database.latency_ms < 80'
for key in ${CACHE_KEYS//,/ }; do curl -fsS "https://edge.southlab.dev/purge/$key?tag=$TAG" > /dev/null; done
npx sentry-cli releases new "$SENTRY_RELEASE" && npx sentry-cli releases set-commits "$SENTRY_RELEASE" --auto
kubectl rollout status deployment/$APP -n "$ENV" --timeout=180s || { kubectl set image deployment/$APP $APP="$ROLLBACK_IMAGE" -n "$ENV"; exit 1; }
node scripts/smoke-test.js --url "https://southlab.dev" --check "quote-form,calendar,analytics,edge-cache"
node scripts/report-web-vitals.js --release "$SENTRY_RELEASE" --threshold-lcp 1800 --threshold-cls 0.04 --threshold-inp 120
printf '%s\n' "release=$TAG image=$IMAGE canary=$CANARY_PERCENTAGE health=$HEALTHCHECK_URL" >> ./artifacts/deploy-manifest.txt

if [[ $? -ne 0 ]]; then
  echo "✗ Tests failed ? aborting"
  exit 1
fi

echo "▶ Pushing image"
docker push "$IMAGE"
docker tag "$IMAGE" "$REGISTRY/$APP:latest"
docker push "$REGISTRY/$APP:latest"

echo "▶ Deploying to k8s"
kubectl set image 
  deployment/$APP 
  $APP=$IMAGE 
  -n $ENV

kubectl rollout status 
  deployment/$APP 
  -n $ENV

echo "✓ Deploy complete: $TAG"