"use strict";exports.id=6910,exports.ids=[6910],exports.modules={46910:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{DX:()=>p,Lt:()=>k,S2:()=>m,Si:()=>r,Sp:()=>q,dr:()=>o,lO:()=>l,n0:()=>s,th:()=>h.th,vx:()=>n});var e=c(77598),f=c(34255),g=c(4160),h=c(76031),i=c(95678),j=a([f,g]);function k(a){let b=(0,f.getDb)().prepare("SELECT * FROM artifact_acls WHERE artifact_id = ?").get(a);return b||{artifact_id:a,scope:"private",team_id:null,updated_at:(0,f.nowIso)(),updated_by:null}}function l(a,{scope:b,team_id:c=null,updated_by:d}){let e=["private","team","org","link"];if(!e.includes(b))throw{status:400,error:"invalid_scope",validScopes:e};if("team"===b&&!c)throw{status:400,error:"team_id_required_for_team_scope"};let g=(0,f.getDb)(),h=g.prepare("SELECT scope FROM artifact_acls WHERE artifact_id = ?").get(a);return h?.scope==="link"&&"link"!==b&&g.prepare(`UPDATE artifact_share_links
         SET revoked = 1
       WHERE artifact_id = ? AND revoked = 0`).run(a),g.prepare(`INSERT INTO artifact_acls (artifact_id, scope, team_id, updated_at, updated_by)
     VALUES (?, ?, ?, ?, ?)
     ON CONFLICT(artifact_id) DO UPDATE SET
       scope      = excluded.scope,
       team_id    = excluded.team_id,
       updated_at = excluded.updated_at,
       updated_by = excluded.updated_by`).run(a,b,c,(0,f.nowIso)(),d||null),{artifact_id:a,scope:b,team_id:c}}async function m(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 l=(0,f.getDb)(),n=k;if(null==n){let a=l.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)("share"),t=c.org_id;l.prepare(`INSERT INTO artifact_share_links
       (id, artifact_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,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.ARTIFACT_SHARE_LINK_CREATED,action_target_id:a,action_target_type:"artifact",status:"success",summary:`Share link created for artifact ${a}`,meta:{share_link_id:s,expires_at:r,max_views:j??null,require_email_otp:n}})}catch(a){console.error("[artifact-acl] Failed to write audit row for createShareLink:",a.message)}return{id:s,token:o,url:(0,i._)(`/share/${o}`),expires_at:r,max_views:j??null,require_email_otp:n}}function n(a){return(0,f.getDb)().prepare(`SELECT id, artifact_id, token, created_by, org_id, expires_at, max_views,
              access_count, revoked, require_email_otp, created_at
       FROM artifact_share_links
       WHERE artifact_id = ? AND revoked = 0
       ORDER BY created_at DESC`).all(a)}async function o(a,b){if(!a)return{ok:!1,status:404,reason:"not_found"};let c=await (0,h.Oj)(),d=(0,h.L5)(a,c),e=(0,f.getDb)(),g=e.prepare("SELECT * FROM artifact_share_links WHERE token_hmac = ?").get(d);if(!g||!(0,h.lr)(d,g.token_hmac))return{ok:!1,status:404,reason:"not_found"};if(1===g.revoked)return{ok:!1,status:410,reason:"revoked"};if(g.expires_at&&new Date(g.expires_at)<new Date)return{ok:!1,status:410,reason:"expired"};if(null!=g.max_views&&g.access_count>=g.max_views)return e.prepare("UPDATE artifact_share_links SET revoked = 1 WHERE id = ?").run(g.id),{ok:!1,status:410,reason:"view_cap_reached"};let i=e.prepare("SELECT * FROM artifacts WHERE id = ?").get(g.artifact_id);return i?{ok:!0,link:g,artifact:i}:{ok:!1,status:404,reason:"not_found"}}function p(a,b,c=null){let d=(0,f.getDb)(),e=d.prepare(`UPDATE artifact_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 artifact_share_links WHERE id = ?").get(a);if(!h)return;let i=h.access_count,j=1===h.revoked,k=(0,g.N)(b),l=(0,g.S)(b);try{(0,g.appendComplianceAudit)({user_id:null,org_id:h.org_id,action:g.ComplianceActions.ARTIFACT_SHARE_LINK_ACCESSED,action_target_id:h.artifact_id,action_target_type:"artifact",status:"success",summary:`Share link ${a} accessed${c?` by ${c}`:""}`,meta:{share_link_id:a,access_count:i,auto_revoked:j,recipient_email:c},ip:k,user_agent:l})}catch(a){console.error("[artifact-acl] Failed to write audit row for recordShareLinkAccess:",a.message)}}function q(a,b){let c=(0,f.getDb)(),d=c.prepare("SELECT * FROM artifact_share_links WHERE id = ?").get(a);if(!d)throw{status:404,error:"share_link_not_found"};c.prepare("UPDATE artifact_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.ARTIFACT_SHARE_LINK_REVOKED,action_target_id:d.artifact_id,action_target_type:"artifact",status:"success",summary:`Share link ${a} revoked`,meta:{share_link_id:a,artifact_id:d.artifact_id}})}catch(a){console.error("[artifact-acl] Failed to write audit row for revokeShareLink:",a.message)}return{ok:!0}}async function r(a,b){let d=(0,f.getDb)(),h=d.prepare("SELECT * FROM artifact_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 artifact_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.artifact_id,action_target_type:"artifact",status:"success",summary:`Share OTP sent to ${b} for link ${a}`,meta:{share_link_id:a,otp_id:n}})}catch(a){console.error("[artifact-acl] Failed to write audit row for createOtpForShareLink:",a.message)}try{let{executeRegistryTool:a}=await Promise.resolve().then(c.bind(c,40718)),d=await a("email_send",{to:b,subject:"Your madarX share link verification code",html:`<p>You requested access to a shared artifact 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 console.warn("[artifact-acl] createOtpForShareLink: email_send returned non-ok:",d),{ok:!0,expires_in:600,email_sent:!1,email_error:d?.status||"unknown"}}catch(a){return console.warn("[artifact-acl] createOtpForShareLink: email_send failed:",a.message),{ok:!0,expires_in:600,email_sent:!1,email_error:a.message}}return{ok:!0,expires_in:600,email_sent:!0}}function s(a,b,c){let d=(0,f.getDb)(),h=d.prepare(`SELECT * FROM artifact_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:"artifact",status:"denied",summary:`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");Buffer.from(i,"utf8");let l=Buffer.from(k,"hex"),m=Buffer.from(j,"hex");if(!(l.length===m.length&&(0,e.timingSafeEqual)(l,m))){d.prepare("UPDATE artifact_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:"artifact",status:"denied",summary:`OTP verification 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 artifact_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:"artifact",status:"success",summary:`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}}};