@donotdev/functions 0.3.2 → 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/lib/chunks/chunk-7T2RZ5A4.js +22 -0
- package/lib/chunks/chunk-7T2RZ5A4.js.map +7 -0
- package/lib/firebase/auth/index.d.ts +1 -0
- package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- 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/index.js +1 -1
- package/package.json +3 -3
- 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/crud/delete.ts +57 -1
- 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/lib/chunks/chunk-TBHRDSX5.js +0 -22
- package/lib/chunks/chunk-TBHRDSX5.js.map +0 -7
package/lib/vercel/api/index.js
CHANGED
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{a as U,d as G,g as le,h as A,i as be,n as N,o as P}from"../../chunks/chunk-CCEGC2T6.js";import{a as Ce,c as ke}from"../../chunks/chunk-HLNYUAZH.js";import{b as xe,c as E,e as ve,f as C,g as _,h as Ee}from"../../chunks/chunk-TBHRDSX5.js";import{B as ye,C as Se,E as Re,a as m,b as q,c as L,d as H,e as ge,h as we,v as Ae,w as M}from"../../chunks/chunk-LJXSA7EP.js";import{F,G as I,H as ee,M as te,S as re,V as R,W as oe,X as se,Y as ne,Z as ie,_ as ae,ga as D,h as Q,l as X,na as ce,r as Y,ra as ue,ta as pe,v as T,va as me,w as Z,wa as de,z as k}from"../../chunks/chunk-Y6BR2QOV.js";import{a as z}from"../../chunks/chunk-IO4MUTT6.js";import{b as he,f as J}from"../../chunks/chunk-4BJP372Z.js";import{a as fe}from"../../chunks/chunk-W6W4L44F.js";import{a}from"../../chunks/chunk-AYY7UXNI.js";function Le(s){return async o=>{let r=o.headers.get("authorization");if(!r?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let e=r.slice(7),t;try{t=(await le(e)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let n=await o.json().catch(()=>({})),u=I(ee,n);if(!u.success){let c=u.issues.map(i=>i.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${c}`}),{status:400,headers:{"Content-Type":"application/json"}})}return we(u.output,s,{userId:t,requestId:crypto.randomUUID()})}}a(Le,"createAIChatRoute");async function Ne(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{getFirebaseAdminAuth:e}=await import("../../chunks/server-YXYTPMRF.js"),t=await e().getUser(r);return o.status(200).json({customClaims:t.customClaims||{}})}catch(r){throw m(r)}}a(Ne,"handler");async function Te(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{getFirebaseAdminAuth:e}=await import("../../chunks/server-YXYTPMRF.js"),t=await e().getUser(r);return o.status(200).json({uid:t.uid,email:t.email,emailVerified:t.emailVerified,customClaims:t.customClaims||{},disabled:t.disabled})}catch(r){throw m(r)}}a(Te,"handler");async function Ie(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{claimsToRemove:e}=s.body;if(!Array.isArray(e))throw m(new Error("claimsToRemove must be an array"));let{getFirebaseAdminAuth:t}=await import("../../chunks/server-YXYTPMRF.js"),c={...(await t().getUser(r)).customClaims||{}};return e.forEach(i=>{delete c[i]}),await t().setCustomUserClaims(r,c),o.status(200).json({success:!0,customClaims:c})}catch(r){throw m(r)}}a(Ie,"handler");var Ge=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Ht(s){let o=new Set(s.allowedClaimKeys);for(let r of o)if(Ge.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return a(async function(e,t){if(e.method!=="POST")return t.status(405).json({error:"Method not allowed"});try{let n=await A(e),{customClaims:u}=e.body;if(!u||typeof u!="object")throw m(new Error("customClaims must be an object"));let c=Object.keys(u).filter(w=>!o.has(w));if(c.length>0)throw m(new Error(`Claim keys not allowed: ${c.join(", ")}`));let{getFirebaseAdminAuth:i}=await import("../../chunks/server-YXYTPMRF.js"),g={...(await i().getUser(n)).customClaims||{},...u};return await i().setCustomUserClaims(n,g),t.status(200).json({success:!0,customClaims:g})}catch(n){throw m(n)}},"handler")}a(Ht,"createSetCustomClaimsHandler");var $=null;async function V(){if($)return $;let s=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:r}=await import("@supabase/supabase-js");return $=r(s,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),$}a(V,"getSupabaseAdmin");async function K(s){if(G(s)==="supabase"){let r=await V();return{authProvider:Ce(r),idempotencyStore:Re(r)}}let{getFirebaseAdminAuth:o}=await import("../../chunks/server-YXYTPMRF.js");return{authProvider:{async getUser(r){return{customClaims:(await o().getUser(r)).customClaims}},async setCustomUserClaims(r,e){await o().setCustomUserClaims(r,e)}},idempotencyStore:be()}}a(K,"resolveBillingBackend");function S(s,o,r,e,t,n){return n!==void 0&&G(n),async(u,c)=>{try{if(u.method!==s)return c.status(405).json({error:"Method not allowed"});let i=I(o,u.body);if(!i.success)return c.status(400).json({error:`Validation failed: ${i.issues.map(y=>y.message).join(", ")}`});let p=i.output,d=await A(u,n),g=`${r}_${d}`,l=J[r]||J.api,h=n==="supabase"?await ke(await V(),g,l):await he(g,l);if(!h.allowed)return t?.audit({type:"rate_limit.exceeded",userId:d,metadata:{operation:r,remaining:0}}),c.status(429).json({error:`Rate limit exceeded. Try again in ${h.blockRemainingSeconds} seconds.`,retryAfter:h.blockRemainingSeconds});let b=await e(u,c,p,{uid:d});return b==null&&console.warn(`[${r}] businessLogic returned ${b} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await z({operation:r,userId:d,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:u.headers["x-request-id"]||"unknown"}}),b}catch(i){process.env.ENABLE_METRICS==="true"&&await z({operation:r,userId:u.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:i instanceof Error?i.message:"Unknown error",requestId:u.headers["x-request-id"]||"unknown"}});try{m(i)}catch(p){let d=He(p);return c.status(d.status).json({error:d.message})}return c.status(500).json({error:"Internal server error"})}}}a(S,"createVercelBaseFunction");function He(s){return s instanceof R?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}a(He,"classifiedToHttp");async function Me(s,o,r,e,t){ve(process.env.STRIPE_SECRET_KEY||""),_();let n={async createStripeSession(i){let p=await C.checkout.sessions.create(i);return{id:p.id,url:p.url}},async retrieveTaxRate(i){let p=await C.taxRates.retrieve(i);return{id:p.id,inclusive:p.inclusive}}},{authProvider:u}=await K(t.backend),c=await Ae(o,r.uid,n,u,e);return s.status(200).json(c)}a(Me,"createCheckoutSessionLogic");function $e(s,o){return S("POST",te,"create_checkout_session",(r,e,t,n)=>Me(e,t,n,s,o),void 0,o.backend)}a($e,"createCheckoutSession");function Ve(s,o){return async(r,e)=>{if(r.method!=="POST"){e.status(405).json({error:"Method not allowed"});return}try{let t=r.headers["stripe-signature"];if(!t||Array.isArray(t))throw new Error("No Stripe signature found");let n=process.env.STRIPE_WEBHOOK_SECRET;if(!n)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(r.headers["content-length"]||"0",10)>_e){e.status(413).json({error:"Payload too large"});return}let c=await Ke(r),{authProvider:i,idempotencyStore:p}=await K(o.backend);await Se(c,t,n,C,s,M,i,p),e.status(200).json({received:!0})}catch(t){fe.error("[Vercel Webhook] Error",{error:t instanceof Error?t:new Error(String(t)),operation:"webhook_processing"}),e.status(400).json({error:"Webhook processing failed"})}}}a(Ve,"createStripeWebhook");var _e=1*1024*1024;async function Ke(s){let o=[],r=0;for await(let e of s){let t=typeof e=="string"?Buffer.from(e):e;if(r+=t.length,r>_e)throw new Error("Request body too large");o.push(t)}return Buffer.concat(o)}a(Ke,"getRawBody");var We=T({userId:F(k(),Q(1,"User ID is required"))});function Ye(s){return{}[s||""]||"free"}a(Ye,"getTierFromPriceId");async function ze(s,o,r,e){_();let t=e.uid,{getFirebaseAdminAuth:n}=await import("../../chunks/server-YXYTPMRF.js"),c=(await n().getUser(t)).customClaims||{};if(!c.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let i=await C.subscriptions.retrieve(c.subscriptionId),p={tier:Ye(i.items.data[0]?.price.id),subscriptionId:i.id,customerId:i.customer,status:i.status,currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString()};return await n().setCustomUserClaims(t,{...c,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}a(ze,"refreshSubscriptionStatusLogic");var Je=a(s=>S("POST",s||We,"refresh_subscription_status",ze),"refreshSubscriptionStatus"),Qe=Je;var Xe=T({userId:k()});async function Ze(s,o,r,e){let t=e.uid,{getFirebaseAdminAuth:n}=await import("../../chunks/server-YXYTPMRF.js"),c=await Ee(t,{async getUser(i){return n().getUser(i)},async setCustomUserClaims(i,p){await n().setCustomUserClaims(i,p)}});return o.status(200).json({success:c.success,cancelAtPeriodEnd:!0,endsAt:c.endsAt})}a(Ze,"cancelSubscriptionLogic");var et=a(()=>S("POST",Xe,"cancel_subscription",Ze),"cancelSubscription"),tt=et;var rt=T({userId:k(),newPriceId:k(),billingConfigKey:k()});async function ot(s,o,r,e,t){_();let n=e.uid,{newPriceId:u,billingConfigKey:c}=r,i=t[c];if(!i||i.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(i.priceId!==u)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-YXYTPMRF.js"),g=(await p().getUser(n)).customClaims?.subscription?.subscriptionId;if(!g)throw m(new Error("No active subscription"));let w=await C.subscriptions.retrieve(g),l=await C.subscriptions.update(g,{items:[{id:w.items.data[0]?.id,price:u}],proration_behavior:"create_prorations"}),b=ye(["active","canceled","past_due","trialing","incomplete"],l.status)?l.status:"incomplete";return await M(n,{tier:i.tier,status:b,subscriptionEnd:new Date(l.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:l.cancel_at_period_end,subscriptionId:l.id,customerId:l.customer},{async getUser(y){return p().getUser(y)},async setCustomUserClaims(y,x){await p().setCustomUserClaims(y,x)}}),o.status(200).json({success:!0,newTier:i.tier,newPrice:i.price})}a(ot,"changePlanLogic");var st=a(s=>S("POST",rt,"change_plan",(o,r,e,t)=>ot(o,r,e,t,s)),"changePlan"),nt=st;var it=T({userId:k(),returnUrl:Z(F(k(),X()))});async function at(s,o,r,e){_();let t=e.uid,{returnUrl:n}=r,{getFirebaseAdminAuth:u}=await import("../../chunks/server-YXYTPMRF.js"),i=(await u().getUser(t)).customClaims?.subscription?.customerId;if(!i)throw m(new Error("No customer found"));let p=await C.billingPortal.sessions.create({customer:i,return_url:n||`${process.env.FRONTEND_URL}/billing`});return o.status(200).json({url:p.url})}a(at,"createCustomerPortalLogic");var ct=a(()=>S("POST",it,"create_customer_portal",at),"createCustomerPortal"),ut=ct;var j=process.env.FIREBASE_REGION||"europe-west1",to={region:j,memory:"1GiB",timeoutSeconds:60},ro={region:j,memory:"512MiB",timeoutSeconds:30},oo={region:j,memory:"256MiB",timeoutSeconds:20},so={region:j,memory:"256MiB",timeoutSeconds:15},no={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},io=a(()=>{let o=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(o.length>0)throw new Error(`Missing required environment variables: ${o.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${j}`)},"validateEnvironment");async function uo(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-YXYTPMRF.js");return await s()}a(uo,"initializeFirebaseAdmin");async function po(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-YXYTPMRF.js");return await s()}a(po,"getFirebaseAdmin");var Pe=Y({}),pt=Y({});async function Be(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),e=s.query.collection,t=typeof e=="string"?e:e?.[0];t||m(new Error("Missing collection")),E(t);let n=I(ce,s.body);if(!n.success)return o.status(400).json({error:`Validation failed: ${n.issues.map(p=>p.message).join(", ")}`});let u=n.output,{getFirebaseAdminFirestore:c}=await import("../../chunks/server-YXYTPMRF.js"),i=await ge({collection:t,ops:u,createSchema:Pe,draftCreateSchema:Pe,updateSchema:pt,access:{create:"user",update:"user",delete:"user"},uid:r,userRole:"user",readStored:a(async p=>{let d=c(),g=d.collection(t),w=await d.getAll(...p.map(h=>g.doc(h))),l=new Map;for(let h of w)h.exists&&l.set(h.id,N(h.data()));return l},"readStored"),mintInsertId:a(()=>c().collection(t).doc().id,"mintInsertId"),stampInsertMetadata:a((p,d)=>({...P(p),...q(d)}),"stampInsertMetadata"),stampUpdateMetadata:a((p,d)=>({...P(p),...L(d)}),"stampUpdateMetadata"),transact:a(async({inserts:p,updates:d,deletes:g})=>{let w=c(),l=w.collection(t);return w.runTransaction(async h=>{let b=await Promise.all(d.map(f=>h.get(l.doc(f.id))));for(let f=0;f<b.length;f++)if(!b[f].exists)throw new Error(`Document not found: ${t}/${d[f].id}`);let y=await Promise.all(g.map(f=>h.get(l.doc(f))));for(let f=0;f<y.length;f++)if(!y[f].exists)throw new Error(`Document not found: ${t}/${g[f]}`);let x=[];for(let{id:f,row:W}of p)h.set(l.doc(f),W),x.push(f);let v=[];for(let{id:f,patch:W}of d)h.update(l.doc(f),W),v.push(f);let O=[];for(let f of g)h.delete(l.doc(f)),O.push(f);return{insertedIds:x,updatedIds:v,deletedIds:O}})},"transact")});return o.status(200).json(i)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let n=r instanceof re||e.code==="invalid-argument"?400:500;return o.status(n).json({error:e.message,code:e.code})}}}a(Be,"handler");async function Ue(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,payload:t}=s.body;(!e||!t)&&m(new Error("Missing schema or payload")),E(e.metadata.collection);let n=H(ue({create:e,draft:e},t),e.metadata.collection,"create"),u={...P(n),...q(r)},{getFirebaseAdminFirestore:c}=await import("../../chunks/server-YXYTPMRF.js"),d=await(await c().collection(e.metadata.collection).add(u)).get(),g=N({id:d.id,...d.data()});return o.status(200).json(g)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Ue,"handler");async function je(s,o){if(s.method!=="DELETE")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t}=s.body;(!e||!t)&&m(new Error("Missing schema or id")),E(e.metadata.collection);let{getFirebaseAdminFirestore:n}=await import("../../chunks/server-YXYTPMRF.js"),u=n();return(await u.collection(e.metadata.collection).doc(t).get()).exists||m(new Error("Document not found")),await u.collection(e.metadata.collection).doc(t).delete(),o.status(200).json({success:!0,message:"Document deleted successfully",id:t})}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(je,"handler");async function Oe(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t}=s.query;(typeof t!="string"||!t)&&m(new Error("Missing or invalid id parameter")),e||m(new Error("Missing schema")),E(e.metadata.collection);let{getFirebaseAdminFirestore:n}=await import("../../chunks/server-YXYTPMRF.js"),c=await n().collection(e.metadata.collection).doc(t).get();c.exists||m(new Error("Document not found"));let i=c.data();de(i,void 0)||m(new Error("Document not found"));let p=N({id:c.id,...i}),d=D(p,e,"user");return o.status(200).json(d)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Oe,"handler");async function Fe(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,limit:t=10,offset:n=0}=s.query;e||m(new Error("Missing schema")),E(e.metadata.collection);let{getFirebaseAdminFirestore:u}=await import("../../chunks/server-YXYTPMRF.js"),i=u().collection(e.metadata.collection);i=i.where("status","not-in",[...me(void 0)]);let p=Math.min(parseInt(t)||1e3,1e3),d=parseInt(n)||0;i=i.limit(p),i=i.offset(d);let g=await i.get(),w=g.docs.map(l=>{let h=N({id:l.id,...l.data()});return D(h,e,"user")});return o.status(200).json({documents:w,total:g.size,limit:p,offset:d})}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Fe,"handler");async function De(s,o){if(s.method!=="PUT")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t,payload:n}=s.body;(!e||!t||!n)&&m(new Error("Missing schema, id, or payload")),E(e.metadata.collection);let{getFirebaseAdminFirestore:u}=await import("../../chunks/server-YXYTPMRF.js"),c=u(),i=await c.collection(e.metadata.collection).doc(t).get();i.exists||m(new Error("Document not found"));let p=N(i.data()||{}),d=H(pe({draft:e,update:e},{id:t,patch:n,stored:p}),e.metadata.collection,"update"),g={...P(d),...L(r)};await c.collection(e.metadata.collection).doc(t).update(g);let w=await c.collection(e.metadata.collection).doc(t).get();w.exists||m(new Error("Document not found"));let l=N({id:w.id,...w.data()});return o.status(200).json(l)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(De,"handler");async function mt(s,o,r,e){let{githubUsername:t,repoConfig:n}=r,u=e.uid;if(!t)throw new Error("GitHub username is required");if(!n?.owner||!n?.repo)throw new Error("Repository owner and name are required");let c=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!c)throw new Error("GitHub Personal Access Token not configured");let p=await new U({accessToken:c}).isCollaborator(n.owner,n.repo,t),{getFirebaseAdminAuth:d}=await import("../../chunks/server-YXYTPMRF.js"),l=((await d().getUser(u)).customClaims||{}).githubAccess?.[n.owner]?.[n.repo],h={success:!0,userId:u,githubUsername:t,repoConfig:n,hasAccess:p,customClaimsAccess:!!l,accessDetails:l||null,message:p?`${t} has access to ${n.owner}/${n.repo}`:`${t} does not have access to ${n.owner}/${n.repo}`};return o.status(200).json(h)}a(mt,"checkGitHubAccessLogic");var dt=a(s=>S("POST",s||ne,"check_github_access",mt),"checkGitHubAccess"),lt=dt;function ft(s){let o=new URL(s);if(o.protocol!=="https:")throw new Error("Instance URL must use HTTPS");let r=o.hostname;if(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.startsWith("10.")||r.startsWith("192.168.")||r.startsWith("172.")||r==="169.254.169.254"||r.endsWith(".internal")||r.endsWith(".local"))throw new Error("Instance URL must not point to internal addresses")}a(ft,"validateInstanceUrl");async function ht(s,o,r,e){let{provider:t,purpose:n,code:u,redirectUri:c,codeVerifier:i,instance:p}=r,d=ae[t]?.endpoints?.tokenUrl;if(t==="mastodon"&&p&&(ft(p),d=`${p.replace(/\/$/,"")}/oauth/token`),!d)throw new Error(`Provider ${t} is not supported`);let g=`${t.toUpperCase()}_CLIENT_ID`,w=`${t.toUpperCase()}_CLIENT_SECRET`,l=process.env[g],h=process.env[w];if(!l||!h)throw new Error(`${t} OAuth is not properly configured`);let b,y={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"};if(t==="github"){y["Content-Type"]="application/json",y["User-Agent"]="DoNotDev-OAuth-Client";let f={client_id:l,client_secret:h,code:u,redirect_uri:c};i&&(f.code_verifier=i),b=JSON.stringify(f)}else{let f=new URLSearchParams({grant_type:"authorization_code",client_id:l,client_secret:h,code:u,redirect_uri:c});i&&f.append("code_verifier",i),b=f}let x=await fetch(d,{method:"POST",headers:y,body:b});if(!x.ok){let f=await x.text();throw console.error("Token exchange HTTP error",{provider:t,status:x.status,statusText:x.statusText,error:f}),new Error(`Failed to exchange code for token: ${x.status} ${x.statusText}`)}let v=await x.json();if(!v.access_token)throw console.error("Invalid token response",{provider:t,hasAccessToken:!!v?.access_token}),new Error("Provider returned invalid token format");let O={access_token:v.access_token,token_type:v.token_type||"Bearer",expires_in:v.expires_in,refresh_token:v.refresh_token,scope:v.scope,id_token:v.id_token,created_at:v.created_at||Math.floor(Date.now()/1e3)};return o.status(200).json(xe(O))}a(ht,"exchangeTokenLogic");var gt=a(s=>S("POST",s||ie,"exchange_token",ht),"exchangeToken"),wt=gt;async function At(s,o,r,e){let{githubUsername:t,repoConfig:n,permission:u="push",customClaims:c}=r,i=e.uid;if(!t)throw new Error("GitHub username is required");if(!n?.owner||!n?.repo)throw new Error("Repository owner and name are required");let p=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!p)throw new Error("GitHub Personal Access Token not configured");if(await new U({accessToken:p}).addCollaborator({owner:n.owner,repo:n.repo,username:t,permission:u}),c){let{getFirebaseAdminAuth:w}=await import("../../chunks/server-YXYTPMRF.js"),l=await w().getUser(i),h={...l.customClaims,...c,githubAccess:{...l.customClaims?.githubAccess,[n.owner]:{...l.customClaims?.githubAccess?.[n.owner],[n.repo]:{username:t,permission:u,grantedAt:new Date().toISOString()}}}};await w().setCustomUserClaims(i,h)}let g={success:!0,userId:i,githubUsername:t,repoConfig:n,permission:u,message:`Successfully granted ${t} ${u} access to ${n.owner}/${n.repo}`};return o.status(200).json(g)}a(At,"grantGitHubAccessLogic");var yt=a(s=>S("POST",s||oe,"grant_github_access",At),"grantGitHubAccess"),St=yt;async function qe(s,o,r){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let e=await A(s),n=I(r||se,s.body);if(!n.success)return o.status(400).json({error:`Validation failed: ${n.issues.map(y=>y.message).join(", ")}`});let{githubUsername:u,repoConfig:c}=n.output,i=e;if(!u)throw m(new Error("GitHub username is required"));if(!c?.owner||!c?.repo)throw m(new Error("Repository owner and name are required"));let p=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!p)throw m(new Error("GitHub Personal Access Token not configured"));await new U({accessToken:p}).removeCollaborator(c.owner,c.repo,u)||console.warn(`Failed to remove ${u} from GitHub repository`);let{getFirebaseAdminAuth:w}=await import("../../chunks/server-YXYTPMRF.js"),h=(await w().getUser(i)).customClaims||{};if(h.githubAccess?.[c.owner]?.[c.repo]){let y={...h};y.githubAccess[c.owner]&&(delete y.githubAccess[c.owner][c.repo],Object.keys(y.githubAccess[c.owner]).length===0&&delete y.githubAccess[c.owner]),await w().setCustomUserClaims(i,y)}let b={success:!0,userId:i,githubUsername:u,repoConfig:c,message:`Successfully revoked ${u} access to ${c.owner}/${c.repo}`};return o.status(200).json(b)}catch(e){throw m(e)}}a(qe,"handler");export{oo as AUTH_CONFIG,no as AVAILABLE_REGIONS,so as CRUD_CONFIG,j as FIREBASE_REGION,to as FUNCTION_CONFIG,ro as STRIPE_CONFIG,Be as bulk,tt as cancelSubscription,nt as changePlan,lt as checkGitHubAccess,Le as createAIChatRoute,$e as createCheckoutSession,ut as createCustomerPortal,Ue as createEntity,Ht as createSetCustomClaimsHandler,Ve as createStripeWebhook,je as deleteEntity,wt as exchangeToken,Ne as getCustomClaims,Oe as getEntity,po as getFirebaseAdmin,Te as getUserAuthStatus,St as grantGitHubAccess,uo as initializeFirebaseAdmin,Fe as listEntities,Qe as refreshSubscriptionStatus,Ie as removeCustomClaims,qe as revokeGitHubAccess,De as updateEntity,M as updateUserSubscription,io as validateEnvironment};
|
|
21
|
+
import{a as U,d as G,g as le,h as A,i as be,n as N,o as P}from"../../chunks/chunk-CCEGC2T6.js";import{a as Ce,c as ke}from"../../chunks/chunk-HLNYUAZH.js";import{b as xe,c as E,d as ve,e as C,f as _,g as Ee}from"../../chunks/chunk-7T2RZ5A4.js";import{B as ye,C as Se,E as Re,a as m,b as q,c as L,d as H,e as ge,h as we,v as Ae,w as M}from"../../chunks/chunk-LJXSA7EP.js";import{F,G as I,H as ee,M as te,S as re,V as R,W as oe,X as se,Y as ne,Z as ie,_ as ae,ga as D,h as Q,l as X,na as ce,r as Y,ra as ue,ta as pe,v as T,va as me,w as Z,wa as de,z as k}from"../../chunks/chunk-Y6BR2QOV.js";import{a as z}from"../../chunks/chunk-IO4MUTT6.js";import{b as he,f as J}from"../../chunks/chunk-4BJP372Z.js";import{a as fe}from"../../chunks/chunk-W6W4L44F.js";import{a}from"../../chunks/chunk-AYY7UXNI.js";function Le(s){return async o=>{let r=o.headers.get("authorization");if(!r?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let e=r.slice(7),t;try{t=(await le(e)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let n=await o.json().catch(()=>({})),u=I(ee,n);if(!u.success){let c=u.issues.map(i=>i.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${c}`}),{status:400,headers:{"Content-Type":"application/json"}})}return we(u.output,s,{userId:t,requestId:crypto.randomUUID()})}}a(Le,"createAIChatRoute");async function Ne(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{getFirebaseAdminAuth:e}=await import("../../chunks/server-YXYTPMRF.js"),t=await e().getUser(r);return o.status(200).json({customClaims:t.customClaims||{}})}catch(r){throw m(r)}}a(Ne,"handler");async function Te(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{getFirebaseAdminAuth:e}=await import("../../chunks/server-YXYTPMRF.js"),t=await e().getUser(r);return o.status(200).json({uid:t.uid,email:t.email,emailVerified:t.emailVerified,customClaims:t.customClaims||{},disabled:t.disabled})}catch(r){throw m(r)}}a(Te,"handler");async function Ie(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{claimsToRemove:e}=s.body;if(!Array.isArray(e))throw m(new Error("claimsToRemove must be an array"));let{getFirebaseAdminAuth:t}=await import("../../chunks/server-YXYTPMRF.js"),c={...(await t().getUser(r)).customClaims||{}};return e.forEach(i=>{delete c[i]}),await t().setCustomUserClaims(r,c),o.status(200).json({success:!0,customClaims:c})}catch(r){throw m(r)}}a(Ie,"handler");var Ge=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Ht(s){let o=new Set(s.allowedClaimKeys);for(let r of o)if(Ge.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return a(async function(e,t){if(e.method!=="POST")return t.status(405).json({error:"Method not allowed"});try{let n=await A(e),{customClaims:u}=e.body;if(!u||typeof u!="object")throw m(new Error("customClaims must be an object"));let c=Object.keys(u).filter(w=>!o.has(w));if(c.length>0)throw m(new Error(`Claim keys not allowed: ${c.join(", ")}`));let{getFirebaseAdminAuth:i}=await import("../../chunks/server-YXYTPMRF.js"),g={...(await i().getUser(n)).customClaims||{},...u};return await i().setCustomUserClaims(n,g),t.status(200).json({success:!0,customClaims:g})}catch(n){throw m(n)}},"handler")}a(Ht,"createSetCustomClaimsHandler");var $=null;async function V(){if($)return $;let s=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:r}=await import("@supabase/supabase-js");return $=r(s,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),$}a(V,"getSupabaseAdmin");async function K(s){if(G(s)==="supabase"){let r=await V();return{authProvider:Ce(r),idempotencyStore:Re(r)}}let{getFirebaseAdminAuth:o}=await import("../../chunks/server-YXYTPMRF.js");return{authProvider:{async getUser(r){return{customClaims:(await o().getUser(r)).customClaims}},async setCustomUserClaims(r,e){await o().setCustomUserClaims(r,e)}},idempotencyStore:be()}}a(K,"resolveBillingBackend");function S(s,o,r,e,t,n){return n!==void 0&&G(n),async(u,c)=>{try{if(u.method!==s)return c.status(405).json({error:"Method not allowed"});let i=I(o,u.body);if(!i.success)return c.status(400).json({error:`Validation failed: ${i.issues.map(y=>y.message).join(", ")}`});let p=i.output,d=await A(u,n),g=`${r}_${d}`,l=J[r]||J.api,h=n==="supabase"?await ke(await V(),g,l):await he(g,l);if(!h.allowed)return t?.audit({type:"rate_limit.exceeded",userId:d,metadata:{operation:r,remaining:0}}),c.status(429).json({error:`Rate limit exceeded. Try again in ${h.blockRemainingSeconds} seconds.`,retryAfter:h.blockRemainingSeconds});let b=await e(u,c,p,{uid:d});return b==null&&console.warn(`[${r}] businessLogic returned ${b} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await z({operation:r,userId:d,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:u.headers["x-request-id"]||"unknown"}}),b}catch(i){process.env.ENABLE_METRICS==="true"&&await z({operation:r,userId:u.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:i instanceof Error?i.message:"Unknown error",requestId:u.headers["x-request-id"]||"unknown"}});try{m(i)}catch(p){let d=He(p);return c.status(d.status).json({error:d.message})}return c.status(500).json({error:"Internal server error"})}}}a(S,"createVercelBaseFunction");function He(s){return s instanceof R?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}a(He,"classifiedToHttp");async function Me(s,o,r,e,t){ve(process.env.STRIPE_SECRET_KEY||""),_();let n={async createStripeSession(i){let p=await C.checkout.sessions.create(i);return{id:p.id,url:p.url}},async retrieveTaxRate(i){let p=await C.taxRates.retrieve(i);return{id:p.id,inclusive:p.inclusive}}},{authProvider:u}=await K(t.backend),c=await Ae(o,r.uid,n,u,e);return s.status(200).json(c)}a(Me,"createCheckoutSessionLogic");function $e(s,o){return S("POST",te,"create_checkout_session",(r,e,t,n)=>Me(e,t,n,s,o),void 0,o.backend)}a($e,"createCheckoutSession");function Ve(s,o){return async(r,e)=>{if(r.method!=="POST"){e.status(405).json({error:"Method not allowed"});return}try{let t=r.headers["stripe-signature"];if(!t||Array.isArray(t))throw new Error("No Stripe signature found");let n=process.env.STRIPE_WEBHOOK_SECRET;if(!n)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(r.headers["content-length"]||"0",10)>_e){e.status(413).json({error:"Payload too large"});return}let c=await Ke(r),{authProvider:i,idempotencyStore:p}=await K(o.backend);await Se(c,t,n,C,s,M,i,p),e.status(200).json({received:!0})}catch(t){fe.error("[Vercel Webhook] Error",{error:t instanceof Error?t:new Error(String(t)),operation:"webhook_processing"}),e.status(400).json({error:"Webhook processing failed"})}}}a(Ve,"createStripeWebhook");var _e=1*1024*1024;async function Ke(s){let o=[],r=0;for await(let e of s){let t=typeof e=="string"?Buffer.from(e):e;if(r+=t.length,r>_e)throw new Error("Request body too large");o.push(t)}return Buffer.concat(o)}a(Ke,"getRawBody");var We=T({userId:F(k(),Q(1,"User ID is required"))});function Ye(s){return{}[s||""]||"free"}a(Ye,"getTierFromPriceId");async function ze(s,o,r,e){_();let t=e.uid,{getFirebaseAdminAuth:n}=await import("../../chunks/server-YXYTPMRF.js"),c=(await n().getUser(t)).customClaims||{};if(!c.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let i=await C.subscriptions.retrieve(c.subscriptionId),p={tier:Ye(i.items.data[0]?.price.id),subscriptionId:i.id,customerId:i.customer,status:i.status,currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString()};return await n().setCustomUserClaims(t,{...c,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}a(ze,"refreshSubscriptionStatusLogic");var Je=a(s=>S("POST",s||We,"refresh_subscription_status",ze),"refreshSubscriptionStatus"),Qe=Je;var Xe=T({userId:k()});async function Ze(s,o,r,e){let t=e.uid,{getFirebaseAdminAuth:n}=await import("../../chunks/server-YXYTPMRF.js"),c=await Ee(t,{async getUser(i){return n().getUser(i)},async setCustomUserClaims(i,p){await n().setCustomUserClaims(i,p)}});return o.status(200).json({success:c.success,cancelAtPeriodEnd:!0,endsAt:c.endsAt})}a(Ze,"cancelSubscriptionLogic");var et=a(()=>S("POST",Xe,"cancel_subscription",Ze),"cancelSubscription"),tt=et;var rt=T({userId:k(),newPriceId:k(),billingConfigKey:k()});async function ot(s,o,r,e,t){_();let n=e.uid,{newPriceId:u,billingConfigKey:c}=r,i=t[c];if(!i||i.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(i.priceId!==u)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-YXYTPMRF.js"),g=(await p().getUser(n)).customClaims?.subscription?.subscriptionId;if(!g)throw m(new Error("No active subscription"));let w=await C.subscriptions.retrieve(g),l=await C.subscriptions.update(g,{items:[{id:w.items.data[0]?.id,price:u}],proration_behavior:"create_prorations"}),b=ye(["active","canceled","past_due","trialing","incomplete"],l.status)?l.status:"incomplete";return await M(n,{tier:i.tier,status:b,subscriptionEnd:new Date(l.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:l.cancel_at_period_end,subscriptionId:l.id,customerId:l.customer},{async getUser(y){return p().getUser(y)},async setCustomUserClaims(y,x){await p().setCustomUserClaims(y,x)}}),o.status(200).json({success:!0,newTier:i.tier,newPrice:i.price})}a(ot,"changePlanLogic");var st=a(s=>S("POST",rt,"change_plan",(o,r,e,t)=>ot(o,r,e,t,s)),"changePlan"),nt=st;var it=T({userId:k(),returnUrl:Z(F(k(),X()))});async function at(s,o,r,e){_();let t=e.uid,{returnUrl:n}=r,{getFirebaseAdminAuth:u}=await import("../../chunks/server-YXYTPMRF.js"),i=(await u().getUser(t)).customClaims?.subscription?.customerId;if(!i)throw m(new Error("No customer found"));let p=await C.billingPortal.sessions.create({customer:i,return_url:n||`${process.env.FRONTEND_URL}/billing`});return o.status(200).json({url:p.url})}a(at,"createCustomerPortalLogic");var ct=a(()=>S("POST",it,"create_customer_portal",at),"createCustomerPortal"),ut=ct;var j=process.env.FIREBASE_REGION||"europe-west1",to={region:j,memory:"1GiB",timeoutSeconds:60},ro={region:j,memory:"512MiB",timeoutSeconds:30},oo={region:j,memory:"256MiB",timeoutSeconds:20},so={region:j,memory:"256MiB",timeoutSeconds:15},no={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},io=a(()=>{let o=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(o.length>0)throw new Error(`Missing required environment variables: ${o.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${j}`)},"validateEnvironment");async function uo(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-YXYTPMRF.js");return await s()}a(uo,"initializeFirebaseAdmin");async function po(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-YXYTPMRF.js");return await s()}a(po,"getFirebaseAdmin");var Pe=Y({}),pt=Y({});async function Be(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),e=s.query.collection,t=typeof e=="string"?e:e?.[0];t||m(new Error("Missing collection")),E(t);let n=I(ce,s.body);if(!n.success)return o.status(400).json({error:`Validation failed: ${n.issues.map(p=>p.message).join(", ")}`});let u=n.output,{getFirebaseAdminFirestore:c}=await import("../../chunks/server-YXYTPMRF.js"),i=await ge({collection:t,ops:u,createSchema:Pe,draftCreateSchema:Pe,updateSchema:pt,access:{create:"user",update:"user",delete:"user"},uid:r,userRole:"user",readStored:a(async p=>{let d=c(),g=d.collection(t),w=await d.getAll(...p.map(h=>g.doc(h))),l=new Map;for(let h of w)h.exists&&l.set(h.id,N(h.data()));return l},"readStored"),mintInsertId:a(()=>c().collection(t).doc().id,"mintInsertId"),stampInsertMetadata:a((p,d)=>({...P(p),...q(d)}),"stampInsertMetadata"),stampUpdateMetadata:a((p,d)=>({...P(p),...L(d)}),"stampUpdateMetadata"),transact:a(async({inserts:p,updates:d,deletes:g})=>{let w=c(),l=w.collection(t);return w.runTransaction(async h=>{let b=await Promise.all(d.map(f=>h.get(l.doc(f.id))));for(let f=0;f<b.length;f++)if(!b[f].exists)throw new Error(`Document not found: ${t}/${d[f].id}`);let y=await Promise.all(g.map(f=>h.get(l.doc(f))));for(let f=0;f<y.length;f++)if(!y[f].exists)throw new Error(`Document not found: ${t}/${g[f]}`);let x=[];for(let{id:f,row:W}of p)h.set(l.doc(f),W),x.push(f);let v=[];for(let{id:f,patch:W}of d)h.update(l.doc(f),W),v.push(f);let O=[];for(let f of g)h.delete(l.doc(f)),O.push(f);return{insertedIds:x,updatedIds:v,deletedIds:O}})},"transact")});return o.status(200).json(i)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let n=r instanceof re||e.code==="invalid-argument"?400:500;return o.status(n).json({error:e.message,code:e.code})}}}a(Be,"handler");async function Ue(s,o){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,payload:t}=s.body;(!e||!t)&&m(new Error("Missing schema or payload")),E(e.metadata.collection);let n=H(ue({create:e,draft:e},t),e.metadata.collection,"create"),u={...P(n),...q(r)},{getFirebaseAdminFirestore:c}=await import("../../chunks/server-YXYTPMRF.js"),d=await(await c().collection(e.metadata.collection).add(u)).get(),g=N({id:d.id,...d.data()});return o.status(200).json(g)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Ue,"handler");async function je(s,o){if(s.method!=="DELETE")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t}=s.body;(!e||!t)&&m(new Error("Missing schema or id")),E(e.metadata.collection);let{getFirebaseAdminFirestore:n}=await import("../../chunks/server-YXYTPMRF.js"),u=n();return(await u.collection(e.metadata.collection).doc(t).get()).exists||m(new Error("Document not found")),await u.collection(e.metadata.collection).doc(t).delete(),o.status(200).json({success:!0,message:"Document deleted successfully",id:t})}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(je,"handler");async function Oe(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t}=s.query;(typeof t!="string"||!t)&&m(new Error("Missing or invalid id parameter")),e||m(new Error("Missing schema")),E(e.metadata.collection);let{getFirebaseAdminFirestore:n}=await import("../../chunks/server-YXYTPMRF.js"),c=await n().collection(e.metadata.collection).doc(t).get();c.exists||m(new Error("Document not found"));let i=c.data();de(i,void 0)||m(new Error("Document not found"));let p=N({id:c.id,...i}),d=D(p,e,"user");return o.status(200).json(d)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Oe,"handler");async function Fe(s,o){if(s.method!=="GET")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,limit:t=10,offset:n=0}=s.query;e||m(new Error("Missing schema")),E(e.metadata.collection);let{getFirebaseAdminFirestore:u}=await import("../../chunks/server-YXYTPMRF.js"),i=u().collection(e.metadata.collection);i=i.where("status","not-in",[...me(void 0)]);let p=Math.min(parseInt(t)||1e3,1e3),d=parseInt(n)||0;i=i.limit(p),i=i.offset(d);let g=await i.get(),w=g.docs.map(l=>{let h=N({id:l.id,...l.data()});return D(h,e,"user")});return o.status(200).json({documents:w,total:g.size,limit:p,offset:d})}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(Fe,"handler");async function De(s,o){if(s.method!=="PUT")return o.status(405).json({error:"Method not allowed"});try{let r=await A(s),{schema:e,id:t,payload:n}=s.body;(!e||!t||!n)&&m(new Error("Missing schema, id, or payload")),E(e.metadata.collection);let{getFirebaseAdminFirestore:u}=await import("../../chunks/server-YXYTPMRF.js"),c=u(),i=await c.collection(e.metadata.collection).doc(t).get();i.exists||m(new Error("Document not found"));let p=N(i.data()||{}),d=H(pe({draft:e,update:e},{id:t,patch:n,stored:p}),e.metadata.collection,"update"),g={...P(d),...L(r)};await c.collection(e.metadata.collection).doc(t).update(g);let w=await c.collection(e.metadata.collection).doc(t).get();w.exists||m(new Error("Document not found"));let l=N({id:w.id,...w.data()});return o.status(200).json(l)}catch(r){try{m(r)}catch(e){if(!(e instanceof R))throw e;let t=e.code==="invalid-argument"?400:500;return o.status(t).json({error:e.message,code:e.code})}}}a(De,"handler");async function mt(s,o,r,e){let{githubUsername:t,repoConfig:n}=r,u=e.uid;if(!t)throw new Error("GitHub username is required");if(!n?.owner||!n?.repo)throw new Error("Repository owner and name are required");let c=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!c)throw new Error("GitHub Personal Access Token not configured");let p=await new U({accessToken:c}).isCollaborator(n.owner,n.repo,t),{getFirebaseAdminAuth:d}=await import("../../chunks/server-YXYTPMRF.js"),l=((await d().getUser(u)).customClaims||{}).githubAccess?.[n.owner]?.[n.repo],h={success:!0,userId:u,githubUsername:t,repoConfig:n,hasAccess:p,customClaimsAccess:!!l,accessDetails:l||null,message:p?`${t} has access to ${n.owner}/${n.repo}`:`${t} does not have access to ${n.owner}/${n.repo}`};return o.status(200).json(h)}a(mt,"checkGitHubAccessLogic");var dt=a(s=>S("POST",s||ne,"check_github_access",mt),"checkGitHubAccess"),lt=dt;function ft(s){let o=new URL(s);if(o.protocol!=="https:")throw new Error("Instance URL must use HTTPS");let r=o.hostname;if(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.startsWith("10.")||r.startsWith("192.168.")||r.startsWith("172.")||r==="169.254.169.254"||r.endsWith(".internal")||r.endsWith(".local"))throw new Error("Instance URL must not point to internal addresses")}a(ft,"validateInstanceUrl");async function ht(s,o,r,e){let{provider:t,purpose:n,code:u,redirectUri:c,codeVerifier:i,instance:p}=r,d=ae[t]?.endpoints?.tokenUrl;if(t==="mastodon"&&p&&(ft(p),d=`${p.replace(/\/$/,"")}/oauth/token`),!d)throw new Error(`Provider ${t} is not supported`);let g=`${t.toUpperCase()}_CLIENT_ID`,w=`${t.toUpperCase()}_CLIENT_SECRET`,l=process.env[g],h=process.env[w];if(!l||!h)throw new Error(`${t} OAuth is not properly configured`);let b,y={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"};if(t==="github"){y["Content-Type"]="application/json",y["User-Agent"]="DoNotDev-OAuth-Client";let f={client_id:l,client_secret:h,code:u,redirect_uri:c};i&&(f.code_verifier=i),b=JSON.stringify(f)}else{let f=new URLSearchParams({grant_type:"authorization_code",client_id:l,client_secret:h,code:u,redirect_uri:c});i&&f.append("code_verifier",i),b=f}let x=await fetch(d,{method:"POST",headers:y,body:b});if(!x.ok){let f=await x.text();throw console.error("Token exchange HTTP error",{provider:t,status:x.status,statusText:x.statusText,error:f}),new Error(`Failed to exchange code for token: ${x.status} ${x.statusText}`)}let v=await x.json();if(!v.access_token)throw console.error("Invalid token response",{provider:t,hasAccessToken:!!v?.access_token}),new Error("Provider returned invalid token format");let O={access_token:v.access_token,token_type:v.token_type||"Bearer",expires_in:v.expires_in,refresh_token:v.refresh_token,scope:v.scope,id_token:v.id_token,created_at:v.created_at||Math.floor(Date.now()/1e3)};return o.status(200).json(xe(O))}a(ht,"exchangeTokenLogic");var gt=a(s=>S("POST",s||ie,"exchange_token",ht),"exchangeToken"),wt=gt;async function At(s,o,r,e){let{githubUsername:t,repoConfig:n,permission:u="push",customClaims:c}=r,i=e.uid;if(!t)throw new Error("GitHub username is required");if(!n?.owner||!n?.repo)throw new Error("Repository owner and name are required");let p=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!p)throw new Error("GitHub Personal Access Token not configured");if(await new U({accessToken:p}).addCollaborator({owner:n.owner,repo:n.repo,username:t,permission:u}),c){let{getFirebaseAdminAuth:w}=await import("../../chunks/server-YXYTPMRF.js"),l=await w().getUser(i),h={...l.customClaims,...c,githubAccess:{...l.customClaims?.githubAccess,[n.owner]:{...l.customClaims?.githubAccess?.[n.owner],[n.repo]:{username:t,permission:u,grantedAt:new Date().toISOString()}}}};await w().setCustomUserClaims(i,h)}let g={success:!0,userId:i,githubUsername:t,repoConfig:n,permission:u,message:`Successfully granted ${t} ${u} access to ${n.owner}/${n.repo}`};return o.status(200).json(g)}a(At,"grantGitHubAccessLogic");var yt=a(s=>S("POST",s||oe,"grant_github_access",At),"grantGitHubAccess"),St=yt;async function qe(s,o,r){if(s.method!=="POST")return o.status(405).json({error:"Method not allowed"});try{let e=await A(s),n=I(r||se,s.body);if(!n.success)return o.status(400).json({error:`Validation failed: ${n.issues.map(y=>y.message).join(", ")}`});let{githubUsername:u,repoConfig:c}=n.output,i=e;if(!u)throw m(new Error("GitHub username is required"));if(!c?.owner||!c?.repo)throw m(new Error("Repository owner and name are required"));let p=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!p)throw m(new Error("GitHub Personal Access Token not configured"));await new U({accessToken:p}).removeCollaborator(c.owner,c.repo,u)||console.warn(`Failed to remove ${u} from GitHub repository`);let{getFirebaseAdminAuth:w}=await import("../../chunks/server-YXYTPMRF.js"),h=(await w().getUser(i)).customClaims||{};if(h.githubAccess?.[c.owner]?.[c.repo]){let y={...h};y.githubAccess[c.owner]&&(delete y.githubAccess[c.owner][c.repo],Object.keys(y.githubAccess[c.owner]).length===0&&delete y.githubAccess[c.owner]),await w().setCustomUserClaims(i,y)}let b={success:!0,userId:i,githubUsername:u,repoConfig:c,message:`Successfully revoked ${u} access to ${c.owner}/${c.repo}`};return o.status(200).json(b)}catch(e){throw m(e)}}a(qe,"handler");export{oo as AUTH_CONFIG,no as AVAILABLE_REGIONS,so as CRUD_CONFIG,j as FIREBASE_REGION,to as FUNCTION_CONFIG,ro as STRIPE_CONFIG,Be as bulk,tt as cancelSubscription,nt as changePlan,lt as checkGitHubAccess,Le as createAIChatRoute,$e as createCheckoutSession,ut as createCustomerPortal,Ue as createEntity,Ht as createSetCustomClaimsHandler,Ve as createStripeWebhook,je as deleteEntity,wt as exchangeToken,Ne as getCustomClaims,Oe as getEntity,po as getFirebaseAdmin,Te as getUserAuthStatus,St as grantGitHubAccess,uo as initializeFirebaseAdmin,Fe as listEntities,Qe as refreshSubscriptionStatus,Ie as removeCustomClaims,qe as revokeGitHubAccess,De as updateEntity,M as updateUserSubscription,io as validateEnvironment};
|
|
22
22
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/functions",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
|
|
6
6
|
"main": "./lib/firebase/index.js",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"serve": "firebase emulators:start --only functions"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@donotdev/core": "^0.3.
|
|
57
|
-
"@donotdev/supabase": "^0.3.
|
|
56
|
+
"@donotdev/core": "^0.3.3",
|
|
57
|
+
"@donotdev/supabase": "^0.3.3"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
60
|
"@ai-sdk/anthropic": "^4.0.102",
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `listAuthUsers` (Firebase).
|
|
3
|
+
* @description Runs the real `createBaseFunction`: a non-admin is refused and
|
|
4
|
+
* nothing is listed; an admin gets every page of Admin SDK
|
|
5
|
+
* `listUsers`, mapped to `AuthUserSummary`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
9
|
+
|
|
10
|
+
vi.mock('firebase-functions/v2', () => ({
|
|
11
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), log: vi.fn() },
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
vi.mock('firebase-functions/v2/https', () => {
|
|
15
|
+
class HttpsError extends Error {
|
|
16
|
+
constructor(
|
|
17
|
+
public code: string,
|
|
18
|
+
message: string,
|
|
19
|
+
public details?: unknown
|
|
20
|
+
) {
|
|
21
|
+
super(message);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
// onCall returns the raw handler so the test calls it with a request
|
|
25
|
+
return {
|
|
26
|
+
onCall: (_config: unknown, handler: unknown) => handler,
|
|
27
|
+
HttpsError,
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const listUsers = vi.fn();
|
|
32
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
33
|
+
getFirebaseAdminAuth: () => ({ listUsers }),
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
import { listAuthUsers } from '../listAuthUsers.js';
|
|
37
|
+
|
|
38
|
+
type Callable = (request: unknown) => Promise<unknown>;
|
|
39
|
+
|
|
40
|
+
function call(role?: string) {
|
|
41
|
+
const handler = listAuthUsers() as unknown as Callable;
|
|
42
|
+
return handler({
|
|
43
|
+
auth: { uid: 'caller', token: role ? { role } : {} },
|
|
44
|
+
data: {},
|
|
45
|
+
app: {},
|
|
46
|
+
rawRequest: { headers: {} },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A Firebase UserRecord; `n` makes uids unique. */
|
|
51
|
+
function record(n: number, extra: Record<string, unknown> = {}) {
|
|
52
|
+
return {
|
|
53
|
+
uid: `u${n}`,
|
|
54
|
+
email: `u${n}@example.com`,
|
|
55
|
+
emailVerified: false,
|
|
56
|
+
metadata: {
|
|
57
|
+
creationTime: 'Thu, 01 Jan 2026 00:00:00 GMT',
|
|
58
|
+
lastSignInTime: null,
|
|
59
|
+
},
|
|
60
|
+
...extra,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
describe('listAuthUsers (Firebase)', () => {
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
listUsers.mockReset();
|
|
67
|
+
process.env.DISABLE_RATE_LIMITING = 'true';
|
|
68
|
+
});
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
delete process.env.DISABLE_RATE_LIMITING;
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it.each([undefined, 'user'])(
|
|
74
|
+
'refuses a non-admin caller (role %s)',
|
|
75
|
+
async (role) => {
|
|
76
|
+
// createBaseFunction's role refusal (plain "Access denied" Error) reaches the
|
|
77
|
+
// client through handleError, which classifies it as `internal` today.
|
|
78
|
+
await expect(call(role)).rejects.toThrow();
|
|
79
|
+
expect(listUsers).not.toHaveBeenCalled();
|
|
80
|
+
}
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
it('pages with the page token (1000 per page) until there is none', async () => {
|
|
84
|
+
listUsers
|
|
85
|
+
.mockResolvedValueOnce({ users: [record(1)], pageToken: 'next' })
|
|
86
|
+
.mockResolvedValueOnce({ users: [record(2)] });
|
|
87
|
+
const result = (await call('admin')) as { users: { id: string }[] };
|
|
88
|
+
expect(result.users.map((u) => u.id)).toEqual(['u1', 'u2']);
|
|
89
|
+
expect(listUsers.mock.calls).toEqual([
|
|
90
|
+
[1000, undefined],
|
|
91
|
+
[1000, 'next'],
|
|
92
|
+
]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('maps the record (ISO dates; verified address carries the creation time)', async () => {
|
|
96
|
+
listUsers.mockResolvedValueOnce({
|
|
97
|
+
users: [
|
|
98
|
+
record(1, {
|
|
99
|
+
emailVerified: true,
|
|
100
|
+
displayName: 'Ana',
|
|
101
|
+
metadata: {
|
|
102
|
+
creationTime: 'Thu, 01 Jan 2026 00:00:00 GMT',
|
|
103
|
+
lastSignInTime: 'Sat, 03 Jan 2026 00:00:00 GMT',
|
|
104
|
+
},
|
|
105
|
+
}),
|
|
106
|
+
record(2, { email: undefined }),
|
|
107
|
+
],
|
|
108
|
+
});
|
|
109
|
+
expect(await call('super')).toEqual({
|
|
110
|
+
users: [
|
|
111
|
+
{
|
|
112
|
+
id: 'u1',
|
|
113
|
+
email: 'u1@example.com',
|
|
114
|
+
emailConfirmedAt: '2026-01-01T00:00:00.000Z',
|
|
115
|
+
createdAt: '2026-01-01T00:00:00.000Z',
|
|
116
|
+
lastSignInAt: '2026-01-03T00:00:00.000Z',
|
|
117
|
+
displayName: 'Ana',
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
id: 'u2',
|
|
121
|
+
email: null,
|
|
122
|
+
emailConfirmedAt: null,
|
|
123
|
+
createdAt: '2026-01-01T00:00:00.000Z',
|
|
124
|
+
lastSignInAt: null,
|
|
125
|
+
displayName: null,
|
|
126
|
+
},
|
|
127
|
+
],
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// packages/functions/src/firebase/auth/listAuthUsers.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview List auth users Firebase function
|
|
5
|
+
* @description Admin-only Firebase callable listing every auth account (email,
|
|
6
|
+
* verification, sign-in dates) straight from Firebase Auth (Admin SDK `listUsers`).
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.3.3
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { UserRecord } from 'firebase-admin/auth';
|
|
14
|
+
import type {
|
|
15
|
+
CallableFunction,
|
|
16
|
+
CallableRequest,
|
|
17
|
+
} from 'firebase-functions/v2/https';
|
|
18
|
+
import * as v from 'valibot';
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
AuthUserSummary,
|
|
22
|
+
ListAuthUsersResponse,
|
|
23
|
+
} from '@donotdev/core/server';
|
|
24
|
+
import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
25
|
+
|
|
26
|
+
import { createBaseFunction } from '../baseFunction.js';
|
|
27
|
+
import { AUTH_CONFIG } from '../config/constants.js';
|
|
28
|
+
|
|
29
|
+
const listAuthUsersSchema = v.object({});
|
|
30
|
+
|
|
31
|
+
export type ListAuthUsersRequest = v.InferOutput<typeof listAuthUsersSchema>;
|
|
32
|
+
|
|
33
|
+
/** Page size of Admin SDK `listUsers` (its maximum). */
|
|
34
|
+
const PER_PAGE = 1000;
|
|
35
|
+
|
|
36
|
+
/** Firebase metadata time (UTC string) as ISO 8601; null when absent. */
|
|
37
|
+
function toIso(time: string | null | undefined): string | null {
|
|
38
|
+
return time ? new Date(time).toISOString() : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Map a Firebase user record to an {@link AuthUserSummary}.
|
|
43
|
+
* Firebase records no confirmation time: a verified address carries the account
|
|
44
|
+
* creation time as `emailConfirmedAt`; an unverified one, null.
|
|
45
|
+
*/
|
|
46
|
+
function toAuthUserSummary(user: UserRecord): AuthUserSummary {
|
|
47
|
+
const createdAt = toIso(user.metadata.creationTime)!;
|
|
48
|
+
return {
|
|
49
|
+
id: user.uid,
|
|
50
|
+
email: user.email ?? null,
|
|
51
|
+
emailConfirmedAt: user.emailVerified ? createdAt : null,
|
|
52
|
+
createdAt,
|
|
53
|
+
lastSignInAt: toIso(user.metadata.lastSignInTime),
|
|
54
|
+
displayName: user.displayName ?? null,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Business logic: pages through Admin SDK `listUsers` (1000 per page) until the last page.
|
|
60
|
+
* Base function handles: validation, auth, admin role check, rate limiting, monitoring
|
|
61
|
+
*
|
|
62
|
+
* @version 0.1.0
|
|
63
|
+
* @since 0.3.3
|
|
64
|
+
* @author AMBROISE PARK Consulting
|
|
65
|
+
*/
|
|
66
|
+
async function listAuthUsersLogic(
|
|
67
|
+
_data: ListAuthUsersRequest,
|
|
68
|
+
_context: { uid: string; request: CallableRequest<ListAuthUsersRequest> }
|
|
69
|
+
): Promise<ListAuthUsersResponse> {
|
|
70
|
+
const auth = getFirebaseAdminAuth();
|
|
71
|
+
const users: AuthUserSummary[] = [];
|
|
72
|
+
let pageToken: string | undefined;
|
|
73
|
+
do {
|
|
74
|
+
const page = await auth.listUsers(PER_PAGE, pageToken);
|
|
75
|
+
users.push(...page.users.map(toAuthUserSummary));
|
|
76
|
+
pageToken = page.pageToken;
|
|
77
|
+
} while (pageToken);
|
|
78
|
+
return { users };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Lists every auth user. Admin only: callers without the `admin` (or `super`) role
|
|
83
|
+
* claim are refused (the base function rejects them before the listing runs).
|
|
84
|
+
* Client side: `useAuthUsers()` / `useAuth('listUsers')` from `@donotdev/auth`
|
|
85
|
+
* (the Firebase auth provider calls the callable named `listAuthUsers`).
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* // functions/src/index.ts
|
|
90
|
+
* import { listAuthUsers as frameworkListAuthUsers } from '@donotdev/functions/firebase';
|
|
91
|
+
* export const listAuthUsers = frameworkListAuthUsers();
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @version 0.1.0
|
|
95
|
+
* @since 0.3.3
|
|
96
|
+
* @author AMBROISE PARK Consulting
|
|
97
|
+
*/
|
|
98
|
+
export const listAuthUsers = (
|
|
99
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: same signature as the sibling auth factories (accepts schemas of any output type)
|
|
100
|
+
customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
|
|
101
|
+
): CallableFunction<ListAuthUsersRequest, Promise<ListAuthUsersResponse>> => {
|
|
102
|
+
const schema = customSchema || listAuthUsersSchema;
|
|
103
|
+
return createBaseFunction(
|
|
104
|
+
AUTH_CONFIG,
|
|
105
|
+
schema,
|
|
106
|
+
'list_auth_users',
|
|
107
|
+
listAuthUsersLogic,
|
|
108
|
+
'admin'
|
|
109
|
+
);
|
|
110
|
+
};
|
|
@@ -19,12 +19,68 @@ import * as v from 'valibot';
|
|
|
19
19
|
import type { UserRole } from '@donotdev/core/server';
|
|
20
20
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
21
21
|
|
|
22
|
-
import { DoNotDevError
|
|
22
|
+
import { DoNotDevError } from '../../shared/utils.js';
|
|
23
23
|
import { createBaseFunction } from '../baseFunction.js';
|
|
24
24
|
import { CRUD_CONFIG } from '../config/constants.js';
|
|
25
25
|
|
|
26
26
|
export type DeleteEntityRequest = { id: string };
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Finds Firestore documents that reference a document.
|
|
30
|
+
*
|
|
31
|
+
* Firebase-only: lives here, not in `shared/utils.ts`, which Supabase Edge
|
|
32
|
+
* Functions import (the edge bundler resolves every import of that module).
|
|
33
|
+
*
|
|
34
|
+
* @param collection - Collection of the document to delete
|
|
35
|
+
* @param docId - Id of the document to delete
|
|
36
|
+
* @param referenceMetadata - Incoming references to check (none: no check)
|
|
37
|
+
* @returns One entry per referencing collection field
|
|
38
|
+
*
|
|
39
|
+
* @version 0.2.0
|
|
40
|
+
* @since 0.0.1
|
|
41
|
+
* @author AMBROISE PARK Consulting
|
|
42
|
+
*/
|
|
43
|
+
async function findReferences(
|
|
44
|
+
collection: string,
|
|
45
|
+
docId: string,
|
|
46
|
+
referenceMetadata?: {
|
|
47
|
+
incoming?: Array<{
|
|
48
|
+
sourceCollection: string;
|
|
49
|
+
sourceField: string;
|
|
50
|
+
}>;
|
|
51
|
+
}
|
|
52
|
+
): Promise<Array<{ collection: string; field: string; count: number }>> {
|
|
53
|
+
const references: Array<{
|
|
54
|
+
collection: string;
|
|
55
|
+
field: string;
|
|
56
|
+
count: number;
|
|
57
|
+
}> = [];
|
|
58
|
+
|
|
59
|
+
if (!referenceMetadata?.incoming?.length) {
|
|
60
|
+
return references;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const db = getFirebaseAdminFirestore();
|
|
64
|
+
|
|
65
|
+
for (const ref of referenceMetadata.incoming) {
|
|
66
|
+
const snapshot = await db
|
|
67
|
+
.collection(ref.sourceCollection)
|
|
68
|
+
.where(ref.sourceField, '==', docId)
|
|
69
|
+
.limit(1)
|
|
70
|
+
.get();
|
|
71
|
+
|
|
72
|
+
if (!snapshot.empty) {
|
|
73
|
+
references.push({
|
|
74
|
+
collection: ref.sourceCollection,
|
|
75
|
+
field: ref.sourceField,
|
|
76
|
+
count: snapshot.size,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return references;
|
|
82
|
+
}
|
|
83
|
+
|
|
28
84
|
/**
|
|
29
85
|
* Generic business logic for deleting entities
|
|
30
86
|
* Base function handles: validation, auth, rate limiting, monitoring
|
|
File without changes
|
|
File without changes
|
package/src/shared/utils.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// packages/functions/src/shared/utils.ts
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* @fileoverview Shared utilities for Firebase and
|
|
5
|
-
* @description Common utilities
|
|
4
|
+
* @fileoverview Shared utilities for Firebase, Vercel and Supabase functions
|
|
5
|
+
* @description Common utilities for every function implementation. Provider-neutral:
|
|
6
|
+
* Supabase Edge Functions import this module, and the edge bundler resolves every
|
|
7
|
+
* import in it (even a lazy `import()` that is never called). Firebase-only code
|
|
8
|
+
* lives under `firebase/`.
|
|
6
9
|
*
|
|
7
10
|
* @version 0.1.0
|
|
8
11
|
* @since 0.0.1
|
|
@@ -133,76 +136,3 @@ export function validateCollectionName(name: string): void {
|
|
|
133
136
|
);
|
|
134
137
|
}
|
|
135
138
|
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Verifies Firebase auth token
|
|
139
|
-
*
|
|
140
|
-
* @version 0.1.0
|
|
141
|
-
* @since 0.0.1
|
|
142
|
-
* @author AMBROISE PARK Consulting
|
|
143
|
-
*/
|
|
144
|
-
export async function verifyFirebaseAuthToken(token: string): Promise<string> {
|
|
145
|
-
if (!token) {
|
|
146
|
-
throw new DoNotDevError('Missing authentication token', 'unauthenticated');
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
150
|
-
const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
|
|
151
|
-
try {
|
|
152
|
-
const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
|
|
153
|
-
return decodedToken.uid;
|
|
154
|
-
} catch (error) {
|
|
155
|
-
throw new DoNotDevError('Invalid or expired token', 'unauthenticated');
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Finds references to a document
|
|
161
|
-
*
|
|
162
|
-
* @version 0.1.0
|
|
163
|
-
* @since 0.0.1
|
|
164
|
-
* @author AMBROISE PARK Consulting
|
|
165
|
-
*/
|
|
166
|
-
export async function findReferences(
|
|
167
|
-
collection: string,
|
|
168
|
-
docId: string,
|
|
169
|
-
referenceMetadata?: {
|
|
170
|
-
incoming?: Array<{
|
|
171
|
-
sourceCollection: string;
|
|
172
|
-
sourceField: string;
|
|
173
|
-
}>;
|
|
174
|
-
}
|
|
175
|
-
): Promise<Array<{ collection: string; field: string; count: number }>> {
|
|
176
|
-
const references: Array<{
|
|
177
|
-
collection: string;
|
|
178
|
-
field: string;
|
|
179
|
-
count: number;
|
|
180
|
-
}> = [];
|
|
181
|
-
|
|
182
|
-
if (!referenceMetadata?.incoming?.length) {
|
|
183
|
-
return references;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
187
|
-
const { getFirebaseAdminFirestore } =
|
|
188
|
-
await import('@donotdev/firebase/server');
|
|
189
|
-
const db = getFirebaseAdminFirestore();
|
|
190
|
-
|
|
191
|
-
for (const ref of referenceMetadata.incoming) {
|
|
192
|
-
const snapshot = await db
|
|
193
|
-
.collection(ref.sourceCollection)
|
|
194
|
-
.where(ref.sourceField, '==', docId)
|
|
195
|
-
.limit(1)
|
|
196
|
-
.get();
|
|
197
|
-
|
|
198
|
-
if (!snapshot.empty) {
|
|
199
|
-
references.push({
|
|
200
|
-
collection: ref.sourceCollection,
|
|
201
|
-
field: ref.sourceField,
|
|
202
|
-
count: snapshot.size,
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
return references;
|
|
208
|
-
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// packages/functions/src/supabase/__tests__/firebaseBoundary.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Regression test: the Supabase entry never references Firebase
|
|
5
|
+
* @description A Supabase app does not install `@donotdev/firebase`,
|
|
6
|
+
* `firebase-admin` or `firebase-functions`. The edge bundler (esbuild) resolves
|
|
7
|
+
* every import reachable from `@donotdev/functions/supabase`, a lazy `import()`
|
|
8
|
+
* included, even one that is never called: a single Firebase specifier anywhere
|
|
9
|
+
* in that graph fails every edge function with `Could not resolve
|
|
10
|
+
* "@donotdev/firebase/server"` (shared/utils.ts did this through
|
|
11
|
+
* `verifyFirebaseAuthToken`). Module mocks cannot see an unexecuted `import()`,
|
|
12
|
+
* so this test walks the import graph with esbuild, as the edge bundler does.
|
|
13
|
+
*
|
|
14
|
+
* @version 0.1.0
|
|
15
|
+
* @since 0.3.3
|
|
16
|
+
* @author AMBROISE PARK Consulting
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
|
|
21
|
+
import { build } from 'esbuild';
|
|
22
|
+
import { describe, expect, it } from 'vitest';
|
|
23
|
+
|
|
24
|
+
const FIREBASE = /^(@donotdev\/firebase|firebase-admin|firebase-functions)(\/|$)/;
|
|
25
|
+
|
|
26
|
+
describe('supabase entry without firebase', () => {
|
|
27
|
+
it('reaches no Firebase specifier, static or dynamic', async () => {
|
|
28
|
+
const hits: string[] = [];
|
|
29
|
+
await build({
|
|
30
|
+
entryPoints: [fileURLToPath(new URL('../index.ts', import.meta.url))],
|
|
31
|
+
bundle: true,
|
|
32
|
+
write: false,
|
|
33
|
+
format: 'esm',
|
|
34
|
+
platform: 'neutral',
|
|
35
|
+
logLevel: 'silent',
|
|
36
|
+
plugins: [
|
|
37
|
+
{
|
|
38
|
+
name: 'record-firebase',
|
|
39
|
+
setup(pluginBuild) {
|
|
40
|
+
// Follow the package's own (relative) modules; record Firebase, keep other packages out
|
|
41
|
+
pluginBuild.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
42
|
+
if (FIREBASE.test(args.path)) {
|
|
43
|
+
hits.push(`${args.path} (${args.kind}) from ${args.importer}`);
|
|
44
|
+
}
|
|
45
|
+
return { path: args.path, external: true };
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
});
|
|
51
|
+
expect(hits).toEqual([]);
|
|
52
|
+
}, 60_000);
|
|
53
|
+
});
|