summaryrefslogtreecommitdiff
path: root/apps/web/app/api/webhook-config/route.ts
blob: df2816f452fbc58684fdd024ffe063c6d170f663 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import { NextResponse } from "next/server"
import { createSupabaseServerClient } from "@/lib/supabase/server"
import { TIER_LIMITS, type SubscriptionTier } from "@asa-news/shared"
import { rateLimit } from "@/lib/rate-limit"
import { validateWebhookUrl } from "@/lib/validate-webhook-url"
import { checkBotId } from "botid/server"

export async function GET() {
  const supabaseClient = await createSupabaseServerClient()
  const {
    data: { user },
  } = await supabaseClient.auth.getUser()

  if (!user) {
    return NextResponse.json({ error: "not authenticated" }, { status: 401 })
  }

  const { data: profile, error } = await supabaseClient
    .from("user_profiles")
    .select(
      "tier, webhook_url, webhook_secret, webhook_enabled, webhook_consecutive_failures"
    )
    .eq("id", user.id)
    .single()

  if (error || !profile) {
    return NextResponse.json(
      { error: "failed to load webhook config" },
      { status: 500 }
    )
  }

  const maskedSecret = profile.webhook_secret
    ? profile.webhook_secret.slice(0, 4) + "••••" + profile.webhook_secret.slice(-4)
    : null

  return NextResponse.json({
    webhookUrl: profile.webhook_url,
    webhookSecret: maskedSecret,
    webhookSecretConfigured: !!profile.webhook_secret,
    webhookEnabled: profile.webhook_enabled,
    consecutiveFailures: profile.webhook_consecutive_failures,
  })
}

export async function PUT(request: Request) {
  const botVerification = await checkBotId()
  if (botVerification.isBot) {
    return NextResponse.json({ error: "access denied" }, { status: 403 })
  }

  const supabaseClient = await createSupabaseServerClient()
  const {
    data: { user },
  } = await supabaseClient.auth.getUser()

  if (!user) {
    return NextResponse.json({ error: "not authenticated" }, { status: 401 })
  }

  const rateLimitResult = await rateLimit(`webhook-config:${user.id}`, 10, 60_000)
  if (!rateLimitResult.success) {
    return NextResponse.json({ error: "too many requests" }, { status: 429 })
  }

  const { data: profile } = await supabaseClient
    .from("user_profiles")
    .select("tier, webhook_url")
    .eq("id", user.id)
    .single()

  if (
    !profile ||
    !TIER_LIMITS[profile.tier as SubscriptionTier]?.allowsWebhooks
  ) {
    return NextResponse.json(
      { error: "webhooks require the developer plan" },
      { status: 403 }
    )
  }

  const body = await request.json().catch(() => ({}))

  const updates: Record<string, unknown> = {}

  if (typeof body.webhookUrl === "string") {
    const trimmedUrl = body.webhookUrl.trim()
    if (trimmedUrl) {
      const validationResult = await validateWebhookUrl(trimmedUrl)
      if (!validationResult.valid) {
        return NextResponse.json(
          { error: validationResult.error },
          { status: 400 }
        )
      }
    }
    updates.webhook_url = trimmedUrl || null
  }

  if (typeof body.webhookSecret === "string") {
    updates.webhook_secret = body.webhookSecret.trim() || null
  }

  if (typeof body.webhookEnabled === "boolean") {
    if (body.webhookEnabled) {
      const effectiveUrl =
        typeof body.webhookUrl === "string"
          ? body.webhookUrl.trim()
          : profile.webhook_url

      if (!effectiveUrl) {
        return NextResponse.json(
          { error: "cannot enable webhooks without a url" },
          { status: 400 }
        )
      }

      updates.webhook_consecutive_failures = 0
    }

    updates.webhook_enabled = body.webhookEnabled
  }

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ error: "no updates provided" }, { status: 400 })
  }

  const { error } = await supabaseClient
    .from("user_profiles")
    .update(updates)
    .eq("id", user.id)

  if (error) {
    return NextResponse.json(
      { error: "failed to update webhook config" },
      { status: 500 }
    )
  }

  return NextResponse.json({ updated: true })
}