diff --git a/LICENSES/libmspack-LGPL-2.1.txt b/LICENSES/libmspack-LGPL-2.1.txt new file mode 100644 index 0000000..b1e3f5a --- /dev/null +++ b/LICENSES/libmspack-LGPL-2.1.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/scripts/package-release.mjs b/scripts/package-release.mjs index b8eaea3..60270c1 100644 --- a/scripts/package-release.mjs +++ b/scripts/package-release.mjs @@ -29,6 +29,7 @@ export async function collectReleaseMetadataFiles(projectRoot) { 'compcol-MIT.txt', 'MPL-2.0.txt', 'lzxd-MIT.txt', + 'libmspack-LGPL-2.1.txt', 'rust-cab-MIT.txt', ]) { files[`LICENSES/${licenseName}`] = await readFile( diff --git a/src/onenote/onepkg/cabinet-set.test.ts b/src/onenote/onepkg/cabinet-set.test.ts new file mode 100644 index 0000000..5d02445 --- /dev/null +++ b/src/onenote/onepkg/cabinet-set.test.ts @@ -0,0 +1,222 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { extractCabinet } from './cabinet.js'; +import { extractCabinetSet } from './cabinet-set.js'; +import { openOneNotePackageSet } from './package.js'; +import type { CabSetPart } from './types.js'; + +const FIXTURE_HASHES = [ + '3658aaf68b0d538a5b321919f1de3eb1bcc258cba44e97b07a1938230995c632', + 'ce5fac4470fb850ae593de70ab03d3493069b77f8f81376216768bbf74e52321', + 'e58b57f63ac0858effa75ceb6f242b447fbce6a910d3840c37228fdbc9e7bc95', + 'fbcd45e503c3cffd5f5946ccc45bbc46b9884fe47abef7d09247154c7f8148fb', + '16ebbb274c8dc09f98415795212683b9ea8b2d6450080a79ab63cd5cdbac7cc4', +] as const; + +function fixturePart(index: number): CabSetPart { + const encoded = readFileSync( + resolve( + process.cwd(), + `tests/fixtures/libmspack-multi-basic-pt${index}.cab.b64` + ), + 'utf8' + ); + const bytes = Uint8Array.from( + Buffer.from(encoded.replaceAll(/\s/gu, ''), 'base64') + ); + expect(createHash('sha256').update(bytes).digest('hex')).toBe( + FIXTURE_HASHES[index - 1] + ); + return { fileName: `cabd_multi_basic_pt${index}.cab`, bytes }; +} + +function fixtureSet(): CabSetPart[] { + return [1, 2, 3, 4, 5].map(fixturePart); +} + +function mutateU16( + part: CabSetPart, + offset: number, + value: number +): CabSetPart { + const bytes = part.bytes.slice(); + new DataView(bytes.buffer).setUint16(offset, value, true); + return { ...part, bytes }; +} + +function withEmptyReserveLayout(part: CabSetPart): CabSetPart { + const original = part.bytes; + const insertAt = 36; + const addedBytes = 4; + const bytes = new Uint8Array(original.length + addedBytes); + bytes.set(original.subarray(0, insertAt)); + bytes.set(original.subarray(insertAt), insertAt + addedBytes); + const view = new DataView(bytes.buffer); + view.setUint32(8, original.length + addedBytes, true); + view.setUint32( + 16, + new DataView(original.buffer, original.byteOffset).getUint32(16, true) + + addedBytes, + true + ); + view.setUint16( + 30, + new DataView(original.buffer, original.byteOffset).getUint16(30, true) | + 0x0004, + true + ); + // cbCFHeader, cbCFFolder, and cbCFData are all zero. + bytes.fill(0, insertAt, insertAt + addedBytes); + // This fixture's only CFFOLDER begins at 0x8e before insertion. + view.setUint32( + 0x8e + addedBytes, + new DataView(original.buffer, original.byteOffset).getUint32(0x8e, true) + + addedBytes, + true + ); + return { ...part, bytes }; +} + +function expectedPart(index: number): string { + return `This is the data from cabinet part ${index}.\n`; +} + +describe('multi-cabinet sets', () => { + it('sorts and extracts the pinned five-part libmspack split block', async () => { + const shuffled = fixtureSet(); + [shuffled[0], shuffled[1], shuffled[2], shuffled[3], shuffled[4]] = [ + shuffled[3]!, + shuffled[0]!, + shuffled[4]!, + shuffled[1]!, + shuffled[2]!, + ]; + const result = await extractCabinetSet(shuffled); + + expect(result.cabinetSetId).toBe(12_345); + expect(result.parts.map((part) => part.cabinetSetIndex)).toEqual([ + 0, 1, 2, 3, 4, + ]); + expect(result.folders).toEqual([ + expect.objectContaining({ + index: 0, + dataBlockCount: 1, + compressedSize: 190, + uncompressedSize: 190, + compression: expect.objectContaining({ kind: 'none' }), + }), + ]); + expect(result.entries.map((entry) => entry.normalizedPath)).toEqual([ + 'test1.txt', + 'test2.txt', + 'test3.txt', + ]); + expect( + result.extractedEntries.map((entry) => + new TextDecoder().decode(entry.bytes) + ) + ).toEqual([ + expectedPart(1) + expectedPart(2), + expectedPart(3), + expectedPart(4) + expectedPart(5), + ]); + }); + + it('retains the single-cabinet API rejection for a spanning part', async () => { + await expect(extractCabinet(fixturePart(1).bytes)).rejects.toMatchObject({ + diagnostic: { code: 'cab-multipart-unsupported' }, + }); + }); + + it('rejects incomplete, misnamed, and mixed-ID cabinet selections', async () => { + const missing = fixtureSet(); + missing.splice(2, 1); + await expect(extractCabinetSet(missing)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-index-gap' }, + }); + + const misnamed = fixtureSet(); + misnamed[2] = { ...misnamed[2]!, fileName: 'wrong-name.cab' }; + await expect(extractCabinetSet(misnamed)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-link-name-mismatch' }, + }); + + const mixed = fixtureSet(); + mixed[2] = mutateU16(mixed[2]!, 32, 12_346); + await expect(extractCabinetSet(mixed)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-id-mismatch' }, + }); + }); + + it('rejects compression and spanning-record discontinuities', async () => { + const compression = fixtureSet(); + // Part 3's CFFOLDER begins at 0x8e; typeCompress is at +6. + compression[2] = mutateU16(compression[2]!, 0x94, 1); + await expect(extractCabinetSet(compression)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-compression-mismatch' }, + }); + + const records = fixtureSet(); + // Part 3's first CFFILE cbFile begins at 0x96. + records[2] = mutateU16(records[2]!, 0x96, 75); + await expect(extractCabinetSet(records)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-file-continuation-mismatch' }, + }); + + const reserve = fixtureSet(); + reserve[2] = withEmptyReserveLayout(reserve[2]!); + await expect(extractCabinetSet(reserve)).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-reserve-layout-mismatch' }, + }); + + const incompleteBlock = fixtureSet(); + // Part 5's last CFDATA cbUncomp is at 0xb5. + incompleteBlock[4] = mutateU16(incompleteBlock[4]!, 0xb5, 0); + await expect(extractCabinetSet(incompleteBlock)).rejects.toMatchObject({ + diagnostic: { code: 'cab-invalid-split-data-block' }, + }); + }); + + it('opens the complete set through the package API', async () => { + const parts = fixtureSet(); + const result = await openOneNotePackageSet(parts, { + sourceName: 'multi.onepkg', + }); + expect(result.package).toMatchObject({ + format: 'onepkg', + sourceName: 'multi.onepkg', + sourceSize: parts.reduce((sum, part) => sum + part.bytes.byteLength, 0), + entries: [ + { path: 'test1.txt', kind: 'other' }, + { path: 'test2.txt', kind: 'other' }, + { path: 'test3.txt', kind: 'other' }, + ], + sections: [], + }); + }); + + it('enforces aggregate set, part, file, and cancellation limits', async () => { + await expect( + extractCabinetSet(fixtureSet(), { + limits: { maxCabinetSetBytes: 1_000 }, + }) + ).rejects.toMatchObject({ diagnostic: { code: 'cab-set-input-limit' } }); + await expect( + extractCabinetSet(fixtureSet(), { limits: { maxCabinetParts: 4 } }) + ).rejects.toMatchObject({ + diagnostic: { code: 'cab-set-part-count-limit' }, + }); + await expect( + extractCabinetSet(fixtureSet(), { limits: { maxFiles: 2 } }) + ).rejects.toMatchObject({ diagnostic: { code: 'cab-entry-count-limit' } }); + await expect( + extractCabinetSet(fixtureSet(), { + cancellation: { isCancelled: () => true }, + }) + ).rejects.toMatchObject({ diagnostic: { code: 'onepkg-cancelled' } }); + }); +}); diff --git a/src/onenote/onepkg/cabinet-set.ts b/src/onenote/onepkg/cabinet-set.ts new file mode 100644 index 0000000..c014b4f --- /dev/null +++ b/src/onenote/onepkg/cabinet-set.ts @@ -0,0 +1,860 @@ +/* + * SPDX-License-Identifier: LGPL-2.1-only + * + * Multi-cabinet folder/file merging follows libmspack `mspack/cabd.c` at + * commit 55d501976171397ccd5d5a7a1ca7da065b1d9a06. + * Copyright (C) 2003-2017 Stuart Caie, LGPL-2.1. + * + * Modified for immutable named browser inputs, strict complete-set/link and + * reserve validation, exact spanning-file records, aggregate limits, and the + * existing bounded TypeScript CAB decoders. + */ + +import { checkCancellation, yieldForCancellation } from './cancellation.js'; +import { + FOLDER_CONTINUED_FROM_PREVIOUS, + FOLDER_CONTINUED_PREVIOUS_AND_NEXT, + FOLDER_CONTINUED_TO_NEXT, + FLAG_RESERVE_PRESENT, + parseCabinetInternal, + verifyDataBlockChecksumInternal, + type CabDataBlockInternal, + type CabFileRecordInternal, + type CabFolderInternal, + type ParsedCabinetInternal, +} from './cabinet.js'; +import { fail } from './errors.js'; +import { LzxDecoder } from './lzx/decoder.js'; +import { MsZipDecoder } from './mszip/decoder.js'; +import { QuantumDecoder } from './quantum/decoder.js'; +import { + resolveLimits, + type CabCompressionMethod, + type CabFileEntry, + type CabFolderSummary, + type CabOpenOptions, + type CabSetExtractionResult, + type CabSetPart, + type ExtractedCabFile, + type OnePkgLimits, +} from './types.js'; + +const MAX_CAB_BLOCK_OUTPUT = 32 * 1024; +const MAX_CAB_BLOCK_INPUT = MAX_CAB_BLOCK_OUTPUT + 6 * 1024; +const MAX_MSZIP_BLOCK_INPUT = MAX_CAB_BLOCK_OUTPUT + 12; + +interface NamedCabinet { + fileName: string; + nameKey: string; + parsed: ParsedCabinetInternal; +} + +interface LogicalBlock { + fragments: CabDataBlockInternal[]; + compressedSize: number; + uncompressedSize: number; +} + +interface LogicalFolder { + index: number; + compression: CabCompressionMethod; + segments: Array<{ cabinet: NamedCabinet; folder: CabFolderInternal }>; + blocks: LogicalBlock[]; + compressedSize: number; + uncompressedSize: number; +} + +interface LogicalCabinetSet { + cabinets: NamedCabinet[]; + limits: OnePkgLimits; + cabinetSetId: number; + declaredSize: number; + folders: LogicalFolder[]; + entries: CabFileEntry[]; + diagnostics: ParsedCabinetInternal['result']['diagnostics']; +} + +function checkedAdd( + left: number, + right: number, + code: string, + structure: string +): number { + const sum = left + right; + if (!Number.isSafeInteger(sum)) { + fail(code, `Integer overflow while reading ${structure}.`, { structure }); + } + return sum; +} + +function bytesEqual(left: Uint8Array, right: Uint8Array): boolean { + return ( + left.length === right.length && + left.every((value, index) => value === right[index]) + ); +} + +function cabinetNameKey(value: string, structure: string): string { + const normalized = value.normalize('NFC'); + if ( + normalized.length === 0 || + normalized.length > 255 || + normalized.includes('/') || + normalized.includes('\\') || + [...normalized].some((character) => { + const codePoint = character.codePointAt(0)!; + return codePoint <= 0x1f || codePoint === 0x7f; + }) + ) { + fail('cab-set-invalid-part-name', `Unsafe cabinet part name: ${value}`, { + structure, + }); + } + return normalized.toLocaleLowerCase('en-US'); +} + +function isContinuedFromPrevious(record: CabFileRecordInternal): boolean { + return ( + record.rawFolderIndex === FOLDER_CONTINUED_FROM_PREVIOUS || + record.rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT + ); +} + +function isContinuedToNext(record: CabFileRecordInternal): boolean { + return ( + record.rawFolderIndex === FOLDER_CONTINUED_TO_NEXT || + record.rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT + ); +} + +function sameSpanningFile( + left: CabFileRecordInternal, + right: CabFileRecordInternal +): boolean { + return ( + left.duplicateKey === right.duplicateKey && + left.entry.normalizedPath === right.entry.normalizedPath && + left.entry.uncompressedOffset === right.entry.uncompressedOffset && + left.entry.uncompressedSize === right.entry.uncompressedSize && + left.entry.attributes === right.entry.attributes && + left.date === right.date && + left.time === right.time + ); +} + +function validateBoundary(left: NamedCabinet, right: NamedCabinet): boolean { + const leftRecords = left.parsed.fileRecords.filter(isContinuedToNext); + const rightRecords = right.parsed.fileRecords.filter(isContinuedFromPrevious); + if ((leftRecords.length === 0) !== (rightRecords.length === 0)) { + fail( + 'cab-set-folder-continuation-mismatch', + 'Adjacent cabinets disagree about a continued folder.', + { structure: 'CFFILE.iFolder' } + ); + } + if (leftRecords.length === 0) return false; + if (leftRecords.length !== rightRecords.length) { + fail( + 'cab-set-file-continuation-mismatch', + 'Adjacent cabinets list different numbers of spanning files.', + { structure: 'CFFILE' } + ); + } + for (let index = 0; index < leftRecords.length; index += 1) { + if (!sameSpanningFile(leftRecords[index]!, rightRecords[index]!)) { + fail( + 'cab-set-file-continuation-mismatch', + 'Adjacent cabinets contain inconsistent spanning-file records.', + { structure: `CFFILE[${index}]` } + ); + } + } + + const leftFolder = left.parsed.folders.at(-1); + const rightFolder = right.parsed.folders[0]; + if (!leftFolder || !rightFolder) { + fail( + 'cab-set-folder-continuation-mismatch', + 'A continued cabinet boundary is missing its folder segment.', + { structure: 'CFFOLDER' } + ); + } + if (leftFolder.compression.raw !== rightFolder.compression.raw) { + fail( + 'cab-set-compression-mismatch', + 'Continued folder segments use different compression settings.', + { structure: 'CFFOLDER.typeCompress' } + ); + } + if (!bytesEqual(leftFolder.reserve, rightFolder.reserve)) { + fail( + 'cab-set-folder-reserve-mismatch', + 'Continued folder segments have different reserved metadata.', + { structure: 'CFFOLDER.abReserve' } + ); + } + return true; +} + +function validateNamedCabinets( + parts: CabSetPart[], + options: CabOpenOptions, + limits: OnePkgLimits +): NamedCabinet[] { + if (parts.length === 0) { + fail('cab-set-empty', 'At least one cabinet part is required.', { + structure: 'cabinet set', + }); + } + if (parts.length > limits.maxCabinetParts) { + fail( + 'cab-set-part-count-limit', + `Cabinet set has ${parts.length} parts; configured limit is ${limits.maxCabinetParts}.`, + { structure: 'cabinet set' } + ); + } + + let totalBytes = 0; + const seenNames = new Set(); + const cabinets = parts.map((part, inputIndex) => { + if (!(part.bytes instanceof Uint8Array)) { + throw new TypeError('Every CAB set part must contain Uint8Array bytes'); + } + const nameKey = cabinetNameKey( + part.fileName, + `cabinet set part ${inputIndex}` + ); + if (seenNames.has(nameKey)) { + fail( + 'cab-set-duplicate-part-name', + `Cabinet part name is duplicated: ${part.fileName}`, + { structure: 'cabinet set' } + ); + } + seenNames.add(nameKey); + totalBytes = checkedAdd( + totalBytes, + part.bytes.byteLength, + 'cab-set-size-overflow', + 'cabinet set bytes' + ); + if (totalBytes > limits.maxCabinetSetBytes) { + fail( + 'cab-set-input-limit', + `Cabinet set exceeds the configured ${limits.maxCabinetSetBytes}-byte input limit.`, + { structure: 'cabinet set' } + ); + } + checkCancellation(options.cancellation); + return { + fileName: part.fileName.normalize('NFC'), + nameKey, + parsed: parseCabinetInternal(part.bytes, { ...options, limits }, true), + }; + }); + + cabinets.sort( + (left, right) => + left.parsed.result.cabinetSetIndex - right.parsed.result.cabinetSetIndex + ); + const setId = cabinets[0]!.parsed.result.cabinetSetId; + const reserveTemplate = cabinets[0]!.parsed; + for (let index = 0; index < cabinets.length; index += 1) { + const cabinet = cabinets[index]!; + const parsed = cabinet.parsed; + if (parsed.result.cabinetSetId !== setId) { + fail( + 'cab-set-id-mismatch', + 'Selected cabinet parts do not share one setID.', + { structure: 'CFHEADER.setID' } + ); + } + if (parsed.result.cabinetSetIndex !== index) { + fail( + 'cab-set-index-gap', + `Expected cabinet index ${index}, found ${parsed.result.cabinetSetIndex}.`, + { structure: 'CFHEADER.iCabinet' } + ); + } + if ( + (parsed.flags & FLAG_RESERVE_PRESENT) !== + (reserveTemplate.flags & FLAG_RESERVE_PRESENT) || + parsed.headerReserveSize !== reserveTemplate.headerReserveSize || + parsed.folderReserveSize !== reserveTemplate.folderReserveSize || + parsed.dataReserveSize !== reserveTemplate.dataReserveSize + ) { + fail( + 'cab-set-reserve-layout-mismatch', + 'Cabinet parts use inconsistent reserve-area layouts.', + { structure: 'CFHEADER reserve sizes' } + ); + } + } + + for (let index = 0; index < cabinets.length; index += 1) { + const cabinet = cabinets[index]!; + const parsed = cabinet.parsed; + const previous = cabinets[index - 1]; + const next = cabinets[index + 1]; + if (previous === undefined) { + if (parsed.previousCabinetName !== undefined) { + fail( + 'cab-set-incomplete', + 'The first selected cabinet refers to a missing previous part.', + { structure: 'CFHEADER.szCabinetPrev' } + ); + } + } else { + if ( + parsed.previousCabinetName === undefined || + cabinetNameKey(parsed.previousCabinetName, 'CFHEADER.szCabinetPrev') !== + previous.nameKey + ) { + fail( + 'cab-set-link-name-mismatch', + `Cabinet ${cabinet.fileName} does not name ${previous.fileName} as its previous part.`, + { structure: 'CFHEADER.szCabinetPrev' } + ); + } + } + if (next === undefined) { + if (parsed.nextCabinetName !== undefined) { + fail( + 'cab-set-incomplete', + 'The last selected cabinet refers to a missing next part.', + { structure: 'CFHEADER.szCabinetNext' } + ); + } + } else if ( + parsed.nextCabinetName === undefined || + cabinetNameKey(parsed.nextCabinetName, 'CFHEADER.szCabinetNext') !== + next.nameKey + ) { + fail( + 'cab-set-link-name-mismatch', + `Cabinet ${cabinet.fileName} does not name ${next.fileName} as its next part.`, + { structure: 'CFHEADER.szCabinetNext' } + ); + } + } + return cabinets; +} + +function buildLogicalFolders( + cabinets: NamedCabinet[], + limits: OnePkgLimits, + options: CabOpenOptions +): { + folders: LogicalFolder[]; + folderBySegment: Map; +} { + let rawFolderCount = 0; + let rawBlockCount = 0; + const joins = cabinets.slice(0, -1).map((cabinet, index) => { + checkCancellation(options.cancellation); + return validateBoundary(cabinet, cabinets[index + 1]!); + }); + const folders: LogicalFolder[] = []; + const folderBySegment = new Map(); + + for ( + let cabinetIndex = 0; + cabinetIndex < cabinets.length; + cabinetIndex += 1 + ) { + const cabinet = cabinets[cabinetIndex]!; + rawFolderCount = checkedAdd( + rawFolderCount, + cabinet.parsed.folders.length, + 'cab-set-folder-count-overflow', + 'CFFOLDER' + ); + if (rawFolderCount > limits.maxFolders) { + fail( + 'cab-entry-count-limit', + `Cabinet set exceeds the configured ${limits.maxFolders}-folder-segment limit.`, + { structure: 'CFFOLDER' } + ); + } + for (const folder of cabinet.parsed.folders) { + rawBlockCount = checkedAdd( + rawBlockCount, + folder.blocks.length, + 'cab-data-block-count-overflow', + 'CFDATA' + ); + if (rawBlockCount > limits.maxDataBlocks) { + fail( + 'cab-data-block-count-limit', + `Cabinet set exceeds the configured ${limits.maxDataBlocks}-fragment limit.`, + { structure: 'CFDATA' } + ); + } + const mergePrevious = + folder.index === 0 && cabinetIndex > 0 && joins[cabinetIndex - 1]; + const logical = mergePrevious + ? folders.at(-1) + : { + index: folders.length, + compression: folder.compression, + segments: [], + blocks: [], + compressedSize: 0, + uncompressedSize: 0, + }; + if (!logical) { + fail( + 'cab-set-folder-continuation-mismatch', + 'Continued folder has no preceding logical folder.', + { structure: 'CFFOLDER' } + ); + } + if (!mergePrevious) folders.push(logical); + logical.segments.push({ cabinet, folder }); + folderBySegment.set(folder, logical); + } + } + + let totalFolderOutput = 0; + let totalLzxOutput = 0; + let totalQuantumOutput = 0; + for (const folder of folders) { + let pending: CabDataBlockInternal[] = []; + for ( + let segmentIndex = 0; + segmentIndex < folder.segments.length; + segmentIndex += 1 + ) { + const segment = folder.segments[segmentIndex]!.folder; + for ( + let blockIndex = 0; + blockIndex < segment.blocks.length; + blockIndex += 1 + ) { + const block = segment.blocks[blockIndex]!; + if (pending.length > 0 && blockIndex !== 0) { + fail( + 'cab-set-split-block-order', + 'A split CFDATA block is not continued by the first block in the next cabinet.', + { structure: 'CFDATA' } + ); + } + pending.push(block); + if (block.uncompressedSize === 0) continue; + + let compressedSize = 0; + for (const fragment of pending) { + compressedSize = checkedAdd( + compressedSize, + fragment.compressedSize, + 'cab-data-block-size-overflow', + 'CFDATA.cbData' + ); + } + if (compressedSize > MAX_CAB_BLOCK_INPUT) { + fail( + 'cab-invalid-compressed-block-size', + `Reassembled CAB data block exceeds ${MAX_CAB_BLOCK_INPUT} bytes.`, + { structure: 'CFDATA.cbData' } + ); + } + if ( + folder.compression.kind === 'mszip' && + compressedSize > MAX_MSZIP_BLOCK_INPUT + ) { + fail( + 'cab-invalid-mszip-block-size', + `Reassembled MSZIP block exceeds ${MAX_MSZIP_BLOCK_INPUT} bytes.`, + { structure: 'CFDATA.cbData' } + ); + } + if ( + folder.compression.kind === 'none' && + compressedSize !== block.uncompressedSize + ) { + fail( + 'cab-uncompressed-size-mismatch', + 'Reassembled uncompressed CAB block has different input and output sizes.', + { structure: 'CFDATA' } + ); + } + folder.blocks.push({ + fragments: pending, + compressedSize, + uncompressedSize: block.uncompressedSize, + }); + folder.compressedSize = checkedAdd( + folder.compressedSize, + compressedSize, + 'cab-folder-size-overflow', + 'CFDATA.cbData' + ); + folder.uncompressedSize = checkedAdd( + folder.uncompressedSize, + block.uncompressedSize, + 'cab-folder-size-overflow', + 'CFDATA.cbUncomp' + ); + pending = []; + } + if (pending.length > 0 && segmentIndex === folder.segments.length - 1) { + fail( + 'cab-set-incomplete-split-block', + 'Cabinet set ends before a split CFDATA block is complete.', + { structure: 'CFDATA.cbUncomp' } + ); + } + } + if (folder.uncompressedSize > limits.maxFolderUncompressedBytes) { + fail( + 'cab-folder-size-limit', + `Merged CAB folder exceeds the configured ${limits.maxFolderUncompressedBytes}-byte output limit.`, + { structure: 'CFDATA.cbUncomp' } + ); + } + if ( + folder.uncompressedSize / folder.compressedSize > + limits.maxCompressionRatio + ) { + fail( + 'cab-compression-ratio-limit', + `Merged CAB folder exceeds the configured ${limits.maxCompressionRatio}:1 compression ratio.`, + { structure: 'CFFOLDER/CFDATA' } + ); + } + totalFolderOutput = checkedAdd( + totalFolderOutput, + folder.uncompressedSize, + 'cab-total-size-overflow', + 'CFDATA.cbUncomp' + ); + if (folder.compression.kind === 'lzx') { + totalLzxOutput = checkedAdd( + totalLzxOutput, + folder.uncompressedSize, + 'lzx-operation-limit', + 'CFDATA.cbUncomp' + ); + } + if (folder.compression.kind === 'quantum') { + totalQuantumOutput = checkedAdd( + totalQuantumOutput, + folder.uncompressedSize, + 'quantum-operation-limit', + 'CFDATA.cbUncomp' + ); + } + } + if (totalFolderOutput > limits.maxTotalUncompressedBytes) { + fail( + 'cab-total-size-limit', + `Cabinet set output exceeds the configured ${limits.maxTotalUncompressedBytes}-byte limit.`, + { structure: 'CFDATA.cbUncomp' } + ); + } + if (totalLzxOutput > limits.maxDecodeOperations) { + fail( + 'lzx-operation-limit', + 'Merged LZX output exceeds the configured operation limit.', + { structure: 'CFDATA.cbUncomp' } + ); + } + if (totalQuantumOutput > limits.maxDecodeOperations) { + fail( + 'quantum-operation-limit', + 'Merged Quantum output exceeds the configured operation limit.', + { structure: 'CFDATA.cbUncomp' } + ); + } + return { folders, folderBySegment }; +} + +function buildLogicalEntries( + cabinets: NamedCabinet[], + folders: LogicalFolder[], + folderBySegment: Map, + limits: OnePkgLimits, + options: CabOpenOptions +): CabFileEntry[] { + const entries: CabFileEntry[] = []; + const byPath = new Map< + string, + { record: CabFileRecordInternal; logicalFolder: LogicalFolder } + >(); + let extractedBytes = 0; + + for (const cabinet of cabinets) { + for (const record of cabinet.parsed.fileRecords) { + checkCancellation(options.cancellation); + const segment = cabinet.parsed.folders[record.entry.folderIndex]; + const logicalFolder = segment ? folderBySegment.get(segment) : undefined; + if (!logicalFolder) { + fail( + 'cab-folder-index-out-of-range', + 'CAB set file has no merged folder.', + { offset: record.entryOffset + 8, structure: 'CFFILE.iFolder' } + ); + } + const existing = byPath.get(record.duplicateKey); + if (existing) { + if ( + record.rawFolderIndex < FOLDER_CONTINUED_FROM_PREVIOUS || + existing.record.rawFolderIndex < FOLDER_CONTINUED_FROM_PREVIOUS || + existing.logicalFolder !== logicalFolder || + !sameSpanningFile(existing.record, record) + ) { + fail( + 'cab-duplicate-path', + `Cabinet set contains a conflicting duplicate path: ${record.entry.normalizedPath}`, + { offset: record.entryOffset, structure: 'CFFILE.szName' } + ); + } + continue; + } + + if (entries.length >= limits.maxFiles) { + fail( + 'cab-entry-count-limit', + `Cabinet set exceeds the configured ${limits.maxFiles}-file limit.`, + { structure: 'CFFILE' } + ); + } + const fileEnd = checkedAdd( + record.entry.uncompressedOffset, + record.entry.uncompressedSize, + 'cab-file-range-overflow', + 'CFFILE' + ); + if (fileEnd > logicalFolder.uncompressedSize) { + fail( + 'cab-file-range-out-of-bounds', + `CAB file ${record.entry.normalizedPath} extends beyond its merged folder data.`, + { offset: record.entryOffset, structure: 'CFFILE' } + ); + } + extractedBytes = checkedAdd( + extractedBytes, + record.entry.uncompressedSize, + 'cab-extracted-size-overflow', + 'CFFILE.cbFile' + ); + if (extractedBytes > limits.maxExtractedBytes) { + fail( + 'cab-extracted-size-limit', + `Cabinet set files exceed the configured ${limits.maxExtractedBytes}-byte extraction limit.`, + { structure: 'CFFILE.cbFile' } + ); + } + const entry: CabFileEntry = { + ...record.entry, + index: entries.length, + folderIndex: logicalFolder.index, + compression: logicalFolder.compression, + }; + entries.push(entry); + byPath.set(record.duplicateKey, { record, logicalFolder }); + } + } + + // Keep this assertion close to the mapping so malformed internal indexes + // cannot silently select a different logical folder. + for (const entry of entries) { + if (!folders[entry.folderIndex]) { + fail('cab-folder-index-out-of-range', 'Merged folder index is invalid.', { + structure: 'CFFILE.iFolder', + }); + } + } + return entries; +} + +function buildLogicalSet( + parts: CabSetPart[], + options: CabOpenOptions +): LogicalCabinetSet { + const limits = resolveLimits(options.limits); + const cabinets = validateNamedCabinets(parts, options, limits); + const { folders, folderBySegment } = buildLogicalFolders( + cabinets, + limits, + options + ); + const entries = buildLogicalEntries( + cabinets, + folders, + folderBySegment, + limits, + options + ); + let declaredSize = 0; + for (const cabinet of cabinets) { + declaredSize = checkedAdd( + declaredSize, + cabinet.parsed.result.declaredSize, + 'cab-set-size-overflow', + 'CFHEADER.cbCabinet' + ); + } + return { + cabinets, + limits, + cabinetSetId: cabinets[0]!.parsed.result.cabinetSetId, + declaredSize, + folders, + entries, + diagnostics: cabinets.flatMap( + (cabinet) => cabinet.parsed.result.diagnostics + ), + }; +} + +function compressedBlockBytes(block: LogicalBlock): Uint8Array { + for (const fragment of block.fragments) { + verifyDataBlockChecksumInternal(fragment.sourceBytes, fragment); + } + if (block.fragments.length === 1) { + const fragment = block.fragments[0]!; + return fragment.sourceBytes.subarray( + fragment.dataOffset, + fragment.dataOffset + fragment.compressedSize + ); + } + const compressed = new Uint8Array(block.compressedSize); + let offset = 0; + for (const fragment of block.fragments) { + compressed.set( + fragment.sourceBytes.subarray( + fragment.dataOffset, + fragment.dataOffset + fragment.compressedSize + ), + offset + ); + offset += fragment.compressedSize; + } + return compressed; +} + +async function extractLogicalFolder( + folder: LogicalFolder, + limits: OnePkgLimits, + options: CabOpenOptions +): Promise { + const output = new Uint8Array(folder.uncompressedSize); + const lzx = + folder.compression.kind === 'lzx' + ? new LzxDecoder(folder.compression.windowBits, { + maxOperations: limits.maxDecodeOperations, + checkCancellation: () => checkCancellation(options.cancellation), + }) + : undefined; + const mszip = + folder.compression.kind === 'mszip' ? new MsZipDecoder() : undefined; + const quantum = + folder.compression.kind === 'quantum' + ? new QuantumDecoder(folder.compression.memoryBits, { + maxOperations: limits.maxDecodeOperations, + checkCancellation: () => checkCancellation(options.cancellation), + }) + : undefined; + let quantumQueuedBlock = -1; + let outputOffset = 0; + + for (let blockIndex = 0; blockIndex < folder.blocks.length; blockIndex += 1) { + checkCancellation(options.cancellation); + const block = folder.blocks[blockIndex]!; + if (quantum) { + const lookahead = Math.min(blockIndex + 1, folder.blocks.length - 1); + while (quantumQueuedBlock < lookahead) { + quantumQueuedBlock += 1; + quantum.appendCabBlock( + compressedBlockBytes(folder.blocks[quantumQueuedBlock]!), + quantumQueuedBlock === folder.blocks.length - 1 + ); + } + } + const compressed = quantum ? undefined : compressedBlockBytes(block); + const blockOutput = lzx + ? lzx.decompressNext(compressed!, block.uncompressedSize) + : mszip + ? mszip.decompressNext(compressed!, block.uncompressedSize) + : quantum + ? quantum.decompressNext( + block.uncompressedSize, + blockIndex === folder.blocks.length - 1 + ) + : compressed!; + if (blockOutput.length !== block.uncompressedSize) { + fail( + 'cab-output-size-mismatch', + `CAB decoder returned ${blockOutput.length} bytes; expected ${block.uncompressedSize}.`, + { structure: 'CFDATA.cbUncomp' } + ); + } + output.set(blockOutput, outputOffset); + outputOffset += blockOutput.length; + await yieldForCancellation(options.cancellation); + } + lzx?.finish(); + if (outputOffset !== output.length) { + fail( + 'cab-folder-output-size-mismatch', + 'Merged CAB folder output is incomplete.', + { structure: `CFFOLDER[${folder.index}]` } + ); + } + return output; +} + +export async function extractCabinetSet( + parts: CabSetPart[], + options: CabOpenOptions = {} +): Promise { + const set = buildLogicalSet(parts, options); + const entriesByFolder = new Map(); + for (const entry of set.entries) { + const current = entriesByFolder.get(entry.folderIndex); + if (current) current.push(entry); + else entriesByFolder.set(entry.folderIndex, [entry]); + } + + const extractedEntries: ExtractedCabFile[] = []; + for (const folder of set.folders) { + checkCancellation(options.cancellation); + const folderOutput = await extractLogicalFolder( + folder, + set.limits, + options + ); + for (const entry of entriesByFolder.get(folder.index) ?? []) { + const start = entry.uncompressedOffset; + extractedEntries.push({ + ...entry, + bytes: folderOutput.slice(start, start + entry.uncompressedSize), + }); + } + } + extractedEntries.sort((left, right) => left.index - right.index); + const folders: CabFolderSummary[] = set.folders.map((folder) => ({ + index: folder.index, + dataBlockCount: folder.blocks.length, + compressedSize: folder.compressedSize, + uncompressedSize: folder.uncompressedSize, + compression: folder.compression, + })); + return { + cabinetSetId: set.cabinetSetId, + cabinetSetIndex: 0, + declaredSize: set.declaredSize, + parts: set.cabinets.map((cabinet) => ({ + fileName: cabinet.fileName, + declaredSize: cabinet.parsed.result.declaredSize, + cabinetSetIndex: cabinet.parsed.result.cabinetSetIndex, + previousCabinetName: cabinet.parsed.previousCabinetName, + nextCabinetName: cabinet.parsed.nextCabinetName, + })), + entries: set.entries, + folders, + diagnostics: set.diagnostics, + extractedEntries, + }; +} diff --git a/src/onenote/onepkg/cabinet.ts b/src/onenote/onepkg/cabinet.ts index 269e94e..3301769 100644 --- a/src/onenote/onepkg/cabinet.ts +++ b/src/onenote/onepkg/cabinet.ts @@ -29,39 +29,68 @@ import { const CAB_SIGNATURE = 0x4643_534d; const FLAG_PREVIOUS_CABINET = 0x0001; const FLAG_NEXT_CABINET = 0x0002; -const FLAG_RESERVE_PRESENT = 0x0004; +export const FLAG_RESERVE_PRESENT = 0x0004; const ATTRIBUTE_NAME_IS_UTF8 = 0x0080; const MAX_CAB_BLOCK_OUTPUT = 32 * 1024; +const MAX_CAB_BLOCK_INPUT = MAX_CAB_BLOCK_OUTPUT + 6 * 1024; const MAX_MSZIP_BLOCK_INPUT = 32 * 1024 + 12; +export const FOLDER_CONTINUED_FROM_PREVIOUS = 0xfffd; +export const FOLDER_CONTINUED_TO_NEXT = 0xfffe; +export const FOLDER_CONTINUED_PREVIOUS_AND_NEXT = 0xffff; +const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true }); -interface CabDataBlock { +export interface CabDataBlockInternal { headerOffset: number; checksum: number; compressedSize: number; uncompressedSize: number; reserve: Uint8Array; dataOffset: number; + sourceBytes: Uint8Array; } -interface CabFolderInternal { +export interface CabFolderInternal { index: number; firstDataBlockOffset: number; dataBlockCount: number; compression: CabCompressionMethod; - blocks: CabDataBlock[]; + reserve: Uint8Array; + blocks: CabDataBlockInternal[]; compressedSize: number; uncompressedSize: number; dataEnd: number; } -interface ParsedCabinet { +export interface CabFileRecordInternal { + entry: CabFileEntry; + rawFolderIndex: number; + duplicateKey: string; + date: number; + time: number; + entryOffset: number; +} + +export interface ParsedCabinetInternal { bytes: Uint8Array; limits: OnePkgLimits; + flags: number; + previousCabinetName?: string; + previousDiskName?: string; + nextCabinetName?: string; + nextDiskName?: string; + headerReserveSize: number; + folderReserveSize: number; + dataReserveSize: number; + headerReserve: Uint8Array; folders: CabFolderInternal[]; + fileRecords: CabFileRecordInternal[]; result: CabEnumerationResult; } -function verifyDataBlockChecksum(bytes: Uint8Array, block: CabDataBlock): void { +export function verifyDataBlockChecksumInternal( + bytes: Uint8Array, + block: CabDataBlockInternal +): void { if (block.checksum === 0) return; const compressed = bytes.subarray( block.dataOffset, @@ -95,6 +124,31 @@ function checkedAdd( return sum; } +function readLinkedCabinetString( + reader: BinaryReader, + limits: OnePkgLimits, + structure: string, + allowEmpty: boolean +): string { + const offset = reader.offset; + const bytes = reader.readNullTerminatedBytes(limits.maxNameBytes, structure); + if (!allowEmpty && bytes.length === 0) { + fail('cab-linked-name-empty', 'Linked cabinet name cannot be empty.', { + offset, + structure, + }); + } + try { + return STRICT_UTF8.decode(bytes).normalize('NFC'); + } catch (error) { + fail( + 'cab-linked-name-invalid-utf8', + `Linked cabinet metadata is not valid UTF-8${error instanceof Error ? `: ${error.message}` : '.'}`, + { offset, structure } + ); + } +} + function parseCompression( raw: number, limits: OnePkgLimits, @@ -201,10 +255,11 @@ function parseCompression( ); } -function parseCabinet( +export function parseCabinetInternal( bytes: Uint8Array, - options: CabOpenOptions -): ParsedCabinet { + options: CabOpenOptions, + allowMultipart = false +): ParsedCabinetInternal { if (!(bytes instanceof Uint8Array)) { throw new TypeError('CAB input must be a Uint8Array'); } @@ -276,7 +331,10 @@ function parseCabinet( } ); } - if ((flags & (FLAG_PREVIOUS_CABINET | FLAG_NEXT_CABINET)) !== 0) { + if ( + !allowMultipart && + (flags & (FLAG_PREVIOUS_CABINET | FLAG_NEXT_CABINET)) !== 0 + ) { fail( 'cab-multipart-unsupported', 'Multi-cabinet archives are not supported for local .onepkg files.', @@ -293,15 +351,41 @@ function parseCabinet( // Re-bind reads to the trusted cbCabinet boundary before parsing variable data. const reader = new BinaryReader(bytes, header.offset, declaredSize); + let headerReserveSize = 0; let folderReserveSize = 0; let dataReserveSize = 0; + let headerReserve: Uint8Array = new Uint8Array(0); if ((flags & FLAG_RESERVE_PRESENT) !== 0) { - const headerReserveSize = reader.readU16('CFHEADER.cbCFHeader'); + headerReserveSize = reader.readU16('CFHEADER.cbCFHeader'); folderReserveSize = reader.readU8('CFHEADER.cbCFFolder'); dataReserveSize = reader.readU8('CFHEADER.cbCFData'); - reader.skip(headerReserveSize, 'CFHEADER.abReserve'); + if (headerReserveSize > 60_000) { + fail( + 'cab-header-reserve-limit', + 'CAB header reserve area exceeds the 60,000-byte format limit.', + { offset: header.offset, structure: 'CFHEADER.cbCFHeader' } + ); + } + headerReserve = reader.readBytes(headerReserveSize, 'CFHEADER.abReserve'); } + const previousCabinetName = + (flags & FLAG_PREVIOUS_CABINET) !== 0 + ? readLinkedCabinetString(reader, limits, 'CFHEADER.szCabinetPrev', false) + : undefined; + const previousDiskName = + (flags & FLAG_PREVIOUS_CABINET) !== 0 + ? readLinkedCabinetString(reader, limits, 'CFHEADER.szDiskPrev', true) + : undefined; + const nextCabinetName = + (flags & FLAG_NEXT_CABINET) !== 0 + ? readLinkedCabinetString(reader, limits, 'CFHEADER.szCabinetNext', false) + : undefined; + const nextDiskName = + (flags & FLAG_NEXT_CABINET) !== 0 + ? readLinkedCabinetString(reader, limits, 'CFHEADER.szDiskNext', true) + : undefined; + const folders: CabFolderInternal[] = []; let totalDataBlocks = 0; for (let index = 0; index < folderCount; index += 1) { @@ -315,7 +399,7 @@ function parseCabinet( limits, compressionRawOffset ); - reader.skip(folderReserveSize, 'CFFOLDER.abReserve'); + const reserve = reader.readBytes(folderReserveSize, 'CFFOLDER.abReserve'); totalDataBlocks = checkedAdd( totalDataBlocks, dataBlockCount, @@ -334,6 +418,7 @@ function parseCabinet( firstDataBlockOffset, dataBlockCount, compression, + reserve, blocks: [], compressedSize: 0, uncompressedSize: 0, @@ -349,6 +434,7 @@ function parseCabinet( } const fileReader = new BinaryReader(bytes, firstFileOffset, declaredSize); const entries: CabFileEntry[] = []; + const fileRecords: CabFileRecordInternal[] = []; const diagnostics = []; const duplicatePaths = new Set(); let extractedByteTotal = 0; @@ -357,9 +443,9 @@ function parseCabinet( const entryOffset = fileReader.offset; const uncompressedSize = fileReader.readU32('CFFILE.cbFile'); const uncompressedOffset = fileReader.readU32('CFFILE.uoffFolderStart'); - const folderIndex = fileReader.readU16('CFFILE.iFolder'); - fileReader.readU16('CFFILE.date'); - fileReader.readU16('CFFILE.time'); + const rawFolderIndex = fileReader.readU16('CFFILE.iFolder'); + const date = fileReader.readU16('CFFILE.date'); + const time = fileReader.readU16('CFFILE.time'); const attributes = fileReader.readU16('CFFILE.attribs'); const nameOffset = fileReader.offset; const nameBytes = fileReader.readNullTerminatedBytes( @@ -367,12 +453,42 @@ function parseCabinet( 'CFFILE.szName' ); - if (folderIndex >= 0xfffd) { - fail( - 'cab-multipart-file-unsupported', - 'CAB file spans another cabinet; multi-cabinet files are unsupported.', - { offset: entryOffset + 8, structure: 'CFFILE.iFolder' } - ); + let folderIndex = rawFolderIndex; + if (rawFolderIndex >= FOLDER_CONTINUED_FROM_PREVIOUS) { + if (!allowMultipart) { + fail( + 'cab-multipart-file-unsupported', + 'CAB file spans another cabinet; multi-cabinet files are unsupported.', + { offset: entryOffset + 8, structure: 'CFFILE.iFolder' } + ); + } + const continuesFromPrevious = + rawFolderIndex === FOLDER_CONTINUED_FROM_PREVIOUS || + rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT; + const continuesToNext = + rawFolderIndex === FOLDER_CONTINUED_TO_NEXT || + rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT; + if ( + (continuesFromPrevious && (flags & FLAG_PREVIOUS_CABINET) === 0) || + (continuesToNext && (flags & FLAG_NEXT_CABINET) === 0) + ) { + fail( + 'cab-spanning-file-flag-mismatch', + 'CAB spanning file marker does not match its prev/next header flags.', + { offset: entryOffset + 8, structure: 'CFFILE.iFolder' } + ); + } + if ( + rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT && + folders.length !== 1 + ) { + fail( + 'cab-spanning-folder-ambiguous', + 'A folder continued from both cabinets must be the only folder in this cabinet.', + { offset: entryOffset + 8, structure: 'CFFILE.iFolder' } + ); + } + folderIndex = continuesFromPrevious ? 0 : folders.length - 1; } const folder = folders[folderIndex]; if (folder === undefined) { @@ -392,18 +508,20 @@ function parseCabinet( { offset: entryOffset, structure: 'CFFILE.cbFile' } ); } - extractedByteTotal = checkedAdd( - extractedByteTotal, - uncompressedSize, - 'cab-extracted-size-overflow', - 'CFFILE.cbFile' - ); - if (extractedByteTotal > limits.maxExtractedBytes) { - fail( - 'cab-extracted-size-limit', - `Extracted files exceed the configured ${limits.maxExtractedBytes}-byte limit.`, - { offset: entryOffset, structure: 'CFFILE.cbFile' } + if (!allowMultipart) { + extractedByteTotal = checkedAdd( + extractedByteTotal, + uncompressedSize, + 'cab-extracted-size-overflow', + 'CFFILE.cbFile' ); + if (extractedByteTotal > limits.maxExtractedBytes) { + fail( + 'cab-extracted-size-limit', + `Extracted files exceed the configured ${limits.maxExtractedBytes}-byte limit.`, + { offset: entryOffset, structure: 'CFFILE.cbFile' } + ); + } } const path = decodeCabFileName( @@ -432,7 +550,7 @@ function parseCabinet( ); } duplicatePaths.add(normalized.duplicateKey); - entries.push({ + const entry: CabFileEntry = { index, path: normalized.path, normalizedPath: normalized.normalizedPath, @@ -441,6 +559,15 @@ function parseCabinet( uncompressedSize, attributes, compression: folder.compression, + }; + entries.push(entry); + fileRecords.push({ + entry, + rawFolderIndex, + duplicateKey: normalized.duplicateKey, + date, + time, + entryOffset, }); } const metadataEnd = fileReader.offset; @@ -449,6 +576,12 @@ function parseCabinet( let totalLzxOutput = 0; let totalQuantumOutput = 0; for (const folder of folders) { + const folderContinuesToNext = fileRecords.some( + (record) => + record.entry.folderIndex === folder.index && + (record.rawFolderIndex === FOLDER_CONTINUED_TO_NEXT || + record.rawFolderIndex === FOLDER_CONTINUED_PREVIOUS_AND_NEXT) + ); if (folder.firstDataBlockOffset > declaredSize) { fail( 'cab-invalid-data-offset', @@ -493,17 +626,32 @@ function parseCabinet( ); const dataOffset = blockReader.offset; blockReader.skip(compressedSize, 'CFDATA.ab'); - if ( - compressedSize === 0 || - uncompressedSize === 0 || - uncompressedSize > MAX_CAB_BLOCK_OUTPUT - ) { + if (compressedSize === 0 || uncompressedSize > MAX_CAB_BLOCK_OUTPUT) { fail( 'cab-invalid-data-block-size', `Invalid CAB data block sizes ${compressedSize}/${uncompressedSize}.`, { offset: headerOffset + 4, structure: 'CFDATA' } ); } + if ( + uncompressedSize === 0 && + (!allowMultipart || + blockIndex !== folder.dataBlockCount - 1 || + !folderContinuesToNext) + ) { + fail( + 'cab-invalid-split-data-block', + 'A zero-output CFDATA fragment must be the final block of a folder continued in the next cabinet.', + { offset: headerOffset + 6, structure: 'CFDATA.cbUncomp' } + ); + } + if (compressedSize > MAX_CAB_BLOCK_INPUT) { + fail( + 'cab-invalid-compressed-block-size', + `CAB data block size ${compressedSize} exceeds ${MAX_CAB_BLOCK_INPUT} bytes.`, + { offset: headerOffset + 4, structure: 'CFDATA.cbData' } + ); + } if ( folder.compression.kind === 'mszip' && compressedSize > MAX_MSZIP_BLOCK_INPUT @@ -516,6 +664,7 @@ function parseCabinet( } if ( folder.compression.kind === 'none' && + !allowMultipart && compressedSize !== uncompressedSize ) { fail( @@ -550,12 +699,14 @@ function parseCabinet( uncompressedSize, reserve, dataOffset, + sourceBytes: bytes, }); } folder.dataEnd = blockReader.offset; if ( + !allowMultipart && folder.uncompressedSize / folder.compressedSize > - limits.maxCompressionRatio + limits.maxCompressionRatio ) { fail( 'cab-compression-ratio-limit', @@ -624,20 +775,22 @@ function parseCabinet( } } - for (const entry of entries) { - const folder = folders[entry.folderIndex]!; - const fileEnd = checkedAdd( - entry.uncompressedOffset, - entry.uncompressedSize, - 'cab-file-range-overflow', - 'CFFILE' - ); - if (fileEnd > folder.uncompressedSize) { - fail( - 'cab-file-range-out-of-bounds', - `CAB file ${entry.normalizedPath} extends beyond its folder data.`, - { structure: 'CFFILE' } + if (!allowMultipart) { + for (const entry of entries) { + const folder = folders[entry.folderIndex]!; + const fileEnd = checkedAdd( + entry.uncompressedOffset, + entry.uncompressedSize, + 'cab-file-range-overflow', + 'CFFILE' ); + if (fileEnd > folder.uncompressedSize) { + fail( + 'cab-file-range-out-of-bounds', + `CAB file ${entry.normalizedPath} extends beyond its folder data.`, + { structure: 'CFFILE' } + ); + } } } @@ -662,7 +815,17 @@ function parseCabinet( return { bytes, limits, + flags, + previousCabinetName, + previousDiskName, + nextCabinetName, + nextDiskName, + headerReserveSize, + folderReserveSize, + dataReserveSize, + headerReserve, folders, + fileRecords, result: { cabinetSetId, cabinetSetIndex, @@ -684,14 +847,14 @@ export function enumerateCabinet( bytes: Uint8Array, options: CabOpenOptions = {} ): CabEnumerationResult { - return parseCabinet(bytes, options).result; + return parseCabinetInternal(bytes, options).result; } export async function extractCabinet( bytes: Uint8Array, options: CabOpenOptions = {} ): Promise { - const parsed = parseCabinet(bytes, options); + const parsed = parseCabinetInternal(bytes, options); const byFolder = new Map(); for (const entry of parsed.result.entries) { const current = byFolder.get(entry.folderIndex); @@ -728,7 +891,7 @@ export async function extractCabinet( while (quantumQueuedBlock < lookahead) { quantumQueuedBlock += 1; const queued = folder.blocks[quantumQueuedBlock]!; - verifyDataBlockChecksum(parsed.bytes, queued); + verifyDataBlockChecksumInternal(parsed.bytes, queued); quantumDecoder.appendCabBlock( parsed.bytes.subarray( queued.dataOffset, @@ -743,7 +906,7 @@ export async function extractCabinet( block.dataOffset + block.compressedSize ); if (quantumDecoder === undefined) { - verifyDataBlockChecksum(parsed.bytes, block); + verifyDataBlockChecksumInternal(parsed.bytes, block); } const output = decoder !== undefined diff --git a/src/onenote/onepkg/index.ts b/src/onenote/onepkg/index.ts index cf9a17d..7fdc12c 100644 --- a/src/onenote/onepkg/index.ts +++ b/src/onenote/onepkg/index.ts @@ -1,6 +1,7 @@ export { enumerateCabinet, extractCabinet } from './cabinet.js'; +export { extractCabinetSet } from './cabinet-set.js'; export { OnePkgError } from './errors.js'; -export { openOneNotePackage } from './package.js'; +export { openOneNotePackage, openOneNotePackageSet } from './package.js'; export type { OneNotePackageOpenOptions, OneNotePackageOpenResult, @@ -17,6 +18,9 @@ export { type CabFileEntry, type CabFolderSummary, type CabOpenOptions, + type CabSetExtractionResult, + type CabSetPart, + type CabSetPartSummary, type ExtractedCabFile, type OnePkgCancellation, type OnePkgLimits, diff --git a/src/onenote/onepkg/package.ts b/src/onenote/onepkg/package.ts index f6fdac9..e9a3c22 100644 --- a/src/onenote/onepkg/package.ts +++ b/src/onenote/onepkg/package.ts @@ -7,10 +7,13 @@ import type { import type { ParserDiagnostic } from '../model/diagnostics.js'; import { checkCancellation } from './cancellation.js'; import { extractCabinet } from './cabinet.js'; +import { extractCabinetSet } from './cabinet-set.js'; import { diagnosticFromUnknown, OnePkgError, warning } from './errors.js'; import { buildOneNotePackageTree } from './toc-hierarchy.js'; import type { CabOpenOptions, + CabExtractionResult, + CabSetPart, ExtractedCabFile, OnePkgCancellation, } from './types.js'; @@ -84,6 +87,34 @@ export async function openOneNotePackage( ): Promise { const sourceName = options.sourceName ?? 'notebook.onepkg'; const extraction = await extractCabinet(bytes, options); + return buildOpenedPackage(extraction, sourceName, bytes.byteLength, options); +} + +export async function openOneNotePackageSet( + parts: CabSetPart[], + options: OneNotePackageOpenOptions = {} +): Promise { + const extraction = await extractCabinetSet(parts, options); + const sourceName = + options.sourceName ?? + parts.find((part) => part.fileName.toLowerCase().endsWith('.onepkg')) + ?.fileName ?? + extraction.parts[0]?.fileName ?? + 'notebook.onepkg'; + return buildOpenedPackage( + extraction, + sourceName, + parts.reduce((sum, part) => sum + part.bytes.byteLength, 0), + options + ); +} + +async function buildOpenedPackage( + extraction: CabExtractionResult, + sourceName: string, + sourceSize: number, + options: OneNotePackageOpenOptions +): Promise { const diagnostics = [...extraction.diagnostics]; const packageEntries: OneNotePackageEntryDto[] = extraction.extractedEntries.map((entry) => ({ @@ -173,7 +204,7 @@ export async function openOneNotePackage( package: { format: 'onepkg', sourceName, - sourceSize: bytes.byteLength, + sourceSize, entries: packageEntries, sections: packagedSections, tree: treeResult.tree, diff --git a/src/onenote/onepkg/types.ts b/src/onenote/onepkg/types.ts index c51162b..2a769e3 100644 --- a/src/onenote/onepkg/types.ts +++ b/src/onenote/onepkg/types.ts @@ -55,6 +55,24 @@ export interface CabExtractionResult extends CabEnumerationResult { extractedEntries: ExtractedCabFile[]; } +export interface CabSetPart { + /** Selected local basename. Used only to validate CAB prev/next links. */ + fileName: string; + bytes: Uint8Array; +} + +export interface CabSetPartSummary { + fileName: string; + declaredSize: number; + cabinetSetIndex: number; + previousCabinetName?: string; + nextCabinetName?: string; +} + +export interface CabSetExtractionResult extends CabExtractionResult { + parts: CabSetPartSummary[]; +} + export interface OnePkgCancellation { signal?: AbortSignal; isCancelled?: () => boolean; @@ -64,6 +82,8 @@ export interface OnePkgCancellation { export interface OnePkgLimits { maxCabinetBytes: number; + maxCabinetSetBytes: number; + maxCabinetParts: number; maxFolders: number; maxFiles: number; maxDataBlocks: number; @@ -83,6 +103,8 @@ export interface OnePkgLimits { export const DEFAULT_ONEPKG_LIMITS: Readonly = { maxCabinetBytes: 512 * 1024 * 1024, + maxCabinetSetBytes: 512 * 1024 * 1024, + maxCabinetParts: 256, maxFolders: 1_024, maxFiles: 10_000, maxDataBlocks: 131_072, diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 6e7a236..906abbe 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -133,6 +133,40 @@ required `0xFF` byte after each CFDATA block in memory. These are CAB-level codec fixtures, not OneNote exports, and do not establish producer-specific `.onepkg` compatibility. +## libmspack five-part CAB fixture + +`libmspack-multi-basic-pt1.cab.b64` through +`libmspack-multi-basic-pt5.cab.b64` are byte-for-byte copies of libmspack's +[`multi_basic_pt*.cab`](https://github.com/kyz/libmspack/tree/55d501976171397ccd5d5a7a1ca7da065b1d9a06/libmspack/test/test_files/cabd) +fixtures at commit +[`55d501976171397ccd5d5a7a1ca7da065b1d9a06`](https://github.com/kyz/libmspack/commit/55d501976171397ccd5d5a7a1ca7da065b1d9a06). +The immediate reviewed source is LGPL-2.1-only; its exact licence text is in +`LICENSES/libmspack-LGPL-2.1.txt`. + +The CAB headers name the parts `cabd_multi_basic_pt1.cab` through +`cabd_multi_basic_pt5.cab`. They form set ID 12345, indexes 0 through 4, and +split one 190-byte uncompressed CFDATA block across all five cabinets. The +three spanning files contain the five ASCII lines +`This is the data from cabinet part N.` (plus line feeds), grouped as parts +1–2, part 3, and parts 4–5. + +- Part 1: 221 bytes; SHA-256 + `3658aaf68b0d538a5b321919f1de3eb1bcc258cba44e97b07a1938230995c632`. +- Part 2: 274 bytes; SHA-256 + `ce5fac4470fb850ae593de70ab03d3493069b77f8f81376216768bbf74e52321`. +- Part 3: 274 bytes; SHA-256 + `e58b57f63ac0858effa75ceb6f242b447fbce6a910d3840c37228fdbc9e7bc95`. +- Part 4: 274 bytes; SHA-256 + `fbcd45e503c3cffd5f5946ccc45bbc46b9884fe47abef7d09247154c7f8148fb`. +- Part 5: 221 bytes; SHA-256 + `16ebbb274c8dc09f98415795212683b9ea8b2d6450080a79ab63cd5cdbac7cc4`. + +Tests retain all hashes and exercise unordered selection, strict link/set/order +validation, `0xFFFD`/`0xFFFE`/`0xFFFF` spanning-file reconciliation, split-block +reassembly, reserve/compression continuity, aggregate limits, and cancellation. +These are generic CAB fixtures, not OneNote exports, and do not establish +producer-specific `.onepkg` compatibility. + ## Distribution policy The decoded fixture bytes are used only by tests. Vite does not copy them into diff --git a/tests/fixtures/libmspack-multi-basic-pt1.cab.b64 b/tests/fixtures/libmspack-multi-basic-pt1.cab.b64 new file mode 100644 index 0000000..2aa8041 --- /dev/null +++ b/tests/fixtures/libmspack-multi-basic-pt1.cab.b64 @@ -0,0 +1 @@ +TVNDRgAAAADdAAAAAAAAAGEAAAAAAAAAAwEBAAMAAgA5MAAAY2FiZF9tdWx0aV9iYXNpY19wdDIuY2FiAGJhc2ljIG11bHRpcGFydCB0ZXN0IHBhcnQgMgCvAAAAAQAAAEwAAAAAAAAA/v9sIrpZIAB0ZXN0MS50eHQAJgAAAEwAAAD+/2wiulkgAHRlc3QyLnR4dABMAAAAcgAAAP7/bCK6WSAAdGVzdDMudHh0AAAAAAAmAAAAVGhpcyBpcyB0aGUgZGF0YSBmcm9tIGNhYmluZXQgcGFydCAxLgo= diff --git a/tests/fixtures/libmspack-multi-basic-pt2.cab.b64 b/tests/fixtures/libmspack-multi-basic-pt2.cab.b64 new file mode 100644 index 0000000..2d92e70 --- /dev/null +++ b/tests/fixtures/libmspack-multi-basic-pt2.cab.b64 @@ -0,0 +1 @@ +TVNDRgAAAAASAQAAAAAAAJYAAAAAAAAAAwEBAAMAAwA5MAEAY2FiZF9tdWx0aV9iYXNpY19wdDEuY2FiAGJhc2ljIG11bHRpcGFydCB0ZXN0IHBhcnQgMQBjYWJkX211bHRpX2Jhc2ljX3B0My5jYWIAYmFzaWMgbXVsdGlwYXJ0IHRlc3QgcGFydCAzAOQAAAABAAAATAAAAAAAAAD//2wiulkgAHRlc3QxLnR4dAAmAAAATAAAAP//bCK6WSAAdGVzdDIudHh0AEwAAAByAAAA//9sIrpZIAB0ZXN0My50eHQAAAAAACYAAABUaGlzIGlzIHRoZSBkYXRhIGZyb20gY2FiaW5ldCBwYXJ0IDIuCg== diff --git a/tests/fixtures/libmspack-multi-basic-pt3.cab.b64 b/tests/fixtures/libmspack-multi-basic-pt3.cab.b64 new file mode 100644 index 0000000..0cb1133 --- /dev/null +++ b/tests/fixtures/libmspack-multi-basic-pt3.cab.b64 @@ -0,0 +1 @@ +TVNDRgAAAAASAQAAAAAAAJYAAAAAAAAAAwEBAAMAAwA5MAIAY2FiZF9tdWx0aV9iYXNpY19wdDIuY2FiAGJhc2ljIG11bHRpcGFydCB0ZXN0IHBhcnQgMgBjYWJkX211bHRpX2Jhc2ljX3B0NC5jYWIAYmFzaWMgbXVsdGlwYXJ0IHRlc3QgcGFydCA0AOQAAAABAAAATAAAAAAAAAD//2wiulkgAHRlc3QxLnR4dAAmAAAATAAAAP//bCK6WSAAdGVzdDIudHh0AEwAAAByAAAA//9sIrpZIAB0ZXN0My50eHQAAAAAACYAAABUaGlzIGlzIHRoZSBkYXRhIGZyb20gY2FiaW5ldCBwYXJ0IDMuCg== diff --git a/tests/fixtures/libmspack-multi-basic-pt4.cab.b64 b/tests/fixtures/libmspack-multi-basic-pt4.cab.b64 new file mode 100644 index 0000000..b229ec9 --- /dev/null +++ b/tests/fixtures/libmspack-multi-basic-pt4.cab.b64 @@ -0,0 +1 @@ +TVNDRgAAAAASAQAAAAAAAJYAAAAAAAAAAwEBAAMAAwA5MAMAY2FiZF9tdWx0aV9iYXNpY19wdDMuY2FiAGJhc2ljIG11bHRpcGFydCB0ZXN0IHBhcnQgMwBjYWJkX211bHRpX2Jhc2ljX3B0NS5jYWIAYmFzaWMgbXVsdGlwYXJ0IHRlc3QgcGFydCA1AOQAAAABAAAATAAAAAAAAAD//2wiulkgAHRlc3QxLnR4dAAmAAAATAAAAP//bCK6WSAAdGVzdDIudHh0AEwAAAByAAAA//9sIrpZIAB0ZXN0My50eHQAAAAAACYAAABUaGlzIGlzIHRoZSBkYXRhIGZyb20gY2FiaW5ldCBwYXJ0IDQuCg== diff --git a/tests/fixtures/libmspack-multi-basic-pt5.cab.b64 b/tests/fixtures/libmspack-multi-basic-pt5.cab.b64 new file mode 100644 index 0000000..1a087e5 --- /dev/null +++ b/tests/fixtures/libmspack-multi-basic-pt5.cab.b64 @@ -0,0 +1 @@ +TVNDRgAAAADdAAAAAAAAAGEAAAAAAAAAAwEBAAMAAQA5MAQAY2FiZF9tdWx0aV9iYXNpY19wdDQuY2FiAGJhc2ljIG11bHRpcGFydCB0ZXN0IHBhcnQgNACvAAAAAQAAAEwAAAAAAAAA/f9sIrpZIAB0ZXN0MS50eHQAJgAAAEwAAAD9/2wiulkgAHRlc3QyLnR4dABMAAAAcgAAAP3/bCK6WSAAdGVzdDMudHh0AAAAAAAmAL4AVGhpcyBpcyB0aGUgZGF0YSBmcm9tIGNhYmluZXQgcGFydCA1Lgo= diff --git a/tests/release-archive.test.ts b/tests/release-archive.test.ts index 81a6b39..551f8be 100644 --- a/tests/release-archive.test.ts +++ b/tests/release-archive.test.ts @@ -77,6 +77,7 @@ describe('release archive', () => { 'LICENSES/compcol-MIT.txt', 'LICENSES/MPL-2.0.txt', 'LICENSES/THIRD-PARTY-LICENSES.txt', + 'LICENSES/libmspack-LGPL-2.1.txt', 'LICENSES/lzxd-MIT.txt', 'LICENSES/rust-cab-MIT.txt', 'THIRD_PARTY_NOTICES.md', @@ -100,6 +101,11 @@ describe('release archive', () => { .update(files['LICENSES/compcol-MIT.txt']!) .digest('hex') ).toBe('a7009ce74b33a2afcf9ab38007bf3c8f5020d9b816dc5fc7296bf17e6d7dc796'); + expect( + createHash('sha256') + .update(files['LICENSES/libmspack-LGPL-2.1.txt']!) + .digest('hex') + ).toBe('a190dc9c8043755d90f8b0a75fa66b9e42d4af4c980bf5ddc633f0124db3cee7'); expect( files['LICENSES/THIRD-PARTY-LICENSES.txt']!.toString('utf8') ).toContain('fflate@0.8.3');