"use strict";exports.id=5858,exports.ids=[5858],exports.modules={35858:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{H1:()=>m,Mh:()=>l,NZ:()=>o,TJ:()=>n,UO:()=>k,er:()=>p,nT:()=>r,uS:()=>q});var e=c(77598),f=c(34255),g=c(4160),h=c(76031),i=c(95678),j=a([f,g]);function k(a){return a?(0,f.getDb)().prepare(`SELECT id, title, kind, content, source_md, created_at
         FROM artifacts
        WHERE space_id = ?
        ORDER BY created_at ASC, id ASC`).all(String(a)).map(a=>({id:a.id,title:a.title||"Untitled",kind:a.kind||"text",content:a.content||a.source_md||"",created_at:a.created_at||null})):[]}async function l(a,b={},c){let{expires_in_days:d=7,max_views:j=50,require_email_otp:k}=b;if(null!=d&&d>90)throw{status:400,error:"expires_in_days_exceeds_maximum",max:90};let m=(0,f.getDb)();if(!m.prepare("SELECT id FROM dashboard_spaces WHERE id = ?").get(String(a)))throw{status:404,error:"space_not_found"};let n=k;if(null==n){let a=m.prepare("SELECT require_share_email_verification FROM organizations WHERE id = ?").get(c.org_id);n=a?.require_share_email_verification===1}let o=(0,e.randomBytes)(32).toString("base64url"),p=await (0,h.Oj)(),q=(0,h.L5)(o,p),r=null;if(null!=d&&d>0){let a=new Date;a.setDate(a.getDate()+d),r=a.toISOString()}let s=(0,f.newId)("spaceshare"),t=c.org_id;m.prepare(`INSERT INTO space_share_links
       (id, space_id, token, token_hmac, created_by, org_id,
        expires_at, max_views, access_count, revoked, require_email_otp, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?)`).run(s,String(a),o,q,c.user_id,t,r,j??null,+!!n,(0,f.nowIso)());try{(0,g.appendComplianceAudit)({user_id:c.user_id,org_id:t,action:g.ComplianceActions.SPACE_SHARE_LINK_CREATED,action_target_id:String(a),action_target_type:"space",status:"success",summary:`Share link created for space ${a}`,meta:{share_link_id:s,expires_at:r,max_views:j??null,require_email_otp:n}})}catch(a){console.error("[space-acl] audit (create) failed:",a.message)}return{id:s,token:o,url:(0,i._)(`/share/space/${o}`),expires_at:r,max_views:j??null,require_email_otp:n}}function m(a,b=null){let c=(0,f.getDb)();return b?c.prepare(`SELECT id, space_id, token, created_by, org_id, expires_at, max_views,
                access_count, revoked, require_email_otp, created_at
           FROM space_share_links
          WHERE space_id = ? AND org_id = ? AND revoked = 0
          ORDER BY created_at DESC`).all(String(a),b):c.prepare(`SELECT id, space_id, token, created_by, org_id, expires_at, max_views,
              access_count, revoked, require_email_otp, created_at
         FROM space_share_links
        WHERE space_id = ? AND revoked = 0
        ORDER BY created_at DESC`).all(String(a))}async function n(a){if(!a)return{ok:!1,status:404,reason:"not_found"};let b=await (0,h.Oj)(),c=(0,h.L5)(a,b),d=(0,f.getDb)(),e=d.prepare("SELECT * FROM space_share_links WHERE token_hmac = ?").get(c);if(!e||!(0,h.lr)(c,e.token_hmac))return{ok:!1,status:404,reason:"not_found"};if(1===e.revoked)return{ok:!1,status:410,reason:"revoked"};if(e.expires_at&&new Date(e.expires_at)<new Date)return{ok:!1,status:410,reason:"expired"};if(null!=e.max_views&&e.access_count>=e.max_views)return d.prepare("UPDATE space_share_links SET revoked = 1 WHERE id = ?").run(e.id),{ok:!1,status:410,reason:"view_cap_reached"};let g=d.prepare("SELECT * FROM dashboard_spaces WHERE id = ?").get(e.space_id);return g?{ok:!0,link:e,space:g}:{ok:!1,status:404,reason:"not_found"}}function o(a,b,c=null){let d=(0,f.getDb)(),e=d.prepare(`UPDATE space_share_links
        SET access_count = access_count + 1,
            revoked = CASE
                        WHEN max_views IS NOT NULL AND access_count + 1 >= max_views THEN 1
                        ELSE revoked
                      END
      WHERE id = ?
        AND revoked = 0
        AND (max_views IS NULL OR access_count < max_views)`).run(a);if(0===e.changes)return;let h=d.prepare("SELECT * FROM space_share_links WHERE id = ?").get(a);if(h)try{(0,g.appendComplianceAudit)({user_id:null,org_id:h.org_id,action:g.ComplianceActions.SPACE_SHARE_LINK_ACCESSED,action_target_id:h.space_id,action_target_type:"space",status:"success",summary:`Space share link ${a} accessed${c?` by ${c}`:""}`,meta:{share_link_id:a,access_count:h.access_count,auto_revoked:1===h.revoked,recipient_email:c},ip:(0,g.N)(b),user_agent:(0,g.S)(b)})}catch(a){console.error("[space-acl] audit (access) failed:",a.message)}}function p(a,b){let c=(0,f.getDb)(),d=c.prepare("SELECT * FROM space_share_links WHERE id = ?").get(a);if(!d)throw{status:404,error:"share_link_not_found"};c.prepare("UPDATE space_share_links SET revoked = 1 WHERE id = ?").run(a);try{(0,g.appendComplianceAudit)({user_id:b?.user_id||null,org_id:d.org_id||b?.org_id||"personal-org",action:g.ComplianceActions.SPACE_SHARE_LINK_REVOKED,action_target_id:d.space_id,action_target_type:"space",status:"success",summary:`Space share link ${a} revoked`,meta:{share_link_id:a,space_id:d.space_id}})}catch(a){console.error("[space-acl] audit (revoke) failed:",a.message)}return{ok:!0}}async function q(a,b){let d=(0,f.getDb)(),h=d.prepare("SELECT * FROM space_share_links WHERE id = ?").get(a);if(!h||1===h.revoked)return{ok:!1,error:"link_invalid"};let i=String(Math.floor(1e5+(0,e.randomBytes)(3).readUIntBE(0,3)%9e5)).padStart(6,"0"),j=(0,e.randomBytes)(16).toString("hex"),k=(0,e.createHash)("sha256").update(j+":"+i).digest("hex"),l=`${j}:${k}`,m=new Date(Date.now()+6e5).toISOString(),n=(0,f.newId)("otp");d.prepare(`INSERT INTO space_share_link_otps (id, share_link_id, email, code_hash, expires_at, attempts, created_at)
     VALUES (?, ?, ?, ?, ?, 0, ?)`).run(n,a,b,l,m,(0,f.nowIso)());try{(0,g.appendComplianceAudit)({user_id:null,org_id:h.org_id,action:g.ComplianceActions.SHARE_OTP_SENT,action_target_id:h.space_id,action_target_type:"space",status:"success",summary:`Space share OTP sent to ${b} for link ${a}`,meta:{share_link_id:a,otp_id:n}})}catch{}try{let{executeRegistryTool:a}=await Promise.resolve().then(c.bind(c,40718)),d=await a("email_send",{to:b,subject:"Your madarX shared space verification code",html:`<p>You requested access to a shared space on madarX.</p>
<p><strong>Your verification code is: ${i}</strong></p>
<p>This code expires in 10 minutes. Do not share it with anyone.</p>`},{agent_id:null,owner_trusted:!0});if(!d||!1===d.ok)return{ok:!0,expires_in:600,email_sent:!1,email_error:d?.status||"unknown"}}catch(a){return{ok:!0,expires_in:600,email_sent:!1,email_error:a.message}}return{ok:!0,expires_in:600,email_sent:!0}}function r(a,b,c){let d=(0,f.getDb)(),h=d.prepare(`SELECT * FROM space_share_link_otps
        WHERE share_link_id = ? AND email = ? AND expires_at > ? AND verified_at IS NULL
        ORDER BY created_at DESC LIMIT 1`).get(a,b,(0,f.nowIso)());if(!h)return{ok:!1,reason:"not_found_or_expired"};if(h.attempts>=5){try{(0,g.appendComplianceAudit)({user_id:null,org_id:"personal-org",action:g.ComplianceActions.SHARE_OTP_LOCKED_OUT,action_target_id:a,action_target_type:"space",status:"denied",summary:`Space share OTP lockout for ${b} on link ${a}`,meta:{share_link_id:a,attempts:h.attempts}})}catch{}return{ok:!1,reason:"lockout"}}let[i,j]=h.code_hash.split(":"),k=(0,e.createHash)("sha256").update(i+":"+c).digest("hex"),l=Buffer.from(k,"hex"),m=Buffer.from(j,"hex");if(!(l.length===m.length&&(0,e.timingSafeEqual)(l,m))){d.prepare("UPDATE space_share_link_otps SET attempts = attempts + 1 WHERE id = ?").run(h.id);try{(0,g.appendComplianceAudit)({user_id:null,org_id:"personal-org",action:g.ComplianceActions.SHARE_OTP_FAILED,action_target_id:a,action_target_type:"space",status:"denied",summary:`Space share OTP failed for ${b} on link ${a}`,meta:{share_link_id:a,attempts:h.attempts+1}})}catch{}return{ok:!1,reason:"invalid_code"}}d.prepare("UPDATE space_share_link_otps SET verified_at = ? WHERE id = ?").run((0,f.nowIso)(),h.id);try{(0,g.appendComplianceAudit)({user_id:null,org_id:"personal-org",action:g.ComplianceActions.SHARE_OTP_VERIFIED,action_target_id:a,action_target_type:"space",status:"success",summary:`Space share OTP verified for ${b} on link ${a}`,meta:{share_link_id:a}})}catch{}return{ok:!0}}[f,g]=j.then?(await j)():j,d()}catch(a){d(a)}})},76031:(a,b,c)=>{c.d(b,{L5:()=>g,Oj:()=>f,lr:()=>h,th:()=>j});var d=c(77598);let e=null;async function f(){if(e)return e;if(process.env.MADARX_SHARE_LINK_SECRET)return e=process.env.MADARX_SHARE_LINK_SECRET;try{let{getSecret:a,setSecret:b}=await Promise.resolve().then(c.bind(c,24516)),f=await a("MADARX_SHARE_LINK_SECRET",{scope:"global"});if(f)return e=f;let g=(0,d.randomBytes)(32).toString("hex");return console.warn("[share-secret] WARNING: MADARX_SHARE_LINK_SECRET is not set. A random key has been generated and stored in the secrets vault. Set MADARX_SHARE_LINK_SECRET in your environment before deploying to production — losing this key invalidates all existing share links."),await b("MADARX_SHARE_LINK_SECRET",g,{scope:"global",source:"auto_generated"}),e=g}catch(a){return console.warn("[share-secret] WARNING: Could not access secrets vault for MADARX_SHARE_LINK_SECRET. Using an ephemeral key — share links will break on restart. Error: "+a.message),e=(0,d.randomBytes)(32).toString("hex")}}function g(a,b){return(0,d.createHmac)("sha256",b).update(a).digest("hex")}function h(a,b){let c=Buffer.from(a,"hex"),e=Buffer.from(b,"hex");return c.length===e.length&&(0,d.timingSafeEqual)(c,e)}let i=new Map;function j(a){if(!a)return{ok:!0};let b=Date.now(),c=i.get(a);return!c||b-c.windowStart>=36e5?(i.set(a,{count:1,windowStart:b}),{ok:!0}):c.count>=100?{ok:!1,retryAfterMs:36e5-(b-c.windowStart)}:(c.count+=1,{ok:!0})}},95678:(a,b,c)=>{c.d(b,{_:()=>e});let d=["MADARX_PUBLIC_SHARE_BASE_URL","NEXT_PUBLIC_SHARE_BASE_URL","NEXT_PUBLIC_SITE_URL"];function e(a){let b=String(a||"").startsWith("/")?String(a||""):`/${a||""}`,c=function(){for(let a of d){let b=process.env[a];if(!b||!String(b).trim())continue;let c=String(b).trim().replace(/\/+$/,"");if(/^https?:\/\//i.test(c))return c}return""}();return c?`${c}${b}`:b}}};