@snyxex/pipex 0.0.0-stage → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +319 -2
- package/dist/compression-2mm0MhWY.mjs +1 -0
- package/dist/compression-CtrHxa9G.d.mts +38 -0
- package/dist/compression-DnVFu8TM.d.cts +38 -0
- package/dist/compression-DrgzribA.cjs +1 -0
- package/dist/compression.cjs +1 -0
- package/dist/compression.d.cts +2 -0
- package/dist/compression.d.mts +2 -0
- package/dist/compression.mjs +1 -0
- package/dist/core-BOdvxKBq.mjs +2 -0
- package/dist/core-B_z1gN5W.cjs +2 -0
- package/dist/dataEngine-4m6GTOLe.mjs +1 -0
- package/dist/dataEngine-Bvl6amzP.cjs +1 -0
- package/dist/dataEngine-D-fIXgE7.d.cts +232 -0
- package/dist/dataEngine-DUEmWp7a.d.mts +232 -0
- package/dist/encryption-BmmNECIc.d.cts +44 -0
- package/dist/encryption-CnSL1BEY.d.mts +44 -0
- package/dist/encryption-CqxtoqAD.mjs +1 -0
- package/dist/encryption-DdP1zFYl.cjs +1 -0
- package/dist/encryption.cjs +1 -0
- package/dist/encryption.d.cts +2 -0
- package/dist/encryption.d.mts +2 -0
- package/dist/encryption.mjs +1 -0
- package/dist/hashing-B6xGcbQR.d.mts +33 -0
- package/dist/hashing-ChrADfcH.mjs +1 -0
- package/dist/hashing-JtOHPybU.cjs +1 -0
- package/dist/hashing-LY-8x66g.d.cts +33 -0
- package/dist/hashing.cjs +1 -0
- package/dist/hashing.d.cts +2 -0
- package/dist/hashing.d.mts +2 -0
- package/dist/hashing.mjs +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +302 -0
- package/dist/index.d.mts +302 -0
- package/dist/index.mjs +1 -0
- package/dist/kms.cjs +1 -0
- package/dist/kms.d.cts +3 -0
- package/dist/kms.d.mts +3 -0
- package/dist/kms.mjs +1 -0
- package/dist/kms_encryption-Da-KqjKI.d.mts +33 -0
- package/dist/kms_encryption-Dh1LEHhk.d.cts +33 -0
- package/dist/kms_encryption-R9auKGW4.mjs +1 -0
- package/dist/kms_encryption-xyWi65rZ.cjs +1 -0
- package/dist/native.cjs +1 -0
- package/dist/native.d.cts +2 -0
- package/dist/native.d.mts +2 -0
- package/dist/native.mjs +1 -0
- package/dist/parallel.cjs +1 -0
- package/dist/parallel.d.cts +2 -0
- package/dist/parallel.d.mts +2 -0
- package/dist/parallel.mjs +1 -0
- package/dist/plugin-C9Kd9coY.d.cts +16 -0
- package/dist/plugin-CE94-p8P.d.mts +16 -0
- package/dist/resourceLimits-C1HHDwXQ.mjs +1 -0
- package/dist/resourceLimits-CI0Qrqdf.cjs +1 -0
- package/dist/types-Bytga6zd.d.mts +155 -0
- package/dist/types-ia4x-Dvp.d.cts +155 -0
- package/dist/validation-CqmhNHdW.d.cts +32 -0
- package/dist/validation-D17IkoHy.d.mts +32 -0
- package/dist/validation-P5WRSAUK.mjs +1 -0
- package/dist/validation-pEeJmCad.cjs +1 -0
- package/dist/validation.cjs +1 -0
- package/dist/validation.d.cts +2 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +1 -0
- package/dist/worker-CbuCpSNc.d.cts +37 -0
- package/dist/worker-CgCC-BWG.d.mts +37 -0
- package/dist/worker-I_kqxWeK.cjs +1 -0
- package/dist/worker-c0_VZ9c7.mjs +1 -0
- package/package.json +188 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./core-B_z1gN5W.cjs`),t=require(`./resourceLimits-CI0Qrqdf.cjs`);let n=require(`node:crypto`),r=require(`node:stream`);require(`zod`);let i=require(`node:path`);i=e.W(i,1);let a=require(`node:fs`),o=require(`node:events`),s=require(`node:module`),c;const l=()=>c??=(0,s.createRequire)(require(`url`).pathToFileURL(__filename).href)(`koffi`),u=e=>{throw Error(`[PipeX] Secure file `+e+` failed`)},d=e=>{let t=i.default.parse(e).root;return e.slice(t.length).split(i.default.sep).filter(Boolean)};function f(t,n,r){let o=a.realpathSync.native(i.default.resolve(r??process.cwd())),s=e.c(t,o),c=e.k(n,o);if(s===c)throw Error(`[PipeX] Input and output must be different files`);return process.platform===`win32`?h(s,c,o):v(s,c)}let p;function m(){let e=l(),t=e.load(`kernel32.dll`),n=e.load(`ntdll.dll`),r=e.struct({Length:`uint16_t`,MaximumLength:`uint16_t`,Buffer:`str16`}),i=e.struct({Length:`uint32_t`,RootDirectory:`intptr_t`,ObjectName:e.pointer(r),Attributes:`uint32_t`,SecurityDescriptor:`void *`,SecurityQualityOfService:`void *`}),a=e.struct({Status:`intptr_t`,Information:`uintptr_t`});return{setRelativeInfo:n.func(`__stdcall`,`NtSetInformationFile`,`int32_t`,[`intptr_t`,e.out(e.pointer(a)),`void *`,`uint32_t`,`int`]),relativeOpen:n.func(`__stdcall`,`NtCreateFile`,`int32_t`,[`_Out_ intptr_t *`,`uint32_t`,e.pointer(i),e.out(e.pointer(a)),`void *`,`uint32_t`,`uint32_t`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`]),attributesSize:e.sizeof(i),pointerBytes:e.sizeof(`void *`),finalPath:t.func(`__stdcall`,`GetFinalPathNameByHandleW`,`uint32_t`,[`intptr_t`,`_Out_ void *`,`uint32_t`,`uint32_t`]),open:t.func(`__stdcall`,`CreateFileW`,`intptr_t`,[`str16`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`,`uint32_t`,`void *`]),info:t.func(`__stdcall`,`GetFileInformationByHandle`,`int`,[`intptr_t`,`_Out_ void *`]),type:t.func(`__stdcall`,`GetFileType`,`uint32_t`,[`intptr_t`]),read:t.func(`__stdcall`,`ReadFile`,`int`,[`intptr_t`,`_Out_ void *`,`uint32_t`,`_Out_ uint32_t *`,`void *`]),write:t.func(`__stdcall`,`WriteFile`,`int`,[`intptr_t`,`void *`,`uint32_t`,`_Out_ uint32_t *`,`void *`]),setInfo:t.func(`__stdcall`,`SetFileInformationByHandle`,`int`,[`intptr_t`,`int`,`void *`,`uint32_t`]),close:t.func(`__stdcall`,`CloseHandle`,`int`,[`intptr_t`])}}function h(t,a,o){let s=p??=m(),c=[],l=new Map,f=new Set,h=!1,g=!1,_,v,y=e=>{let t=Buffer.alloc(52);return s.info(e,t)||u(`handle inspection`),t},b=(e,t,n,r,i)=>{let a=s.open(e,t,n,null,r,2097152|(i?33554432:128),null);BigInt(a)===-1n&&u(`open`),c.push(a);let o=y(a).readUInt32LE(0);return(o&1024||!!(o&16)!==i||s.type(a)!==1)&&u(`file type validation`),a},x=(e,t,n,r,i,a=!1)=>{(!t||t===`.`||t===`..`||/[\\/:]/.test(t))&&u(`relative name validation`);let o=[0],l=s.relativeOpen(o,(n|1048576)>>>0,{Length:s.attributesSize,RootDirectory:e,ObjectName:{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(t,`utf16le`)+2,Buffer:t},Attributes:64,SecurityDescriptor:null,SecurityQualityOfService:null},{},null,128,i?3:1,r?2:1,2097184|(i?1:64),null,0);if(l<0){if(a&&l>>>0==3221225524)return;u(`relative open`)}let d=o[0];c.push(d),r&&(v=d);let f=y(d).readUInt32LE(0);return(f&1024||!!(f&16)!==i||s.type(d)!==1)&&u(`relative type validation`),d},S=(e,t)=>{let n=``,r=t;for(let t of d(i.default.relative(o,i.default.dirname(e)))){n=i.default.join(n,t);let e=l.get(n.toLowerCase());e===void 0?(r=x(r,t,2147483648,!1,!0),l.set(n.toLowerCase(),r)):r=e}return r},C,w=()=>{for(let e of c.reverse())s.close(e);c.length=0};try{let e=b(o,2147483648,3,3,!0),r=Buffer.alloc(65536),l=s.finalPath(e,r,r.length/2,0);(!l||l>=r.length/2)&&u(`root identity validation`),i.default.normalize((e=>e.startsWith(`\\\\?\\UNC\\`)?`\\\\`+e.slice(8):e.startsWith(`\\\\?\\`)?e.slice(4):e)(r.subarray(0,l*2).toString(`utf16le`))).toLowerCase()!==i.default.normalize(o).toLowerCase()&&u(`root identity validation`);let d=S(t,e);C=S(a,e),_=x(d,i.default.basename(t),2147483648,!1,!1);let f=x(C,i.default.basename(a),2147483648,!1,!1,!0);if(f!==void 0)try{let e=y(_),t=y(f);if(e.readUInt32LE(28)===t.readUInt32LE(28)&&e.subarray(44,52).equals(t.subarray(44,52)))throw Error(`[PipeX] Input and output must be different files`);t.readUInt32LE(0)&1024&&u(`output reparse validation`)}finally{s.close(f),c.pop()}let p=`.pipex-`+(0,n.randomUUID)()+`.tmp`;v=x(C,p,1073807488,!0,!1)}catch(e){throw v!==void 0&&s.setInfo(v,4,Buffer.from([1]),1),w(),e}let T=(e,t)=>{let n=[0],r=new Promise((r,i)=>{(e?s.write:s.read).async(e?v:_,t,t.length,n,null,(t,a)=>{t||!a?i(Error(`[PipeX] Secure file `+(e?`write`:`read`)+` failed`)):r(n[0])})});return f.add(r),r.then(()=>f.delete(r),()=>f.delete(r)),r},E=!1,D=new r.Readable({highWaterMark:e.t,read(){if(E)return;E=!0;let t=Buffer.allocUnsafe(e.t);T(!1,t).then(e=>{E=!1,this.destroyed||this.push(e?t.subarray(0,e):null)},e=>{E=!1,this.destroy(e)})}}),O=new r.Writable({highWaterMark:e.t,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){g&&u(`write after disposal`);let n=await T(!0,e.subarray(t));n||u(`write progress`),t+=n}})();f.add(r),r.then(()=>{f.delete(r),n()},e=>{f.delete(r),n(e)})}});return{source:D,destination:O,commit(){(g||h)&&u(`commit state`);let e=s.pointerBytes,t=e===8?8:4,n=t+e,r=n+4,o=Buffer.from(i.default.basename(a)+`\0`,`utf16le`),c=Buffer.alloc(r+o.length);c[0]=1,e===8?c.writeBigUInt64LE(BigInt(C),t):c.writeUInt32LE(Number(C),t),c.writeUInt32LE(o.length-2,n),o.copy(c,r);let l=s.setRelativeInfo(v,{},c,c.length,10);l<0&&u(`atomic rename status `+(l>>>0).toString(16)),h=!0},async dispose(){g||(g=!0,D.destroy(),O.destroy(),await Promise.allSettled([...f]),h||s.setInfo(v,4,Buffer.from([1]),1),w())}}}let g;function _(){let e=l().load(null);return{read:e.func(`intptr_t read(int fd, _Out_ void *buffer, size_t count)`),write:e.func(`intptr_t write(int fd, const void *buffer, size_t count)`),fcntl:e.func(`int fcntl(int fd, int command, int argument)`),openat:e.func(`int openat(int dirfd, const char *path, int flags, unsigned int mode)`),mkdirat:e.func(`int mkdirat(int dirfd, const char *path, unsigned int mode)`),renameat:e.func(`int renameat(int oldfd, const char *oldname, int newfd, const char *newname)`),unlinkat:e.func(`int unlinkat(int dirfd, const char *path, int flags)`)}}function v(t,o){let s=g??=_(),c=[],l=a.constants.O_NOFOLLOW,f=a.constants.O_DIRECTORY;(!l||!f)&&u(`platform support`);let p=()=>{for(let e of c.reverse())try{(0,a.closeSync)(e)}catch{}c.length=0},m=(e,t,n,r=0)=>{let i=s.openat(e,t,n|l,r);return i<0&&u(`relative open`),c.push(i),s.fcntl(i,2,1)<0&&u(`descriptor inheritance protection`),i},h=e=>{let t=(0,a.openSync)(i.default.parse(e).root,a.constants.O_RDONLY|f);c.push(t);for(let n of d(i.default.dirname(e)))t=m(t,n,a.constants.O_RDONLY|f);return t},v=`.pipex-`+(0,n.randomUUID)(),y,b,x,S,C=!1,w=!1,T=!1,E=new Set,D=process.platform===`linux`?512:process.platform===`darwin`?128:process.platform===`openbsd`?8:2048,O=()=>{b!==void 0&&!C&&s.unlinkat(b,`data`,0),y!==void 0&&T&&s.unlinkat(y,v,D),p()};try{let e=h(t);y=h(o),x=m(e,i.default.basename(t),a.constants.O_RDONLY|a.constants.O_NONBLOCK);let n=(0,a.fstatSync)(x,{bigint:!0});n.isFile()||u(`input type validation`);let r=s.openat(y,i.default.basename(o),a.constants.O_RDONLY|l|a.constants.O_NONBLOCK,0);if(r>=0)try{let e=(0,a.fstatSync)(r,{bigint:!0});if(n.dev===e.dev&&n.ino===e.ino)throw Error(`[PipeX] Input and output must be different files`)}finally{(0,a.closeSync)(r)}s.mkdirat(y,v,448)!==0&&u(`temporary directory creation`),T=!0,b=m(y,v,a.constants.O_RDONLY|f);let c=(0,a.fstatSync)(b);(c.mode&63||c.uid!==process.geteuid?.())&&u(`temporary directory permissions`),S=m(b,`data`,a.constants.O_WRONLY|a.constants.O_CREAT|a.constants.O_EXCL,384)}catch(e){throw O(),e}let k=(e,t)=>{let n=new Promise((n,r)=>{(e?s.write:s.read).async(e?S:x,t,t.length,(e,t)=>{e||t<0?r(Error(`[PipeX] Secure relative file I/O failed`)):n(Number(t))})});return E.add(n),n.then(()=>E.delete(n),()=>E.delete(n)),n},A=!1,j=new r.Readable({highWaterMark:e.t,read(){if(A)return;A=!0;let t=Buffer.allocUnsafe(e.t);k(!1,t).then(e=>{A=!1,this.destroyed||this.push(e?t.subarray(0,e):null)},e=>{A=!1,this.destroy(e)})}}),M=new r.Writable({highWaterMark:e.t,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){w&&u(`write after disposal`);let n=await k(!0,e.subarray(t));n||u(`relative write progress`),t+=n}})();E.add(r),r.then(()=>{E.delete(r),n()},e=>{E.delete(r),n(e)})}});return{source:j,destination:M,commit(){(w||C)&&u(`commit state`),s.renameat(b,`data`,y,i.default.basename(o))!==0&&u(`atomic relative rename`),C=!0},async dispose(){w||(w=!0,j.destroy(),M.destroy(),await Promise.allSettled([...E]),O())}}}var y=class{#e;constructor(e){this.#e=e}async#t(t,n,r,i,a){let o=f(t,n,r);try{await a(o.source,o.destination),e.B(i),o.commit()}finally{await o.dispose()}}#n(e,t){return{requestId:e,signal:t,track:t=>this.#e.trackWork(e,t),limits:this.#e.limits,logger:this.#e.logger,tracer:this.#e.tracer}}async process(t,n,r,i={}){let a=this.#e.createOperationSignal(i);e.B(a);let o=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(t,n,r,a,async(t,n)=>{let r=this.#n(o,a);await e.A(t,[e.p(this.#e.limits.maxInputBytes,`input`),...e.x(this.#e.plugins,`compress`,!1,e=>this.#e.emitProgress(e,o),this.#e.logger,this.#e.tracer,this.#e.dlq,r),e.p(this.#e.limits.maxOutputBytes,`output`)],n,{signal:a})}),await e.R(this.#e.emitAudit({requestId:o,operation:`process`,metadata:{controller:`file`}}),a,e=>this.#e.trackWork(o,e)),e.B(a),this.#e.endRequest(o)}catch(e){throw this.#e.emitError(e,o),e}}async reverse(t,n,r,i={}){let a=this.#e.createOperationSignal(i);e.B(a);let o=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(t,n,r,a,async(t,n)=>{let r=this.#n(o,a);await e.A(t,[e.p(this.#e.limits.maxInputBytes,`input`),...e.x(this.#e.plugins,`decompress`,!0,e=>this.#e.emitProgress(e,o),this.#e.logger,this.#e.tracer,this.#e.dlq,r),e.p(this.#e.limits.maxOutputBytes,`output`)],n,{signal:a})}),await e.R(this.#e.emitAudit({requestId:o,operation:`reverse`,metadata:{controller:`file`}}),a,e=>this.#e.trackWork(o,e)),e.B(a),this.#e.endRequest(o)}catch(e){throw this.#e.emitError(e,o),e}}async pack(t,n,r,i={}){let a=this.#e.createOperationSignal(i);e.B(a);let o=this.#e.startRequest();try{await this.#t(t,n,r,a,async(t,n)=>{await e.A(t,[e.p(this.#e.limits.maxInputBytes,`input`),e.b(this.#e.limits.maxFrames),e.h(this.#e.limits.maxFrameBytes,`MessagePack frame`),e.S(),e.v(e.g([])),e.H(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),e.p(this.#e.limits.maxOutputBytes,`output`)],n,{signal:a})}),await e.R(this.#e.emitAudit({requestId:o,operation:`pack`,metadata:{controller:`file`}}),a,e=>this.#e.trackWork(o,e)),e.B(a),this.#e.endRequest(o)}catch(e){throw this.#e.emitError(e,o),e}}async unpack(t,n,i,a={}){let o=this.#e.createOperationSignal(a);e.B(o);let s=this.#e.startRequest();try{await this.#t(t,n,i,o,async(t,n)=>{let i=e.C(this.#e.limits.maxInputBytes),a=e._(e=>{let t=[];if(e.plugins.length!==t.length||e.plugins.some((e,n)=>e!==t[n]))throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);this.#e.emit(`manifest`,e,s)}),c=e.y(),l=new r.Transform({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}});await e.A(t,[e.p(this.#e.limits.maxInputBytes,`input`),e.H(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),i,a,e.b(this.#e.limits.maxFrames),l,c,e.p(this.#e.limits.maxOutputBytes,`output`)],n,{signal:o})}),await e.R(this.#e.emitAudit({requestId:s,operation:`unpack`,metadata:{controller:`file`}}),o,e=>this.#e.trackWork(s,e)),e.B(o),this.#e.endRequest(s)}catch(e){throw this.#e.emitError(e,s),e}}},b=class{#e;constructor(e){this.#e=e}pack(n){try{e.l(n,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let t=e.a.pack(n);if(t.length>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Packed input exceeds configured limit`);if(e.V(t,this.#e.limits.maxFrameBytes,1),t.length>this.#e.limits.maxOutputBytes)throw Error(`[PipeX] Packed output exceeds configured limit`);return t}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:new t.w({stage:`pack`})}}unpack(n){try{if(n.byteLength>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Serialized input exceeds configured limit`);return e.V(n,this.#e.limits.maxFrameBytes,1),e.s.unpack(n)}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:new t.w({stage:`unpack`})}}#t=new WeakMap;async run(t,n={}){let r=this.#e.createOperationSignal(n);e.B(r);let i=e.w(t);e.u(i);let a=this.#e.plugins,o=[...this.#e.pipeline],s=this.#e.limits,c=this.#e.startRequest({operation:`run`}),l=Date.now(),u=this.#e.tracer?.startSpan(`binary:run`,{requestId:c});try{u?.setAttribute(`input.type`,i),this.#e.validate(t),e.l(t,s.maxInputBytes,`Input`);let n=e.N(t);if(n.length>s.maxInputBytes)throw Error(`[PipeX] Input exceeds configured limit`);(i===`object`||i===`array`)&&e.V(n,s.maxFrameBytes,1);let d=Object.create(null);for(let t of a){let a=Date.now(),o=this.#e.tracer?.startSpan(`plugin:${t.name}`,{requestId:c});try{o?.setAttribute(`mode`,`process`);let a=e.O(c,{originalType:i},this.#e.logger,o,r,s);if(n=await e.P(()=>t.process(n,a),t.retryOptions,this.#e.logger,{signal:r,limits:s,track:e=>this.#e.trackWork(c,e)}),!Buffer.isBuffer(n)||n.length>s.maxOutputBytes)throw Error(`[PipeX] Plugin output exceeds configured limit`)}catch(e){throw o?.setAttribute(`error`,!0),e}finally{o?.end()}d[t.name]=Date.now()-a,this.#e.emit(`plugin:after`,t.name,d[t.name])}if(n.length>s.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);e.B(r);let f=Date.now()-l;await e.R(this.#e.emitAudit({requestId:c,operation:`process`,metadata:{inputType:i,durationMs:f}}),r,e=>this.#e.trackWork(c,e)),e.B(r),this.#t.set(n,i);let p={data:n,originalType:i,pipeline:o,metrics:{durationMs:f,steps:d}};return u?.setAttribute(`duration_ms`,f),this.#e.endRequest(c,f),p}catch(e){throw u?.setAttribute(`error`,!0),this.#e.emitError(e,c),e}finally{u?.end(),this.#e.releaseRequest(c)}}async undo(t,n,r={}){let i=Buffer.isBuffer(t),a,o,s;if(i)e.u(n),a=t,o=n,s=r;else{let r=t;if(!r||typeof r!=`object`||!Buffer.isBuffer(r.data)||!Array.isArray(r.pipeline)||r.pipeline.length>256||!r.pipeline.every(e=>typeof e==`string`&&e.length<=512)||!r.metrics||!Number.isFinite(r.metrics.durationMs)||r.metrics.durationMs<0||!r.metrics.steps||typeof r.metrics.steps!=`object`||Array.isArray(r.metrics.steps)||!Object.values(r.metrics.steps).every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0))throw Error(`[PipeX] Invalid EngineResult`);if(e.u(r.originalType),n!==void 0&&(typeof n!=`object`||!n))throw Error(`[PipeX] Invalid undo options`);let i=n,c=i?.expectedType??this.#t.get(r.data);if(c===void 0)throw Error(`[PipeX] Transported EngineResult requires a trusted expectedType`);if(e.u(c),c!==r.originalType)throw Error(`[PipeX] Result type does not match the expected type`);a=r.data,o=c,s=i??{}}let c=this.#e.createOperationSignal(s);e.B(c);let l=this.#e.plugins;e.d(l);let u=this.#e.limits;if(a.length>u.maxInputBytes)throw Error(`[PipeX] Undo input exceeds configured limit`);let d=this.#e.startRequest({operation:`undo`,originalType:o}),f=this.#e.tracer?.startSpan(`binary:undo`,{requestId:d});try{if(i&&l.length===0&&a.length>0){let t;try{t=this.unpackWithManifest(a)}catch{}if(t){if(t.manifest.plugins.length!==0)throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);if(e.w(t.data)!==o)throw Error(`[PipeX] Manifest data does not match the expected type`);a=e.N(t.data)}}for(let t of[...l].reverse()){let n=this.#e.tracer?.startSpan(`plugin:${t.name}`,{requestId:d});try{n?.setAttribute(`mode`,`reverse`);let r=e.O(d,{originalType:o},this.#e.logger,n,c,u);if(a=await e.P(()=>t.reverse(a,r),t.retryOptions,this.#e.logger,{signal:c,limits:u,track:e=>this.#e.trackWork(d,e)}),!Buffer.isBuffer(a)||a.length>u.maxOutputBytes)throw Error(`[PipeX] Plugin output exceeds configured limit`)}catch(e){throw n?.setAttribute(`error`,!0),e}finally{n?.end()}this.#e.emit(`plugin:after`,t.name,0)}if(a.length>u.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);e.B(c);let t=e.T(a,o,u.maxFrameBytes);return this.#e.validate(t),e.B(c),await e.R(this.#e.emitAudit({requestId:d,operation:`reverse`,metadata:{originalType:o}}),c,e=>this.#e.trackWork(d,e)),e.B(c),this.#e.endRequest(d),t}catch(e){throw f?.setAttribute(`error`,!0),this.#e.emitError(e,d),e}finally{f?.end(),this.#e.releaseRequest(d)}}packWithManifest(t){if(this.#e.plugins.length>0)throw Error(`[PipeX] packWithManifest is serialization-only; use binary.run for plugin transforms`);let n=e.g([]);e.l(t,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let r=e.a.pack(n),i=e.a.pack(t);if(e.V(r,this.#e.limits.maxFrameBytes,1),e.V(i,this.#e.limits.maxFrameBytes,1),r.length+i.length>Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxOutputBytes))throw Error(`[PipeX] Serialized input exceeds configured limit`);return Buffer.concat([r,i])}unpackWithManifest(t){if(t.length>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Serialized input exceeds configured limit`);e.V(t,this.#e.limits.maxFrameBytes,2);let n=[];try{e.s.unpackMultiple(t,e=>{if(n.length>=2)throw Error(`[PipeX] Frame count exceeds configured limit`);n.push(e)})}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:Error(`[PipeX] binary.unpackWithManifest: invalid MessagePack input`)}if(n.length<2)throw Error(`[PipeX] binary.unpackWithManifest: buffer contains fewer than 2 frames`);if(!e.U(n[0]))throw Error(`[PipeX] binary.unpackWithManifest: first frame is not a PipeXManifest`);return{manifest:n[0],data:n[1]}}},x=class{#e;constructor(e){this.#e=e}#t(e,t){return{requestId:e,signal:t,track:t=>this.#e.trackWork(e,t),limits:this.#e.limits,logger:this.#e.logger,tracer:this.#e.tracer}}#n(e,t){return r.Duplex.from({writable:e,readable:t})}#r(t,n,i){let a=this.#e.createOperationSignal(i);if(e.B(a),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let o=this.#e.startRequest(),s=this.#t(o,a),c=n?`decompress`:`compress`,l;try{l=e.x(this.#e.plugins,c,n,e=>this.#e.emitProgress(e,o),this.#e.logger,this.#e.tracer,this.#e.dlq,s)}catch(e){throw this.#e.emitError(e,o),e}let u=new r.PassThrough,d,f=new r.Writable({write(e,n,r){if(u.destroyed){let e=t.errored??u.errored;r(e instanceof Error?e:Error(`[PipeX] Stream pipeline is closed`));return}u.write(e,n,r)},final(e){d=e,u.end()},destroy(e,t){d=void 0,u.destroyed||u.destroy(e??void 0),t(e)}}),p=e=>{let t=d;d=void 0,t?t(e):e&&!f.destroyed&&f.destroy(e)};return e.A(u,[e.p(this.#e.limits.maxInputBytes,`input`),...l,e.p(this.#e.limits.maxOutputBytes,`output`)],t,{signal:a}).then(async()=>{await e.R(this.#e.emitAudit({requestId:o,operation:n?`reverse`:`process`,metadata:{controller:`stream`}}),a,e=>this.#e.trackWork(o,e)),e.B(a),this.#e.endRequest(o),p()}).catch(e=>{let t=e instanceof Error?e:Error(String(e));this.#e.emitError(t,o),p(t)}),f}into(e,t={}){return this.#r(e,!1,t)}reverseInto(e,t={}){return this.#r(e,!0,t)}pack(t={}){let n=this.#e.createOperationSignal(t);e.B(n);let i=this.#e.startRequest({operation:`pack`}),a=new r.PassThrough({objectMode:!0}),o=new r.PassThrough,s=[e.b(this.#e.limits.maxFrames),e.h(this.#e.limits.maxFrameBytes,`MessagePack frame`),e.S(),e.v(e.g([])),e.H(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),e.p(this.#e.limits.maxOutputBytes,`output`)],c=this.#n(a,o);return e.A(a,s,o,{signal:n}).then(async()=>{await e.R(this.#e.emitAudit({requestId:i,operation:`pack`,metadata:{controller:`stream`}}),n,e=>this.#e.trackWork(i,e)),e.B(n),this.#e.endRequest(i)}).catch(e=>{this.#e.emitError(e,i),c.destroy(e instanceof Error?e:Error(String(e)))}),c}unpack(t={}){let n=this.#e.createOperationSignal(t);e.B(n);let i=this.#e.startRequest({operation:`unpack`}),a=new r.PassThrough,o=new r.PassThrough({objectMode:!0}),s=e.C(this.#e.limits.maxInputBytes),c=e._(e=>{let t=[];if(e.plugins.length!==t.length||e.plugins.some((e,n)=>e!==t[n]))throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);this.#e.emit(`manifest`,e,i)}),l=new r.Transform({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}}),u=[e.p(this.#e.limits.maxInputBytes,`input`),e.H(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),s,c,e.b(this.#e.limits.maxFrames),l],d=this.#n(a,o);return e.A(a,u,o,{signal:n}).then(async()=>{await e.R(this.#e.emitAudit({requestId:i,operation:`unpack`,metadata:{controller:`stream`}}),n,e=>this.#e.trackWork(i,e)),e.B(n),this.#e.endRequest(i)}).catch(e=>{this.#e.emitError(e,i),d.destroy(e instanceof Error?e:Error(String(e)))}),d}async pipe(t,n,r=!1,i={}){let a=this.#e.createOperationSignal(i);if(e.B(a),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let o=this.#e.startRequest(),s=r?`decompress`:`compress`,c=this.#t(o,a);try{let i=e.x(this.#e.plugins,s,r,e=>this.#e.emitProgress(e,o),this.#e.logger,this.#e.tracer,this.#e.dlq,c);await e.A(t,[e.p(this.#e.limits.maxInputBytes,`input`),...i,e.p(this.#e.limits.maxOutputBytes,`output`)],n,{signal:a}),await e.R(this.#e.emitAudit({requestId:o,operation:r?`reverse`:`process`,metadata:{controller:`stream`}}),a,e=>this.#e.trackWork(o,e)),e.B(a),this.#e.endRequest(o)}catch(e){throw this.#e.emitError(e,o),e}}};const S=2147483647;var C=class r extends o.EventEmitter{static pluginRegistry=new Map;static registerPlugin(e,t){if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(e)||typeof t!=`function`)throw Error(`[PipeX] Invalid plugin registration`);this.pluginRegistry.set(e,e=>new t(e))}static async fromConfig(e){if(!e||typeof e!=`object`)throw Error(`[PipeX] Configuration must be an object`);let t=new r(e.limits);if(e.logger&&t.setLogger(e.logger),e.tracer&&t.setTracer(e.tracer),e.auditLogger&&t.setAuditLogger(e.auditLogger),e.dlq&&t.setDlq(e.dlq),e.schemaRegistry&&t.setSchemaRegistry(e.schemaRegistry),e.schema&&t.setSchema(e.schema),e.plugins){if(!Array.isArray(e.plugins))throw Error(`[PipeX] Configuration plugins must be an array`);for(let n of e.plugins){let e=this.pluginRegistry.get(n.name);if(!e)throw Error(`[PipeX] Unknown plugin in config: ${n.name}`);try{t.use(e(n.options))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[PipeX] Failed to initialize plugin "${n.name}": ${t}`,{cause:e})}}}return t}#e=[];#t=Object.freeze([]);#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=new Map;#d=new Set;#f=new Map;file;binary;stream;constructor(e={}){super(),this.#c=Object.freeze({...t.t,...e}),this.#p(this.#c),this.file=new y(this),this.binary=new b(this),this.stream=new x(this)}#p(e){for(let[t,n]of Object.entries(e))if(!Number.isSafeInteger(n)||n<0)throw Error(`[PipeX] Invalid engine limit ${t}`);if(e.maxInputBytes<1||e.maxOutputBytes<1||e.maxFrameBytes<1||e.maxFrames<1||e.maxConcurrentOperations<1||e.maxRetryAttempts<1||e.maxKmsEncryptedKeyBytes<1||e.maxKmsKeyIdBytes<1)throw Error(`[PipeX] Engine limits must be positive`);if(e.operationTimeoutMs>S||e.maxKmsEncryptedKeyBytes>4294967295)throw Error(`[PipeX] Engine limit exceeds its supported protocol or timer range`)}get limits(){return this.#c}setLimits(e){if(this.#l.size>0)throw Error(`[PipeX] Cannot modify engine limits while operations are active`);let t={...this.#c,...e};return this.#p(t),this.#c=Object.freeze(t),this}createOperationSignal(t={}){let n=t.timeoutMs??this.#c.operationTimeoutMs;if(!Number.isSafeInteger(n)||n<0||n>S)throw Error(`[PipeX] Invalid operation timeout`);let r=t.signal?[t.signal]:[];n>0&&r.push(AbortSignal.timeout(n));let i=r.length===0?new AbortController().signal:AbortSignal.any(r);return e.z(i,n),i}setDlq(e){if(!e||typeof e.write!=`function`)throw Error(`[PipeX] DLQ must be a writable stream`);return this.#o=e,this}get dlq(){return this.#o}setLogger(t){if(!t||![`info`,`warn`,`error`,`debug`].every(e=>typeof t[e]==`function`))throw Error(`[PipeX] Logger must implement info, warn, error, and debug`);return this.#i=e.I(t),this}get logger(){return this.#i}setTracer(t){if(!t||typeof t.startSpan!=`function`)throw Error(`[PipeX] Tracer must implement startSpan`);return this.#a=e.L(t),this}get tracer(){return this.#a}setAuditLogger(e){if(!e||typeof e.log!=`function`)throw Error(`[PipeX] Audit logger must implement log`);return this.#s=e,this}async emitAudit(e){this.#s&&await this.#s.log({...e,pluginChain:e.operation===`pack`||e.operation===`unpack`?[]:[...this.#f.get(e.requestId)??this.pipeline],timestamp:Date.now()})}setSchemaRegistry(e){if(!e||typeof e.getSchema!=`function`)throw Error(`[PipeX] Schema registry must implement getSchema`);return this.#r=e,this}async loadSchema(e,t){if(!this.#r)throw Error(`[PipeX] No Schema Registry configured`);let n=await this.#r.getSchema(e,t);this.setSchema(n)}setSchema(e){if(!e||typeof e.safeParse!=`function`)throw Error(`[PipeX] Schema must implement safeParse`);return this.#n=e,this}get schema(){return this.#n}validate(e){if(this.#n&&!this.#n.safeParse(e).success)throw Error(`[PipeX] Core Validation failed`)}use(t){if(!t||typeof t.name!=`string`||t.name.length===0||t.name.length>128||typeof t.version!=`string`||t.version.length===0||typeof t.process!=`function`)throw Error(`[PipeX] Invalid processor plugin`);if(e.E(t),this.#l.size>0)throw Error(`[PipeX] Cannot modify the plugin pipeline while operations are active`);if(this.#e.length>=256)throw Error(`[PipeX] Maximum plugin count exceeded`);return this.#e.push(t),this.#t=Object.freeze([...this.#e]),this}get plugins(){return this.#t}get pipeline(){return Object.freeze(this.#t.map(e=>`${e.name}@${e.version}`))}get pluginCapabilities(){return Object.freeze(this.#t.map(t=>Object.freeze({plugin:`${t.name}@${t.version}`,...e.E(t)})))}startRequest(e={}){if(this.#l.size>=this.#c.maxConcurrentOperations)throw Error(`[PipeX] Maximum concurrent operations exceeded`);let t=(0,n.randomUUID)();this.#l.add(t),this.#f.set(t,this.pipeline);try{this.#i?.info(`[PipeX] Request started`,{requestId:t,...e})}catch{}return this.emit(`start`,t),t}trackWork(e,t){let n=this.#u.get(e);n||this.#u.set(e,n=new Set),n.add(t);let r=()=>{n.delete(t),n.size===0&&(this.#u.delete(e),this.#d.has(e)&&this.releaseRequest(e))};t.then(r,r)}releaseRequest(e){if(this.#u.get(e)?.size){this.#d.add(e);return}this.#l.delete(e),this.#d.delete(e),this.#f.delete(e)}endRequest(e,t){this.releaseRequest(e);try{this.#i?.info(`[PipeX] Request ended`,{requestId:e,durationMs:t})}catch{}this.emit(`end`,e,t)}emitProgress(e,t){this.emit(`progress`,e,t)}emitError(e,t){let n=e instanceof Error?e:Error(String(e));this.releaseRequest(t);try{this.#i?.error(`[PipeX] Request failed`,{requestId:t,error:n.message})}catch{}this.listenerCount(`error`)>0&&this.emit(`error`,n,t)}emit(t,...n){let r=this.rawListeners(t);for(let t of r)e.F(()=>Reflect.apply(t,this,n));return r.length>0}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return C}});
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { f as Logger, i as EngineConfig, m as PipeXManifest, n as AuditRecord, o as EngineLimits, p as OperationOptions, r as BinaryUndoOptions, s as EngineResult, t as AuditLogger, v as ProcessorPlugin, w as Tracer, x as SchemaRegistry, y as RegisteredPluginCapabilities } from "./types-ia4x-Dvp.cjs";
|
|
2
|
+
import { Duplex, Readable, Writable } from "node:stream";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
|
|
6
|
+
//#region src/core/controllers/FileController.d.ts
|
|
7
|
+
declare class FileController {
|
|
8
|
+
#private;
|
|
9
|
+
constructor(engine: DataEngine);
|
|
10
|
+
/**
|
|
11
|
+
* Source file → Plugin pipeline (compress) → Destination file.
|
|
12
|
+
*/
|
|
13
|
+
process(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Source file → Plugin pipeline (decompress, reversed) → Destination file.
|
|
16
|
+
*/
|
|
17
|
+
reverse(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Source file → PackrStream → manifest header → Destination msgpack file.
|
|
20
|
+
*
|
|
21
|
+
* Output format: [ PipeXManifest frame ][ ...data frames ]
|
|
22
|
+
* The serialization-only manifest declares an empty plugin chain.
|
|
23
|
+
*/
|
|
24
|
+
pack(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Source msgpack file → UnpackrStream → manifest extraction → NDJSON → Destination file.
|
|
27
|
+
*
|
|
28
|
+
* Fires 'manifest' event with the recovered PipeXManifest before streaming data.
|
|
29
|
+
*/
|
|
30
|
+
unpack(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/core/controllers/BinaryController.d.ts
|
|
34
|
+
declare class BinaryController {
|
|
35
|
+
#private;
|
|
36
|
+
constructor(engine: DataEngine);
|
|
37
|
+
/**
|
|
38
|
+
* Serialise a supported JS value to a msgpack Buffer (synchronous).
|
|
39
|
+
* For streaming large datasets use engine.stream or engine.file.pack instead.
|
|
40
|
+
*/
|
|
41
|
+
pack(data: unknown): Buffer;
|
|
42
|
+
/**
|
|
43
|
+
* Deserialise a msgpack Buffer back to T (synchronous).
|
|
44
|
+
*/
|
|
45
|
+
unpack<T = unknown>(input: Buffer | Uint8Array): T;
|
|
46
|
+
run(input: unknown, options?: OperationOptions): Promise<EngineResult>;
|
|
47
|
+
undo<T = unknown>(result: EngineResult, options?: BinaryUndoOptions): Promise<T>;
|
|
48
|
+
undo<T = unknown>(input: Buffer, forceType: string, options?: OperationOptions): Promise<T>;
|
|
49
|
+
/**
|
|
50
|
+
* Pack data AND embed a manifest header as the first msgpack frame.
|
|
51
|
+
* Mirrors what file.pack writes to disk — useful for in-memory transport.
|
|
52
|
+
*/
|
|
53
|
+
packWithManifest(data: unknown): Buffer;
|
|
54
|
+
/**
|
|
55
|
+
* Unpack a buffer that begins with a PipeXManifest frame.
|
|
56
|
+
* Returns { manifest, data } — callers can inspect the manifest to verify
|
|
57
|
+
* the pipeline that produced the buffer before consuming data.
|
|
58
|
+
*/
|
|
59
|
+
unpackWithManifest<T = unknown>(input: Buffer): {
|
|
60
|
+
manifest: PipeXManifest;
|
|
61
|
+
data: T;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/core/controllers/StreamController.d.ts
|
|
66
|
+
declare class StreamController {
|
|
67
|
+
#private;
|
|
68
|
+
constructor(engine: DataEngine);
|
|
69
|
+
/**
|
|
70
|
+
* Returns a Writable that pumps incoming bytes through the plugin pipeline
|
|
71
|
+
* (compress direction) and forwards them to `destination`.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* await pipeline(readableSource, engine.stream.into(createWriteStream('out')));
|
|
75
|
+
*/
|
|
76
|
+
into(destination: Writable, options?: OperationOptions): Writable;
|
|
77
|
+
/**
|
|
78
|
+
* Returns a Writable that pumps bytes through the reversed plugin pipeline
|
|
79
|
+
* (decompress direction) and forwards to `destination`.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* await pipeline(readableSource, engine.stream.reverseInto(createWriteStream('restored')));
|
|
83
|
+
*/
|
|
84
|
+
reverseInto(destination: Writable, options?: OperationOptions): Writable;
|
|
85
|
+
/**
|
|
86
|
+
* Returns a PackrStream: write JS objects, read msgpack bytes.
|
|
87
|
+
* A manifest header frame is prepended automatically.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* await pipeline(objectSource, engine.stream.pack(), tcpSocket);
|
|
91
|
+
*/
|
|
92
|
+
pack(options?: OperationOptions): Duplex;
|
|
93
|
+
/**
|
|
94
|
+
* Returns a GuardedUnpackrStream: write msgpack bytes, read JS objects.
|
|
95
|
+
* Fires the engine's 'manifest' event when the header frame is detected.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* await pipeline(tcpSocket, engine.stream.unpack(), objectDestination);
|
|
99
|
+
*/
|
|
100
|
+
unpack(options?: OperationOptions): Duplex;
|
|
101
|
+
/**
|
|
102
|
+
* Orchestrate a complete pipeline: Readable → plugin chain → Writable.
|
|
103
|
+
* This is the primary low-level entry point — file/binary controllers
|
|
104
|
+
* build on top of this.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* await engine.stream.pipe(
|
|
108
|
+
* createReadStream('input.bin'),
|
|
109
|
+
* createWriteStream('output.bin'),
|
|
110
|
+
* );
|
|
111
|
+
*/
|
|
112
|
+
pipe(source: Readable, destination: Writable, reverse?: boolean, options?: OperationOptions): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
//#region src/core/dataEngine.d.ts
|
|
116
|
+
interface PipeXEventMap {
|
|
117
|
+
start: [requestId: string];
|
|
118
|
+
'plugin:after': [name: string, durationMs: number];
|
|
119
|
+
progress: [bytes: number, requestId: string];
|
|
120
|
+
error: [err: Error, requestId: string];
|
|
121
|
+
end: [requestId: string, durationMs?: number];
|
|
122
|
+
manifest: [manifest: unknown, requestId?: string];
|
|
123
|
+
}
|
|
124
|
+
type PluginConstructor<TOptions = unknown> = new (options: TOptions) => ProcessorPlugin;
|
|
125
|
+
declare class DataEngine extends EventEmitter {
|
|
126
|
+
#private;
|
|
127
|
+
/** Built-in plugin registry for config-driven bootstrap. */
|
|
128
|
+
private static readonly pluginRegistry;
|
|
129
|
+
/** Register a plugin class for use in fromConfig(). */
|
|
130
|
+
static registerPlugin<TOptions>(name: string, pluginClass: PluginConstructor<TOptions>): void;
|
|
131
|
+
/**
|
|
132
|
+
* Bootstrap a DataEngine from a configuration object.
|
|
133
|
+
*/
|
|
134
|
+
static fromConfig(config: EngineConfig): Promise<DataEngine>;
|
|
135
|
+
readonly file: FileController;
|
|
136
|
+
readonly binary: BinaryController;
|
|
137
|
+
readonly stream: StreamController;
|
|
138
|
+
constructor(limits?: Partial<EngineLimits>);
|
|
139
|
+
get limits(): Readonly<EngineLimits>;
|
|
140
|
+
setLimits(limits: Partial<EngineLimits>): this;
|
|
141
|
+
createOperationSignal(options?: OperationOptions): AbortSignal;
|
|
142
|
+
/**
|
|
143
|
+
* Set the optional, caller-owned failure sink (legacy DLQ terminology).
|
|
144
|
+
* A failed fallback-transform chunk is written after retries are exhausted;
|
|
145
|
+
* the operation still rejects. PipeX does not persist, replay, end, or own
|
|
146
|
+
* the supplied Writable.
|
|
147
|
+
*
|
|
148
|
+
* @param stream The caller-provided Writable used as a failure sink.
|
|
149
|
+
*/
|
|
150
|
+
setDlq(stream: Writable): this;
|
|
151
|
+
/** The current caller-provided failure sink, if any. */
|
|
152
|
+
get dlq(): Writable | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* Set the engine's logger for structured observability.
|
|
155
|
+
* Compatible with Pino, Winston, or any logger implementing the Logger interface.
|
|
156
|
+
*
|
|
157
|
+
* @param logger The logger instance.
|
|
158
|
+
*/
|
|
159
|
+
setLogger(logger: Logger): this;
|
|
160
|
+
/** The current logger instance. */
|
|
161
|
+
get logger(): Logger | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* Set the engine's tracer for OpenTelemetry-compatible tracing.
|
|
164
|
+
*
|
|
165
|
+
* @param tracer The tracer instance.
|
|
166
|
+
*/
|
|
167
|
+
setTracer(tracer: Tracer): this;
|
|
168
|
+
/** The current tracer instance. */
|
|
169
|
+
get tracer(): Tracer | undefined;
|
|
170
|
+
/**
|
|
171
|
+
* Set the engine's audit logger for compliance and security auditing.
|
|
172
|
+
*
|
|
173
|
+
* @param logger The audit logger instance.
|
|
174
|
+
*/
|
|
175
|
+
setAuditLogger(logger: AuditLogger): this;
|
|
176
|
+
/**
|
|
177
|
+
* Emits an audit record if an audit logger is configured.
|
|
178
|
+
* This is called automatically by controllers.
|
|
179
|
+
*
|
|
180
|
+
* @param record The audit record metadata.
|
|
181
|
+
*/
|
|
182
|
+
emitAudit(record: Omit<AuditRecord, 'pluginChain' | 'timestamp'>): Promise<void>;
|
|
183
|
+
/**
|
|
184
|
+
* Set a Schema Registry to fetch schemas dynamically.
|
|
185
|
+
*
|
|
186
|
+
* @param registry The schema registry provider.
|
|
187
|
+
*/
|
|
188
|
+
setSchemaRegistry(registry: SchemaRegistry): this;
|
|
189
|
+
/**
|
|
190
|
+
* Fetch a schema from the registry and set it as the engine's active schema.
|
|
191
|
+
*
|
|
192
|
+
* @param subject The name of the schema to fetch.
|
|
193
|
+
* @param version Optional version of the schema.
|
|
194
|
+
*/
|
|
195
|
+
loadSchema(subject: string, version?: number): Promise<void>;
|
|
196
|
+
/**
|
|
197
|
+
* Set a global Zod schema for input/output validation.
|
|
198
|
+
* When set, controllers will automatically validate data against this schema.
|
|
199
|
+
*/
|
|
200
|
+
setSchema(schema: z.ZodType<any>): this;
|
|
201
|
+
get schema(): z.ZodType<any> | undefined;
|
|
202
|
+
/** Validates data against the registered schema (if any). Throws on failure. */
|
|
203
|
+
validate(data: unknown): void;
|
|
204
|
+
/** Register a plugin and return this for fluent chaining. */
|
|
205
|
+
use(plugin: ProcessorPlugin): this;
|
|
206
|
+
/**
|
|
207
|
+
* Read-only view of the registered plugins.
|
|
208
|
+
* Exposed so controllers can iterate without mutating the list.
|
|
209
|
+
*/
|
|
210
|
+
get plugins(): readonly ProcessorPlugin[];
|
|
211
|
+
/** Human-readable plugin identifiers in execution order. */
|
|
212
|
+
get pipeline(): readonly string[];
|
|
213
|
+
/** Runtime-validated capabilities in pipeline order. */
|
|
214
|
+
get pluginCapabilities(): readonly Readonly<RegisteredPluginCapabilities>[];
|
|
215
|
+
/** Generates a requestId, emits 'start', returns the id. */
|
|
216
|
+
startRequest(metadata?: Record<string, unknown>): string;
|
|
217
|
+
/** Keep capacity reserved for accepted non-cooperative work after caller cancellation. */
|
|
218
|
+
trackWork(requestId: string, pending: Promise<unknown>): void;
|
|
219
|
+
/** Idempotent cleanup, including error paths that fail before transformation starts. */
|
|
220
|
+
releaseRequest(requestId: string): void;
|
|
221
|
+
/** Emits 'end' with optional duration. */
|
|
222
|
+
endRequest(requestId: string, durationMs?: number): void;
|
|
223
|
+
/** Emits 'progress'. */
|
|
224
|
+
emitProgress(bytes: number, requestId: string): void;
|
|
225
|
+
/** Normalises unknown throws → Error and emits 'error'. */
|
|
226
|
+
emitError(err: unknown, requestId: string): void;
|
|
227
|
+
emit<K extends keyof PipeXEventMap>(event: K, ...args: PipeXEventMap[K]): boolean;
|
|
228
|
+
on<K extends keyof PipeXEventMap>(event: K, listener: (...args: PipeXEventMap[K]) => void): this;
|
|
229
|
+
once<K extends keyof PipeXEventMap>(event: K, listener: (...args: PipeXEventMap[K]) => void): this;
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
export { PluginConstructor as n, DataEngine as t };
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { f as Logger, i as EngineConfig, m as PipeXManifest, n as AuditRecord, o as EngineLimits, p as OperationOptions, r as BinaryUndoOptions, s as EngineResult, t as AuditLogger, v as ProcessorPlugin, w as Tracer, x as SchemaRegistry, y as RegisteredPluginCapabilities } from "./types-Bytga6zd.mjs";
|
|
2
|
+
import { Duplex, Readable, Writable } from "node:stream";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
|
|
6
|
+
//#region src/core/controllers/FileController.d.ts
|
|
7
|
+
declare class FileController {
|
|
8
|
+
#private;
|
|
9
|
+
constructor(engine: DataEngine);
|
|
10
|
+
/**
|
|
11
|
+
* Source file → Plugin pipeline (compress) → Destination file.
|
|
12
|
+
*/
|
|
13
|
+
process(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Source file → Plugin pipeline (decompress, reversed) → Destination file.
|
|
16
|
+
*/
|
|
17
|
+
reverse(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Source file → PackrStream → manifest header → Destination msgpack file.
|
|
20
|
+
*
|
|
21
|
+
* Output format: [ PipeXManifest frame ][ ...data frames ]
|
|
22
|
+
* The serialization-only manifest declares an empty plugin chain.
|
|
23
|
+
*/
|
|
24
|
+
pack(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Source msgpack file → UnpackrStream → manifest extraction → NDJSON → Destination file.
|
|
27
|
+
*
|
|
28
|
+
* Fires 'manifest' event with the recovered PipeXManifest before streaming data.
|
|
29
|
+
*/
|
|
30
|
+
unpack(inputPath: string, outputPath: string, allowedRoot?: string, options?: OperationOptions): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/core/controllers/BinaryController.d.ts
|
|
34
|
+
declare class BinaryController {
|
|
35
|
+
#private;
|
|
36
|
+
constructor(engine: DataEngine);
|
|
37
|
+
/**
|
|
38
|
+
* Serialise a supported JS value to a msgpack Buffer (synchronous).
|
|
39
|
+
* For streaming large datasets use engine.stream or engine.file.pack instead.
|
|
40
|
+
*/
|
|
41
|
+
pack(data: unknown): Buffer;
|
|
42
|
+
/**
|
|
43
|
+
* Deserialise a msgpack Buffer back to T (synchronous).
|
|
44
|
+
*/
|
|
45
|
+
unpack<T = unknown>(input: Buffer | Uint8Array): T;
|
|
46
|
+
run(input: unknown, options?: OperationOptions): Promise<EngineResult>;
|
|
47
|
+
undo<T = unknown>(result: EngineResult, options?: BinaryUndoOptions): Promise<T>;
|
|
48
|
+
undo<T = unknown>(input: Buffer, forceType: string, options?: OperationOptions): Promise<T>;
|
|
49
|
+
/**
|
|
50
|
+
* Pack data AND embed a manifest header as the first msgpack frame.
|
|
51
|
+
* Mirrors what file.pack writes to disk — useful for in-memory transport.
|
|
52
|
+
*/
|
|
53
|
+
packWithManifest(data: unknown): Buffer;
|
|
54
|
+
/**
|
|
55
|
+
* Unpack a buffer that begins with a PipeXManifest frame.
|
|
56
|
+
* Returns { manifest, data } — callers can inspect the manifest to verify
|
|
57
|
+
* the pipeline that produced the buffer before consuming data.
|
|
58
|
+
*/
|
|
59
|
+
unpackWithManifest<T = unknown>(input: Buffer): {
|
|
60
|
+
manifest: PipeXManifest;
|
|
61
|
+
data: T;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/core/controllers/StreamController.d.ts
|
|
66
|
+
declare class StreamController {
|
|
67
|
+
#private;
|
|
68
|
+
constructor(engine: DataEngine);
|
|
69
|
+
/**
|
|
70
|
+
* Returns a Writable that pumps incoming bytes through the plugin pipeline
|
|
71
|
+
* (compress direction) and forwards them to `destination`.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* await pipeline(readableSource, engine.stream.into(createWriteStream('out')));
|
|
75
|
+
*/
|
|
76
|
+
into(destination: Writable, options?: OperationOptions): Writable;
|
|
77
|
+
/**
|
|
78
|
+
* Returns a Writable that pumps bytes through the reversed plugin pipeline
|
|
79
|
+
* (decompress direction) and forwards to `destination`.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* await pipeline(readableSource, engine.stream.reverseInto(createWriteStream('restored')));
|
|
83
|
+
*/
|
|
84
|
+
reverseInto(destination: Writable, options?: OperationOptions): Writable;
|
|
85
|
+
/**
|
|
86
|
+
* Returns a PackrStream: write JS objects, read msgpack bytes.
|
|
87
|
+
* A manifest header frame is prepended automatically.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* await pipeline(objectSource, engine.stream.pack(), tcpSocket);
|
|
91
|
+
*/
|
|
92
|
+
pack(options?: OperationOptions): Duplex;
|
|
93
|
+
/**
|
|
94
|
+
* Returns a GuardedUnpackrStream: write msgpack bytes, read JS objects.
|
|
95
|
+
* Fires the engine's 'manifest' event when the header frame is detected.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* await pipeline(tcpSocket, engine.stream.unpack(), objectDestination);
|
|
99
|
+
*/
|
|
100
|
+
unpack(options?: OperationOptions): Duplex;
|
|
101
|
+
/**
|
|
102
|
+
* Orchestrate a complete pipeline: Readable → plugin chain → Writable.
|
|
103
|
+
* This is the primary low-level entry point — file/binary controllers
|
|
104
|
+
* build on top of this.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* await engine.stream.pipe(
|
|
108
|
+
* createReadStream('input.bin'),
|
|
109
|
+
* createWriteStream('output.bin'),
|
|
110
|
+
* );
|
|
111
|
+
*/
|
|
112
|
+
pipe(source: Readable, destination: Writable, reverse?: boolean, options?: OperationOptions): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
//#region src/core/dataEngine.d.ts
|
|
116
|
+
interface PipeXEventMap {
|
|
117
|
+
start: [requestId: string];
|
|
118
|
+
'plugin:after': [name: string, durationMs: number];
|
|
119
|
+
progress: [bytes: number, requestId: string];
|
|
120
|
+
error: [err: Error, requestId: string];
|
|
121
|
+
end: [requestId: string, durationMs?: number];
|
|
122
|
+
manifest: [manifest: unknown, requestId?: string];
|
|
123
|
+
}
|
|
124
|
+
type PluginConstructor<TOptions = unknown> = new (options: TOptions) => ProcessorPlugin;
|
|
125
|
+
declare class DataEngine extends EventEmitter {
|
|
126
|
+
#private;
|
|
127
|
+
/** Built-in plugin registry for config-driven bootstrap. */
|
|
128
|
+
private static readonly pluginRegistry;
|
|
129
|
+
/** Register a plugin class for use in fromConfig(). */
|
|
130
|
+
static registerPlugin<TOptions>(name: string, pluginClass: PluginConstructor<TOptions>): void;
|
|
131
|
+
/**
|
|
132
|
+
* Bootstrap a DataEngine from a configuration object.
|
|
133
|
+
*/
|
|
134
|
+
static fromConfig(config: EngineConfig): Promise<DataEngine>;
|
|
135
|
+
readonly file: FileController;
|
|
136
|
+
readonly binary: BinaryController;
|
|
137
|
+
readonly stream: StreamController;
|
|
138
|
+
constructor(limits?: Partial<EngineLimits>);
|
|
139
|
+
get limits(): Readonly<EngineLimits>;
|
|
140
|
+
setLimits(limits: Partial<EngineLimits>): this;
|
|
141
|
+
createOperationSignal(options?: OperationOptions): AbortSignal;
|
|
142
|
+
/**
|
|
143
|
+
* Set the optional, caller-owned failure sink (legacy DLQ terminology).
|
|
144
|
+
* A failed fallback-transform chunk is written after retries are exhausted;
|
|
145
|
+
* the operation still rejects. PipeX does not persist, replay, end, or own
|
|
146
|
+
* the supplied Writable.
|
|
147
|
+
*
|
|
148
|
+
* @param stream The caller-provided Writable used as a failure sink.
|
|
149
|
+
*/
|
|
150
|
+
setDlq(stream: Writable): this;
|
|
151
|
+
/** The current caller-provided failure sink, if any. */
|
|
152
|
+
get dlq(): Writable | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* Set the engine's logger for structured observability.
|
|
155
|
+
* Compatible with Pino, Winston, or any logger implementing the Logger interface.
|
|
156
|
+
*
|
|
157
|
+
* @param logger The logger instance.
|
|
158
|
+
*/
|
|
159
|
+
setLogger(logger: Logger): this;
|
|
160
|
+
/** The current logger instance. */
|
|
161
|
+
get logger(): Logger | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* Set the engine's tracer for OpenTelemetry-compatible tracing.
|
|
164
|
+
*
|
|
165
|
+
* @param tracer The tracer instance.
|
|
166
|
+
*/
|
|
167
|
+
setTracer(tracer: Tracer): this;
|
|
168
|
+
/** The current tracer instance. */
|
|
169
|
+
get tracer(): Tracer | undefined;
|
|
170
|
+
/**
|
|
171
|
+
* Set the engine's audit logger for compliance and security auditing.
|
|
172
|
+
*
|
|
173
|
+
* @param logger The audit logger instance.
|
|
174
|
+
*/
|
|
175
|
+
setAuditLogger(logger: AuditLogger): this;
|
|
176
|
+
/**
|
|
177
|
+
* Emits an audit record if an audit logger is configured.
|
|
178
|
+
* This is called automatically by controllers.
|
|
179
|
+
*
|
|
180
|
+
* @param record The audit record metadata.
|
|
181
|
+
*/
|
|
182
|
+
emitAudit(record: Omit<AuditRecord, 'pluginChain' | 'timestamp'>): Promise<void>;
|
|
183
|
+
/**
|
|
184
|
+
* Set a Schema Registry to fetch schemas dynamically.
|
|
185
|
+
*
|
|
186
|
+
* @param registry The schema registry provider.
|
|
187
|
+
*/
|
|
188
|
+
setSchemaRegistry(registry: SchemaRegistry): this;
|
|
189
|
+
/**
|
|
190
|
+
* Fetch a schema from the registry and set it as the engine's active schema.
|
|
191
|
+
*
|
|
192
|
+
* @param subject The name of the schema to fetch.
|
|
193
|
+
* @param version Optional version of the schema.
|
|
194
|
+
*/
|
|
195
|
+
loadSchema(subject: string, version?: number): Promise<void>;
|
|
196
|
+
/**
|
|
197
|
+
* Set a global Zod schema for input/output validation.
|
|
198
|
+
* When set, controllers will automatically validate data against this schema.
|
|
199
|
+
*/
|
|
200
|
+
setSchema(schema: z.ZodType<any>): this;
|
|
201
|
+
get schema(): z.ZodType<any> | undefined;
|
|
202
|
+
/** Validates data against the registered schema (if any). Throws on failure. */
|
|
203
|
+
validate(data: unknown): void;
|
|
204
|
+
/** Register a plugin and return this for fluent chaining. */
|
|
205
|
+
use(plugin: ProcessorPlugin): this;
|
|
206
|
+
/**
|
|
207
|
+
* Read-only view of the registered plugins.
|
|
208
|
+
* Exposed so controllers can iterate without mutating the list.
|
|
209
|
+
*/
|
|
210
|
+
get plugins(): readonly ProcessorPlugin[];
|
|
211
|
+
/** Human-readable plugin identifiers in execution order. */
|
|
212
|
+
get pipeline(): readonly string[];
|
|
213
|
+
/** Runtime-validated capabilities in pipeline order. */
|
|
214
|
+
get pluginCapabilities(): readonly Readonly<RegisteredPluginCapabilities>[];
|
|
215
|
+
/** Generates a requestId, emits 'start', returns the id. */
|
|
216
|
+
startRequest(metadata?: Record<string, unknown>): string;
|
|
217
|
+
/** Keep capacity reserved for accepted non-cooperative work after caller cancellation. */
|
|
218
|
+
trackWork(requestId: string, pending: Promise<unknown>): void;
|
|
219
|
+
/** Idempotent cleanup, including error paths that fail before transformation starts. */
|
|
220
|
+
releaseRequest(requestId: string): void;
|
|
221
|
+
/** Emits 'end' with optional duration. */
|
|
222
|
+
endRequest(requestId: string, durationMs?: number): void;
|
|
223
|
+
/** Emits 'progress'. */
|
|
224
|
+
emitProgress(bytes: number, requestId: string): void;
|
|
225
|
+
/** Normalises unknown throws → Error and emits 'error'. */
|
|
226
|
+
emitError(err: unknown, requestId: string): void;
|
|
227
|
+
emit<K extends keyof PipeXEventMap>(event: K, ...args: PipeXEventMap[K]): boolean;
|
|
228
|
+
on<K extends keyof PipeXEventMap>(event: K, listener: (...args: PipeXEventMap[K]) => void): this;
|
|
229
|
+
once<K extends keyof PipeXEventMap>(event: K, listener: (...args: PipeXEventMap[K]) => void): this;
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
export { PluginConstructor as n, DataEngine as t };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { C as StreamPluginContext, _ as ProcessorContext } from "./types-ia4x-Dvp.cjs";
|
|
2
|
+
import { t as BasePlugin } from "./plugin-C9Kd9coY.cjs";
|
|
3
|
+
import { Transform } from "node:stream";
|
|
4
|
+
|
|
5
|
+
//#region src/plugin/encryptionFormat.d.ts
|
|
6
|
+
type EncryptionAlgorithm = 'aes-256-gcm' | 'chacha20-poly1305';
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/plugin/encryption.d.ts
|
|
9
|
+
/** Shared authenticated-encryption settings. */
|
|
10
|
+
interface EncryptionCommonOptions {
|
|
11
|
+
/** Secret 32-byte encryption key; length is enforced at runtime. */
|
|
12
|
+
readonly key: Buffer;
|
|
13
|
+
/** Maximum plaintext bytes per authenticated frame (default 64 KiB). */
|
|
14
|
+
readonly frameSizeBytes?: number;
|
|
15
|
+
/** Allow reading old records only during an explicit migration. */
|
|
16
|
+
readonly allowLegacyDecrypt?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** AES-256-GCM configuration. */
|
|
19
|
+
interface Aes256GcmOptions extends EncryptionCommonOptions {
|
|
20
|
+
readonly algorithm: 'aes-256-gcm';
|
|
21
|
+
}
|
|
22
|
+
/** ChaCha20-Poly1305 configuration. */
|
|
23
|
+
interface ChaCha20Poly1305Options extends EncryptionCommonOptions {
|
|
24
|
+
readonly algorithm: 'chacha20-poly1305';
|
|
25
|
+
}
|
|
26
|
+
/** Algorithm-discriminated encryption settings. */
|
|
27
|
+
type EncryptionOptions = Aes256GcmOptions | ChaCha20Poly1305Options;
|
|
28
|
+
/**
|
|
29
|
+
* Authenticated, bounded-memory stream encryption.
|
|
30
|
+
*
|
|
31
|
+
* Version 4 writes the versioned PXAE framed format. The legacy unversioned
|
|
32
|
+
* format can be explicitly enabled for migration, but is never written.
|
|
33
|
+
*/
|
|
34
|
+
declare class EncryptionPlugin extends BasePlugin {
|
|
35
|
+
protected options: EncryptionOptions;
|
|
36
|
+
readonly name = "encryption";
|
|
37
|
+
readonly version = "4.0.0";
|
|
38
|
+
constructor(options: EncryptionOptions);
|
|
39
|
+
process(data: Buffer, context: ProcessorContext): Promise<Buffer>;
|
|
40
|
+
reverse(data: Buffer, context: ProcessorContext): Promise<Buffer>;
|
|
41
|
+
createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Transform;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { EncryptionPlugin as a, EncryptionOptions as i, ChaCha20Poly1305Options as n, EncryptionAlgorithm as o, EncryptionCommonOptions as r, Aes256GcmOptions as t };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { C as StreamPluginContext, _ as ProcessorContext } from "./types-Bytga6zd.mjs";
|
|
2
|
+
import { t as BasePlugin } from "./plugin-CE94-p8P.mjs";
|
|
3
|
+
import { Transform } from "node:stream";
|
|
4
|
+
|
|
5
|
+
//#region src/plugin/encryptionFormat.d.ts
|
|
6
|
+
type EncryptionAlgorithm = 'aes-256-gcm' | 'chacha20-poly1305';
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/plugin/encryption.d.ts
|
|
9
|
+
/** Shared authenticated-encryption settings. */
|
|
10
|
+
interface EncryptionCommonOptions {
|
|
11
|
+
/** Secret 32-byte encryption key; length is enforced at runtime. */
|
|
12
|
+
readonly key: Buffer;
|
|
13
|
+
/** Maximum plaintext bytes per authenticated frame (default 64 KiB). */
|
|
14
|
+
readonly frameSizeBytes?: number;
|
|
15
|
+
/** Allow reading old records only during an explicit migration. */
|
|
16
|
+
readonly allowLegacyDecrypt?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** AES-256-GCM configuration. */
|
|
19
|
+
interface Aes256GcmOptions extends EncryptionCommonOptions {
|
|
20
|
+
readonly algorithm: 'aes-256-gcm';
|
|
21
|
+
}
|
|
22
|
+
/** ChaCha20-Poly1305 configuration. */
|
|
23
|
+
interface ChaCha20Poly1305Options extends EncryptionCommonOptions {
|
|
24
|
+
readonly algorithm: 'chacha20-poly1305';
|
|
25
|
+
}
|
|
26
|
+
/** Algorithm-discriminated encryption settings. */
|
|
27
|
+
type EncryptionOptions = Aes256GcmOptions | ChaCha20Poly1305Options;
|
|
28
|
+
/**
|
|
29
|
+
* Authenticated, bounded-memory stream encryption.
|
|
30
|
+
*
|
|
31
|
+
* Version 4 writes the versioned PXAE framed format. The legacy unversioned
|
|
32
|
+
* format can be explicitly enabled for migration, but is never written.
|
|
33
|
+
*/
|
|
34
|
+
declare class EncryptionPlugin extends BasePlugin {
|
|
35
|
+
protected options: EncryptionOptions;
|
|
36
|
+
readonly name = "encryption";
|
|
37
|
+
readonly version = "4.0.0";
|
|
38
|
+
constructor(options: EncryptionOptions);
|
|
39
|
+
process(data: Buffer, context: ProcessorContext): Promise<Buffer>;
|
|
40
|
+
reverse(data: Buffer, context: ProcessorContext): Promise<Buffer>;
|
|
41
|
+
createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Transform;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { EncryptionPlugin as a, EncryptionOptions as i, ChaCha20Poly1305Options as n, EncryptionAlgorithm as o, EncryptionCommonOptions as r, Aes256GcmOptions as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,b as t,i as n,l as r,n as i,r as a,s as o,t as s}from"./resourceLimits-C1HHDwXQ.mjs";import{createCipheriv as c,createDecipheriv as l,hkdfSync as u,randomBytes as d}from"node:crypto";import{Transform as f}from"node:stream";const p=Buffer.from(`PXAE`),m={"aes-256-gcm":1,"chacha20-poly1305":2},h={1:`aes-256-gcm`,2:`chacha20-poly1305`};function g(e){if(!Buffer.isBuffer(e)||e.length!==32)throw new r}function _(e){return{maxInputBytes:i(e),maxOutputBytes:a(e),maxFrameBytes:e?.limits?.maxFrameBytes??s.maxFrameBytes,maxFrames:e?.limits?.maxFrames??s.maxFrames}}function v(e,t){let n=t.maxFrameBytes-29;if(n<1||t.maxFrameBytes<28)throw Error(`[PipeX] Encryption frame limit ${t.maxFrameBytes} bytes is too small`);let r=e.frameSizeBytes??Math.min(65536,n);if(!Number.isSafeInteger(r)||r<1||r>4294967295)throw Error(`[PipeX] Encryption frameSizeBytes must be a positive 32-bit integer`);if(r>n)throw Error(`[PipeX] Encryption frameSizeBytes exceeds the ${t.maxFrameBytes}-byte frame limit`);return r}function y(e,t){let n=e===0?0:Math.ceil(e/t);return 28+e+(n+1)*29}function b(e,t){return e===0?0:Math.ceil(e/t)}function x(e,t,n=d(16)){let r=Buffer.alloc(28);return p.copy(r,0),r.writeUInt8(1,4),r.writeUInt8(m[e],5),r.writeUInt16BE(0,6),r.writeUInt32BE(t,8),n.copy(r,12),r}function S(e,t){if(e.length!==28||!e.subarray(0,4).equals(p))throw Error(`[PipeX] Decryption failed: invalid framed header`);if(e.readUInt8(4)!==1)throw Error(`[PipeX] Decryption failed: unsupported format version`);let n=h[e.readUInt8(5)];if(!n||e.readUInt16BE(6)!==0)throw Error(`[PipeX] Decryption failed: invalid framed header`);let r=e.readUInt32BE(8);if(r<1||r>t.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: invalid frame size`);return{bytes:e,algorithm:n,frameSizeBytes:r,salt:e.subarray(12,28)}}function C(e,t){let n=Buffer.from(`PipeX AEAD framed v1:${t.algorithm}`,`utf8`);return Buffer.from(u(`sha256`,e,t.salt,n,32))}function w(e){if(e<0n||e>18446744073709551615n)throw Error(`[PipeX] Encryption frame sequence exhausted`);let t=Buffer.alloc(12);return t.writeBigUInt64BE(e,4),t}function T(e,t,n){let r=Buffer.alloc(13);return r.writeUInt8(e,0),r.writeBigUInt64BE(t,1),r.writeUInt32BE(n,9),r}function E(e,t,n,r,i,a){let o=T(t,n,e.length),s=w(n);try{let t=c(r,i,s,{authTagLength:16});t.setAAD(Buffer.concat([a,o]));let n=Buffer.concat([t.update(e),t.final()]);return Buffer.concat([o,n,t.getAuthTag()],29+n.length)}finally{s.fill(0)}}function D(t,n,r,i,a,o,s){let c=w(i),u=l(a,o,c,{authTagLength:16});if(u.setAAD(Buffer.concat([s,r])),n.length!==16)throw new e;u.setAuthTag(n);let d=u.update(t);try{let e=u.final();return e.length===0?d:Buffer.concat([d,e])}catch{throw d.fill(0),new e}finally{c.fill(0)}}function O(e,t,n){if(e.length<29)throw Error(`[PipeX] Decryption failed: packet too short`);if(e.length-29>n.maxOutputBytes)throw Error(`[PipeX] Decryption output exceeds ${n.maxOutputBytes} bytes`);let r=h[e.readUInt8(0)];if(!r)throw Error(`[PipeX] Decryption failed: unknown legacy algorithm`);let i=l(r,t,e.subarray(1,13),{authTagLength:16});i.setAuthTag(e.subarray(13,29));let a=i.update(e.subarray(29));try{let e=i.final();return e.length===0?a:Buffer.concat([a,e])}catch{throw a.fill(0),Error(`[PipeX] Decryption failed: authentication failed`)}}function k(e){return e.length>=p.length&&e.subarray(0,p.length).equals(p)}function A(e,t,n){g(t.key);let r=_(n);if(e.length>r.maxInputBytes)throw Error(`[PipeX] Encryption input exceeds ${r.maxInputBytes} bytes`);let i=v(t,r);if(b(e.length,i)>r.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${r.maxFrames}`);let a=y(e.length,i);if(a>r.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${r.maxOutputBytes} bytes`);let o=x(t.algorithm,i),s=S(o,r),c=C(t.key,s),l=[o],u=0n;try{for(let n=0;n<e.length;n+=i)l.push(E(e.subarray(n,Math.min(e.length,n+i)),1,u++,t.algorithm,c,o));return l.push(E(Buffer.alloc(0),2,u,t.algorithm,c,o)),Buffer.concat(l,a)}finally{c.fill(0)}}function j(e,t,n){g(t.key);let r=_(n);if(e.length>r.maxInputBytes)throw Error(`[PipeX] Decryption input exceeds ${r.maxInputBytes} bytes`);if(e.length===0||!k(e)&&e.readUInt8(0)!==p.readUInt8(0)){if(t.allowLegacyDecrypt!==!0)throw Error(`[PipeX] Decryption failed: legacy format disabled`);return O(e,t.key,r)}if(e.length<28)throw Error(`[PipeX] Decryption failed: incomplete framed header`);let i=S(e.subarray(0,28),r),a=C(t.key,i),o=[],s=0,c=28,l=0n,u=0,d=!1;try{for(;c<e.length;){if(d||e.length-c<13)throw Error(`[PipeX] Decryption failed: incomplete or trailing frame`);let t=e.subarray(c,c+13);c+=13;let n=t.readUInt8(0),f=t.readBigUInt64BE(1),p=t.readUInt32BE(9);if(f!==l)throw Error(`[PipeX] Decryption failed: invalid frame sequence`);if(n!==1&&n!==2)throw Error(`[PipeX] Decryption failed: invalid frame type`);if(n===2&&p!==0)throw Error(`[PipeX] Decryption failed: invalid final frame`);if(p>i.frameSizeBytes||p>r.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: frame length exceeds configured limit`);if(n===1&&u>=r.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${r.maxFrames}`);if(n===1&&p>r.maxOutputBytes-s)throw Error(`[PipeX] Decryption output exceeds ${r.maxOutputBytes} bytes`);if(e.length-c<p+16)throw Error(`[PipeX] Decryption failed: incomplete frame`);let m=e.subarray(c,c+p);c+=p;let h=e.subarray(c,c+16);c+=16;let g=D(m,h,t,f,i.algorithm,a,i.bytes);n===2?(g.fill(0),d=!0):(u++,s+=g.length,o.push(g)),l++}if(!d)throw Error(`[PipeX] Decryption failed: missing authenticated final frame`);let t=Buffer.concat(o,s);for(let e of o)e.fill(0);return t}catch(e){for(let e of o)e.fill(0);throw e}finally{a.fill(0)}}function M(e,t){g(e.key);let n=_(t),r=v(e,n);if(y(0,r)>n.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${n.maxOutputBytes} bytes`);let i=x(e.algorithm,r),a=S(i,n),o=C(e.key,a),s=Buffer.alloc(r),c=0,l=0,u=0,d=0n,p=!1,m=()=>{s.fill(0),o.fill(0)};return new f({transform(t,a,f){try{let a=Buffer.isBuffer(t)?t:Buffer.from(t);if(a.length>n.maxInputBytes-l)throw Error(`[PipeX] Encryption input exceeds ${n.maxInputBytes} bytes`);let m=l+a.length;if(b(m,r)>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);if(y(m,r)>n.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${n.maxOutputBytes} bytes`);l=m,p||=(this.push(i),!0);let h=0;for(;h<a.length;){let t=Math.min(r-c,a.length-h);if(a.copy(s,c,h,h+t),c+=t,h+=t,c===r){if(++u>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);this.push(E(s,1,d++,e.algorithm,o,i)),s.fill(0),c=0}}f()}catch(e){m(),f(e)}},flush(t){try{if(p||=(this.push(i),!0),c>0){if(++u>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);this.push(E(s.subarray(0,c),1,d++,e.algorithm,o,i))}this.push(E(Buffer.alloc(0),2,d,e.algorithm,o,i)),m(),t()}catch(e){m(),t(e)}},destroy(e,t){m(),t(e)}})}function N(e,t){g(e.key);let n=_(t),r=`unknown`,i=0,a=0,o=Buffer.alloc(28),s=0,c,l,u=Buffer.alloc(13),d=0,m,h=0,v=0n,y=0,b=!1,x=[],w=()=>{l?.fill(0),m?.fill(0),o.fill(0),u.fill(0),x=[]},T=(t,r)=>{let i=0;for(;i<t.length;){if(b)throw Error(`[PipeX] Decryption failed: trailing data after final frame`);if(!c){let r=Math.min(28-s,t.length-i);t.copy(o,s,i,i+r),s+=r,i+=r,s===28&&(c=S(o,n),l=C(e.key,c));continue}if(d<13){let e=Math.min(13-d,t.length-i);if(t.copy(u,d,i,i+e),d+=e,i+=e,d<13)continue;let r=u.readUInt8(0),o=u.readBigUInt64BE(1),s=u.readUInt32BE(9);if(o!==v)throw Error(`[PipeX] Decryption failed: invalid frame sequence`);if(r!==1&&r!==2)throw Error(`[PipeX] Decryption failed: invalid frame type`);if(r===2&&s!==0)throw Error(`[PipeX] Decryption failed: invalid final frame`);if(s>c.frameSizeBytes||s>n.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: frame length exceeds configured limit`);if(r===1&&y>=n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);if(r===1&&s>n.maxOutputBytes-a)throw Error(`[PipeX] Decryption output exceeds ${n.maxOutputBytes} bytes`);m=Buffer.alloc(s+16),h=0}let f=Math.min(m.length-h,t.length-i);if(t.copy(m,h,i,i+f),h+=f,i+=f,h<m.length)continue;let p=u.readUInt8(0),g=u.readBigUInt64BE(1),_=u.readUInt32BE(9),x=D(m.subarray(0,_),m.subarray(_),u,g,c.algorithm,l,c.bytes);p===2?(x.fill(0),b=!0):(y++,a+=x.length,r.push(x)),v++,m.fill(0),m=void 0,h=0,u.fill(0),d=0}};return new f({transform(t,a,o){try{let a=Buffer.isBuffer(t)?t:Buffer.from(t);if(a.length>n.maxInputBytes-i)throw Error(`[PipeX] Decryption input exceeds ${n.maxInputBytes} bytes`);if(i+=a.length,a.length===0)return o();if(r===`unknown`&&(r=a.readUInt8(0)===p.readUInt8(0)?`framed`:`legacy`,r===`legacy`&&e.allowLegacyDecrypt===!1))throw Error(`[PipeX] Decryption failed: legacy format disabled`);r===`legacy`?x.push(a):T(a,this),o()}catch(e){w(),o(e)}},flush(t){try{if(r===`legacy`){let r=O(Buffer.concat(x,i),e.key,n);return this.push(r),w(),t()}if(r!==`framed`||!c||d!==0||m)throw Error(`[PipeX] Decryption failed: incomplete encrypted stream`);if(!b)throw Error(`[PipeX] Decryption failed: missing authenticated final frame`);w(),t()}catch(e){w(),t(e)}},destroy(e,t){w(),t(e)}})}var P=class extends n{name=`encryption`;version=`4.0.0`;constructor(e){if(super(e),this.options=e,!e||!Buffer.isBuffer(e.key)||e.key.length!==32)throw new r;if(![`aes-256-gcm`,`chacha20-poly1305`].includes(e.algorithm))throw new t({transformName:`encryption`,stage:`configuration`});if(e.frameSizeBytes!==void 0&&(!Number.isSafeInteger(e.frameSizeBytes)||e.frameSizeBytes<1||e.frameSizeBytes>4294967295))throw new o(`[PipeX] Invalid encryption frame size`);if(e.allowLegacyDecrypt!==void 0&&typeof e.allowLegacyDecrypt!=`boolean`)throw new o(`[PipeX] Invalid legacy decryption setting`)}async process(e,t){return A(e,this.options,t)}async reverse(e,t){return j(e,this.options,t)}createStream(e,t){return e===`compress`?M(this.options,t):N(this.options,t)}};export{P as t};
|