@donotdev/functions 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/guidelines/VERCEL.md +24 -15
- package/lib/chunks/{chunk-2N73OZFE.js → chunk-4BJP372Z.js} +2 -2
- package/lib/chunks/chunk-7T2RZ5A4.js +22 -0
- package/lib/chunks/chunk-7T2RZ5A4.js.map +7 -0
- package/lib/chunks/chunk-CCEGC2T6.js +22 -0
- package/lib/chunks/chunk-CCEGC2T6.js.map +7 -0
- package/lib/chunks/{chunk-DGBZDD6D.js → chunk-IO4MUTT6.js} +2 -2
- package/lib/chunks/chunk-LJXSA7EP.js +151 -0
- package/lib/chunks/chunk-LJXSA7EP.js.map +7 -0
- package/lib/chunks/chunk-MJ5VZTLM.js +22 -0
- package/lib/chunks/chunk-MJ5VZTLM.js.map +7 -0
- package/lib/chunks/chunk-NP4Y2LAO.js +22 -0
- package/lib/chunks/chunk-NP4Y2LAO.js.map +7 -0
- package/lib/chunks/{chunk-XWMG2FWZ.js → chunk-WJUL2W7Y.js} +2 -2
- package/lib/chunks/{chunk-XWMG2FWZ.js.map → chunk-WJUL2W7Y.js.map} +1 -1
- package/lib/chunks/{chunk-ZCY6GTIC.js → chunk-Y6BR2QOV.js} +2 -2
- package/lib/chunks/{chunk-ZCY6GTIC.js.map → chunk-Y6BR2QOV.js.map} +1 -1
- package/lib/chunks/{monitoring-KF7FRUQ6.js → monitoring-B2DYDCYC.js} +2 -2
- package/lib/chunks/{rateLimiter-S7TITXOD.js → rateLimiter-JCBEG33M.js} +2 -2
- package/lib/chunks/{server-SU4BVPPF.js → server-YXYTPMRF.js} +2 -2
- package/lib/firebase/auth/index.d.ts +1 -0
- package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
- package/lib/firebase/billing/cancelSubscription.d.ts +2 -1
- package/lib/firebase/billing/changePlan.d.ts +2 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -1
- package/lib/firebase/billing/createCustomerPortal.d.ts +4 -0
- package/lib/firebase/billing/healthCheck.d.ts +2 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -1
- package/lib/firebase/billing/webhookHandler.d.ts +2 -0
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/exchangeToken.d.ts +21 -4
- package/lib/firebase/oauth/providerSecrets.d.ts +22 -0
- package/lib/firebase/oauth/refreshToken.d.ts +34 -4
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +5 -27
- package/lib/supabase/auth/listAuthUsers.d.ts +19 -0
- package/lib/supabase/index.d.ts +1 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/auth/index.d.ts +3 -3
- package/lib/vercel/api/crud/index.d.ts +6 -6
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/index.d.ts +4 -4
- package/package.json +5 -5
- package/src/firebase/auth/__tests__/listAuthUsers.test.ts +130 -0
- package/src/firebase/auth/index.ts +1 -0
- package/src/firebase/auth/listAuthUsers.ts +110 -0
- package/src/firebase/billing/__tests__/secretDeclarations.test.ts +55 -0
- package/src/firebase/billing/cancelSubscription.ts +9 -2
- package/src/firebase/billing/changePlan.ts +6 -2
- package/src/firebase/billing/createCheckoutSession.ts +6 -2
- package/src/firebase/billing/createCustomerPortal.ts +8 -1
- package/src/firebase/billing/healthCheck.ts +13 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +14 -2
- package/src/firebase/billing/webhookHandler.ts +9 -1
- package/src/firebase/crud/delete.ts +57 -1
- package/src/firebase/oauth/__tests__/tokenFactories.test.ts +99 -0
- package/src/firebase/oauth/exchangeToken.ts +53 -8
- package/src/firebase/oauth/providerSecrets.ts +65 -0
- package/src/firebase/oauth/refreshToken.ts +57 -12
- package/src/shared/email/provider.ts +0 -0
- package/src/shared/email/resendProvider.ts +0 -0
- package/src/shared/utils.ts +5 -75
- package/src/supabase/__tests__/firebaseBoundary.test.ts +53 -0
- package/src/supabase/auth/__tests__/listAuthUsers.test.ts +156 -0
- package/src/supabase/auth/listAuthUsers.ts +98 -0
- package/src/supabase/baseFunction.ts +0 -0
- package/src/supabase/index.ts +1 -0
- package/src/vercel/__tests__/firebaseOptional.test.ts +24 -0
- package/src/vercel/api/auth/index.ts +4 -3
- package/src/vercel/api/crud/index.ts +7 -6
- package/src/vercel/api/oauth/index.ts +5 -4
- package/lib/chunks/chunk-472JD6X7.js +0 -22
- package/lib/chunks/chunk-472JD6X7.js.map +0 -7
- package/lib/chunks/chunk-BTWJEJCV.js +0 -22
- package/lib/chunks/chunk-BTWJEJCV.js.map +0 -7
- package/lib/chunks/chunk-CN6WXKYF.js +0 -22
- package/lib/chunks/chunk-CN6WXKYF.js.map +0 -7
- package/lib/chunks/chunk-GBZQPOX4.js +0 -151
- package/lib/chunks/chunk-GBZQPOX4.js.map +0 -7
- package/lib/chunks/chunk-ORBGTVJI.js +0 -22
- package/lib/chunks/chunk-ORBGTVJI.js.map +0 -7
- package/lib/chunks/chunk-R3I7U5QT.js +0 -22
- package/lib/chunks/chunk-R3I7U5QT.js.map +0 -7
- /package/lib/chunks/{chunk-2N73OZFE.js.map → chunk-4BJP372Z.js.map} +0 -0
- /package/lib/chunks/{chunk-DGBZDD6D.js.map → chunk-IO4MUTT6.js.map} +0 -0
- /package/lib/chunks/{monitoring-KF7FRUQ6.js.map → monitoring-B2DYDCYC.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-S7TITXOD.js.map → rateLimiter-JCBEG33M.js.map} +0 -0
- /package/lib/chunks/{server-SU4BVPPF.js.map → server-YXYTPMRF.js.map} +0 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{E as le,G as L,I as me,J as B,K as fe,L as he,P as ge,S as _e,V as g,a as ae,b as z,ba as q,c as ce,d as de,ja as K,la as we,na as Ee,o as ue,oa as ke,pa as ye,qa as Se,ra as ve,sa as Ie,ta as be,x as pe}from"./chunk-Y6BR2QOV.js";import{a as p}from"./chunk-W6W4L44F.js";import{a as s}from"./chunk-AYY7UXNI.js";function S(e){let t,r,o;if(e instanceof g)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||"name"in e&&e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||"name"in e&&e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new g(r,t,o?{details:o}:void 0)}s(S,"handleError");function Tt(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}s(Tt,"createMetadata");function At(e){return{updatedAt:new Date().toISOString(),updatedById:e}}s(At,"updateMetadata");function J(e,t,r){if(e.unknownKeys.length>0&&console.warn(`[dndev] ${t} ${r}: fields the entity does not have, not written: ${e.unknownKeys.join(", ")}`),e.ok)return e.written;let o=e.issues.map(n=>`${n.path?.map(i=>String(i.key)).join(".")||"root"}: ${n.message}`).join("; ");throw new g(`Validation failed on ${t} ${r}: ${o}`,"invalid-argument",{details:{validationErrors:e.issues}})}s(J,"writtenOf");var Ye=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function Mt(e){let{collection:t,ops:r,createSchema:o,draftCreateSchema:n,updateSchema:i,access:a,uid:c,userRole:u,transact:d,readStored:m,mintInsertId:_,stampInsertMetadata:k,stampUpdateMetadata:I,audit:A}=e,C=L(Ee,r);if(!C.success){let f=C.issues.map(w=>`${w.path?.map(P=>P.key).join(".")||"root"}: ${w.message}`).join("; ");throw new g(`Bulk payload validation failed: ${f}`,"invalid-argument",{details:{validationErrors:C.issues}})}let R=C.output,v=R.inserts??[],h=R.updates??[],E=R.deletes??[],T=ye(R);if(T.where!==null)throw new _e(T.collisions,T.where);if(v.length===0&&h.length===0&&E.length===0)return Ye;if(v.length>0){if(!a.create)throw new g(`Bulk insert requested on ${t} but no create role is configured`,"permission-denied");if(!q(u,a.create))throw new g(`Access denied for bulk insert on ${t}. Required: ${a.create}, your role: ${u}`,"permission-denied")}if(h.length>0){if(!a.update)throw new g(`Bulk update requested on ${t} but no update role is configured`,"permission-denied");if(!q(u,a.update))throw new g(`Access denied for bulk update on ${t}. Required: ${a.update}, your role: ${u}`,"permission-denied")}if(E.length>0){if(!a.delete)throw new g(`Bulk delete requested on ${t} but no delete role is configured`,"permission-denied");if(!q(u,a.delete))throw new g(`Access denied for bulk delete on ${t}. Required: ${a.delete}, your role: ${u}`,"permission-denied")}let y=s(f=>{throw new g(`Validation failed on ${f}: draft row sent to ${t} but no draft schema is configured`,"invalid-argument")},"noDraftSchema"),U={create:o,draft:n??o,update:i},$=[];for(let f=0;f<v.length;f++){let w=v[f];!n&&we(Se(w),"saveIncomplete")&&y(`inserts[${f}]`);let P=J(ve(U,w),t,`inserts[${f}]`);$.push({row:P,id:typeof w.id=="string"?w.id:null})}if(h.length>0&&!m)throw new g(`Bulk update requested on ${t} but no readStored is configured: the stored row decides each patch's rules`,"internal");let l=h.length>0&&m?await m(h.map(f=>f.id)):new Map,b=[];for(let f=0;f<h.length;f++){let{id:w,patch:P}=h[f],O=`updates[${f}]`,M=l.get(w);if(!M)throw new g(`Document not found on ${O}: ${t}/${w}`,"not-found");!n&&Ie(P,M).schemaKey==="draft"&&y(O),b.push(J(be(U,{id:w,patch:P,stored:M}),t,O))}let D=$.map(({row:f,id:w})=>{let P=_?_():w??"",O=!_&&w!==null?{...f,id:w}:f,M=k?k(O,c):O;return{id:P,row:M}}),W=h.map((f,w)=>({id:f.id,patch:I?I(b[w],c):b[w]})),Y=await d({inserts:D,updates:W,deletes:[...E]}),se=L(ke,Y);if(!se.success)throw new g(`Bulk transact() returned an unexpected shape for ${t}`,"internal");return A&&A(`crud.bulk.${t}`,{counts:{inserts:D.length,updates:W.length,deletes:E.length}}),se.output}s(Mt,"executeBulk");function Z(e,t,r=ce){let o=de[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,a=n+i;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}s(Z,"calculateCost");function j(){return globalThis.Deno?.env}s(j,"getDenoEnv");async function ze(e,t){let o={anthropic:s(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:s(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:s(async()=>{let{createGoogle:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=tt(e);return(await o())(n)}s(ze,"resolveModel");var Je={maxRequests:30,windowMs:6e4},x=null;async function Ze(){if(x)return x;let e=V("UPSTASH_REDIS_REST_URL"),t=V("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),x={check:s(async()=>{},"check")},x;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return x={check:s(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},x}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),x={check:s(async()=>{},"check")},x}}s(Ze,"getRateLimiter");function Qe(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,a]of Object.entries(o))n[i]=e.tool({description:a.description,inputSchema:e.jsonSchema(a.parameters)});return n}s(Qe,"resolveTools");function Q(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}s(Q,"toAIUsage");async function et(e,t,r){let o=me(e);if(!o.success)return H(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=ae[n],a=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(a))return H(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Ze()).check(r.userId,t.rateLimitConfig||Je)}catch(l){return H(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await ze(n,a)}catch(l){return H(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
|
|
22
|
+
`):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),_=e.maxTokens||t.maxTokens||4096,k=e.temperature??t.temperature??.7,I=r.requestId||crypto.randomUUID(),A=await import("ai"),{streamText:C,generateText:R,toUIMessageStream:v,createUIMessageStreamResponse:h}=A,E=Qe(A,e.tools,t.tools),T=s(async l=>{if(!r.onCostRecord)return;let b=t.cost?.markup??4,D=Z(l,a,b),W={userId:r.userId,model:a,provider:n,usage:l,providerCost:D.providerCost,billedCost:D.billedCost,markup:b,timestamp:new Date().toISOString(),requestId:I};r.onCostRecord(W).catch(Y=>{console.error("[AI] Failed to record cost:",Y)})},"recordCost");if(e.stream!==!1){let l=C({model:c,messages:m,instructions:d,maxOutputTokens:_,temperature:k,tools:E,onEnd:s(async({usage:b})=>{await T(Q(b))},"onEnd")});return h({stream:v({stream:l.stream,messageMetadata:s(({part:b})=>b.type==="finish"?{usage:Q(b.totalUsage)}:void 0,"messageMetadata")})})}let y=await R({model:c,messages:m,instructions:d,maxOutputTokens:_,temperature:k,tools:E}),U=Q(y.usage);await T(U);let $=y.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:y.text},usage:U,finishReason:y.finishReason,toolCalls:$.length>0?$:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}s(et,"handleAIRequest");function H(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}s(H,"jsonError");function V(e){return typeof globalThis<"u"&&"Deno"in globalThis?j()?.get(e):typeof process<"u"?process.env[e]:void 0}s(V,"getEnv");function tt(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=V(r);if(n)return n}let o=V("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}s(tt,"getAIApiKey");function Re(e){return typeof globalThis<"u"&&"Deno"in globalThis?j()?.get(e):typeof process<"u"?process.env[e]:void 0}s(Re,"getEnv");function rt(e,t){if(t){let n=Re(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=Re(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(z).find(n=>n.id===e)?.defaultModel??z.STANDARD.defaultModel)}s(rt,"resolveModelForTier");function ot(e){let t=it(e),r=st(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:Te(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:Te(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}s(ot,"classifyAIError");function nt(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}s(nt,"mapClassifiedToHTTP");function it(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error=="object"&&e.error!==null&&"status"in e.error&&typeof e.error.status=="number")return e.error.status}}s(it,"extractStatus");function st(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}s(st,"extractMessage");function Te(e){if(e&&typeof e=="object"){let t="headers"in e?e.headers:void 0;if(t&&typeof t=="object"){let r="get"in t&&typeof t.get=="function"?t.get("retry-after"):"retry-after"in t?t["retry-after"]:void 0;if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}s(Te,"extractRetryAfter");var Ae="2025-02-24.acacia";var ee=Ae,F="orderId",X="productId";function G(e){return e===null?null:typeof e=="string"?e:e.id}s(G,"idOf");function Pe(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}s(Pe,"toAddress");function at(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:G(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?Pe(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:Pe(r.address)}:null,invoiceId:G(e.invoice),paymentIntentId:G(e.payment_intent),metadata:e.metadata??{}}}s(at,"toCheckoutSessionSnapshot");async function ct(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,i=n&&typeof n!="string"&&!n.deleted?n.metadata[X]:void 0;if(!i)throw new Error(`Line item ${o.id} of session ${t} has no ${X} product metadata`);r.push({productId:i,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}s(ct,"listPaidLineItems");async function xe(e,t,r,o,n,i,a){if(!r||r.slice(0,10)<ee.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[F]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${ee} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${ee}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[F];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},_=at(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let I=await ct(a,o.id);await i.onOrderPaid(_,I,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":i.onOrderPaymentFailed&&await i.onOrderPaymentFailed(_,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":i.onOrderExpired&&await i.onOrderExpired(_,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}s(xe,"handleOrderSessionEvent");function dt(e){return{id:e.id,customerId:G(e.customer),type:e.type,value:e.value,country:e.country,verification:e.verification&&{status:e.verification.status,verifiedName:e.verification.verified_name,verifiedAddress:e.verification.verified_address}}}s(dt,"toTaxIdSnapshot");async function Oe(e,t,r){let o=dt(t),n=new Set;for(let[i,a]of Object.entries(r))a.type!=="StripeOrder"||!a.onTaxIdUpdated||n.has(a.onTaxIdUpdated)||(n.add(a.onTaxIdUpdated),await a.onTaxIdUpdated(o,{billingConfigKey:i,eventId:e}),p.info("[Webhook] Tax ID updated",{taxIdId:o.id,status:o.verification?.status??null,billingConfigKey:i,operation:"tax_id_updated"}));n.size===0&&p.debug("[Webhook] customer.tax_id.updated without onTaxIdUpdated hook",{eventId:e})}s(Oe,"handleTaxIdUpdated");function Ne(e,t){let{billingConfigKey:r,priceId:o}=t,[n]=t.lineItems;if(t.lineItems.length!==1||!n||n.productId!==r||n.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let i=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,mode:i}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,mode:i}}s(Ne,"resolvePricePlan");function Ue(e){let t=e.mode||"payment";return{mode:t,line_items:[{price:e.priceId,quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}s(Ue,"toStripeSessionParams");var ut={maxKeys:50,maxKeyLength:40,maxValueLength:500};function re(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}s(re,"validateCheckoutUrl");function De(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}s(De,"sanitizeMetadata");function oe(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=ut,i=Object.entries(e);if(i.length>r)throw new Error(`${t}: ${i.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of i){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}s(oe,"assertStripeMetadata");function ne(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&oe(o,r)}s(ne,"assertCheckoutSessionMetadata");function Me(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&ht(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`);if(r.taxCode!==void 0&&!ft.test(r.taxCode))throw new Error(`Line '${r.productId}': taxCode must be a Stripe tax code (txcd_ + 8 digits), got '${r.taxCode}'`)}}s(Me,"assertResolvedOrder");var pt={minSeconds:1800,maxSeconds:1440*60},$e=5e3,lt=["card","sepa_debit"],mt=/^cus_[A-Za-z0-9]+$/,ft=/^txcd_\d{8}$/;function ht(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:i,invoiceFooter:a,customerId:c}=e;if(c!==void 0&&!mt.test(c))throw new Error(`resolveLineItems for '${t}': session.customerId must be a Stripe Customer ID (cus_...), got '${c}'`);if(o&&o.some(u=>typeof u!="string"||u.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let u of n)if(!lt.includes(u))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${u}'`)}if(i!==void 0){let{minSeconds:u,maxSeconds:d}=pt;if(!Number.isInteger(i)||i<r+u||i>r+d)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${i}`)}if(a!==void 0&&(a.length===0||a.length>$e))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${$e} characters`)}s(ht,"assertResolvedOrderSession");var te=new Map;async function ie(e,t,r){for(let o of t){let n=te.get(o);if(n||(n=e(o).then(i=>i.inclusive),te.set(o,n),n.catch(()=>te.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}s(ie,"assertExclusiveTaxRates");function Le(e){return"createStripeSession"in e}s(Le,"isSessionProvider");function Be(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}s(Be,"resolveRedirectUrl");function gt(e,t){let r={...e.tax.mode==="automatic"&&{address:"auto"},...e.shipping&&{shipping:"auto"},...t&&{name:"auto"}};return Object.keys(r).length>0?r:void 0}s(gt,"customerUpdate");function _t(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,i={...r.metadata,[F]:t.orderId},a=e.taxIdCollection!=="disabled",c=gt(e,a),u=o.customerId?{customer:o.customerId,...c&&{customer_update:c}}:{customer_creation:e.customerCreation,customer_email:r.customerEmail};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(d=>({price_data:{currency:e.currency,unit_amount:d.unitAmount,tax_behavior:"exclusive",product_data:{name:d.name,...d.description&&{description:d.description},...d.taxCode&&{tax_code:d.taxCode},metadata:{[X]:d.productId}}},quantity:d.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:a?{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"}:{enabled:!1},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(d=>({shipping_rate:d}))}},...u,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:i,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,metadata:i,payment_intent_data:{metadata:i}}}s(_t,"buildOrderSessionParams");async function Er(e,...t){let r=t.length===3,[o,n,i,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",_=m?void 0:Ne(d,u);await i.getUser(o);let k=De(u.metadata??{}),I={...k,userId:o,billingConfigKey:c};oe(m?{...I,[F]:""}:I,"metadata");let A=u.allowPromotionCodes??!0;if(d.beforeCheckout){let h={...u,userId:o,mode:_?.mode??"payment",priceId:_?.priceId,metadata:u.metadata??{},allowPromotionCodes:A},E=await d.beforeCheckout(o,h,k);if(!E.allowed)throw new Error(E.reason||"Checkout blocked by beforeCheckout hook")}let C=Be(u.successUrl,"success"),R=Be(u.cancelUrl,"cancel");re(C,"success"),re(R,"cancel");let v;if(d.type==="StripeOrder"){if(!Le(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await ie(y=>n.retrieveTaxRate(y),d.tax.taxRateIds,c);let h=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:k});Me(h,c);let E=h.session;if(E?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await ie(y=>n.retrieveTaxRate(y),E.taxRateIds,c)}if(d.tax.mode!=="automatic"&&h.lineItems.some(y=>y.taxCode!==void 0))throw new Error(`resolveLineItems for '${c}': line taxCode needs tax.mode 'automatic'`);if(E?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let T=_t(d,h,{successUrl:C,cancelUrl:R,customerEmail:u.customerEmail,metadata:I});ne(T),v=await n.createStripeSession(T)}else{let h={priceId:_?.priceId,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:I,allowPromotionCodes:A,successUrl:C,cancelUrl:R,mode:_?.mode};if(Le(n)){let E=Ue(h);ne(E),v=await n.createStripeSession(E)}else v=await n.createCheckoutSession(h)}return{sessionId:v.id,sessionUrl:v.url}}s(Er,"createCheckoutAlgorithm");async function vr(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");let i=le(he,{tier:t.tier,subscriptionId:t.subscriptionId??null,customerId:t.customerId??null,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd??!1,updatedAt:new Date().toISOString(),isDefault:!1}),a={...n,subscription:i};await r.setCustomUserClaims(e,a)}s(vr,"updateUserSubscription");var N=class extends Error{static{s(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},Fe=4200*1e3,Cr=720*60*60*1e3;function We(){return crypto.randomUUID()}s(We,"newOwnerToken");function qe(e){return e.subscription}s(qe,"pinnedInvoiceSubscriptionId");function Ar(e,t){return e.includes(t)}s(Ar,"isOneOf");async function je(e,t,r,o,n){let i={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){p.info("[Webhook] Purchase awaiting async payment",{...i,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw S(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await Ke(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await Ke(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...i,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",i);return}}s(je,"handleTierCheckoutEvent");async function Ke(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)throw S(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${i}`));let a=t[i];if(!a)throw S(new Error(`Unknown billing config key: ${i}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:i,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:B.ACTIVE,subscriptionEnd:K(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:B.ACTIVE,subscriptionEnd:K(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:i,operation:"purchase_processed"})}s(Ke,"grantCheckoutPurchase");async function He(e,t,r,o,n){let i=qe(e);if(!i)return;let a=await o.subscriptions.retrieve(i),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:i,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw S(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:B.ACTIVE,subscriptionEnd:K(d.duration),subscriptionId:i,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}s(He,"handleInvoicePaymentSucceeded");async function Ve(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)return;let a=t[i];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:fe.FREE,status:B.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:i,operation:"subscription_cancelled"})}}s(Ve,"handleSubscriptionDeleted");async function Ge(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){p.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}s(Ge,"handlePaymentFailed");var wt=3,Et=200;async function Hr(e,t,r,o,n,i,a,c){try{ge(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new g(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:_}=m;a||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await St(d,u,i,o,a)}catch(k){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:k instanceof Error?k:new Error(String(k)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await kt(c,d.id,_),k}return await yt(c,d.id,_),{success:!0,message:"Webhook processed"}}catch(u){throw S(u)}}s(Hr,"processWebhook");async function kt(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}s(kt,"releaseReservation");async function yt(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let i=n instanceof Error?n:new Error(String(n));if(n instanceof N)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:i,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=wt)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:i,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:i.message}),await new Promise(a=>setTimeout(a,Et*o))}}s(yt,"markProcessedWithRetry");async function St(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await vt(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await He(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await Ve(e.data.object,t,r,n);break;case"invoice.payment_failed":await Ge(e.data.object,t);break;case"customer.tax_id.updated":await Oe(e.id,e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}s(St,"routeEvent");async function vt(e,t,r,o,n,i,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await xe(e,t,r,o,u,d,a);return}await je(e,o,n,i,c)}s(vt,"handleCheckoutSessionEvent");var zr=`
|
|
23
|
+
CREATE TABLE IF NOT EXISTS public.webhook_events (
|
|
24
|
+
event_id TEXT PRIMARY KEY,
|
|
25
|
+
status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
|
|
26
|
+
owner_token UUID NOT NULL,
|
|
27
|
+
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
28
|
+
processed_at TIMESTAMPTZ
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
-- Only service_role accesses this table
|
|
32
|
+
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
|
|
33
|
+
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
|
|
35
|
+
ON public.webhook_events (processed_at);
|
|
36
|
+
|
|
37
|
+
-- The functions below run as the caller (SECURITY INVOKER) and refuse every
|
|
38
|
+
-- role but service_role. EXECUTE is deliberately not revoked: on Supabase
|
|
39
|
+
-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
|
|
40
|
+
-- crashes the backend (signal 11), which restarts every connection.
|
|
41
|
+
CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
|
|
42
|
+
RETURNS VOID
|
|
43
|
+
LANGUAGE plpgsql
|
|
44
|
+
SET search_path = public
|
|
45
|
+
AS $$
|
|
46
|
+
BEGIN
|
|
47
|
+
IF current_user IS DISTINCT FROM 'service_role' THEN
|
|
48
|
+
RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
|
|
49
|
+
USING ERRCODE = 'insufficient_privilege';
|
|
50
|
+
END IF;
|
|
51
|
+
END;
|
|
52
|
+
$$;
|
|
53
|
+
|
|
54
|
+
-- Atomic reservation. Returns:
|
|
55
|
+
-- 'reserved' the caller now owns the event under p_owner_token
|
|
56
|
+
-- 'processed' the event was already processed (skip, answer 2xx)
|
|
57
|
+
-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
|
|
58
|
+
-- A 'processing' row older than the lease is retaken (abandoned worker).
|
|
59
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
|
|
60
|
+
p_event_id TEXT,
|
|
61
|
+
p_owner_token UUID,
|
|
62
|
+
p_lease_seconds INT
|
|
63
|
+
)
|
|
64
|
+
RETURNS TEXT
|
|
65
|
+
LANGUAGE plpgsql
|
|
66
|
+
SET search_path = public
|
|
67
|
+
AS $$
|
|
68
|
+
DECLARE
|
|
69
|
+
v_status TEXT;
|
|
70
|
+
BEGIN
|
|
71
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
72
|
+
|
|
73
|
+
INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
|
|
74
|
+
VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
|
|
75
|
+
ON CONFLICT (event_id) DO UPDATE
|
|
76
|
+
SET owner_token = EXCLUDED.owner_token,
|
|
77
|
+
reserved_at = clock_timestamp()
|
|
78
|
+
WHERE webhook_events.status = 'processing'
|
|
79
|
+
AND webhook_events.reserved_at
|
|
80
|
+
< clock_timestamp() - make_interval(secs => p_lease_seconds);
|
|
81
|
+
IF FOUND THEN
|
|
82
|
+
RETURN 'reserved';
|
|
83
|
+
END IF;
|
|
84
|
+
|
|
85
|
+
SELECT status INTO v_status
|
|
86
|
+
FROM public.webhook_events
|
|
87
|
+
WHERE event_id = p_event_id;
|
|
88
|
+
IF v_status = 'processed' THEN
|
|
89
|
+
RETURN 'processed';
|
|
90
|
+
END IF;
|
|
91
|
+
-- Live lease, or the row was released in between: Stripe retries either way
|
|
92
|
+
RETURN 'in_progress';
|
|
93
|
+
END;
|
|
94
|
+
$$;
|
|
95
|
+
|
|
96
|
+
-- Mark a reservation processed. Returns false when p_owner_token no longer owns
|
|
97
|
+
-- the row (lease retaken, released, or deleted). Repeating it for the same
|
|
98
|
+
-- owner is a no-op that returns true.
|
|
99
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
|
|
100
|
+
p_event_id TEXT,
|
|
101
|
+
p_owner_token UUID
|
|
102
|
+
)
|
|
103
|
+
RETURNS BOOLEAN
|
|
104
|
+
LANGUAGE plpgsql
|
|
105
|
+
SET search_path = public
|
|
106
|
+
AS $$
|
|
107
|
+
BEGIN
|
|
108
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
109
|
+
|
|
110
|
+
UPDATE public.webhook_events
|
|
111
|
+
SET status = 'processed',
|
|
112
|
+
processed_at = COALESCE(processed_at, clock_timestamp())
|
|
113
|
+
WHERE event_id = p_event_id
|
|
114
|
+
AND owner_token = p_owner_token;
|
|
115
|
+
RETURN FOUND;
|
|
116
|
+
END;
|
|
117
|
+
$$;
|
|
118
|
+
|
|
119
|
+
-- Drop a reservation after a processing failure. Returns false when
|
|
120
|
+
-- p_owner_token does not own a 'processing' row (nothing is deleted).
|
|
121
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_release(
|
|
122
|
+
p_event_id TEXT,
|
|
123
|
+
p_owner_token UUID
|
|
124
|
+
)
|
|
125
|
+
RETURNS BOOLEAN
|
|
126
|
+
LANGUAGE plpgsql
|
|
127
|
+
SET search_path = public
|
|
128
|
+
AS $$
|
|
129
|
+
BEGIN
|
|
130
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
131
|
+
|
|
132
|
+
DELETE FROM public.webhook_events
|
|
133
|
+
WHERE event_id = p_event_id
|
|
134
|
+
AND owner_token = p_owner_token
|
|
135
|
+
AND status = 'processing';
|
|
136
|
+
RETURN FOUND;
|
|
137
|
+
END;
|
|
138
|
+
$$;
|
|
139
|
+
|
|
140
|
+
-- Enable pg_cron extension (if not already enabled)
|
|
141
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
142
|
+
|
|
143
|
+
-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
|
|
144
|
+
-- Stripe retries an event for up to 3 days, so older rows are never read again.
|
|
145
|
+
SELECT cron.schedule(
|
|
146
|
+
'cleanup-webhook-events',
|
|
147
|
+
'0 5 * * *',
|
|
148
|
+
$$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
|
|
149
|
+
);
|
|
150
|
+
`,It=pe(["reserved","processed","in_progress"]),Xe=ue();function Jr(e){let t=s(async(r,o,n)=>{let{data:i,error:a}=await e.rpc(r,o);if(a)throw S(a);let c=L(n,i);if(!c.success)throw S(new Error(`${r} returned an unexpected result: ${JSON.stringify(i)}`));return c.output},"call");return{async reserve(r){let o=We(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:Fe/1e3},It);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Xe))throw new N(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Xe)}}}s(Jr,"createSupabaseIdempotencyStore");export{S as a,Tt as b,At as c,J as d,Mt as e,Z as f,j as g,et as h,rt as i,ot as j,nt as k,ne as l,Ae as m,ee as n,F as o,X as p,at as q,ct as r,xe as s,dt as t,Oe as u,Er as v,vr as w,N as x,Fe as y,Cr as z,We as A,Ar as B,Hr as C,zr as D,Jr as E};
|
|
151
|
+
//# sourceMappingURL=chunk-LJXSA7EP.js.map
|