@donotdev/functions 0.2.3 → 0.3.0
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-6NXIK35R.js → chunk-522YXGDA.js} +2 -2
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-7ODXXXES.js.map} +3 -3
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-GDIUOJMD.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/{chunk-UH445BGK.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/{chunk-QXIOO2RL.js → chunk-OKRR7ST5.js} +2 -2
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-NODQAE3F.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +0 -9
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -1
- package/lib/supabase/crud/entityStore.d.ts +54 -14
- package/lib/supabase/crud/update.d.ts +7 -2
- package/lib/supabase/index.d.ts +4 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/package.json +3 -3
- package/src/firebase/auth/removeCustomClaims.ts +31 -1
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +10 -21
- package/src/firebase/crud/bulk.ts +23 -10
- package/src/firebase/crud/create.ts +19 -18
- package/src/firebase/crud/get.ts +3 -12
- package/src/firebase/crud/list.ts +5 -4
- package/src/firebase/crud/update.ts +35 -19
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/crud/bulkCore.ts +110 -81
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/utils.ts +0 -43
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/crud/bulk.ts +47 -0
- package/src/supabase/crud/create.ts +14 -24
- package/src/supabase/crud/entityStore.ts +106 -17
- package/src/supabase/crud/get.ts +3 -12
- package/src/supabase/crud/list.ts +5 -4
- package/src/supabase/crud/update.ts +20 -18
- package/src/supabase/index.ts +7 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/crud/bulk.ts +27 -4
- package/src/vercel/api/crud/create.ts +17 -19
- package/src/vercel/api/crud/get.ts +5 -6
- package/src/vercel/api/crud/list.ts +4 -5
- package/src/vercel/api/crud/update.ts +20 -18
- package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js.map +0 -7
- package/lib/chunks/chunk-F3WBFWPO.js +0 -151
- package/lib/chunks/chunk-G5DRV3DH.js +0 -22
- package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
- package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
- package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
- package/lib/chunks/chunk-W74UL7AY.js +0 -22
- package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -188
- /package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-522YXGDA.js.map} +0 -0
- /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-CVYSXC27.js.map} +0 -0
- /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-OKRR7ST5.js.map} +0 -0
- /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-NODQAE3F.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview Create entity API handler
|
|
3
|
-
* @description Vercel API route for creating entities
|
|
3
|
+
* @description Vercel API route for creating entities.
|
|
4
|
+
*
|
|
5
|
+
* The request carries one schema (W22): the caller sends the one
|
|
6
|
+
* `prepareCreate` (core/schemas crud/create) picks (`draft` or `create`). A create
|
|
7
|
+
* without status gets `DEFAULT_STATUS_VALUE`; the parse output is written, never the
|
|
8
|
+
* raw payload.
|
|
4
9
|
*
|
|
5
10
|
* @version 0.1.0
|
|
6
11
|
* @since 0.0.1
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview Update entity API handler
|
|
3
|
-
* @description Vercel API route for updating entities
|
|
3
|
+
* @description Vercel API route for updating entities.
|
|
4
|
+
*
|
|
5
|
+
* The request carries one schema (W22): the caller sends the one
|
|
6
|
+
* `prepareUpdate` (core/schemas crud/update) picks. The server applies
|
|
7
|
+
* the same status rule to choose what it checks (draft: the merged document; an
|
|
8
|
+
* update entering a visible status, `updateCheck`: the whole merged document;
|
|
9
|
+
* other: the patch with its id) and writes the parse output of the sent keys, never
|
|
10
|
+
* the raw payload.
|
|
4
11
|
*
|
|
5
12
|
* @version 0.1.0
|
|
6
13
|
* @since 0.0.1
|
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{b as B,e as M,f as P,g as z}from"../../chunks/chunk-EZKRLLSQ.js";import{a as Q,c as ee}from"../../chunks/chunk-HLNYUAZH.js";import{a as X,b as d,c as A,d as Z}from"../../chunks/chunk-QXIOO2RL.js";import{A as J,a as m,d as $,r as G,s as k,x as H,y as Y}from"../../chunks/chunk-F3WBFWPO.js";import{C as E,D as I,E as F,I as V,N as K,h as j,l as L,t as y,u as q,x as l}from"../../chunks/chunk-W74UL7AY.js";import{a as O}from"../../chunks/chunk-GDIUOJMD.js";import{b as W,f as U}from"../../chunks/chunk-UH445BGK.js";import{a as D}from"../../chunks/chunk-W6W4L44F.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function se(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=I(F,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(se,"createAIChatRoute");var oe=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function je(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(oe.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await P(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(C=>!t.has(C));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-NODQAE3F.js"),S={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,S),n.status(200).json({success:!0,customClaims:S})}catch(a){throw m(a)}},"handler")}o(je,"createSetCustomClaimsHandler");var _=null;async function T(){if(_)return _;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return _=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),_}o(T,"getSupabaseAdmin");async function N(s){if(B(s)==="supabase"){let e=await T();return{authProvider:Q(e),idempotencyStore:J(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-NODQAE3F.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:z()}}o(N,"resolveBillingBackend");function f(s,t,e,i,n,a){return a!==void 0&&B(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=I(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(b=>b.message).join(", ")}`});let p=r.output,g=await P(c,a),S=`${e}_${g}`,h=U[e]||U.api,x=a==="supabase"?await ee(await T(),S,h):await W(S,h);if(!x.allowed)return n?.audit({type:"rate_limit.exceeded",userId:g,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${x.blockRemainingSeconds} seconds.`,retryAfter:x.blockRemainingSeconds});let w=await i(c,u,p,{uid:g});return w==null&&console.warn(`[${e}] businessLogic returned ${w} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:g,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),w}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let g=ie(p);return u.status(g.status).json({error:g.message})}return u.status(500).json({error:"Internal server error"})}}}o(f,"createVercelBaseFunction");function ie(s){return s instanceof K?{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"}}o(ie,"classifiedToHttp");async function ne(s,t,e,i,n){X(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await N(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ne,"createCheckoutSessionLogic");function ae(s,t){return f("POST",V,"create_checkout_session",(e,i,n,a)=>ne(i,n,a,s,t),void 0,t.backend)}o(ae,"createCheckoutSession");function ce(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>te){i.status(413).json({error:"Payload too large"});return}let u=await ue(e),{authProvider:r,idempotencyStore:p}=await N(t.backend);await Y(u,n,a,d,s,k,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ce,"createStripeWebhook");var te=1*1024*1024;async function ue(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>te)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ue,"getRawBody");var pe=y({userId:E(l(),j(1,"User ID is required"))});function me(s){return{}[s||""]||"free"}o(me,"getTierFromPriceId");async function de(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-NODQAE3F.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:me(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(de,"refreshSubscriptionStatusLogic");var le=o(s=>f("POST",s||pe,"refresh_subscription_status",de),"refreshSubscriptionStatus"),fe=le;var ge=y({userId:l()});async function Se(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-NODQAE3F.js"),u=await Z(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(Se,"cancelSubscriptionLogic");var he=o(()=>f("POST",ge,"cancel_subscription",Se),"cancelSubscription"),ye=he;var Ae=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function we(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-NODQAE3F.js"),S=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!S)throw m(new Error("No active subscription"));let C=await d.subscriptions.retrieve(S),h=await d.subscriptions.update(S,{items:[{id:C.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),w=H(["active","canceled","past_due","trialing","incomplete"],h.status)?h.status:"incomplete";return await k(a,{tier:r.tier,status:w,subscriptionEnd:new Date(h.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:h.cancel_at_period_end,subscriptionId:h.id,customerId:h.customer},{async getUser(b){return p().getUser(b)},async setCustomUserClaims(b,re){await p().setCustomUserClaims(b,re)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(we,"changePlanLogic");var be=o(s=>f("POST",Ae,"change_plan",(t,e,i,n)=>we(t,e,i,n,s)),"changePlan"),Re=be;var ve=y({userId:l(),returnUrl:q(E(l(),L()))});async function Ce(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-NODQAE3F.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Ce,"createCustomerPortalLogic");var xe=o(()=>f("POST",ve,"create_customer_portal",Ce),"createCustomerPortal"),Ee=xe;var v=process.env.FIREBASE_REGION||"europe-west1",Wt={region:v,memory:"1GiB",timeoutSeconds:60},$t={region:v,memory:"512MiB",timeoutSeconds:30},Gt={region:v,memory:"256MiB",timeoutSeconds:20},Ht={region:v,memory:"256MiB",timeoutSeconds:15},Yt={"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"},zt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${v}`)},"validateEnvironment");async function Zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-NODQAE3F.js");return await s()}o(Zt,"initializeFirebaseAdmin");async function Qt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-NODQAE3F.js");return await s()}o(Qt,"getFirebaseAdmin");export{Gt as AUTH_CONFIG,Yt as AVAILABLE_REGIONS,Ht as CRUD_CONFIG,v as FIREBASE_REGION,Wt as FUNCTION_CONFIG,$t as STRIPE_CONFIG,ye as cancelSubscription,Re as changePlan,se as createAIChatRoute,ae as createCheckoutSession,Ee as createCustomerPortal,je as createSetCustomClaimsHandler,ce as createStripeWebhook,Qt as getFirebaseAdmin,Zt as initializeFirebaseAdmin,fe as refreshSubscriptionStatus,k as updateUserSubscription,zt as validateEnvironment};
|
|
21
|
+
import{b as B,e as M,f as P,g as z}from"../../chunks/chunk-TJPJXJEK.js";import{a as Q,c as ee}from"../../chunks/chunk-HLNYUAZH.js";import{a as X,b as d,c as A,d as Z}from"../../chunks/chunk-OKRR7ST5.js";import{A as J,a as m,d as $,r as G,s as k,x as H,y as Y}from"../../chunks/chunk-7ODXXXES.js";import{C as E,D as I,E as F,J as V,S as K,h as j,l as L,t as y,u as q,x as l}from"../../chunks/chunk-ICNQCRLV.js";import{a as O}from"../../chunks/chunk-CVYSXC27.js";import{b as W,f as U}from"../../chunks/chunk-HZM5X5A7.js";import{a as D}from"../../chunks/chunk-W6W4L44F.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function se(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=I(F,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(se,"createAIChatRoute");var oe=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function je(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(oe.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await P(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(C=>!t.has(C));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-24XGDDO3.js"),S={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,S),n.status(200).json({success:!0,customClaims:S})}catch(a){throw m(a)}},"handler")}o(je,"createSetCustomClaimsHandler");var _=null;async function T(){if(_)return _;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return _=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),_}o(T,"getSupabaseAdmin");async function N(s){if(B(s)==="supabase"){let e=await T();return{authProvider:Q(e),idempotencyStore:J(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-24XGDDO3.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:z()}}o(N,"resolveBillingBackend");function f(s,t,e,i,n,a){return a!==void 0&&B(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=I(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(b=>b.message).join(", ")}`});let p=r.output,g=await P(c,a),S=`${e}_${g}`,h=U[e]||U.api,x=a==="supabase"?await ee(await T(),S,h):await W(S,h);if(!x.allowed)return n?.audit({type:"rate_limit.exceeded",userId:g,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${x.blockRemainingSeconds} seconds.`,retryAfter:x.blockRemainingSeconds});let w=await i(c,u,p,{uid:g});return w==null&&console.warn(`[${e}] businessLogic returned ${w} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:g,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),w}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let g=ie(p);return u.status(g.status).json({error:g.message})}return u.status(500).json({error:"Internal server error"})}}}o(f,"createVercelBaseFunction");function ie(s){return s instanceof K?{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"}}o(ie,"classifiedToHttp");async function ne(s,t,e,i,n){X(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await N(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ne,"createCheckoutSessionLogic");function ae(s,t){return f("POST",V,"create_checkout_session",(e,i,n,a)=>ne(i,n,a,s,t),void 0,t.backend)}o(ae,"createCheckoutSession");function ce(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>te){i.status(413).json({error:"Payload too large"});return}let u=await ue(e),{authProvider:r,idempotencyStore:p}=await N(t.backend);await Y(u,n,a,d,s,k,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ce,"createStripeWebhook");var te=1*1024*1024;async function ue(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>te)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ue,"getRawBody");var pe=y({userId:E(l(),j(1,"User ID is required"))});function me(s){return{}[s||""]||"free"}o(me,"getTierFromPriceId");async function de(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-24XGDDO3.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:me(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(de,"refreshSubscriptionStatusLogic");var le=o(s=>f("POST",s||pe,"refresh_subscription_status",de),"refreshSubscriptionStatus"),fe=le;var ge=y({userId:l()});async function Se(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-24XGDDO3.js"),u=await Z(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(Se,"cancelSubscriptionLogic");var he=o(()=>f("POST",ge,"cancel_subscription",Se),"cancelSubscription"),ye=he;var Ae=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function we(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-24XGDDO3.js"),S=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!S)throw m(new Error("No active subscription"));let C=await d.subscriptions.retrieve(S),h=await d.subscriptions.update(S,{items:[{id:C.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),w=H(["active","canceled","past_due","trialing","incomplete"],h.status)?h.status:"incomplete";return await k(a,{tier:r.tier,status:w,subscriptionEnd:new Date(h.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:h.cancel_at_period_end,subscriptionId:h.id,customerId:h.customer},{async getUser(b){return p().getUser(b)},async setCustomUserClaims(b,re){await p().setCustomUserClaims(b,re)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(we,"changePlanLogic");var be=o(s=>f("POST",Ae,"change_plan",(t,e,i,n)=>we(t,e,i,n,s)),"changePlan"),Re=be;var ve=y({userId:l(),returnUrl:q(E(l(),L()))});async function Ce(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-24XGDDO3.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Ce,"createCustomerPortalLogic");var xe=o(()=>f("POST",ve,"create_customer_portal",Ce),"createCustomerPortal"),Ee=xe;var v=process.env.FIREBASE_REGION||"europe-west1",Wt={region:v,memory:"1GiB",timeoutSeconds:60},$t={region:v,memory:"512MiB",timeoutSeconds:30},Gt={region:v,memory:"256MiB",timeoutSeconds:20},Ht={region:v,memory:"256MiB",timeoutSeconds:15},Yt={"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"},zt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${v}`)},"validateEnvironment");async function Zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-24XGDDO3.js");return await s()}o(Zt,"initializeFirebaseAdmin");async function Qt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-24XGDDO3.js");return await s()}o(Qt,"getFirebaseAdmin");export{Gt as AUTH_CONFIG,Yt as AVAILABLE_REGIONS,Ht as CRUD_CONFIG,v as FIREBASE_REGION,Wt as FUNCTION_CONFIG,$t as STRIPE_CONFIG,ye as cancelSubscription,Re as changePlan,se as createAIChatRoute,ae as createCheckoutSession,Ee as createCustomerPortal,je as createSetCustomClaimsHandler,ce as createStripeWebhook,Qt as getFirebaseAdmin,Zt as initializeFirebaseAdmin,fe as refreshSubscriptionStatus,k as updateUserSubscription,zt 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
|
+
"version": "0.3.0",
|
|
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.
|
|
57
|
-
"@donotdev/supabase": "^0.
|
|
56
|
+
"@donotdev/core": "^0.3.0",
|
|
57
|
+
"@donotdev/supabase": "^0.3.0"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
60
|
"@ai-sdk/anthropic": "^4.0.102",
|
|
@@ -20,6 +20,29 @@ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
|
20
20
|
import { createBaseFunction } from '../baseFunction.js';
|
|
21
21
|
import { AUTH_CONFIG } from '../config/constants.js';
|
|
22
22
|
|
|
23
|
+
/** Claim keys users must not remove: access and identity integrity. */
|
|
24
|
+
const BLOCKED_CLAIM_KEYS = new Set([
|
|
25
|
+
'admin',
|
|
26
|
+
'isAdmin',
|
|
27
|
+
'isSuper',
|
|
28
|
+
'isSuperAdmin',
|
|
29
|
+
'role',
|
|
30
|
+
'roles',
|
|
31
|
+
'permissions',
|
|
32
|
+
'superuser',
|
|
33
|
+
'moderator',
|
|
34
|
+
'staff',
|
|
35
|
+
'elevated',
|
|
36
|
+
'plan',
|
|
37
|
+
'tier',
|
|
38
|
+
'subscription',
|
|
39
|
+
'provider',
|
|
40
|
+
'providers',
|
|
41
|
+
'sub',
|
|
42
|
+
'iss',
|
|
43
|
+
'aud',
|
|
44
|
+
]);
|
|
45
|
+
|
|
23
46
|
const removeCustomClaimsSchema = v.object({
|
|
24
47
|
claimsToRemove: v.pipe(
|
|
25
48
|
v.array(v.string()),
|
|
@@ -53,6 +76,13 @@ async function removeCustomClaimsLogic(
|
|
|
53
76
|
) {
|
|
54
77
|
const { claimsToRemove } = data;
|
|
55
78
|
|
|
79
|
+
const blocked = claimsToRemove.filter((key) => BLOCKED_CLAIM_KEYS.has(key));
|
|
80
|
+
if (blocked.length > 0) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`Protected claims cannot be removed: ${blocked.join(', ')}`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
56
86
|
const user = await getFirebaseAdminAuth().getUser(context.uid);
|
|
57
87
|
const currentClaims = user.customClaims || {};
|
|
58
88
|
|
|
@@ -68,7 +98,7 @@ async function removeCustomClaimsLogic(
|
|
|
68
98
|
}
|
|
69
99
|
|
|
70
100
|
/**
|
|
71
|
-
* Removes user's custom claims
|
|
101
|
+
* Removes user's custom claims, except protected access and identity claims.
|
|
72
102
|
* Base function handles all common concerns automatically
|
|
73
103
|
*
|
|
74
104
|
* @version 0.1.0
|
|
@@ -51,8 +51,19 @@ const tx = {
|
|
|
51
51
|
}),
|
|
52
52
|
};
|
|
53
53
|
|
|
54
|
+
/** Stored rows read before validation (status rule); every id exists unless listed in `missingIds`. */
|
|
55
|
+
let storedRows: Record<string, Record<string, unknown>> = {};
|
|
56
|
+
const missingIds = new Set<string>();
|
|
57
|
+
|
|
54
58
|
const mockDb = {
|
|
55
59
|
collection: vi.fn(() => mockCollection()),
|
|
60
|
+
getAll: vi.fn(async (...refs: MockRef[]) =>
|
|
61
|
+
refs.map((ref) => ({
|
|
62
|
+
id: ref.id,
|
|
63
|
+
exists: !missingIds.has(ref.id),
|
|
64
|
+
data: () => storedRows[ref.id] ?? { status: 'available' },
|
|
65
|
+
}))
|
|
66
|
+
),
|
|
56
67
|
runTransaction: vi.fn(async (fn: (t: typeof tx) => Promise<any>) => {
|
|
57
68
|
runTransactionInvocations += 1;
|
|
58
69
|
if (simulateRollback) {
|
|
@@ -74,11 +85,12 @@ vi.mock('@donotdev/firebase/server', () => ({
|
|
|
74
85
|
}));
|
|
75
86
|
|
|
76
87
|
// Import AFTER mocks are in place.
|
|
77
|
-
import { BulkCollisionError } from '@donotdev/core/server';
|
|
88
|
+
import { BulkCollisionError, createSchemas } from '@donotdev/core/server';
|
|
78
89
|
|
|
79
90
|
import { bulkEntityLogicFactory } from '../bulk';
|
|
80
91
|
|
|
81
92
|
import * as v from 'valibot';
|
|
93
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
82
94
|
|
|
83
95
|
// ---------------------------------------------------------------------------
|
|
84
96
|
// Fixtures
|
|
@@ -110,6 +122,8 @@ function resetState() {
|
|
|
110
122
|
mintedIdCounter = 0;
|
|
111
123
|
runTransactionInvocations = 0;
|
|
112
124
|
simulateRollback = null;
|
|
125
|
+
storedRows = {};
|
|
126
|
+
missingIds.clear();
|
|
113
127
|
tx.set.mockClear();
|
|
114
128
|
tx.update.mockClear();
|
|
115
129
|
tx.delete.mockClear();
|
|
@@ -330,3 +344,38 @@ describe('bulkEntityLogicFactory', () => {
|
|
|
330
344
|
expect(runTransactionInvocations).toBe(1);
|
|
331
345
|
});
|
|
332
346
|
});
|
|
347
|
+
|
|
348
|
+
describe('bulkEntityLogicFactory — status rule on the stored row', () => {
|
|
349
|
+
const schemas = createSchemas(contactEntity);
|
|
350
|
+
const logic = () =>
|
|
351
|
+
bulkEntityLogicFactory(COLLECTION, schemas.create as never, schemas.draft as never, schemas.update as never, access);
|
|
352
|
+
|
|
353
|
+
beforeEach(() => {
|
|
354
|
+
resetState();
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
it('edit of a stored draft without a status is a draft write (empty required field accepted)', async () => {
|
|
358
|
+
storedRows = { c1: { name: 'Ana', status: 'draft' } };
|
|
359
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { name: null } }] }, ctx)).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
360
|
+
// Same patch on a published row: rejected
|
|
361
|
+
storedRows = { c1: { name: 'Ana', status: 'available' } };
|
|
362
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { name: null } }] }, ctx)).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
it('publishing a draft through a status-only patch checks the whole stored row', async () => {
|
|
366
|
+
storedRows = { c1: { status: 'draft' } };
|
|
367
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { status: 'available' } }] }, ctx)).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
368
|
+
expect(runTransactionInvocations).toBe(0);
|
|
369
|
+
storedRows = { c1: { name: 'Ana', status: 'draft' } };
|
|
370
|
+
await logic()({ updates: [{ id: 'c1', patch: { status: 'available' } }] }, ctx);
|
|
371
|
+
const updateCall = txCalls.find((c) => c.op === 'update') as { data: Record<string, unknown> };
|
|
372
|
+
expect(updateCall.data.status).toBe('available');
|
|
373
|
+
expect(updateCall.data).not.toHaveProperty('name');
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it('rejects an update of a missing row before opening the transaction', async () => {
|
|
377
|
+
missingIds.add('gone');
|
|
378
|
+
await expect(logic()({ updates: [{ id: 'gone', patch: { name: 'X' } }] }, ctx)).rejects.toMatchObject({ code: 'not-found' });
|
|
379
|
+
expect(runTransactionInvocations).toBe(0);
|
|
380
|
+
});
|
|
381
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// packages/functions/src/firebase/crud/__tests__/create.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Unit tests for the Firestore create logic: status rule
|
|
5
|
+
* (`DEFAULT_STATUS_VALUE`, `writeSchemaFor`) and parse-output writes.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi, beforeEach } 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
|
+
/** Last document added to the mock Firestore. */
|
|
15
|
+
let added: Record<string, unknown> = {};
|
|
16
|
+
const add = vi.fn(async (data: Record<string, unknown>) => {
|
|
17
|
+
added = data;
|
|
18
|
+
return { get: async () => ({ id: 'n1', data: () => added }) };
|
|
19
|
+
});
|
|
20
|
+
const mockDb = { collection: vi.fn(() => ({ add })) };
|
|
21
|
+
|
|
22
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
23
|
+
getFirebaseAdminFirestore: () => mockDb,
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
// Import AFTER mocks are in place.
|
|
27
|
+
import { createSchemas } from '@donotdev/core/server';
|
|
28
|
+
|
|
29
|
+
import { createEntityLogicFactory } from '../create';
|
|
30
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
31
|
+
|
|
32
|
+
const schemas = createSchemas(contactEntity);
|
|
33
|
+
|
|
34
|
+
const logic = createEntityLogicFactory('contacts', schemas.create as never, schemas.draft as never);
|
|
35
|
+
const context = { uid: 'u1', userRole: 'user', request: {} } as never;
|
|
36
|
+
const run = (payload: Record<string, unknown>) => logic({ payload }, context);
|
|
37
|
+
|
|
38
|
+
describe('createEntity status rule and writes', () => {
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
add.mockClear();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('a create without status is published (DEFAULT_STATUS_VALUE) and validated as a create', async () => {
|
|
44
|
+
await expect(run({ phone: '+33 6 12 34 56 78' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
45
|
+
await run({ name: 'Ana' });
|
|
46
|
+
expect(added.status).toBe('available');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('a draft is validated with the draft schema: required may be empty, filled values keep their format', async () => {
|
|
50
|
+
await run({ status: 'draft', name: null });
|
|
51
|
+
expect(added.status).toBe('draft');
|
|
52
|
+
await expect(run({ status: 'draft', phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('writes the parse output: unknown, hidden and generated keys never reach the DB', async () => {
|
|
56
|
+
await run({ name: 'Ana', secret: 's', role: 'admin', createdById: 'evil', id: 'x' });
|
|
57
|
+
expect(added).not.toHaveProperty('secret');
|
|
58
|
+
expect(added).not.toHaveProperty('role');
|
|
59
|
+
expect(added).not.toHaveProperty('id');
|
|
60
|
+
// createdById comes from the server metadata only
|
|
61
|
+
expect(added.createdById).toBe('u1');
|
|
62
|
+
expect(added.name).toBe('Ana');
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// packages/functions/src/firebase/crud/__tests__/update.test.ts
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
4
|
+
|
|
5
|
+
vi.mock('firebase-functions/v2', () => ({
|
|
6
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), log: vi.fn() },
|
|
7
|
+
}));
|
|
8
|
+
|
|
9
|
+
/** Stored document of the mock Firestore (one collection, one document). */
|
|
10
|
+
let stored: Record<string, unknown> = {};
|
|
11
|
+
const update = vi.fn(async (data: Record<string, unknown>) => {
|
|
12
|
+
stored = { ...stored, ...data };
|
|
13
|
+
});
|
|
14
|
+
const docRef = {
|
|
15
|
+
get: vi.fn(async () => ({ exists: true, id: 'c1', data: () => stored })),
|
|
16
|
+
update,
|
|
17
|
+
};
|
|
18
|
+
const mockDb = { collection: vi.fn(() => ({ doc: () => docRef })) };
|
|
19
|
+
|
|
20
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
21
|
+
getFirebaseAdminFirestore: () => mockDb,
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
// Import AFTER mocks are in place.
|
|
25
|
+
import { createSchemas } from '@donotdev/core/server';
|
|
26
|
+
|
|
27
|
+
import { updateEntityLogicFactory } from '../update';
|
|
28
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
29
|
+
|
|
30
|
+
const schemas = createSchemas(contactEntity);
|
|
31
|
+
|
|
32
|
+
const logic = updateEntityLogicFactory('contacts', schemas.update as never, schemas.draft as never);
|
|
33
|
+
const context = { uid: 'u1', userRole: 'user', request: {} } as never;
|
|
34
|
+
const run = (payload: Record<string, unknown>) => logic({ id: 'c1', payload }, context);
|
|
35
|
+
|
|
36
|
+
describe('updateEntity validation (same rules as the client)', () => {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
update.mockClear();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('non-draft: checks what the update writes against the update schema', async () => {
|
|
42
|
+
// Legacy document with a required field empty: an update of another field passes
|
|
43
|
+
stored = { name: null, status: 'available' };
|
|
44
|
+
await expect(run({ phone: '+33 6 12 34 56 78' })).resolves.toBeDefined();
|
|
45
|
+
await expect(run({ name: null })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
46
|
+
await expect(run({ name: '' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
47
|
+
await expect(run({ phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('draft: required fields may be empty, filled ones keep their format', async () => {
|
|
51
|
+
stored = { name: 'Ana', status: 'draft' };
|
|
52
|
+
await expect(run({ name: null })).resolves.toBeDefined();
|
|
53
|
+
await expect(run({ phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
54
|
+
expect(update).toHaveBeenCalledTimes(1);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('writes the parse output of the sent keys, never the raw payload', async () => {
|
|
58
|
+
stored = { name: 'Ana', status: 'available' };
|
|
59
|
+
await run({ phone: '+33 6 12 34 56 78', createdById: 'evil', role: 'admin' });
|
|
60
|
+
const written = update.mock.calls[0]![0];
|
|
61
|
+
expect(written).toMatchObject({ phone: '+33 6 12 34 56 78' });
|
|
62
|
+
expect(written).not.toHaveProperty('role');
|
|
63
|
+
expect(written.createdById).toBeUndefined();
|
|
64
|
+
expect(written).not.toHaveProperty('name');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('status rule: the sent status wins over the stored one (writeSchemaFor)', async () => {
|
|
68
|
+
// Publishing a draft: the patch is checked against the update schema
|
|
69
|
+
stored = { name: null, status: 'draft' };
|
|
70
|
+
await expect(run({ status: 'available', name: '' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
71
|
+
// Back to draft from a published document: the merged document against the draft schema
|
|
72
|
+
stored = { name: 'Ana', status: 'available' };
|
|
73
|
+
await expect(run({ status: 'draft', name: null })).resolves.toBeDefined();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('publishing a draft through a status-only patch checks the whole merged document', async () => {
|
|
77
|
+
update.mockClear();
|
|
78
|
+
// Stored null required field
|
|
79
|
+
stored = { name: null, status: 'draft' };
|
|
80
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
81
|
+
// Required key absent from the stored document (counted as null)
|
|
82
|
+
stored = { status: 'draft' };
|
|
83
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
84
|
+
expect(update).not.toHaveBeenCalled();
|
|
85
|
+
// Filled in: published; only the sent keys are written
|
|
86
|
+
stored = { name: 'Ana', status: 'draft' };
|
|
87
|
+
await expect(run({ status: 'available' })).resolves.toBeDefined();
|
|
88
|
+
const written = update.mock.calls[0]![0];
|
|
89
|
+
expect(written.status).toBe('available');
|
|
90
|
+
expect(written).not.toHaveProperty('name');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('soft-deleting a draft stays relaxed (deleted is hidden)', async () => {
|
|
94
|
+
stored = { name: null, status: 'draft' };
|
|
95
|
+
await expect(run({ status: 'deleted' })).resolves.toBeDefined();
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -13,11 +13,10 @@
|
|
|
13
13
|
import type { CallableRequest } from 'firebase-functions/v2/https';
|
|
14
14
|
import * as v from 'valibot';
|
|
15
15
|
|
|
16
|
-
import {
|
|
17
|
-
import type { UserRole } from '@donotdev/core/server';
|
|
16
|
+
import { isFieldVisible, VISIBILITY } from '@donotdev/core/server';
|
|
17
|
+
import type { UserRole, Visibility } from '@donotdev/core/server';
|
|
18
18
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
19
19
|
|
|
20
|
-
import { isFieldVisible } from '../../shared/schema.js';
|
|
21
20
|
import { DoNotDevError } from '../../shared/utils.js';
|
|
22
21
|
import { createBaseFunction } from '../baseFunction.js';
|
|
23
22
|
import { CRUD_CONFIG } from '../config/constants.js';
|
|
@@ -92,37 +91,28 @@ function getFieldVisibilityFromSchema(
|
|
|
92
91
|
return 'visibility' in field ? field.visibility : undefined;
|
|
93
92
|
}
|
|
94
93
|
|
|
95
|
-
|
|
96
|
-
type FieldVisibility = NonNullable<Parameters<typeof isFieldVisible>[1]>;
|
|
94
|
+
const FIELD_VISIBILITY_LEVELS: readonly string[] = Object.values(VISIBILITY);
|
|
97
95
|
|
|
98
|
-
|
|
99
|
-
'guest',
|
|
100
|
-
'user',
|
|
101
|
-
'admin',
|
|
102
|
-
'technical',
|
|
103
|
-
'hidden',
|
|
104
|
-
'owner',
|
|
105
|
-
] satisfies readonly FieldVisibility[];
|
|
106
|
-
|
|
107
|
-
function isFieldVisibility(value: unknown): value is FieldVisibility {
|
|
96
|
+
function isFieldVisibility(value: unknown): value is Visibility {
|
|
108
97
|
return typeof value === 'string' && FIELD_VISIBILITY_LEVELS.includes(value);
|
|
109
98
|
}
|
|
110
99
|
|
|
111
100
|
/**
|
|
112
|
-
* Checks if user can access a field for aggregation
|
|
101
|
+
* Checks if user can access a field for aggregation (core visibility rule,
|
|
102
|
+
* `isFieldVisible`; `owner` fields need a document and are denied here)
|
|
113
103
|
*/
|
|
114
104
|
function canAggregateField(
|
|
115
105
|
fieldName: string,
|
|
116
106
|
schema: unknown,
|
|
117
|
-
|
|
107
|
+
userRole: UserRole
|
|
118
108
|
): boolean {
|
|
119
109
|
// '*' is always allowed (count all)
|
|
120
110
|
if (fieldName === '*') return true;
|
|
121
111
|
|
|
122
112
|
const visibility = getFieldVisibilityFromSchema(schema, fieldName);
|
|
123
|
-
// Unknown visibility levels are denied
|
|
113
|
+
// Unknown visibility levels are denied
|
|
124
114
|
if (visibility !== undefined && !isFieldVisibility(visibility)) return false;
|
|
125
|
-
return isFieldVisible(
|
|
115
|
+
return isFieldVisible(visibility, userRole);
|
|
126
116
|
}
|
|
127
117
|
|
|
128
118
|
/**
|
|
@@ -255,7 +245,6 @@ function aggregateEntitiesLogicFactory(
|
|
|
255
245
|
) {
|
|
256
246
|
const db = getFirebaseAdminFirestore();
|
|
257
247
|
const { userRole } = context;
|
|
258
|
-
const isAdmin = hasRoleAccess(userRole, 'admin');
|
|
259
248
|
|
|
260
249
|
// Validate that user can access the fields being aggregated
|
|
261
250
|
const allFields = new Set<string>();
|
|
@@ -267,7 +256,7 @@ function aggregateEntitiesLogicFactory(
|
|
|
267
256
|
});
|
|
268
257
|
|
|
269
258
|
for (const field of allFields) {
|
|
270
|
-
if (!canAggregateField(field, documentSchema,
|
|
259
|
+
if (!canAggregateField(field, documentSchema, userRole)) {
|
|
271
260
|
throw new DoNotDevError(
|
|
272
261
|
`Access denied: cannot aggregate field '${field}'`,
|
|
273
262
|
'permission-denied'
|
|
@@ -21,7 +21,7 @@ import type {
|
|
|
21
21
|
} from 'firebase-functions/v2/https';
|
|
22
22
|
import type * as v from 'valibot';
|
|
23
23
|
|
|
24
|
-
import { BulkRequestSchema
|
|
24
|
+
import { BulkRequestSchema } from '@donotdev/core/server';
|
|
25
25
|
import type {
|
|
26
26
|
BulkRequest,
|
|
27
27
|
BulkResponse,
|
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
createMetadata,
|
|
34
34
|
executeBulk,
|
|
35
35
|
prepareForFirestore,
|
|
36
|
+
transformFirestoreData,
|
|
36
37
|
updateMetadata,
|
|
37
38
|
} from '../../shared/index.js';
|
|
38
39
|
import { createBaseFunction } from '../baseFunction.js';
|
|
@@ -124,16 +125,28 @@ export function bulkEntityLogicFactory(
|
|
|
124
125
|
userRole,
|
|
125
126
|
// Mint ids via Firestore's `doc()` — gives us stable ids across retry
|
|
126
127
|
// of the transaction callback (Firestore may run it more than once).
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
130
|
-
(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
128
|
+
// Stored rows of the updated ids: their status decides each patch's schema.
|
|
129
|
+
readStored: async (ids) => {
|
|
130
|
+
const snapshots = await getFirebaseAdminFirestore().getAll(
|
|
131
|
+
...ids.map((id) => col().doc(id))
|
|
132
|
+
);
|
|
133
|
+
const rows = new Map<string, Record<string, unknown>>();
|
|
134
|
+
for (const snapshot of snapshots) {
|
|
135
|
+
if (snapshot.exists) {
|
|
136
|
+
rows.set(
|
|
137
|
+
snapshot.id,
|
|
138
|
+
transformFirestoreData(snapshot.data() as Record<string, unknown>)
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return rows;
|
|
136
143
|
},
|
|
144
|
+
mintInsertId: () => col().doc().id,
|
|
145
|
+
// The row carries its status: the CRUD create rules set it (prepareCreate).
|
|
146
|
+
stampInsertMetadata: (row, creatorUid) => ({
|
|
147
|
+
...prepareForFirestore(row),
|
|
148
|
+
...createMetadata(creatorUid),
|
|
149
|
+
}),
|
|
137
150
|
stampUpdateMetadata: (patch, editorUid) => ({
|
|
138
151
|
...prepareForFirestore(patch),
|
|
139
152
|
...updateMetadata(editorUid),
|
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
} from 'firebase-functions/v2/https';
|
|
18
18
|
import * as v from 'valibot';
|
|
19
19
|
|
|
20
|
+
import { prepareCreate } from '@donotdev/core/server';
|
|
20
21
|
import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
|
|
21
22
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
22
23
|
|
|
@@ -25,7 +26,8 @@ import {
|
|
|
25
26
|
transformFirestoreData,
|
|
26
27
|
} from '../../shared/index.js';
|
|
27
28
|
import { createMetadata } from '../../shared/index.js';
|
|
28
|
-
import {
|
|
29
|
+
import { writtenOf } from '../../shared/crud/written.js';
|
|
30
|
+
import { DoNotDevError } from '../../shared/utils.js';
|
|
29
31
|
import { createBaseFunction } from '../baseFunction.js';
|
|
30
32
|
import { CRUD_CONFIG } from '../config/constants.js';
|
|
31
33
|
|
|
@@ -147,11 +149,19 @@ async function checkUniqueKeys(
|
|
|
147
149
|
* Generic business logic for creating entities
|
|
148
150
|
* Base function handles: validation, auth, rate limiting, monitoring
|
|
149
151
|
*
|
|
150
|
-
*
|
|
152
|
+
* Status rule: a create without status gets `DEFAULT_STATUS_VALUE`; the CRUD rules
|
|
153
|
+
* picks the draft or create schema; the parse output is written, never the raw payload.
|
|
154
|
+
*
|
|
155
|
+
* @param collection - The Firestore collection name
|
|
156
|
+
* @param createDocumentSchema - The create schema (`createSchemas(entity).create`)
|
|
157
|
+
* @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`)
|
|
158
|
+
* @returns The callable logic (exported for unit tests)
|
|
159
|
+
*
|
|
160
|
+
* @version 0.2.0
|
|
151
161
|
* @since 0.0.1
|
|
152
162
|
* @author AMBROISE PARK Consulting
|
|
153
163
|
*/
|
|
154
|
-
function createEntityLogicFactory(
|
|
164
|
+
export function createEntityLogicFactory(
|
|
155
165
|
collection: string,
|
|
156
166
|
createDocumentSchema: v.GenericSchema,
|
|
157
167
|
draftDocumentSchema: v.GenericSchema
|
|
@@ -217,9 +227,9 @@ function createEntityLogicFactory(
|
|
|
217
227
|
}
|
|
218
228
|
}
|
|
219
229
|
|
|
220
|
-
//
|
|
221
|
-
const
|
|
222
|
-
const isDraft =
|
|
230
|
+
// CRUD create rules (core/schemas crud/create), as on the client.
|
|
231
|
+
const schemas = { create: createDocumentSchema, draft: draftDocumentSchema };
|
|
232
|
+
const isDraft = prepareCreate(schemas, payload).schemaKey === 'draft';
|
|
223
233
|
|
|
224
234
|
// Check unique keys if schema has metadata with uniqueKeys
|
|
225
235
|
// This handles findOrCreate behavior and duplicate prevention
|
|
@@ -256,21 +266,12 @@ function createEntityLogicFactory(
|
|
|
256
266
|
? normalizePayloadForUniqueKeys(payload, uniqueKeys)
|
|
257
267
|
: payload;
|
|
258
268
|
|
|
259
|
-
//
|
|
260
|
-
|
|
261
|
-
// nullish/optional (so `null` empties don't fail strict `schemas.create`).
|
|
262
|
-
const payloadForValidation = { ...normalizedPayload, status };
|
|
263
|
-
if (isDraft) {
|
|
264
|
-
validateDocument(payloadForValidation, draftDocumentSchema);
|
|
265
|
-
} else {
|
|
266
|
-
validateDocument(payloadForValidation, createDocumentSchema);
|
|
267
|
-
}
|
|
269
|
+
// Store the rules' `written` (resulting status included), never the raw payload.
|
|
270
|
+
const written = writtenOf(prepareCreate(schemas, normalizedPayload), collection, 'create');
|
|
268
271
|
|
|
269
272
|
// Prepare the document for Firestore and add metadata
|
|
270
|
-
// Always ensure status is set
|
|
271
273
|
const documentData = {
|
|
272
|
-
...prepareForFirestore(
|
|
273
|
-
status, // Ensure status is always present
|
|
274
|
+
...prepareForFirestore(written),
|
|
274
275
|
...createMetadata(uid),
|
|
275
276
|
};
|
|
276
277
|
|