@crossbind/extension-msix 0.0.0-stage → 2.0.0-beta.79

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Buğra Sarı and crossbind contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @crossbind/extension-msix
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Windows app's MSIX package: for the Microsoft Store, which signs, hosts and updates it, or handed out, signed with the
4
+ app's key.
5
+
6
+ It comes with `@crossbind/core-app-host`: there is nothing to install or list.
7
+
8
+ ## Use
9
+
10
+ For the Store, `app.windows.msix` in `crossbind.config.js` gives the identity Partner Center's Product identity page
11
+ shows once the app's name is reserved as an "MSIX or PWA app":
12
+
13
+ ```js
14
+ app: {
15
+ icon: 'icon.png',
16
+ windows: {
17
+ msix: { name: '12345Example.Demo', publisher: 'CN=1A2B3C4D-…', publisherDisplayName: 'Example' },
18
+ },
19
+ },
20
+ ```
21
+
22
+ ```sh
23
+ npx crossbind app build -p windows
24
+ ```
25
+
26
+ A Windows build then writes an `.msix` named after the app and its architecture beside the app's folder, unsigned,
27
+ which Partner Center takes and the Store signs.
28
+
29
+ A package to hand out instead, with `msix` in `app.installers` and no `app.windows.msix`, takes the app's id as its name
30
+ and its publisher from the certificate of the app's signing key (`CROSSBIND_WINDOWS_SIGNING_*`), which signs it too.
31
+ Windows installs it where that certificate is trusted.
32
+
33
+ - The version is `package.json`'s, as `1.2.3.0`. A prerelease such as `1.2.3-beta.1` stops the build, as the Store
34
+ cannot tell it from the release.
35
+ - The logos come from `app.icon`, and the URL schemes and file types from `app.urlSchemes` and `app.fileTypes`. The app
36
+ also opens by its executable's name, as an alias.
37
+ - An app from its package does not update itself: `updater.check()` rejects there, and the Store, or a newer package,
38
+ updates it.
39
+
40
+ ## Platforms
41
+
42
+ Windows 10 1809 and later, x64 and arm64.
43
+
44
+ ## Replace or leave out
45
+
46
+ An extension named `msix` with an installer takes its place, and `app: { without: ['msix'] }` in `crossbind.config.js`
47
+ leaves it out. [extensions.md](https://github.com/crossbind/crossbind/blob/main/docs/api/extensions.md#installers) says
48
+ what one gives.
49
+
50
+ [app.md](https://github.com/crossbind/crossbind/blob/main/docs/api/app.md#installers) has every installer.
@@ -0,0 +1,99 @@
1
+ import path from 'node:path';
2
+ import { LOGOS, appxManifest } from './src/manifest.js';
3
+ import { filesIn, writeMsix } from './src/pack.js';
4
+ import { commonName, signingCertificate, windowsPublisher } from './src/publisher.js';
5
+
6
+ const MAX_VERSION_NUMBER = 65535;
7
+ // The name of an MSIX package: the one Partner Center reserves for the app, or the app's id.
8
+ const PACKAGE_NAME = /^[-.A-Za-z0-9]{3,50}$/;
9
+ const IDENTITY = ['name', 'publisher', 'publisherDisplayName'];
10
+ const isPlainObject = (value) => Object.prototype.toString.call(value) === '[object Object]';
11
+
12
+ // The version of the app's package: package.json's three numbers and a 0, the fourth number, which the Store keeps for
13
+ // itself. The Store takes only a version above the last it has, which a prerelease cannot be told by.
14
+ export function msixVersion(version) {
15
+ const numbers = /^(\d+)\.(\d+)\.(\d+)$/.exec(version)?.slice(1).map(Number);
16
+ if (!numbers || numbers.some((number) => number > MAX_VERSION_NUMBER)) {
17
+ throw new Error(`crossbind: package.json's version ${JSON.stringify(version)} is no version of an MSIX package, which is three numbers from 0 to ${MAX_VERSION_NUMBER}, as 1.2.3 is: the Store cannot tell a prerelease, as 1.2.3-beta.1, from its release, and refuses the second.`);
18
+ }
19
+ return `${numbers.join('.')}.0`;
20
+ }
21
+
22
+ // app.windows.msix: the identity Partner Center's Product identity page gives the app, which its package for the Store
23
+ // carries as it is, or null.
24
+ export function storeIdentity(api) {
25
+ const identity = api.config.app.windows?.msix;
26
+ if (identity === undefined) return null;
27
+ if (!isPlainObject(identity)) {
28
+ throw new Error(`crossbind: app.windows.msix ${JSON.stringify(identity)} is no object of ${IDENTITY.join(', ')}, which Partner Center's Product identity page gives.`);
29
+ }
30
+ const unknown = Object.keys(identity).filter((key) => !IDENTITY.includes(key));
31
+ if (unknown.length > 0) throw new Error(`crossbind: app.windows.msix takes ${IDENTITY.join(', ')}; ${unknown.join(', ')} is none of them.`);
32
+ const missing = IDENTITY.filter((key) => typeof identity[key] !== 'string' || !identity[key].trim());
33
+ if (missing.length > 0) {
34
+ throw new Error(`crossbind: app.windows.msix has no ${missing.join(' or ')}, which Partner Center's Product identity page gives as Package/Identity/Name, Package/Identity/Publisher and Package/Properties/PublisherDisplayName.`);
35
+ }
36
+ return { name: packageName(identity.name, 'app.windows.msix.name'), publisher: identity.publisher, publisherDisplayName: identity.publisherDisplayName };
37
+ }
38
+
39
+ function packageName(name, where) {
40
+ if (!PACKAGE_NAME.test(name)) throw new Error(`crossbind: ${where} ${JSON.stringify(name)} is no name of an MSIX package, which is 3 to 50 letters, digits, dots and hyphens.`);
41
+ return name;
42
+ }
43
+
44
+ // The package's identity: the Store's, for a package the Store signs; or for one handed out, which the key that signs the
45
+ // app signs, the app's id and the subject of that key's certificate, which Windows holds the package's publisher to.
46
+ function identityOf(api) {
47
+ const store = storeIdentity(api);
48
+ if (store) return { ...store, isSigned: false };
49
+ if (!api.windows.signer) {
50
+ throw new Error("crossbind: an MSIX package the Store does not sign is signed with the app's key, which no CROSSBIND_WINDOWS_SIGNING_STORETYPE names, so Windows would install none: set the key, or give the Store's identity in app.windows.msix.");
51
+ }
52
+ const { subject } = signingCertificate(api);
53
+ return { name: packageName(api.app.id, "the app's id"), publisher: windowsPublisher(subject), publisherDisplayName: commonName(subject), isSigned: true };
54
+ }
55
+
56
+ // A build makes the app's package for the Store with app.windows.msix, and one handed out where app.installers names
57
+ // msix.
58
+ const isWanted = (api) => api.config.app.windows?.msix !== undefined || (api.config.app.installers ?? []).includes('msix');
59
+
60
+ // crossbind's installer of a Windows app as an MSIX package beside its folder, which the Microsoft Store takes, signs and
61
+ // updates, or which its developer hands out signed with the app's key. Windows starts the app from it with the package's
62
+ // identity, through its alias as well, and registers its URL schemes and file types.
63
+ export default function msix() {
64
+ return {
65
+ name: 'msix',
66
+ contract: 1,
67
+ root: import.meta.dirname,
68
+ reads: ['windows.msix'],
69
+ installer: {
70
+ platform: 'windows',
71
+ check(api) {
72
+ if (!isWanted(api)) return;
73
+ msixVersion(api.app.version);
74
+ identityOf(api);
75
+ if (api.config.app.icon === undefined) throw new Error('crossbind: an MSIX package shows the app by logos made from app.icon, which crossbind.config.js does not give.');
76
+ },
77
+ make(api, { app, arch }) {
78
+ if (!isWanted(api)) return [];
79
+ const identity = identityOf(api);
80
+ const executable = `${api.project.name}.exe`;
81
+ const manifest = appxManifest({
82
+ identity: { name: identity.name, publisher: identity.publisher, version: msixVersion(api.app.version), arch },
83
+ displayName: api.app.name,
84
+ publisherDisplayName: identity.publisherDisplayName,
85
+ description: api.project.package?.description || api.app.name,
86
+ executable,
87
+ urlSchemes: api.app.urlSchemes,
88
+ fileTypes: api.app.fileTypes,
89
+ alias: executable,
90
+ });
91
+ const logos = Object.values(LOGOS).map(({ file, size }) => ({ name: file, data: api.windows.logo(size) }));
92
+ const output = `${app}.msix`;
93
+ writeMsix({ files: [...filesIn(app), ...logos], manifest }, output);
94
+ if (identity.isSigned) api.run(['sh', api.windows.signer, path.basename(output)], { cwd: path.dirname(output), isSigning: true });
95
+ return [output];
96
+ },
97
+ },
98
+ };
99
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@crossbind/extension-msix",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0-beta.79",
4
+ "description": "crossbind app extension: a Windows app's MSIX package, for the Microsoft Store or handed out signed.",
5
+ "homepage": "https://github.com/crossbind/crossbind/tree/main/extensions/msix#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/crossbind/crossbind.git"
9
+ },
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "exports": {
13
+ "./crossbind.extension.js": "./crossbind.extension.js"
14
+ },
15
+ "files": [
16
+ "crossbind.extension.js",
17
+ "src/"
18
+ ],
19
+ "crossbind": {
20
+ "extension": "./crossbind.extension.js"
21
+ },
22
+ "keywords": [
23
+ "crossbind-extension",
24
+ "crossbind",
25
+ "msix",
26
+ "microsoft-store",
27
+ "installer",
28
+ "app"
29
+ ]
6
30
  }
@@ -0,0 +1,72 @@
1
+ import { xmlText } from './pack.js';
2
+
3
+ // Windows 10 1809, the first to run a Win32 app from its MSIX package without a converter.
4
+ const MIN_VERSION = '10.0.17763.0';
5
+ const MAX_VERSION_TESTED = '10.0.26100.0';
6
+
7
+ // The logos the manifest names, which the package carries at these sizes.
8
+ export const LOGOS = Object.freeze({
9
+ store: { file: 'Assets/StoreLogo.png', size: 50 },
10
+ square150: { file: 'Assets/Square150x150Logo.png', size: 150 },
11
+ square44: { file: 'Assets/Square44x44Logo.png', size: 44 },
12
+ });
13
+ const manifestPath = (file) => file.replaceAll('/', '\\');
14
+
15
+ // An extension a Win32 app's URL scheme or file type opens it by: Windows starts its executable with the URL or the
16
+ // file's path, as the app's setup program registers them.
17
+ const OPEN_ARGUMENT = '"%1"';
18
+ const protocolXml = (scheme) =>
19
+ `<uap3:Extension Category="windows.protocol"><uap3:Protocol Name="${xmlText(scheme)}" Parameters="${OPEN_ARGUMENT}"/></uap3:Extension>`;
20
+ const fileTypeXml = ({ name, extensions, mimeTypes }) =>
21
+ [
22
+ `<uap3:Extension Category="windows.fileTypeAssociation"><uap3:FileTypeAssociation Name="${extensions[0]}" Parameters="${OPEN_ARGUMENT}">`,
23
+ `<uap:DisplayName>${xmlText(name)}</uap:DisplayName><uap:SupportedFileTypes>`,
24
+ ...extensions.map((ending) => `<uap:FileType${mimeTypes[0] ? ` ContentType="${xmlText(mimeTypes[0])}"` : ''}>.${ending}</uap:FileType>`),
25
+ '</uap:SupportedFileTypes></uap3:FileTypeAssociation></uap3:Extension>',
26
+ ].join('');
27
+ const aliasXml = (alias) =>
28
+ `<uap3:Extension Category="windows.appExecutionAlias"><uap3:AppExecutionAlias><desktop:ExecutionAlias Alias="${xmlText(alias)}"/></uap3:AppExecutionAlias></uap3:Extension>`;
29
+
30
+ // The AppxManifest.xml of a Win32 app in an MSIX package: its identity, which the Store gives an app it publishes,
31
+ // its names and logos, the executable Windows starts with full trust, and what opens it.
32
+ export function appxManifest({
33
+ identity,
34
+ displayName,
35
+ publisherDisplayName,
36
+ description,
37
+ executable,
38
+ urlSchemes = [],
39
+ fileTypes = [],
40
+ alias = null,
41
+ }) {
42
+ const extensions = [...urlSchemes.map(protocolXml), ...fileTypes.map(fileTypeXml), ...(alias ? [aliasXml(alias)] : [])];
43
+ return `<?xml version="1.0" encoding="utf-8"?>
44
+ <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3" xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap uap3 desktop rescap">
45
+ <Identity Name="${xmlText(identity.name)}" Publisher="${xmlText(identity.publisher)}" Version="${identity.version}" ProcessorArchitecture="${identity.arch}"/>
46
+ <Properties>
47
+ <DisplayName>${xmlText(displayName)}</DisplayName>
48
+ <PublisherDisplayName>${xmlText(publisherDisplayName)}</PublisherDisplayName>
49
+ <Logo>${manifestPath(LOGOS.store.file)}</Logo>
50
+ </Properties>
51
+ <Dependencies>
52
+ <TargetDeviceFamily Name="Windows.Desktop" MinVersion="${MIN_VERSION}" MaxVersionTested="${MAX_VERSION_TESTED}"/>
53
+ </Dependencies>
54
+ <Resources>
55
+ <Resource Language="en-us"/>
56
+ </Resources>
57
+ <Applications>
58
+ <Application Id="App" Executable="${xmlText(executable)}" EntryPoint="Windows.FullTrustApplication">
59
+ <uap:VisualElements DisplayName="${xmlText(displayName)}" Description="${xmlText(description)}" BackgroundColor="transparent" Square150x150Logo="${manifestPath(LOGOS.square150.file)}" Square44x44Logo="${manifestPath(LOGOS.square44.file)}"/>${
60
+ extensions.length > 0
61
+ ? `
62
+ <Extensions>${extensions.join('')}</Extensions>`
63
+ : ''
64
+ }
65
+ </Application>
66
+ </Applications>
67
+ <Capabilities>
68
+ <rescap:Capability Name="runFullTrust"/>
69
+ </Capabilities>
70
+ </Package>
71
+ `;
72
+ }
package/src/pack.js ADDED
@@ -0,0 +1,242 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import zlib from 'node:zlib';
5
+
6
+ // An MSIX package as Microsoft's packaging SDK writes one (microsoft/msix-packaging, src/msix/pack): a ZIP64 archive
7
+ // with a data descriptor after each file, whose AppxBlockMap.xml holds the SHA-256 of every 64 KB block of every file.
8
+ // A compressed file deflates each block on its own, closed by a full flush, so the block map can give each block's
9
+ // compressed size; an empty final block ends its stream.
10
+ const BLOCK_SIZE = 65536;
11
+ const ZIP64_VERSION = 45;
12
+ const DATA_DESCRIPTOR_FLAG = 0x0008;
13
+ const DEFLATE = 8;
14
+ const STORE = 0;
15
+ const MAX32 = 0xffffffff;
16
+ // 1 Jan 2026, 00:00, so a package of the same files is the same bytes.
17
+ const DOS_DATE = ((2026 - 1980) << 9) | (1 << 5) | 1;
18
+ const DOS_TIME = 0;
19
+ const DEFLATE_OPTIONS = { level: 9, memLevel: 9 };
20
+
21
+ const MANIFEST = 'AppxManifest.xml';
22
+ const BLOCK_MAP = 'AppxBlockMap.xml';
23
+ const CONTENT_TYPES = '[Content_Types].xml';
24
+ const MANIFEST_TYPE = 'application/vnd.ms-appx.manifest+xml';
25
+ const BLOCK_MAP_TYPE = 'application/vnd.ms-appx.blockmap+xml';
26
+ const RESERVED_FILES = new Set([MANIFEST, BLOCK_MAP, CONTENT_TYPES, 'AppxSignature.p7x'].map((name) => name.toLowerCase()));
27
+ const RESERVED_FOLDER = 'appxmetadata/';
28
+
29
+ // The content types of the files an app carries, as the SDK names them; any other is a stream of bytes. The SDK stores
30
+ // what is compressed already, and deflates the rest.
31
+ const TYPES = {
32
+ css: 'text/css',
33
+ csv: 'text/csv',
34
+ dll: 'application/x-msdownload',
35
+ exe: 'application/x-msdownload',
36
+ gif: 'image/gif',
37
+ htm: 'text/html',
38
+ html: 'text/html',
39
+ ico: 'image/vnd.microsoft.icon',
40
+ jpeg: 'image/jpeg',
41
+ jpg: 'image/jpeg',
42
+ js: 'application/x-javascript',
43
+ json: 'application/json',
44
+ png: 'image/png',
45
+ svg: 'image/svg+xml',
46
+ txt: 'text/plain',
47
+ xml: 'text/xml',
48
+ zip: 'application/x-zip-compressed',
49
+ };
50
+ const STORED = new Set(['avi', 'cab', 'gif', 'gz', 'jpeg', 'jpg', 'm4a', 'mov', 'mp3', 'mpeg', 'mpg', 'png', 'rar', 'tar', 'wma', 'wmv', 'zip']);
51
+
52
+ const extensionOf = (name) => {
53
+ const base = name.slice(name.lastIndexOf('/') + 1);
54
+ const dot = base.lastIndexOf('.');
55
+ return dot >= 0 ? base.slice(dot + 1).toLowerCase() : '';
56
+ };
57
+
58
+ // A part's name in the ZIP: the characters the SDK escapes as %XX, and the UTF-8 bytes of the rest above ASCII.
59
+ const ESCAPED = new Set([' ', '!', '#', '$', '%', '&', "'", '(', ')', '+', ',', ';', '=', '@', '[', ']', '^', '`', '{', '}']);
60
+ export function partName(name) {
61
+ let encoded = '';
62
+ for (const char of name) {
63
+ if (char === '\\') encoded += '/';
64
+ else if (ESCAPED.has(char) || char.codePointAt(0) > 0x7f) {
65
+ encoded += [...Buffer.from(char, 'utf8')].map((byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`).join('');
66
+ } else encoded += char;
67
+ }
68
+ return encoded;
69
+ }
70
+
71
+ export const xmlText = (text) => text.replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[char]);
72
+
73
+ // The [Content_Types].xml of the parts: a Default for each extension's first type, an Override for a part with no
74
+ // extension or another type than its extension's.
75
+ function contentTypesXml(parts) {
76
+ const defaults = new Map();
77
+ const lines = [];
78
+ for (const { name, type } of parts) {
79
+ const extension = extensionOf(name);
80
+ if (extension && !defaults.has(extension)) {
81
+ defaults.set(extension, type);
82
+ lines.push(`<Default Extension="${xmlText(extension)}" ContentType="${type}"/>`);
83
+ } else if (!extension || defaults.get(extension) !== type) {
84
+ lines.push(`<Override PartName="/${xmlText(partName(name))}" ContentType="${type}"/>`);
85
+ }
86
+ }
87
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${lines.join('')}</Types>`;
88
+ }
89
+
90
+ function blockMapXml(files) {
91
+ const entries = files.map(({ name, size, lfhSize, blocks }) => {
92
+ const children = blocks.map(
93
+ ({ hash, size: compressed }) => `<Block Hash="${hash}"${compressed === undefined ? '' : ` Size="${compressed}"`}/>`,
94
+ );
95
+ return `<File Name="${xmlText(name.replaceAll('/', '\\'))}" Size="${size}" LfhSize="${lfhSize}">${children.join('')}</File>`;
96
+ });
97
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<BlockMap xmlns="http://schemas.microsoft.com/appx/2010/blockmap" HashMethod="http://www.w3.org/2001/04/xmlenc#sha256">${entries.join('')}</BlockMap>`;
98
+ }
99
+
100
+ function localHeader(name, method) {
101
+ const header = Buffer.alloc(30);
102
+ header.writeUInt32LE(0x04034b50, 0);
103
+ header.writeUInt16LE(ZIP64_VERSION, 4);
104
+ header.writeUInt16LE(DATA_DESCRIPTOR_FLAG, 6);
105
+ header.writeUInt16LE(method, 8);
106
+ header.writeUInt16LE(DOS_TIME, 10);
107
+ header.writeUInt16LE(DOS_DATE, 12);
108
+ header.writeUInt16LE(name.length, 26);
109
+ return Buffer.concat([header, name]);
110
+ }
111
+
112
+ function dataDescriptor(crc, compressed, uncompressed) {
113
+ const descriptor = Buffer.alloc(24);
114
+ descriptor.writeUInt32LE(0x08074b50, 0);
115
+ descriptor.writeUInt32LE(crc, 4);
116
+ descriptor.writeBigUInt64LE(BigInt(compressed), 8);
117
+ descriptor.writeBigUInt64LE(BigInt(uncompressed), 16);
118
+ return descriptor;
119
+ }
120
+
121
+ function centralHeader({ name, method, crc, compressed, uncompressed, offset }) {
122
+ const large = [uncompressed, compressed, offset].filter((value) => value >= MAX32);
123
+ const extra = Buffer.alloc(large.length > 0 ? 4 + 8 * large.length : 0);
124
+ if (large.length > 0) {
125
+ extra.writeUInt16LE(0x0001, 0);
126
+ extra.writeUInt16LE(8 * large.length, 2);
127
+ large.forEach((value, index) => extra.writeBigUInt64LE(BigInt(value), 4 + 8 * index));
128
+ }
129
+ const header = Buffer.alloc(46);
130
+ header.writeUInt32LE(0x02014b50, 0);
131
+ header.writeUInt16LE(ZIP64_VERSION, 4);
132
+ header.writeUInt16LE(ZIP64_VERSION, 6);
133
+ header.writeUInt16LE(DATA_DESCRIPTOR_FLAG, 8);
134
+ header.writeUInt16LE(method, 10);
135
+ header.writeUInt16LE(DOS_TIME, 12);
136
+ header.writeUInt16LE(DOS_DATE, 14);
137
+ header.writeUInt32LE(crc, 16);
138
+ header.writeUInt32LE(Math.min(compressed, MAX32), 20);
139
+ header.writeUInt32LE(Math.min(uncompressed, MAX32), 24);
140
+ header.writeUInt16LE(name.length, 28);
141
+ header.writeUInt16LE(extra.length, 30);
142
+ header.writeUInt32LE(Math.min(offset, MAX32), 42);
143
+ return Buffer.concat([header, name, extra]);
144
+ }
145
+
146
+ function endRecords(count, size, offset) {
147
+ const zip64 = Buffer.alloc(56);
148
+ zip64.writeUInt32LE(0x06064b50, 0);
149
+ zip64.writeBigUInt64LE(44n, 4);
150
+ zip64.writeUInt16LE(ZIP64_VERSION, 12);
151
+ zip64.writeUInt16LE(ZIP64_VERSION, 14);
152
+ zip64.writeBigUInt64LE(BigInt(count), 24);
153
+ zip64.writeBigUInt64LE(BigInt(count), 32);
154
+ zip64.writeBigUInt64LE(BigInt(size), 40);
155
+ zip64.writeBigUInt64LE(BigInt(offset), 48);
156
+ const locator = Buffer.alloc(20);
157
+ locator.writeUInt32LE(0x07064b50, 0);
158
+ locator.writeBigUInt64LE(BigInt(offset + size), 8);
159
+ locator.writeUInt32LE(1, 16);
160
+ const end = Buffer.alloc(22);
161
+ end.writeUInt32LE(0x06054b50, 0);
162
+ end.writeUInt16LE(0xffff, 8);
163
+ end.writeUInt16LE(0xffff, 10);
164
+ end.writeUInt32LE(MAX32, 12);
165
+ end.writeUInt32LE(MAX32, 16);
166
+ return Buffer.concat([zip64, locator, end]);
167
+ }
168
+
169
+ // Every file under a folder, by its path inside it with forward slashes, in a fixed order.
170
+ export function filesIn(root) {
171
+ const found = [];
172
+ const walk = (dir) => {
173
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
174
+ const file = path.join(dir, entry.name);
175
+ if (entry.isDirectory()) walk(file);
176
+ else if (entry.isFile()) found.push({ name: path.relative(root, file).split(path.sep).join('/'), file });
177
+ }
178
+ };
179
+ walk(root);
180
+ return found;
181
+ }
182
+
183
+ // Writes an MSIX package of the files ({ name, file } or { name, data }) and the manifest's text to output.
184
+ export function writeMsix({ files, manifest }, output) {
185
+ const fd = fs.openSync(output, 'w');
186
+ let offset = 0;
187
+ const write = (buffer) => {
188
+ fs.writeSync(fd, buffer);
189
+ offset += buffer.length;
190
+ };
191
+ const central = [];
192
+ const mapped = [];
193
+ const typed = [];
194
+
195
+ const add = (name, data, { type, inBlockMap, encodeName = true }) => {
196
+ const isCompressed = !STORED.has(extensionOf(name));
197
+ const method = isCompressed ? DEFLATE : STORE;
198
+ const zipName = Buffer.from(encodeName ? partName(name) : name, 'utf8');
199
+ const start = offset;
200
+ write(localHeader(zipName, method));
201
+ let crc = 0;
202
+ let compressed = 0;
203
+ const blocks = [];
204
+ for (let at = 0; at < data.length; at += BLOCK_SIZE) {
205
+ const block = data.subarray(at, Math.min(at + BLOCK_SIZE, data.length));
206
+ crc = zlib.crc32(block, crc);
207
+ const hash = crypto.createHash('sha256').update(block).digest('base64');
208
+ const bytes = isCompressed ? zlib.deflateRawSync(block, { ...DEFLATE_OPTIONS, finishFlush: zlib.constants.Z_FULL_FLUSH }) : block;
209
+ write(bytes);
210
+ compressed += bytes.length;
211
+ blocks.push(isCompressed ? { hash, size: bytes.length } : { hash });
212
+ }
213
+ if (isCompressed) {
214
+ const end = zlib.deflateRawSync(Buffer.alloc(0), DEFLATE_OPTIONS);
215
+ write(end);
216
+ compressed += end.length;
217
+ }
218
+ write(dataDescriptor(crc, compressed, data.length));
219
+ central.push(centralHeader({ name: zipName, method, crc, compressed, uncompressed: data.length, offset: start }));
220
+ if (inBlockMap) mapped.push({ name, size: data.length, lfhSize: 30 + zipName.length, blocks });
221
+ if (type) typed.push({ name, type });
222
+ };
223
+
224
+ try {
225
+ for (const { name, file, data } of files) {
226
+ const lower = name.toLowerCase();
227
+ if (RESERVED_FILES.has(lower) || lower.startsWith(RESERVED_FOLDER)) {
228
+ throw new Error(`crossbind: ${name} is a file an MSIX package makes itself, and no file of the app may take its name.`);
229
+ }
230
+ add(name, data ?? fs.readFileSync(file), { type: TYPES[extensionOf(name)] ?? 'application/octet-stream', inBlockMap: true });
231
+ }
232
+ add(MANIFEST, Buffer.from(manifest, 'utf8'), { type: MANIFEST_TYPE, inBlockMap: true });
233
+ add(BLOCK_MAP, Buffer.from(blockMapXml(mapped), 'utf8'), { type: BLOCK_MAP_TYPE, inBlockMap: false });
234
+ add(CONTENT_TYPES, Buffer.from(contentTypesXml(typed), 'utf8'), { inBlockMap: false, encodeName: false });
235
+ const directoryOffset = offset;
236
+ for (const header of central) write(header);
237
+ write(endRecords(central.length, offset - directoryOffset, directoryOffset));
238
+ } finally {
239
+ fs.closeSync(fd);
240
+ }
241
+ return output;
242
+ }
@@ -0,0 +1,70 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const CERTFILE = 'CROSSBIND_WINDOWS_SIGNING_CERTFILE';
6
+ const CERTIFICATE = /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/;
7
+ // Windows' names of a subject's attributes, as it writes a certificate's subject and a package's publisher, by
8
+ // OpenSSL's; another keeps OpenSSL's.
9
+ const WINDOWS_NAMES = { ST: 'S', emailAddress: 'E', street: 'STREET', title: 'T', GN: 'G', givenName: 'G', SN: 'SN', serialNumber: 'SERIALNUMBER' };
10
+ // What Windows quotes in a value of a name.
11
+ const QUOTED = /[,+=";<>#\n]|^\s|\s$/;
12
+
13
+ // A value as RFC 2253 escapes it, as Node gives a subject: a backslash before a character, or before two hex digits of a
14
+ // byte of its UTF-8.
15
+ function unescaped(value) {
16
+ const bytes = [];
17
+ for (let at = 0; at < value.length; at += 1) {
18
+ if (value[at] === '\\' && /^[0-9A-Fa-f]{2}$/.test(value.slice(at + 1, at + 3))) {
19
+ bytes.push(parseInt(value.slice(at + 1, at + 3), 16));
20
+ at += 2;
21
+ } else {
22
+ if (value[at] === '\\') at += 1;
23
+ bytes.push(...Buffer.from(value[at] ?? '', 'utf8'));
24
+ }
25
+ }
26
+ return Buffer.from(bytes).toString('utf8');
27
+ }
28
+
29
+ // A certificate's subject, as Node gives it, one name a line in the certificate's order, as Windows writes it and an
30
+ // MSIX package's publisher must be: its most particular name first, as CN=Example, O=Example, C=TR.
31
+ export function windowsPublisher(subject) {
32
+ return subject.split('\n').reverse().map((line) => line.split(/(?<!\\) \+ /).map((part) => {
33
+ const at = part.indexOf('=');
34
+ const type = part.slice(0, at);
35
+ const value = unescaped(part.slice(at + 1));
36
+ return `${WINDOWS_NAMES[type] ?? type}=${QUOTED.test(value) ? `"${value.replaceAll('"', '""')}"` : value}`;
37
+ }).join(' + ')).join(', ');
38
+ }
39
+
40
+ // The common name of a certificate's subject, as Node gives it, or the whole subject without one.
41
+ export function commonName(subject) {
42
+ const line = subject.split('\n').find((name) => name.startsWith('CN='));
43
+ return line ? unescaped(line.slice('CN='.length)) : windowsPublisher(subject);
44
+ }
45
+
46
+ // The certificate that signs the app: CROSSBIND_WINDOWS_SIGNING_CERTFILE's, else the one the keystore holds, which keytool
47
+ // prints in the windows image, where the keystore is.
48
+ export function signingCertificate(api) {
49
+ const certfile = process.env[CERTFILE];
50
+ if (certfile) return certificateOf(fs.readFileSync(certfile), certfile);
51
+ if (!['PKCS12', 'JKS', 'JCEKS'].includes(process.env.CROSSBIND_WINDOWS_SIGNING_STORETYPE?.toUpperCase())) {
52
+ throw new Error(`crossbind: an MSIX package names its publisher as the certificate that signs it does, which crossbind reads from ${CERTFILE} or a keystore file. Set ${CERTFILE} to the certificate of the cloud's key, or give the Store's identity in app.windows.msix.`);
53
+ }
54
+ fs.mkdirSync(api.workDir, { recursive: true });
55
+ const listing = path.join(api.workDir, 'signing-certificate.txt');
56
+ api.run(['sh', '-c', 'keytool -list -rfc ${CROSSBIND_WINDOWS_SIGNING_ALIAS:+-alias "$CROSSBIND_WINDOWS_SIGNING_ALIAS"} -keystore "$CROSSBIND_WINDOWS_SIGNING_KEYSTORE" -storetype "$CROSSBIND_WINDOWS_SIGNING_STORETYPE" ${CROSSBIND_WINDOWS_SIGNING_STOREPASS:+-storepass:env CROSSBIND_WINDOWS_SIGNING_STOREPASS} > "$1"', 'sh', path.basename(listing)], { cwd: api.workDir, isSigning: true });
57
+ try {
58
+ return certificateOf(fs.readFileSync(listing, 'utf8').match(CERTIFICATE)?.[0] ?? '', 'the keystore');
59
+ } finally {
60
+ fs.rmSync(listing, { force: true });
61
+ }
62
+ }
63
+
64
+ function certificateOf(bytes, where) {
65
+ try {
66
+ return new crypto.X509Certificate(bytes);
67
+ } catch (error) {
68
+ throw new Error(`crossbind: ${where} holds no certificate crossbind reads, in PEM or DER: ${error.message}`, { cause: error });
69
+ }
70
+ }