nucleus-core-ts 0.10.259 → 0.10.260

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/dist/.build-ok CHANGED
@@ -1 +1 @@
1
- 0.10.259
1
+ 0.10.260
package/dist/index.js CHANGED
@@ -119,7 +119,7 @@ end
119
119
  redis.call('ZADD', KEYS[1], now, ARGV[4])
120
120
  redis.call('PEXPIRE', KEYS[1], windowMs + 1000)
121
121
  return {1, count + 1}
122
- `,hashIdentity=(identity)=>createHash3("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});import{createCipheriv as createCipheriv2,createDecipheriv as createDecipheriv2,randomBytes as randomBytes3,scryptSync as scryptSync2,timingSafeEqual as timingSafeEqual2}from"crypto";var VERSION="v1",IV_LEN2=12,KEY_LEN=32,SCRYPT_SALT="nucleus-secrets-v1",keyCache,deriveKey2=(masterKey)=>{let cached=keyCache.get(masterKey);if(cached)return cached;let key2=scryptSync2(masterKey,SCRYPT_SALT,KEY_LEN);return keyCache.set(masterKey,key2),key2},encryptSecret=(plaintext,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let iv=randomBytes3(IV_LEN2),cipher=createCipheriv2("aes-256-gcm",deriveKey2(masterKey),iv),ciphertext=Buffer.concat([cipher.update(plaintext,"utf-8"),cipher.final()]),tag=cipher.getAuthTag();return[VERSION,iv.toString("base64"),tag.toString("base64"),ciphertext.toString("base64")].join(":")},decryptSecret=(envelope,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let[version,ivB64,tagB64,ctB64,...extra]=envelope.split(":");if(version!==VERSION||ivB64===void 0||tagB64===void 0||ctB64===void 0||extra.length>0)throw Error("not an encrypted secret envelope");let decipher=createDecipheriv2("aes-256-gcm",deriveKey2(masterKey),Buffer.from(ivB64,"base64"));return decipher.setAuthTag(Buffer.from(tagB64,"base64")),Buffer.concat([decipher.update(Buffer.from(ctB64,"base64")),decipher.final()]).toString("utf-8")},previewOf=(plaintext)=>{let len=plaintext.length;if(len===0)return"";if(len<12)return`\u2022\u2022\u2022\u2022${len}`;return`\u2022\u2022\u2022\u2022${plaintext.slice(-4)}`};var init_crypto=__esm(()=>{keyCache=new Map});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value2=node[key2];if(typeof value2==="string")return value2;if(Array.isArray(value2)&&value2.every((entry)=>typeof entry==="string"))return value2.length>0?value2.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value2]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value2)){walk(value2,childPath,depth+1);continue}if(typeof value2!=="string"&&value2!==void 0&&value2!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value2==="string"?value2:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value2)=>typeof value2==="object"&&value2!==null&&!Array.isArray(value2),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value2)=>!!value2&&/^[A-Z][A-Z0-9_]{2,}$/.test(value2);var init_registry2=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and12,eq as eq17}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq17(col(table,"isActive"),!0))).map(secretRowOf)}catch(error3){if(isMissingTableError(error3))return{values,failed:failed2,tableMissing:!0};throw error3}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error3){if(isMissingTableError(error3))return[];throw error3}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now,isActive:!0,updatedAt:now,updatedBy:params.actorId??null}).where(eq17(col(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now,updatedAt:now,updatedBy:actorId??null}).where(eq17(col(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq17(col(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq17(col(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col,SECRET_KINDS,isSecretKind=(value2)=>Object.hasOwn(SECRET_KINDS,value2),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value2)=>value2?new Date(value2).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error3)=>{let seen=new Set,current=typeof error3==="object"&&error3!==null?error3:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error3){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error3 instanceof Error?error3.message:String(error3)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record3=byId.get(id),{value:value2,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value2,preview:slot.secret?source==="db"&&record3?record3.preview:value2?previewOf(value2):"":value2??"",envName,version:record3?.version,rotatedAt:record3?.rotatedAt??null,canRollback:record3?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value2=fieldOf(node,key2);if(typeof value2==="boolean")return value2;if(typeof value2==="string")return value2==="true"||value2==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry2();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry2();init_SecretsService();init_store3()});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value2)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value2||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value2)=>{if(!value2||typeof value2!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value2)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value2)=>{if(!Array.isArray(value2))return[];return value2.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value2)=>Array.isArray(value2)?value2.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers2=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema3=pgSchema(schemaName),built={tables:deps.createTables(schema3),relations:deps.createRelations?deps.createRelations(schema3):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise3,timeoutMs,message){promise3.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise3,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns2,sql as sql10}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema3,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema3}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema3,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema3}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema3,drift){let statements=[],unsafe3=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema3,table,column);if(statement)statements.push(statement);else unsafe3.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema3,table,column);if(statement)statements.push(statement)}return{statements,unsafe:unsafe3,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3){let code=error3.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage2(error3))}async function createMissingTables(options){let{run,tables:tables2,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables2)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error3){let message=error3 instanceof Error?error3.message:String(error3);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors2=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error3){if(isAlreadyExists(error3))continue;let message=error3 instanceof Error?error3.message:String(error3);errors2.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors:errors2}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables2){let out=[];for(let value2 of Object.values(tables2)){let table=asTable(value2);if(!table)continue;let columns;try{columns=getTableColumns2(table)}catch{continue}if(!columns)continue;let list2=Object.values(columns),name=tableNameOf(table);if(!name||list2.length===0)continue;out.push({name,columns:list2.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value2){if(typeof value2==="string")return`'${value2.replace(/'/g,"''")}'`;if(typeof value2==="number")return Number.isFinite(value2)?String(value2):void 0;if(typeof value2==="boolean")return value2?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value2=Reflect.get(table,key2);if(typeof value2==="string"&&value2.length>0)return value2}return null}async function readActualSchema(execute2,schema3){return(await readActualSchemaDetailed(execute2,schema3)).columns}async function readActualSchemaDetailed(execute2,schema3){let result=await execute2(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema3.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema:schema3,tables:tables2,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql10.raw(statement));try{let expected=expectedFromTables(tables2);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema3),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema3,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables:tables2,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema3);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error3){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error3 instanceof Error?error3.message:String(error3)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error3){return logger2.error(`[Schema] the additive repair could not run: ${error3 instanceof Error?error3.message:String(error3)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error3)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error3)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema3()});import{sql as sql11}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text4=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text4);if(!target||!text4.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value2)=>value2.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql11`select c.conname as name, a.attname as col
122
+ `,hashIdentity=(identity)=>createHash3("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});import{createCipheriv as createCipheriv2,createDecipheriv as createDecipheriv2,randomBytes as randomBytes3,scryptSync as scryptSync2,timingSafeEqual as timingSafeEqual2}from"crypto";var VERSION="v1",IV_LEN2=12,KEY_LEN=32,SCRYPT_SALT="nucleus-secrets-v1",keyCache,deriveKey2=(masterKey)=>{let cached=keyCache.get(masterKey);if(cached)return cached;let key2=scryptSync2(masterKey,SCRYPT_SALT,KEY_LEN);return keyCache.set(masterKey,key2),key2},encryptSecret=(plaintext,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let iv=randomBytes3(IV_LEN2),cipher=createCipheriv2("aes-256-gcm",deriveKey2(masterKey),iv),ciphertext=Buffer.concat([cipher.update(plaintext,"utf-8"),cipher.final()]),tag=cipher.getAuthTag();return[VERSION,iv.toString("base64"),tag.toString("base64"),ciphertext.toString("base64")].join(":")},decryptSecret=(envelope,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let[version,ivB64,tagB64,ctB64,...extra]=envelope.split(":");if(version!==VERSION||ivB64===void 0||tagB64===void 0||ctB64===void 0||extra.length>0)throw Error("not an encrypted secret envelope");let decipher=createDecipheriv2("aes-256-gcm",deriveKey2(masterKey),Buffer.from(ivB64,"base64"));return decipher.setAuthTag(Buffer.from(tagB64,"base64")),Buffer.concat([decipher.update(Buffer.from(ctB64,"base64")),decipher.final()]).toString("utf-8")},previewOf=(plaintext)=>{let len=plaintext.length;if(len===0)return"";if(len<12)return`\u2022\u2022\u2022\u2022${len}`;return`\u2022\u2022\u2022\u2022${plaintext.slice(-4)}`};var init_crypto=__esm(()=>{keyCache=new Map});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value2=node[key2];if(typeof value2==="string")return value2;if(Array.isArray(value2)&&value2.every((entry)=>typeof entry==="string"))return value2.length>0?value2.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value2]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value2)){walk(value2,childPath,depth+1);continue}if(typeof value2!=="string"&&value2!==void 0&&value2!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value2==="string"?value2:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value2)=>typeof value2==="object"&&value2!==null&&!Array.isArray(value2),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value2)=>!!value2&&/^[A-Z][A-Z0-9_]{2,}$/.test(value2);var init_registry2=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",secret:!1,label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",secret:!1,label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",secret:!1,label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",secret:!1,label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",secret:!1,label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and12,eq as eq17}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq17(col(table,"isActive"),!0))).map(secretRowOf)}catch(error3){if(isMissingTableError(error3))return{values,failed:failed2,tableMissing:!0};throw error3}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error3){if(isMissingTableError(error3))return[];throw error3}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now,isActive:!0,updatedAt:now,updatedBy:params.actorId??null}).where(eq17(col(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now,updatedAt:now,updatedBy:actorId??null}).where(eq17(col(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq17(col(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq17(col(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col,SECRET_KINDS,isSecretKind=(value2)=>Object.hasOwn(SECRET_KINDS,value2),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value2)=>value2?new Date(value2).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error3)=>{let seen=new Set,current=typeof error3==="object"&&error3!==null?error3:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error3){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error3 instanceof Error?error3.message:String(error3)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record3=byId.get(id),{value:value2,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value2,preview:slot.secret?source==="db"&&record3?record3.preview:value2?previewOf(value2):"":value2??"",envName,version:record3?.version,rotatedAt:record3?.rotatedAt??null,canRollback:record3?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value2=fieldOf(node,key2);if(typeof value2==="boolean")return value2;if(typeof value2==="string")return value2==="true"||value2==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry2();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry2();init_SecretsService();init_store3()});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value2)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value2||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value2)=>{if(!value2||typeof value2!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value2)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value2)=>{if(!Array.isArray(value2))return[];return value2.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value2)=>Array.isArray(value2)?value2.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers2=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema3=pgSchema(schemaName),built={tables:deps.createTables(schema3),relations:deps.createRelations?deps.createRelations(schema3):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise3,timeoutMs,message){promise3.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise3,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns2,sql as sql10}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema3,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema3}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema3,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema3}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema3,drift){let statements=[],unsafe3=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema3,table,column);if(statement)statements.push(statement);else unsafe3.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema3,table,column);if(statement)statements.push(statement)}return{statements,unsafe:unsafe3,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3){let code=error3.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage2(error3))}async function createMissingTables(options){let{run,tables:tables2,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables2)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error3){let message=error3 instanceof Error?error3.message:String(error3);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors2=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error3){if(isAlreadyExists(error3))continue;let message=error3 instanceof Error?error3.message:String(error3);errors2.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors:errors2}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables2){let out=[];for(let value2 of Object.values(tables2)){let table=asTable(value2);if(!table)continue;let columns;try{columns=getTableColumns2(table)}catch{continue}if(!columns)continue;let list2=Object.values(columns),name=tableNameOf(table);if(!name||list2.length===0)continue;out.push({name,columns:list2.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value2){if(typeof value2==="string")return`'${value2.replace(/'/g,"''")}'`;if(typeof value2==="number")return Number.isFinite(value2)?String(value2):void 0;if(typeof value2==="boolean")return value2?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value2=Reflect.get(table,key2);if(typeof value2==="string"&&value2.length>0)return value2}return null}async function readActualSchema(execute2,schema3){return(await readActualSchemaDetailed(execute2,schema3)).columns}async function readActualSchemaDetailed(execute2,schema3){let result=await execute2(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema3.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema:schema3,tables:tables2,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql10.raw(statement));try{let expected=expectedFromTables(tables2);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema3),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema3,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables:tables2,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema3);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error3){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error3 instanceof Error?error3.message:String(error3)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error3){return logger2.error(`[Schema] the additive repair could not run: ${error3 instanceof Error?error3.message:String(error3)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error3)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error3)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema3()});import{sql as sql11}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text4=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text4);if(!target||!text4.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value2)=>value2.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql11`select c.conname as name, a.attname as col
123
123
  from pg_catalog.pg_constraint c
124
124
  join pg_catalog.pg_class t on t.oid = c.conrelid
125
125
  join pg_catalog.pg_namespace n on n.oid = t.relnamespace
package/dist/server.js CHANGED
@@ -129,7 +129,7 @@ end
129
129
  redis.call('ZADD', KEYS[1], now, ARGV[4])
130
130
  redis.call('PEXPIRE', KEYS[1], windowMs + 1000)
131
131
  return {1, count + 1}
132
- `,hashIdentity=(identity)=>createHash2("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add2=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value=node[key2];if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((entry)=>typeof entry==="string"))return value.length>0?value.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add2({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value)){walk(value,childPath,depth+1);continue}if(typeof value!=="string"&&value!==void 0&&value!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add2({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value==="string"?value:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value)=>!!value&&/^[A-Z][A-Z0-9_]{2,}$/.test(value);var init_registry=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and14,eq as eq18}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq18(col2(table,"isActive"),!0))).map(secretRowOf)}catch(error){if(isMissingTableError(error))return{values,failed:failed2,tableMissing:!0};throw error}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error){if(isMissingTableError(error))return[];throw error}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now2=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now2,isActive:!0,updatedAt:now2,updatedBy:params.actorId??null}).where(eq18(col2(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now2=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now2,updatedAt:now2,updatedBy:actorId??null}).where(eq18(col2(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq18(col2(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq18(col2(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col2,SECRET_KINDS,isSecretKind=(value)=>Object.hasOwn(SECRET_KINDS,value),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value)=>value?new Date(value).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error)=>{let seen=new Set,current=typeof error==="object"&&error!==null?error:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col2=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error instanceof Error?error.message:String(error)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record=byId.get(id),{value,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value,preview:slot.secret?source==="db"&&record?record.preview:value?previewOf(value):"":value??"",envName,version:record?.version,rotatedAt:record?.rotatedAt??null,canRollback:record?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value=fieldOf(node,key2);if(typeof value==="boolean")return value;if(typeof value==="string")return value==="true"||value==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry();init_SecretsService();init_store3()});var exports_schema={};__export(exports_schema,{validateIdentifier:()=>validateIdentifier,reasonOf:()=>reasonOf,isAlreadyPresent:()=>isAlreadyPresent,isAdditiveStatement:()=>isAdditiveStatement,ensureSchemaExists:()=>ensureSchemaExists,dropsSchemaObject:()=>dropsSchemaObject,applySchemaPush:()=>applySchemaPush});import{sql as sql15}from"drizzle-orm";function reasonOf(error){if(!(error instanceof Error))return String(error);let chain=errorChain(error),parts=[];for(let link of chain){let detail=fieldOf(link,"detail"),hint=fieldOf(link,"hint"),code=fieldOf(link,"code"),message=link.message.startsWith("Failed query:")&&chain.length>1?"":link.message;parts.push(message,detail?`detail: ${String(detail)}`:"",hint?`hint: ${String(hint)}`:"",code?`code: ${String(code)}`:"")}return parts.filter(Boolean).join(" \u2014 ")}function errorChain(error){let chain=[],current=error;while(current&&!chain.includes(current)&&chain.length<5)chain.push(current),current=current.cause instanceof Error?current.cause:void 0;return chain}function isAlreadyPresent(error){if(!(error instanceof Error))return!1;return errorChain(error).some((link)=>{let code=fieldOf(link,"code");return typeof code==="string"&&ALREADY_PRESENT.has(code)})}var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName),found=await db.execute(sql15`select 1 from pg_catalog.pg_namespace where nspname = ${safeName} limit 1`);if(rowCountOf(found)>0)return;await db.execute(sql15.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},rowCountOf=(result)=>{if(Array.isArray(result))return result.length;return"rows"in result&&Array.isArray(result.rows)?result.rows.length:0},ADDITIVE_PREFIXES,ALREADY_PRESENT,isAdditiveStatement=(statement)=>{let normalized=statement.trim().toUpperCase();if(/^ALTER TABLE .+ ADD COLUMN/.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ SET DEFAULT /.test(normalized))return!0;if(/^ALTER TABLE .+ ADD CONSTRAINT /.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ DROP NOT NULL$/.test(normalized))return!0;return ADDITIVE_PREFIXES.some((prefix)=>normalized.startsWith(prefix))},dropsSchemaObject=(statement)=>{let normalized=statement.trim().toUpperCase();return/^DROP INDEX /.test(normalized)||/^ALTER TABLE .+ DROP CONSTRAINT /.test(normalized)||/^DROP SEQUENCE /.test(normalized)},withoutKeptDrops=(push,opts)=>{let keep=opts.keep??dropsSchemaObject,kept=push.statementsToExecute.filter(keep);if(kept.length===0)return push;opts.logger.warn(`[Schema] Kept ${kept.length} index/constraint/sequence object(s) in "${opts.schemaName}" ${opts.reason??"that the table model does not declare (database.keepUndeclaredObjects). Declare them in the model, or drop them by hand if they are really gone."}`,{statements:kept});let{execute}=opts;if(!execute)return opts.logger.error(`[Schema] The schema push for "${opts.schemaName}" was not applied: keeping undeclared objects needs a statement executor to run the rest of it.`),null;let rest=push.statementsToExecute.filter((statement)=>!keep(statement));return{...push,statementsToExecute:rest,apply:async()=>{for(let statement of rest)await execute(statement)}}},applySchemaPush=async(planned,opts)=>{let{schemaName,allowDataLoss,logger:logger2,execute}=opts,owned=opts.keepObject?withoutKeptDrops(planned,{schemaName,logger:logger2,execute,keep:opts.keepObject,reason:"owned by a migration of the ledger (database.migrations)."}):planned,push=owned&&opts.keepUndeclaredObjects===!0&&!allowDataLoss?withoutKeptDrops(owned,opts):owned;if(!push)return!1;if(push.hasDataLoss&&!allowDataLoss){let additive=push.statementsToExecute.filter(isAdditiveStatement),blocked=push.statementsToExecute.filter((s)=>!isAdditiveStatement(s));if(logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 ${blocked.length} statement(s) skipped. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:blocked}),additive.length===0||!execute)return!1;let applied=0;for(let statement of additive)try{await execute(statement),applied++}catch(error){logger2.warn(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(error)}`)}return logger2.info(`[Schema] Applied ${applied}/${additive.length} additive statement(s) for "${schemaName}" despite the destructive changes being held back`),applied>0}if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});try{return await push.apply(),!0}catch(error){let message=error instanceof Error?error.message:String(error);if(!execute)return logger2.error(`[Schema] Could not apply schema changes to "${schemaName}": ${message}. The database does not match this build, so queries against the missing columns will fail.`,{warnings:push.warnings}),!1;logger2.error(`[Schema] The schema push for "${schemaName}" failed as a batch (${message}) \u2014 retrying its ${push.statementsToExecute.length} statement(s) one at a time so one bad statement does not hold back the rest.`);let applied=0,alreadyPresent=0,failures=[];for(let statement of push.statementsToExecute)try{await execute(statement),applied++}catch(statementError){if(isAlreadyPresent(statementError)){alreadyPresent++;continue}failures.push(statement),logger2.error(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(statementError)}`)}if(alreadyPresent>0)logger2.info(`[Schema] ${alreadyPresent} statement(s) for "${schemaName}" found their object already in place (applied before the batch stopped).`);if(failures.length>0)logger2.error(`[Schema] ${failures.length} of ${push.statementsToExecute.length} statement(s) could not be applied to "${schemaName}". Any query touching what they would have created will fail until they are.`);return applied>0||alreadyPresent>0}};var init_schema=__esm(()=>{ADDITIVE_PREFIXES=["CREATE TABLE IF NOT EXISTS","CREATE TABLE","CREATE SCHEMA IF NOT EXISTS","CREATE SCHEMA","CREATE INDEX IF NOT EXISTS","CREATE INDEX","CREATE UNIQUE INDEX IF NOT EXISTS","CREATE UNIQUE INDEX","CREATE TYPE","DO $$"];ALREADY_PRESENT=new Set(["42P07","42P06","42710","42701","42723"])});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema=pgSchema(schemaName),built={tables:deps.createTables(schema),relations:deps.createRelations?deps.createRelations(schema):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise,timeoutMs,message){promise.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns6,sql as sql16}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema,drift){let statements=[],unsafe=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema,table,column);if(statement)statements.push(statement);else unsafe.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema,table,column);if(statement)statements.push(statement)}return{statements,unsafe,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error){if(typeof error==="object"&&error!==null&&"code"in error){let code=error.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage(error))}async function createMissingTables(options){let{run,tables,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error){let message=error instanceof Error?error.message:String(error);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error){if(isAlreadyExists(error))continue;let message=error instanceof Error?error.message:String(error);errors.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables){let out=[];for(let value of Object.values(tables)){let table=asTable(value);if(!table)continue;let columns;try{columns=getTableColumns6(table)}catch{continue}if(!columns)continue;let list3=Object.values(columns),name=tableNameOf(table);if(!name||list3.length===0)continue;out.push({name,columns:list3.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value){if(typeof value==="string")return`'${value.replace(/'/g,"''")}'`;if(typeof value==="number")return Number.isFinite(value)?String(value):void 0;if(typeof value==="boolean")return value?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value=Reflect.get(table,key2);if(typeof value==="string"&&value.length>0)return value}return null}async function readActualSchema(execute,schema){return(await readActualSchemaDetailed(execute,schema)).columns}async function readActualSchemaDetailed(execute,schema){let result=await execute(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema,tables,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql16.raw(statement));try{let expected=expectedFromTables(tables);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error instanceof Error?error.message:String(error)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error){return logger2.error(`[Schema] the additive repair could not run: ${error instanceof Error?error.message:String(error)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool as Pool2}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool2(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool2))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema()});import{sql as sql17}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text3=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text3);if(!target||!text3.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value)=>value.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql17`select c.conname as name, a.attname as col
132
+ `,hashIdentity=(identity)=>createHash2("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add2=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value=node[key2];if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((entry)=>typeof entry==="string"))return value.length>0?value.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add2({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value)){walk(value,childPath,depth+1);continue}if(typeof value!=="string"&&value!==void 0&&value!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add2({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value==="string"?value:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value)=>!!value&&/^[A-Z][A-Z0-9_]{2,}$/.test(value);var init_registry=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",secret:!1,label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",secret:!1,label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",secret:!1,label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",secret:!1,label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",secret:!1,label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and14,eq as eq18}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq18(col2(table,"isActive"),!0))).map(secretRowOf)}catch(error){if(isMissingTableError(error))return{values,failed:failed2,tableMissing:!0};throw error}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error){if(isMissingTableError(error))return[];throw error}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now2=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now2,isActive:!0,updatedAt:now2,updatedBy:params.actorId??null}).where(eq18(col2(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now2=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now2,updatedAt:now2,updatedBy:actorId??null}).where(eq18(col2(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq18(col2(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq18(col2(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col2,SECRET_KINDS,isSecretKind=(value)=>Object.hasOwn(SECRET_KINDS,value),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value)=>value?new Date(value).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error)=>{let seen=new Set,current=typeof error==="object"&&error!==null?error:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col2=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error instanceof Error?error.message:String(error)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record=byId.get(id),{value,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value,preview:slot.secret?source==="db"&&record?record.preview:value?previewOf(value):"":value??"",envName,version:record?.version,rotatedAt:record?.rotatedAt??null,canRollback:record?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value=fieldOf(node,key2);if(typeof value==="boolean")return value;if(typeof value==="string")return value==="true"||value==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry();init_SecretsService();init_store3()});var exports_schema={};__export(exports_schema,{validateIdentifier:()=>validateIdentifier,reasonOf:()=>reasonOf,isAlreadyPresent:()=>isAlreadyPresent,isAdditiveStatement:()=>isAdditiveStatement,ensureSchemaExists:()=>ensureSchemaExists,dropsSchemaObject:()=>dropsSchemaObject,applySchemaPush:()=>applySchemaPush});import{sql as sql15}from"drizzle-orm";function reasonOf(error){if(!(error instanceof Error))return String(error);let chain=errorChain(error),parts=[];for(let link of chain){let detail=fieldOf(link,"detail"),hint=fieldOf(link,"hint"),code=fieldOf(link,"code"),message=link.message.startsWith("Failed query:")&&chain.length>1?"":link.message;parts.push(message,detail?`detail: ${String(detail)}`:"",hint?`hint: ${String(hint)}`:"",code?`code: ${String(code)}`:"")}return parts.filter(Boolean).join(" \u2014 ")}function errorChain(error){let chain=[],current=error;while(current&&!chain.includes(current)&&chain.length<5)chain.push(current),current=current.cause instanceof Error?current.cause:void 0;return chain}function isAlreadyPresent(error){if(!(error instanceof Error))return!1;return errorChain(error).some((link)=>{let code=fieldOf(link,"code");return typeof code==="string"&&ALREADY_PRESENT.has(code)})}var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName),found=await db.execute(sql15`select 1 from pg_catalog.pg_namespace where nspname = ${safeName} limit 1`);if(rowCountOf(found)>0)return;await db.execute(sql15.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},rowCountOf=(result)=>{if(Array.isArray(result))return result.length;return"rows"in result&&Array.isArray(result.rows)?result.rows.length:0},ADDITIVE_PREFIXES,ALREADY_PRESENT,isAdditiveStatement=(statement)=>{let normalized=statement.trim().toUpperCase();if(/^ALTER TABLE .+ ADD COLUMN/.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ SET DEFAULT /.test(normalized))return!0;if(/^ALTER TABLE .+ ADD CONSTRAINT /.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ DROP NOT NULL$/.test(normalized))return!0;return ADDITIVE_PREFIXES.some((prefix)=>normalized.startsWith(prefix))},dropsSchemaObject=(statement)=>{let normalized=statement.trim().toUpperCase();return/^DROP INDEX /.test(normalized)||/^ALTER TABLE .+ DROP CONSTRAINT /.test(normalized)||/^DROP SEQUENCE /.test(normalized)},withoutKeptDrops=(push,opts)=>{let keep=opts.keep??dropsSchemaObject,kept=push.statementsToExecute.filter(keep);if(kept.length===0)return push;opts.logger.warn(`[Schema] Kept ${kept.length} index/constraint/sequence object(s) in "${opts.schemaName}" ${opts.reason??"that the table model does not declare (database.keepUndeclaredObjects). Declare them in the model, or drop them by hand if they are really gone."}`,{statements:kept});let{execute}=opts;if(!execute)return opts.logger.error(`[Schema] The schema push for "${opts.schemaName}" was not applied: keeping undeclared objects needs a statement executor to run the rest of it.`),null;let rest=push.statementsToExecute.filter((statement)=>!keep(statement));return{...push,statementsToExecute:rest,apply:async()=>{for(let statement of rest)await execute(statement)}}},applySchemaPush=async(planned,opts)=>{let{schemaName,allowDataLoss,logger:logger2,execute}=opts,owned=opts.keepObject?withoutKeptDrops(planned,{schemaName,logger:logger2,execute,keep:opts.keepObject,reason:"owned by a migration of the ledger (database.migrations)."}):planned,push=owned&&opts.keepUndeclaredObjects===!0&&!allowDataLoss?withoutKeptDrops(owned,opts):owned;if(!push)return!1;if(push.hasDataLoss&&!allowDataLoss){let additive=push.statementsToExecute.filter(isAdditiveStatement),blocked=push.statementsToExecute.filter((s)=>!isAdditiveStatement(s));if(logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 ${blocked.length} statement(s) skipped. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:blocked}),additive.length===0||!execute)return!1;let applied=0;for(let statement of additive)try{await execute(statement),applied++}catch(error){logger2.warn(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(error)}`)}return logger2.info(`[Schema] Applied ${applied}/${additive.length} additive statement(s) for "${schemaName}" despite the destructive changes being held back`),applied>0}if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});try{return await push.apply(),!0}catch(error){let message=error instanceof Error?error.message:String(error);if(!execute)return logger2.error(`[Schema] Could not apply schema changes to "${schemaName}": ${message}. The database does not match this build, so queries against the missing columns will fail.`,{warnings:push.warnings}),!1;logger2.error(`[Schema] The schema push for "${schemaName}" failed as a batch (${message}) \u2014 retrying its ${push.statementsToExecute.length} statement(s) one at a time so one bad statement does not hold back the rest.`);let applied=0,alreadyPresent=0,failures=[];for(let statement of push.statementsToExecute)try{await execute(statement),applied++}catch(statementError){if(isAlreadyPresent(statementError)){alreadyPresent++;continue}failures.push(statement),logger2.error(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(statementError)}`)}if(alreadyPresent>0)logger2.info(`[Schema] ${alreadyPresent} statement(s) for "${schemaName}" found their object already in place (applied before the batch stopped).`);if(failures.length>0)logger2.error(`[Schema] ${failures.length} of ${push.statementsToExecute.length} statement(s) could not be applied to "${schemaName}". Any query touching what they would have created will fail until they are.`);return applied>0||alreadyPresent>0}};var init_schema=__esm(()=>{ADDITIVE_PREFIXES=["CREATE TABLE IF NOT EXISTS","CREATE TABLE","CREATE SCHEMA IF NOT EXISTS","CREATE SCHEMA","CREATE INDEX IF NOT EXISTS","CREATE INDEX","CREATE UNIQUE INDEX IF NOT EXISTS","CREATE UNIQUE INDEX","CREATE TYPE","DO $$"];ALREADY_PRESENT=new Set(["42P07","42P06","42710","42701","42723"])});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema=pgSchema(schemaName),built={tables:deps.createTables(schema),relations:deps.createRelations?deps.createRelations(schema):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise,timeoutMs,message){promise.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns6,sql as sql16}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema,drift){let statements=[],unsafe=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema,table,column);if(statement)statements.push(statement);else unsafe.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema,table,column);if(statement)statements.push(statement)}return{statements,unsafe,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error){if(typeof error==="object"&&error!==null&&"code"in error){let code=error.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage(error))}async function createMissingTables(options){let{run,tables,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error){let message=error instanceof Error?error.message:String(error);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error){if(isAlreadyExists(error))continue;let message=error instanceof Error?error.message:String(error);errors.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables){let out=[];for(let value of Object.values(tables)){let table=asTable(value);if(!table)continue;let columns;try{columns=getTableColumns6(table)}catch{continue}if(!columns)continue;let list3=Object.values(columns),name=tableNameOf(table);if(!name||list3.length===0)continue;out.push({name,columns:list3.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value){if(typeof value==="string")return`'${value.replace(/'/g,"''")}'`;if(typeof value==="number")return Number.isFinite(value)?String(value):void 0;if(typeof value==="boolean")return value?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value=Reflect.get(table,key2);if(typeof value==="string"&&value.length>0)return value}return null}async function readActualSchema(execute,schema){return(await readActualSchemaDetailed(execute,schema)).columns}async function readActualSchemaDetailed(execute,schema){let result=await execute(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema,tables,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql16.raw(statement));try{let expected=expectedFromTables(tables);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error instanceof Error?error.message:String(error)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error){return logger2.error(`[Schema] the additive repair could not run: ${error instanceof Error?error.message:String(error)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool as Pool2}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool2(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool2))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema()});import{sql as sql17}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text3=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text3);if(!target||!text3.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value)=>value.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql17`select c.conname as name, a.attname as col
133
133
  from pg_catalog.pg_constraint c
134
134
  join pg_catalog.pg_class t on t.oid = c.conrelid
135
135
  join pg_catalog.pg_namespace n on n.oid = t.relnamespace
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nucleus-core-ts",
3
- "version": "0.10.259",
3
+ "version": "0.10.260",
4
4
  "description": "Production-ready, enterprise-grade TypeScript framework for building multi-tenant APIs",
5
5
  "author": "Hidayet Can Özcan <hidayetcan@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",