|
@@ -0,0 +1,222 @@
|
|
|
|
|
+import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
|
|
|
|
|
+import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
|
|
|
|
+import { createHmac, timingSafeEqual } from 'https://deno.land/std@0.168.0/node/crypto.ts'
|
|
|
|
|
+
|
|
|
|
|
+const corsHeaders = {
|
|
|
|
|
+ 'Access-Control-Allow-Origin': '*',
|
|
|
|
|
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// Validate HMAC signature from ShopRenter
|
|
|
|
|
+function validateHMAC(query: Record<string, string>, clientSecret: string): boolean {
|
|
|
|
|
+ const { hmac, ...params } = query
|
|
|
|
|
+
|
|
|
|
|
+ if (!hmac) {
|
|
|
|
|
+ console.error('[ShopRenter] HMAC missing from request')
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Build sorted query string without HMAC
|
|
|
|
|
+ const sortedParams = Object.keys(params)
|
|
|
|
|
+ .sort()
|
|
|
|
|
+ .map(key => `${key}=${params[key]}`)
|
|
|
|
|
+ .join('&')
|
|
|
|
|
+
|
|
|
|
|
+ // Calculate HMAC using sha256
|
|
|
|
|
+ const calculatedHmac = createHmac('sha256', clientSecret)
|
|
|
|
|
+ .update(sortedParams)
|
|
|
|
|
+ .digest('hex')
|
|
|
|
|
+
|
|
|
|
|
+ // Timing-safe comparison
|
|
|
|
|
+ try {
|
|
|
|
|
+ return timingSafeEqual(
|
|
|
|
|
+ new TextEncoder().encode(calculatedHmac),
|
|
|
|
|
+ new TextEncoder().encode(hmac)
|
|
|
|
|
+ )
|
|
|
|
|
+ } catch (error) {
|
|
|
|
|
+ console.error('[ShopRenter] HMAC comparison error:', error)
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// Validate timestamp to prevent replay attacks
|
|
|
|
|
+function validateTimestamp(timestamp: string, maxAgeSeconds = 300): boolean {
|
|
|
|
|
+ const requestTime = parseInt(timestamp, 10)
|
|
|
|
|
+ const currentTime = Math.floor(Date.now() / 1000)
|
|
|
|
|
+ const age = currentTime - requestTime
|
|
|
|
|
+
|
|
|
|
|
+ if (age < 0) {
|
|
|
|
|
+ console.error('[ShopRenter] Request timestamp is in the future')
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (age > maxAgeSeconds) {
|
|
|
|
|
+ console.error(`[ShopRenter] Request timestamp too old: ${age}s > ${maxAgeSeconds}s`)
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return true
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// Exchange authorization code for access token
|
|
|
|
|
+async function exchangeCodeForToken(shopname: string, code: string, clientId: string, clientSecret: string, redirectUri: string) {
|
|
|
|
|
+ const tokenUrl = `https://${shopname}.shoprenter.hu/oauth/token`
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ const response = await fetch(tokenUrl, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'Content-Type': 'application/json',
|
|
|
|
|
+ 'Accept': 'application/json'
|
|
|
|
|
+ },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ grant_type: 'authorization_code',
|
|
|
|
|
+ client_id: clientId,
|
|
|
|
|
+ client_secret: clientSecret,
|
|
|
|
|
+ code: code,
|
|
|
|
|
+ redirect_uri: redirectUri
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ if (!response.ok) {
|
|
|
|
|
+ const errorData = await response.text()
|
|
|
|
|
+ console.error('[ShopRenter] Token exchange error:', errorData)
|
|
|
|
|
+ throw new Error('Failed to exchange code for token')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const data = await response.json()
|
|
|
|
|
+ console.log(`[ShopRenter] Token acquired for ${shopname}`)
|
|
|
|
|
+ return data
|
|
|
|
|
+ } catch (error) {
|
|
|
|
|
+ console.error('[ShopRenter] Token exchange error:', error)
|
|
|
|
|
+ throw new Error('Failed to exchange code for token')
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+serve(async (req) => {
|
|
|
|
|
+ if (req.method === 'OPTIONS') {
|
|
|
|
|
+ return new Response('ok', { headers: corsHeaders })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ const url = new URL(req.url)
|
|
|
|
|
+ const shopname = url.searchParams.get('shopname')
|
|
|
|
|
+ const code = url.searchParams.get('code')
|
|
|
|
|
+ const timestamp = url.searchParams.get('timestamp')
|
|
|
|
|
+ const hmac = url.searchParams.get('hmac')
|
|
|
|
|
+ const app_url = url.searchParams.get('app_url')
|
|
|
|
|
+
|
|
|
|
|
+ console.log(`[ShopRenter] OAuth callback received for ${shopname}`)
|
|
|
|
|
+
|
|
|
|
|
+ // Check required parameters
|
|
|
|
|
+ if (!shopname || !code || !timestamp || !hmac) {
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({ error: 'Missing required parameters' }),
|
|
|
|
|
+ { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Get environment variables
|
|
|
|
|
+ const shoprenterClientId = Deno.env.get('SHOPRENTER_CLIENT_ID')
|
|
|
|
|
+ const shoprenterClientSecret = Deno.env.get('SHOPRENTER_CLIENT_SECRET')
|
|
|
|
|
+ const frontendUrl = Deno.env.get('FRONTEND_URL') || 'https://shopcall.ai'
|
|
|
|
|
+ const supabaseUrl = Deno.env.get('SUPABASE_URL')!
|
|
|
|
|
+ const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
|
|
|
|
+
|
|
|
|
|
+ if (!shoprenterClientId || !shoprenterClientSecret) {
|
|
|
|
|
+ console.error('SHOPRENTER_CLIENT_ID or SHOPRENTER_CLIENT_SECRET not configured')
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({ error: 'ShopRenter integration not configured' }),
|
|
|
|
|
+ { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Validate timestamp
|
|
|
|
|
+ if (!validateTimestamp(timestamp)) {
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({ error: 'Request timestamp invalid or expired' }),
|
|
|
|
|
+ { status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Validate HMAC
|
|
|
|
|
+ const queryParams: Record<string, string> = {
|
|
|
|
|
+ shopname,
|
|
|
|
|
+ code,
|
|
|
|
|
+ timestamp,
|
|
|
|
|
+ hmac
|
|
|
|
|
+ }
|
|
|
|
|
+ if (app_url) {
|
|
|
|
|
+ queryParams.app_url = app_url
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!validateHMAC(queryParams, shoprenterClientSecret)) {
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({ error: 'HMAC validation failed' }),
|
|
|
|
|
+ { status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Exchange code for token
|
|
|
|
|
+ const currentFunctionUrl = `${url.protocol}//${url.host}${url.pathname}`
|
|
|
|
|
+ const tokenData = await exchangeCodeForToken(
|
|
|
|
|
+ shopname,
|
|
|
|
|
+ code,
|
|
|
|
|
+ shoprenterClientId,
|
|
|
|
|
+ shoprenterClientSecret,
|
|
|
|
|
+ currentFunctionUrl
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+ // Create Supabase client with service role key for admin operations
|
|
|
|
|
+ const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
|
|
|
|
+
|
|
|
|
|
+ // Store installation in pending state
|
|
|
|
|
+ const installationId = crypto.randomUUID()
|
|
|
|
|
+ const { error: installError } = await supabase
|
|
|
|
|
+ .from('pending_shoprenter_installs')
|
|
|
|
|
+ .insert({
|
|
|
|
|
+ installation_id: installationId,
|
|
|
|
|
+ shopname,
|
|
|
|
|
+ access_token: tokenData.access_token,
|
|
|
|
|
+ refresh_token: tokenData.refresh_token,
|
|
|
|
|
+ token_type: tokenData.token_type || 'Bearer',
|
|
|
|
|
+ expires_in: tokenData.expires_in || 3600,
|
|
|
|
|
+ scopes: tokenData.scope ? tokenData.scope.split(' ') : [],
|
|
|
|
|
+ expires_at: new Date(Date.now() + 15 * 60 * 1000).toISOString()
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ if (installError) {
|
|
|
|
|
+ console.error('[ShopRenter] Error storing installation:', installError)
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({ error: 'Failed to store installation' }),
|
|
|
|
|
+ { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // Redirect to app_url or frontend with installation_id
|
|
|
|
|
+ const redirectUrl = app_url
|
|
|
|
|
+ ? `${app_url}?sr_install=${installationId}`
|
|
|
|
|
+ : `${frontendUrl}/integrations?sr_install=${installationId}`
|
|
|
|
|
+
|
|
|
|
|
+ console.log(`[ShopRenter] Redirecting to: ${redirectUrl}`)
|
|
|
|
|
+
|
|
|
|
|
+ return new Response(null, {
|
|
|
|
|
+ status: 302,
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ ...corsHeaders,
|
|
|
|
|
+ 'Location': redirectUrl
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ } catch (error) {
|
|
|
|
|
+ console.error('[ShopRenter] OAuth callback error:', error)
|
|
|
|
|
+ const frontendUrl = Deno.env.get('FRONTEND_URL') || 'https://shopcall.ai'
|
|
|
|
|
+ return new Response(null, {
|
|
|
|
|
+ status: 302,
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ ...corsHeaders,
|
|
|
|
|
+ 'Location': `${frontendUrl}/integrations?error=shoprenter_oauth_failed`
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+})
|