first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Declare files that will always have specific line endings on checkout.
*.sh text eol=lf
cli.js text eol=lf
*.ps1 text eol=CRLF
+11
View File
@@ -0,0 +1,11 @@
office-addin-dev-certs v0.0.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+81
View File
@@ -0,0 +1,81 @@
# Office-Addin-dev-certs
This package can be used to manage certificates for development server using https://localhost.
## Installation
```
npm install office-addin-dev-certs
```
Upon installation a development CA certicate and localhost key and
certificate will be generated inside `<userhome>/.office-addin-dev-certs`.
The certificate is valid for 30 days by default.
#
## Command-Line Interface
* [install](#install)
* [verify](#verify)
* [uninstall](#uninstall)
#
### install
Creates an SSL certificate for "localhost" signed by a developer CA certificate and installs the developer CA certificate so that the certificates are trusted. If the certificates were installed but are no longer valid, they will be replaced with valid certificates.
Syntax:
`office-addin-dev-certs install [options]`
Options:
`--machine`
Install the CA certificate for all users. You must be an Administrator.
`--days <days>`
Specifies the number of days until the CA certificate expires. Default: 30 days.
#
### verify
Verify the certificate.
Syntax:
`office-addin-dev-certs verify`
#
### uninstall
Uninstall the certificate.
Syntax:
`office-addin-dev-certs uninstall [options]`
Options:
`--machine`
Uninstall the CA certificate for all users. You must be an Administrator.
#
## API Usage
```js
var https = require('https')
var devCerts = require("office-addin-dev-certs");
var options = await devCerts.getHttpsServerOptions();
var server = https.createServer(options, function (req, res) {
res.end('This is servered over HTTPS')
})
server.listen(443, function () {
console.log('The server is running on https://localhost:443')
})
```
Generated Vendored Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env node
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
//
// If the package.json bin config specifies a file in the lib folder, it will cause an
// error during "npm install" if the lib folder doesn't exist (because the package hasn't been built yet).
// It specifies this file instead which then calls into the file in the lib folder.
require("./lib/cli.js");
+14
View File
@@ -0,0 +1,14 @@
import officeAddins from "eslint-plugin-office-addins";
import tsParser from "@typescript-eslint/parser";
export default [
...officeAddins.configs.recommended,
{
plugins: {
"office-addins": officeAddins,
},
languageOptions: {
parser: tsParser,
},
},
];
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const commands = __importStar(require("./commands"));
const defaults = __importStar(require("./defaults"));
/* global process */
const commander = new commander_1.Command();
commander.name("office-addin-dev-certs");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command("install")
.option("--machine", "Install the CA certificate for all users. You must be an Administrator.")
.option("--days <days>", `Specifies the validity of CA certificate in days. Default: ${defaults.daysUntilCertificateExpires}`)
.option("--domains <domains>", `List of IP address and domains separated by commas. Default: ${defaults.domain.join(",")}`)
.description(`Generate an SSL certificate for "localhost" issued by a CA certificate which is installed.`)
.action(commands.install);
commander.command("verify").description(`Verify the CA certificate.`).action(commands.verify);
commander
.command("uninstall")
.option("--machine", "Uninstall the CA certificate for all users. You must be an Administrator.")
.description(`Uninstall the certificate.`)
.action(commands.uninstall);
// if the command is not known, display an error
commander.on("command:*", function () {
(0, office_addin_usage_data_1.logErrorMessage)(`The command syntax is not valid.\n`);
process.exitCode = 1;
commander.help();
});
if (process.argv.length > 2) {
commander.parse(process.argv);
}
else {
commander.help();
}
//# sourceMappingURL=cli.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;AAEA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,yCAAoC;AACpC,qEAA0D;AAC1D,qDAAuC;AACvC,qDAAuC;AAEvC,oBAAoB;AAEpB,MAAM,SAAS,GAAG,IAAI,mBAAO,EAAE,CAAC;AAEhC,SAAS,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;AACzC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,yBAAyB,CAAC,CAAC;AAEhF,SAAS;KACN,OAAO,CAAC,SAAS,CAAC;KAClB,MAAM,CAAC,WAAW,EAAE,yEAAyE,CAAC;KAC9F,MAAM,CACL,eAAe,EACf,8DAA8D,QAAQ,CAAC,2BAA2B,EAAE,CACrG;KACA,MAAM,CACL,qBAAqB,EACrB,gEAAgE,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAC5F;KACA,WAAW,CACV,4FAA4F,CAC7F;KACA,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAE5B,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC,4BAA4B,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAE9F,SAAS;KACN,OAAO,CAAC,WAAW,CAAC;KACpB,MAAM,CAAC,WAAW,EAAE,2EAA2E,CAAC;KAChG,WAAW,CAAC,4BAA4B,CAAC;KACzC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAE9B,gDAAgD;AAChD,SAAS,CAAC,EAAE,CAAC,WAAW,EAAE;IACxB,IAAA,yCAAe,EAAC,oCAAoC,CAAC,CAAC;IACtD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACrB,SAAS,CAAC,IAAI,EAAE,CAAC;AACnB,CAAC,CAAC,CAAC;AAEH,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;IAC3B,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;KAAM;IACL,SAAS,CAAC,IAAI,EAAE,CAAC;CAClB"}
+4
View File
@@ -0,0 +1,4 @@
import { OptionValues } from "commander";
export declare function install(options: OptionValues): Promise<void>;
export declare function uninstall(options: OptionValues): Promise<void>;
export declare function verify(options: OptionValues): Promise<void>;
+124
View File
@@ -0,0 +1,124 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verify = exports.uninstall = exports.install = void 0;
const office_addin_cli_1 = require("office-addin-cli");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const defaults = __importStar(require("./defaults"));
const install_1 = require("./install");
const uninstall_1 = require("./uninstall");
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_2 = require("office-addin-usage-data");
/* global console */
function install(options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const days = parseDays(options.days);
const domains = parseDomains(options.domains);
yield (0, install_1.ensureCertificatesAreInstalled)(days, domains, options.machine);
defaults_1.usageDataObject.reportSuccess("install");
}
catch (err) {
defaults_1.usageDataObject.reportException("install", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.install = install;
function parseDays(optionValue) {
const days = (0, office_addin_cli_1.parseNumber)(optionValue, "--days should specify a number.");
if (days !== undefined) {
if (!Number.isInteger(days)) {
throw new office_addin_usage_data_2.ExpectedError("--days should be integer.");
}
if (days <= 0) {
throw new office_addin_usage_data_2.ExpectedError("--days should be greater than zero.");
}
}
return days;
}
function parseDomains(optionValue) {
switch (typeof optionValue) {
case "string": {
try {
return optionValue.split(",");
}
catch (_a) {
throw new Error("string value not in the correct format");
}
}
case "undefined": {
return undefined;
}
default: {
throw new Error("--domains value should be a string.");
}
}
}
function uninstall(options) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield (0, uninstall_1.uninstallCaCertificate)(options.machine);
(0, uninstall_1.deleteCertificateFiles)(defaults.certificateDirectory);
defaults_1.usageDataObject.reportSuccess("uninstall");
}
catch (err) {
defaults_1.usageDataObject.reportException("uninstall", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.uninstall = uninstall;
function verify(options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (yield (0, verify_1.verifyCertificates)()) {
console.log(`You have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
else {
console.log(`You need to install certificates for trusted access to https://localhost.`);
}
defaults_1.usageDataObject.reportSuccess("verify");
}
catch (err) {
defaults_1.usageDataObject.reportException("verify", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.verify = verify;
//# sourceMappingURL=commands.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;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CAAC,wCAAwC,CAAC,CAAC;aAC3D;SACF;QACD,KAAK,WAAW,CAAC,CAAC;YAChB,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,CAAC,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;SACxD;KACF;AACH,CAAC;AAED,SAAsB,SAAS,CAAC,OAAqB;;QACnD,IAAI;YACF,MAAM,IAAA,kCAAsB,EAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAC9C,IAAA,kCAAsB,EAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAC;YACtD,0BAAe,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;SAC5C;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;YAClD,IAAA,yCAAe,EAAC,GAAG,CAAC,CAAC;SACtB;IACH,CAAC;CAAA;AATD,8BASC;AAED,SAAsB,MAAM,CAC1B,OAAqB,CAAC,2DAA2D;;QAEjF,IAAI;YACF,IAAI,MAAM,IAAA,2BAAkB,GAAE,EAAE;gBAC9B,OAAO,CAAC,GAAG,CACT,+DAA+D,QAAQ,CAAC,wBAAwB,UAAU,QAAQ,CAAC,gBAAgB,EAAE,CACtI,CAAC;aACH;iBAAM;gBACL,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;aAC1F;YACD,0BAAe,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;SACzC;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC/C,IAAA,yCAAe,EAAC,GAAG,CAAC,CAAC;SACtB;IACH,CAAC;CAAA;AAhBD,wBAgBC"}
+16
View File
@@ -0,0 +1,16 @@
import { OfficeAddinUsageData } from "office-addin-usage-data";
export declare const certificateDirectoryName = ".office-addin-dev-certs";
export declare const certificateDirectory: string;
export declare const caCertificateFileName = "ca.crt";
export declare const caCertificatePath: string;
export declare const localhostCertificateFileName = "localhost.crt";
export declare const localhostCertificatePath: string;
export declare const localhostKeyFileName = "localhost.key";
export declare const localhostKeyPath: string;
export declare const certificateName = "Developer CA for Microsoft Office Add-ins";
export declare const countryCode = "US";
export declare const daysUntilCertificateExpires = 30;
export declare const domain: string[];
export declare const locality = "Redmond";
export declare const state = "WA";
export declare const usageDataObject: OfficeAddinUsageData;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.usageDataObject = exports.state = exports.locality = exports.domain = exports.daysUntilCertificateExpires = exports.countryCode = exports.certificateName = exports.localhostKeyPath = exports.localhostKeyFileName = exports.localhostCertificatePath = exports.localhostCertificateFileName = exports.caCertificatePath = exports.caCertificateFileName = exports.certificateDirectory = exports.certificateDirectoryName = void 0;
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const office_addin_usage_data_1 = require("office-addin-usage-data");
// Default certificate names
exports.certificateDirectoryName = ".office-addin-dev-certs";
exports.certificateDirectory = path_1.default.join(os_1.default.homedir(), exports.certificateDirectoryName);
exports.caCertificateFileName = "ca.crt";
exports.caCertificatePath = path_1.default.join(exports.certificateDirectory, exports.caCertificateFileName);
exports.localhostCertificateFileName = "localhost.crt";
exports.localhostCertificatePath = path_1.default.join(exports.certificateDirectory, exports.localhostCertificateFileName);
exports.localhostKeyFileName = "localhost.key";
exports.localhostKeyPath = path_1.default.join(exports.certificateDirectory, exports.localhostKeyFileName);
// Default certificate details
exports.certificateName = "Developer CA for Microsoft Office Add-ins";
exports.countryCode = "US";
exports.daysUntilCertificateExpires = 30;
exports.domain = ["127.0.0.1", "localhost"];
exports.locality = "Redmond";
exports.state = "WA";
// Usage data defaults
exports.usageDataObject = new office_addin_usage_data_1.OfficeAddinUsageData({
projectName: "office-addin-dev-certs",
instrumentationKey: office_addin_usage_data_1.instrumentationKeyForOfficeAddinCLITools,
raisePrompt: false,
});
//# sourceMappingURL=defaults.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;AAElC,4CAAoB;AACpB,gDAAwB;AACxB,qEAGiC;AAEjC,4BAA4B;AACf,QAAA,wBAAwB,GAAG,yBAAyB,CAAC;AACrD,QAAA,oBAAoB,GAAG,cAAI,CAAC,IAAI,CAAC,YAAE,CAAC,OAAO,EAAE,EAAE,gCAAwB,CAAC,CAAC;AACzE,QAAA,qBAAqB,GAAG,QAAQ,CAAC;AACjC,QAAA,iBAAiB,GAAG,cAAI,CAAC,IAAI,CAAC,4BAAoB,EAAE,6BAAqB,CAAC,CAAC;AAC3E,QAAA,4BAA4B,GAAG,eAAe,CAAC;AAC/C,QAAA,wBAAwB,GAAG,cAAI,CAAC,IAAI,CAC/C,4BAAoB,EACpB,oCAA4B,CAC7B,CAAC;AACW,QAAA,oBAAoB,GAAG,eAAe,CAAC;AACvC,QAAA,gBAAgB,GAAG,cAAI,CAAC,IAAI,CAAC,4BAAoB,EAAE,4BAAoB,CAAC,CAAC;AAEtF,8BAA8B;AACjB,QAAA,eAAe,GAAG,2CAA2C,CAAC;AAC9D,QAAA,WAAW,GAAG,IAAI,CAAC;AACnB,QAAA,2BAA2B,GAAG,EAAE,CAAC;AACjC,QAAA,MAAM,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACpC,QAAA,QAAQ,GAAG,SAAS,CAAC;AACrB,QAAA,KAAK,GAAG,IAAI,CAAC;AAE1B,sBAAsB;AACT,QAAA,eAAe,GAAyB,IAAI,8CAAoB,CAAC;IAC5E,WAAW,EAAE,wBAAwB;IACrC,kBAAkB,EAAE,kEAAwC;IAC5D,WAAW,EAAE,KAAK;CACnB,CAAC,CAAC"}
+1
View File
@@ -0,0 +1 @@
export declare function generateCertificates(caCertificatePath?: string, localhostCertificatePath?: string, localhostKeyPath?: string, daysUntilCertificateExpires?: number, domains?: string[]): Promise<void>;
+106
View File
@@ -0,0 +1,106 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCertificates = void 0;
const fs_1 = __importDefault(require("fs"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const mkcert = __importStar(require("mkcert"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
/* global console */
/* Generate operation will check if there is already valid certificate installed.
if yes, then this operation will be no op.
else, new certificates are generated and installed if --install was provided.
*/
function generateCertificates(caCertificatePath = defaults.caCertificatePath, localhostCertificatePath = defaults.localhostCertificatePath, localhostKeyPath = defaults.localhostKeyPath, daysUntilCertificateExpires = defaults.daysUntilCertificateExpires, domains = defaults.domain) {
return __awaiter(this, void 0, void 0, function* () {
try {
fs_extra_1.default.ensureDirSync(path_1.default.dirname(caCertificatePath));
fs_extra_1.default.ensureDirSync(path_1.default.dirname(localhostCertificatePath));
fs_extra_1.default.ensureDirSync(path_1.default.dirname(localhostKeyPath));
}
catch (err) {
throw new Error(`Unable to create the directory.\n${err}`);
}
const cACertificateInfo = {
countryCode: defaults.countryCode,
locality: defaults.locality,
organization: defaults.certificateName,
state: defaults.state,
validity: daysUntilCertificateExpires,
};
let caCertificate;
try {
caCertificate = yield mkcert.createCA(cACertificateInfo);
}
catch (err) {
throw new Error(`Unable to generate the CA certificate.\n${err}`);
}
const localhostCertificateInfo = {
ca: caCertificate,
domains,
validity: daysUntilCertificateExpires,
};
let localhostCertificate;
try {
localhostCertificate = yield mkcert.createCert(localhostCertificateInfo);
}
catch (err) {
throw new Error(`Unable to generate the localhost certificate.\n${err}`);
}
try {
if (!fs_1.default.existsSync(caCertificatePath)) {
fs_1.default.writeFileSync(`${caCertificatePath}`, caCertificate.cert);
fs_1.default.writeFileSync(`${localhostCertificatePath}`, localhostCertificate.cert);
fs_1.default.writeFileSync(`${localhostKeyPath}`, localhostCertificate.key);
}
}
catch (err) {
throw new Error(`Unable to write generated certificates.\n${err}`);
}
if (caCertificatePath === defaults.caCertificatePath) {
console.log("The developer certificates have been generated in " + defaults.certificateDirectory);
}
else {
console.log("The developer certificates have been generated.");
}
});
}
exports.generateCertificates = generateCertificates;
//# sourceMappingURL=generate.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../src/generate.ts"],"names":[],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;YACP,QAAQ,EAAE,2BAA2B;SACtC,CAAC;QACF,IAAI,oBAAwC,CAAC;QAC7C,IAAI;YACF,oBAAoB,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,wBAAwB,CAAC,CAAC;SAC1E;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,kDAAkD,GAAG,EAAE,CAAC,CAAC;SAC1E;QAED,IAAI;YACF,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE;gBACrC,YAAE,CAAC,aAAa,CAAC,GAAG,iBAAiB,EAAE,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;gBAC7D,YAAE,CAAC,aAAa,CAAC,GAAG,wBAAwB,EAAE,EAAE,oBAAoB,CAAC,IAAI,CAAC,CAAC;gBAC3E,YAAE,CAAC,aAAa,CAAC,GAAG,gBAAgB,EAAE,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC;aACnE;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,4CAA4C,GAAG,EAAE,CAAC,CAAC;SACpE;QAED,IAAI,iBAAiB,KAAK,QAAQ,CAAC,iBAAiB,EAAE;YACpD,OAAO,CAAC,GAAG,CACT,oDAAoD,GAAG,QAAQ,CAAC,oBAAoB,CACrF,CAAC;SACH;aAAM;YACL,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;SAChE;IACH,CAAC;CAAA;AA1DD,oDA0DC"}
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="node" />
interface IHttpsServerOptions {
ca: Buffer;
cert: Buffer;
key: Buffer;
}
export declare function getHttpsServerOptions(daysUntilCertificateExpires?: number, domains?: string[], machine?: boolean): Promise<IHttpsServerOptions>;
export {};
+70
View File
@@ -0,0 +1,70 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHttpsServerOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const defaults = __importStar(require("./defaults"));
const install_1 = require("./install");
function getHttpsServerOptions(daysUntilCertificateExpires, domains, machine) {
return __awaiter(this, void 0, void 0, function* () {
yield (0, install_1.ensureCertificatesAreInstalled)(daysUntilCertificateExpires, domains, machine);
const httpsServerOptions = {};
try {
httpsServerOptions.ca = fs_1.default.readFileSync(defaults.caCertificatePath);
}
catch (err) {
throw new Error(`Unable to read the CA certificate file.\n${err}`);
}
try {
httpsServerOptions.cert = fs_1.default.readFileSync(defaults.localhostCertificatePath);
}
catch (err) {
throw new Error(`Unable to read the certificate file.\n${err}`);
}
try {
httpsServerOptions.key = fs_1.default.readFileSync(defaults.localhostKeyPath);
}
catch (err) {
throw new Error(`Unable to read the certificate key.\n${err}`);
}
return httpsServerOptions;
});
}
exports.getHttpsServerOptions = getHttpsServerOptions;
//# sourceMappingURL=httpsServerOptions.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"httpsServerOptions.js","sourceRoot":"","sources":["../src/httpsServerOptions.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,4CAAoB;AACpB,qDAAuC;AACvC,uCAA2D;AAU3D,SAAsB,qBAAqB,CACzC,2BAAoC,EACpC,OAAkB,EAClB,OAAiB;;QAEjB,MAAM,IAAA,wCAA8B,EAAC,2BAA2B,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAEpF,MAAM,kBAAkB,GAAG,EAAyB,CAAC;QACrD,IAAI;YACF,kBAAkB,CAAC,EAAE,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC;SACrE;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,4CAA4C,GAAG,EAAE,CAAC,CAAC;SACpE;QAED,IAAI;YACF,kBAAkB,CAAC,IAAI,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,wBAAwB,CAAC,CAAC;SAC9E;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,EAAE,CAAC,CAAC;SACjE;QAED,IAAI;YACF,kBAAkB,CAAC,GAAG,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;SACrE;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,wCAAwC,GAAG,EAAE,CAAC,CAAC;SAChE;QAED,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CAAA;AA3BD,sDA2BC"}
+2
View File
@@ -0,0 +1,2 @@
export declare function ensureCertificatesAreInstalled(daysUntilCertificateExpires?: number, domains?: string[], machine?: boolean): Promise<void>;
export declare function installCaCertificate(caCertificatePath?: string, machine?: boolean): Promise<void>;
+111
View File
@@ -0,0 +1,111 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installCaCertificate = exports.ensureCertificatesAreInstalled = void 0;
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const generate_1 = require("./generate");
const uninstall_1 = require("./uninstall");
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process __dirname */
function getInstallCommand(caCertificatePath, machine = false) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\install.ps1");
return `powershell -ExecutionPolicy Bypass -File "${script}" ${machine ? "LocalMachine" : "CurrentUser"} "${caCertificatePath}"`;
}
case "darwin": {
// macOS
const prefix = machine ? "sudo " : "";
const keychainFile = machine
? "/Library/Keychains/System.keychain"
: "~/Library/Keychains/login.keychain-db";
return `${prefix}security add-trusted-cert -d -r trustRoot -k ${keychainFile} '${caCertificatePath}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/install_linux.sh");
return `sudo sh '${script}' '${caCertificatePath}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
function ensureCertificatesAreInstalled(daysUntilCertificateExpires = defaults.daysUntilCertificateExpires, domains = defaults.domain, machine = false) {
return __awaiter(this, void 0, void 0, function* () {
try {
const areCertificatesValid = (0, verify_1.verifyCertificates)();
if (areCertificatesValid) {
console.log(`You already have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
else {
yield (0, uninstall_1.uninstallCaCertificate)(false, false);
(0, uninstall_1.deleteCertificateFiles)(defaults.certificateDirectory);
yield (0, generate_1.generateCertificates)(defaults.caCertificatePath, defaults.localhostCertificatePath, defaults.localhostKeyPath, daysUntilCertificateExpires, domains);
yield installCaCertificate(defaults.caCertificatePath, machine);
}
defaults_1.usageDataObject.reportSuccess("ensureCertificatesAreInstalled()");
}
catch (err) {
defaults_1.usageDataObject.reportException("ensureCertificatesAreInstalled()", err);
throw err;
}
});
}
exports.ensureCertificatesAreInstalled = ensureCertificatesAreInstalled;
function installCaCertificate(caCertificatePath = defaults.caCertificatePath, machine = false) {
return __awaiter(this, void 0, void 0, function* () {
const command = getInstallCommand(caCertificatePath, machine);
try {
console.log(`Installing CA certificate "Developer CA for Microsoft Office Add-ins"...`);
// If the certificate is already installed by another instance skip it.
if (!(0, verify_1.isCaCertificateInstalled)()) {
(0, child_process_1.execSync)(command, { stdio: "pipe" });
}
console.log(`You now have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
catch (error) {
throw new Error(`Unable to install the CA certificate. ${error.stderr.toString()}`);
}
});
}
exports.installCaCertificate = installCaCertificate;
//# sourceMappingURL=install.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"install.js","sourceRoot":"","sources":["../src/install.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,iDAAyC;AACzC,gDAAwB;AACxB,qDAAuC;AACvC,yCAAkD;AAClD,2CAA6E;AAC7E,qCAAwE;AACxE,yCAA6C;AAC7C,qEAAwD;AAExD,sCAAsC;AAEtC,SAAS,iBAAiB,CAAC,iBAAyB,EAAE,UAAmB,KAAK;IAC5E,QAAQ,OAAO,CAAC,QAAQ,EAAE;QACxB,KAAK,OAAO,CAAC,CAAC;YACZ,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,0BAA0B,CAAC,CAAC;YACnE,OAAO,6CAA6C,MAAM,KACxD,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,aAC7B,KAAK,iBAAiB,GAAG,CAAC;SAC3B;QACD,KAAK,QAAQ,CAAC,CAAC;YACb,QAAQ;YACR,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;YACtC,MAAM,YAAY,GAAG,OAAO;gBAC1B,CAAC,CAAC,oCAAoC;gBACtC,CAAC,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A8BC;AAED,SAAsB,oBAAoB,CACxC,oBAA4B,QAAQ,CAAC,iBAAiB,EACtD,UAAmB,KAAK;;QAExB,MAAM,OAAO,GAAG,iBAAiB,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;QAE9D,IAAI;YACF,OAAO,CAAC,GAAG,CAAC,0EAA0E,CAAC,CAAC;YACxF,uEAAuE;YACvE,IAAI,CAAC,IAAA,iCAAwB,GAAE,EAAE;gBAC/B,IAAA,wBAAQ,EAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;aACtC;YACD,OAAO,CAAC,GAAG,CACT,mEAAmE,QAAQ,CAAC,wBAAwB,UAAU,QAAQ,CAAC,gBAAgB,EAAE,CAC1I,CAAC;SACH;QAAC,OAAO,KAAU,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,yCAAyC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;SACrF;IACH,CAAC;CAAA;AAlBD,oDAkBC"}
+5
View File
@@ -0,0 +1,5 @@
export * from "./generate";
export * from "./httpsServerOptions";
export * from "./install";
export * from "./verify";
export * from "./uninstall";
+24
View File
@@ -0,0 +1,24 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./generate"), exports);
__exportStar(require("./httpsServerOptions"), exports);
__exportStar(require("./install"), exports);
__exportStar(require("./verify"), exports);
__exportStar(require("./uninstall"), exports);
//# sourceMappingURL=main.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;AAElC,6CAA2B;AAC3B,uDAAqC;AACrC,4CAA0B;AAC1B,2CAAyB;AACzB,8CAA4B"}
+2
View File
@@ -0,0 +1,2 @@
export declare function deleteCertificateFiles(certificateDirectory?: string): void;
export declare function uninstallCaCertificate(machine?: boolean, verbose?: boolean): Promise<void>;
+103
View File
@@ -0,0 +1,103 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uninstallCaCertificate = exports.deleteCertificateFiles = void 0;
const child_process_1 = require("child_process");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process __dirname */
function getUninstallCommand(machine = false) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\uninstall.ps1");
return `powershell -ExecutionPolicy Bypass -File "${script}" ${machine ? "LocalMachine" : "CurrentUser"} "${defaults.certificateName}"`;
}
case "darwin": {
// macOS
const script = path_1.default.resolve(__dirname, "../scripts/uninstall.sh");
return `sudo sh '${script}' '${defaults.certificateName}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/uninstall_linux.sh");
return `sudo sh '${script}' '${defaults.caCertificateFileName}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
// Deletes the generated certificate files and delete the certificate directory if its empty
function deleteCertificateFiles(certificateDirectory = defaults.certificateDirectory) {
if (fs_extra_1.default.existsSync(certificateDirectory)) {
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.localhostCertificateFileName));
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.localhostKeyFileName));
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.caCertificateFileName));
if (fs_extra_1.default.readdirSync(certificateDirectory).length === 0) {
fs_extra_1.default.removeSync(certificateDirectory);
}
}
}
exports.deleteCertificateFiles = deleteCertificateFiles;
function uninstallCaCertificate(machine = false, verbose = true) {
return __awaiter(this, void 0, void 0, function* () {
if ((0, verify_1.isCaCertificateInstalled)(/* returnInvalidCertificate */ true)) {
const command = getUninstallCommand(machine);
try {
console.log(`Uninstalling CA certificate "Developer CA for Microsoft Office Add-ins"...`);
(0, child_process_1.execSync)(command, { stdio: "pipe" });
console.log(`You no longer have trusted access to https://localhost.`);
defaults_1.usageDataObject.reportSuccess("uninstallCaCertificate()");
}
catch (error) {
defaults_1.usageDataObject.reportException("uninstallCaCertificate()", error);
throw new Error(`Unable to uninstall the CA certificate.\n${error.stderr.toString()}`);
}
}
else {
if (verbose) {
console.log(`The CA certificate is not installed.`);
}
}
});
}
exports.uninstallCaCertificate = uninstallCaCertificate;
//# sourceMappingURL=uninstall.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uninstall.js","sourceRoot":"","sources":["../src/uninstall.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,iDAAyC;AACzC,wDAA+B;AAC/B,gDAAwB;AACxB,qDAAuC;AACvC,qCAAoD;AACpD,yCAA6C;AAC7C,qEAAwD;AAExD,sCAAsC;AAEtC,SAAS,mBAAmB,CAAC,UAAmB,KAAK;IACnD,QAAQ,OAAO,CAAC,QAAQ,EAAE;QACxB,KAAK,OAAO,CAAC,CAAC;YACZ,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,4BAA4B,CAAC,CAAC;YACrE,OAAO,6CAA6C,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,KACrG,QAAQ,CAAC,eACX,GAAG,CAAC;SACL;QACD,KAAK,QAAQ,CAAC,CAAC;YACb,QAAQ;YACR,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,yBAAyB,CAAC,CAAC;YAClE,OAAO,YAAY,MAAM,MAAM,QAAQ,CAAC,eAAe,GAAG,CAAC;SAC5D;QACD,KAAK,OAAO,CAAC,C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AAC,GAAG,CAAC,yDAAyD,CAAC,CAAC;gBACvE,0BAAe,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAU,EAAE;gBACnB,0BAAe,CAAC,eAAe,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;gBACnE,MAAM,IAAI,KAAK,CAAC,4CAA4C,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;aACxF;SACF;aAAM;YACL,IAAI,OAAO,EAAE;gBACX,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;aACrD;SACF;IACH,CAAC;CAAA;AAlBD,wDAkBC"}
+3
View File
@@ -0,0 +1,3 @@
export declare const outputMarker: string;
export declare function isCaCertificateInstalled(returnInvalidCertificate?: boolean): boolean;
export declare function verifyCertificates(certificatePath?: string, keyPath?: string): boolean;
+134
View File
@@ -0,0 +1,134 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyCertificates = exports.isCaCertificateInstalled = exports.outputMarker = void 0;
const child_process_1 = require("child_process");
const crypto_1 = __importDefault(require("crypto"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global Buffer process __dirname */
// On win32 this is a unique hash used with PowerShell command to reliably delineate command output
exports.outputMarker = process.platform === "win32"
? `[${crypto_1.default.createHash("md5").update(`${defaults.certificateName}${defaults.caCertificatePath}`).digest("hex")}]`
: "";
function getVerifyCommand(returnInvalidCertificate) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\verify.ps1");
const defaultCommand = `powershell -ExecutionPolicy Bypass -File "${script}" -CaCertificateName "${defaults.certificateName}" -CaCertificatePath "${defaults.caCertificatePath}" -LocalhostCertificatePath "${defaults.localhostCertificatePath}" -OutputMarker "${exports.outputMarker}"`;
if (returnInvalidCertificate) {
return defaultCommand + ` -ReturnInvalidCertificate`;
}
return defaultCommand;
}
case "darwin": {
// macOS
const script = path_1.default.resolve(__dirname, "../scripts/verify.sh");
return `sh '${script}' '${defaults.certificateName}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/verify_linux.sh");
return `sh '${script}' '${defaults.caCertificateFileName}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
function isCaCertificateInstalled(returnInvalidCertificate = false) {
const command = getVerifyCommand(returnInvalidCertificate);
try {
const output = (0, child_process_1.execSync)(command, { stdio: "pipe" }).toString();
if (process.platform === "win32") {
// Remove any PowerShell output that preceeds invoking the actual certificate check command
return (output.slice(output.lastIndexOf(exports.outputMarker) + exports.outputMarker.length).trim().length !== 0);
}
// script files return empty string if the certificate not found or expired
if (output.length !== 0) {
return true;
}
}
catch (_a) {
// Some commands throw errors if the certifcate is not found or expired
}
return false;
}
exports.isCaCertificateInstalled = isCaCertificateInstalled;
function validateCertificateAndKey(certificatePath, keyPath) {
let certificate = "";
let key = "";
try {
certificate = fs_1.default.readFileSync(certificatePath).toString();
}
catch (err) {
throw new Error(`Unable to read the certificate.\n${err}`);
}
try {
key = fs_1.default.readFileSync(keyPath).toString();
}
catch (err) {
throw new Error(`Unable to read the certificate key.\n${err}`);
}
let encrypted;
try {
encrypted = crypto_1.default.publicEncrypt(certificate, Buffer.from("test"));
}
catch (err) {
throw new Error(`The certificate is not valid.\n${err}`);
}
try {
crypto_1.default.privateDecrypt(key, encrypted);
}
catch (err) {
throw new Error(`The certificate key is not valid.\n${err}`);
}
}
function verifyCertificates(certificatePath = defaults.localhostCertificatePath, keyPath = defaults.localhostKeyPath) {
try {
let isCertificateValid = true;
try {
validateCertificateAndKey(certificatePath, keyPath);
}
catch (_a) {
isCertificateValid = false;
}
let output = isCertificateValid && isCaCertificateInstalled();
defaults_1.usageDataObject.reportSuccess("verifyCertificates()");
return output;
}
catch (err) {
defaults_1.usageDataObject.reportException("verifyCertificates()", err);
throw err;
}
}
exports.verifyCertificates = verifyCertificates;
//# sourceMappingURL=verify.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"verify.js","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,iDAAyC;AACzC,oDAA4B;AAC5B,4CAAoB;AACpB,gDAAwB;AACxB,qDAAuC;AACvC,yCAA6C;AAC7C,qEAAwD;AAExD,qCAAqC;AAErC,mGAAmG;AACtF,QAAA,YAAY,GACvB,OAAO,CAAC,QAAQ,KAAK,OAAO;IAC1B,CAAC,CAAC,IAAI,gBAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,iBAAiB,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG;IAClH,CA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AAC;KAC9D;AACH,CAAC;AAED,SAAgB,kBAAkB,CAChC,kBAA0B,QAAQ,CAAC,wBAAwB,EAC3D,UAAkB,QAAQ,CAAC,gBAAgB;IAE3C,IAAI;QACF,IAAI,kBAAkB,GAAY,IAAI,CAAC;QACvC,IAAI;YACF,yBAAyB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;SACrD;QAAC,WAAM;YACN,kBAAkB,GAAG,KAAK,CAAC;SAC5B;QACD,IAAI,MAAM,GAAG,kBAAkB,IAAI,wBAAwB,EAAE,CAAC;QAC9D,0BAAe,CAAC,aAAa,CAAC,sBAAsB,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;KACf;IAAC,OAAO,GAAQ,EAAE;QACjB,0BAAe,CAAC,eAAe,CAAC,sBAAsB,EAAE,GAAG,CAAC,CAAC;QAC7D,MAAM,GAAG,CAAC;KACX;AACH,CAAC;AAlBD,gDAkBC"}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
import commander from './index.js';
// wrapper to provide named exports for ESM.
export const {
program,
createCommand,
createArgument,
createOption,
CommanderError,
InvalidArgumentError,
InvalidOptionArgumentError, // deprecated old name
Command,
Argument,
Option,
Help,
} = commander;
+24
View File
@@ -0,0 +1,24 @@
const { Argument } = require('./lib/argument.js');
const { Command } = require('./lib/command.js');
const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
const { Help } = require('./lib/help.js');
const { Option } = require('./lib/option.js');
exports.program = new Command();
exports.createCommand = (name) => new Command(name);
exports.createOption = (flags, description) => new Option(flags, description);
exports.createArgument = (name, description) => new Argument(name, description);
/**
* Expose classes
*/
exports.Command = Command;
exports.Option = Option;
exports.Argument = Argument;
exports.Help = Help;
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
@@ -0,0 +1,149 @@
const { InvalidArgumentError } = require('./error.js');
class Argument {
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @param {string} name
* @param {string} [description]
*/
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.required = true;
this._name = name.slice(1, -1);
break;
case '[': // e.g. [optional]
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && this._name.slice(-3) === '...') {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
this.required = false;
return this;
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Argument} arg
* @return {string}
* @private
*/
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
/**
* CommanderError class
*/
class CommanderError extends Error {
/**
* Constructs the CommanderError class
* @param {number} exitCode suggested exit code which could be used with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
*/
constructor(exitCode, code, message) {
super(message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
this.nestedError = undefined;
}
}
/**
* InvalidArgumentError class
*/
class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(message) {
super(1, 'commander.invalidArgument', message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
+709
View File
@@ -0,0 +1,709 @@
const { humanReadableArgName } = require('./argument.js');
/**
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
* @typedef { import("./argument.js").Argument } Argument
* @typedef { import("./command.js").Command } Command
* @typedef { import("./option.js").Option } Option
*/
// Although this is a class, methods are static in style to allow override using subclass or just functions.
class Help {
constructor() {
this.helpWidth = undefined;
this.minWidthToWrap = 40;
this.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
* and just before calling `formatHelp()`.
*
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
*
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
*/
prepareContext(contextOptions) {
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
}
/**
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
*
* @param {Command} cmd
* @returns {Command[]}
*/
visibleCommands(cmd) {
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
const helpCommand = cmd._getHelpCommand();
if (helpCommand && !helpCommand._hidden) {
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
// @ts-ignore: because overloaded return type
return a.name().localeCompare(b.name());
});
}
return visibleCommands;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(a, b) {
const getSortKey = (option) => {
// WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
return option.short
? option.short.replace(/^-/, '')
: option.long.replace(/^--/, '');
};
return getSortKey(a).localeCompare(getSortKey(b));
}
/**
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleOptions(cmd) {
const visibleOptions = cmd.options.filter((option) => !option.hidden);
// Built-in help option.
const helpOption = cmd._getHelpOption();
if (helpOption && !helpOption.hidden) {
// Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
if (!removeShort && !removeLong) {
visibleOptions.push(helpOption); // no changes needed
} else if (helpOption.long && !removeLong) {
visibleOptions.push(
cmd.createOption(helpOption.long, helpOption.description),
);
} else if (helpOption.short && !removeShort) {
visibleOptions.push(
cmd.createOption(helpOption.short, helpOption.description),
);
}
}
if (this.sortOptions) {
visibleOptions.sort(this.compareOptions);
}
return visibleOptions;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(cmd) {
if (!this.showGlobalOptions) return [];
const globalOptions = [];
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
const visibleOptions = ancestorCmd.options.filter(
(option) => !option.hidden,
);
globalOptions.push(...visibleOptions);
}
if (this.sortOptions) {
globalOptions.sort(this.compareOptions);
}
return globalOptions;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(cmd) {
// Side effect! Apply the legacy descriptions before the arguments are displayed.
if (cmd._argsDescription) {
cmd.registeredArguments.forEach((argument) => {
argument.description =
argument.description || cmd._argsDescription[argument.name()] || '';
});
}
// If there are any arguments with a description then return all the arguments.
if (cmd.registeredArguments.find((argument) => argument.description)) {
return cmd.registeredArguments;
}
return [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(cmd) {
// Legacy. Ignores custom usage string, and nested commands.
const args = cmd.registeredArguments
.map((arg) => humanReadableArgName(arg))
.join(' ');
return (
cmd._name +
(cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
(cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
(args ? ' ' + args : '')
);
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(option) {
return option.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(argument) {
return argument.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(cmd, helper) {
return helper.visibleCommands(cmd).reduce((max, command) => {
return Math.max(
max,
this.displayWidth(
helper.styleSubcommandTerm(helper.subcommandTerm(command)),
),
);
}, 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(cmd, helper) {
return helper.visibleOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(cmd, helper) {
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(cmd, helper) {
return helper.visibleArguments(cmd).reduce((max, argument) => {
return Math.max(
max,
this.displayWidth(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
),
);
}, 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(cmd) {
// Usage
let cmdName = cmd._name;
if (cmd._aliases[0]) {
cmdName = cmdName + '|' + cmd._aliases[0];
}
let ancestorCmdNames = '';
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
}
return ancestorCmdNames + cmdName + ' ' + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.summary() || cmd.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(option) {
const extraInfo = [];
if (option.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (option.defaultValue !== undefined) {
// default for boolean and negated more for programmer than end user,
// but show true/false for boolean option as may be for hand-rolled env or config processing.
const showDefault =
option.required ||
option.optional ||
(option.isBoolean() && typeof option.defaultValue === 'boolean');
if (showDefault) {
extraInfo.push(
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
);
}
}
// preset for boolean and negated are more for programmer than end user
if (option.presetArg !== undefined && option.optional) {
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
}
if (option.envVar !== undefined) {
extraInfo.push(`env: ${option.envVar}`);
}
if (extraInfo.length > 0) {
return `${option.description} (${extraInfo.join(', ')})`;
}
return option.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(argument) {
const extraInfo = [];
if (argument.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (argument.defaultValue !== undefined) {
extraInfo.push(
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
);
}
if (extraInfo.length > 0) {
const extraDescription = `(${extraInfo.join(', ')})`;
if (argument.description) {
return `${argument.description} ${extraDescription}`;
}
return extraDescription;
}
return argument.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(cmd, helper) {
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
function callFormatItem(term, description) {
return helper.formatItem(term, termWidth, description, helper);
}
// Usage
let output = [
`${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
'',
];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.boxWrap(
helper.styleCommandDescription(commandDescription),
helpWidth,
),
'',
]);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return callFormatItem(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
helper.styleArgumentDescription(helper.argumentDescription(argument)),
);
});
if (argumentList.length > 0) {
output = output.concat([
helper.styleTitle('Arguments:'),
...argumentList,
'',
]);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (optionList.length > 0) {
output = output.concat([
helper.styleTitle('Options:'),
...optionList,
'',
]);
}
if (helper.showGlobalOptions) {
const globalOptionList = helper
.visibleGlobalOptions(cmd)
.map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (globalOptionList.length > 0) {
output = output.concat([
helper.styleTitle('Global Options:'),
...globalOptionList,
'',
]);
}
}
// Commands
const commandList = helper.visibleCommands(cmd).map((cmd) => {
return callFormatItem(
helper.styleSubcommandTerm(helper.subcommandTerm(cmd)),
helper.styleSubcommandDescription(helper.subcommandDescription(cmd)),
);
});
if (commandList.length > 0) {
output = output.concat([
helper.styleTitle('Commands:'),
...commandList,
'',
]);
}
return output.join('\n');
}
/**
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
*
* @param {string} str
* @returns {number}
*/
displayWidth(str) {
return stripColor(str).length;
}
/**
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
*
* @param {string} str
* @returns {string}
*/
styleTitle(str) {
return str;
}
styleUsage(str) {
// Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
// command subcommand [options] [command] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word === '[command]') return this.styleSubcommandText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleCommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleCommandDescription(str) {
return this.styleDescriptionText(str);
}
styleOptionDescription(str) {
return this.styleDescriptionText(str);
}
styleSubcommandDescription(str) {
return this.styleDescriptionText(str);
}
styleArgumentDescription(str) {
return this.styleDescriptionText(str);
}
styleDescriptionText(str) {
return str;
}
styleOptionTerm(str) {
return this.styleOptionText(str);
}
styleSubcommandTerm(str) {
// This is very like usage with lots of parts! Assume default string which is formed like:
// subcommand [options] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleSubcommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleArgumentTerm(str) {
return this.styleArgumentText(str);
}
styleOptionText(str) {
return str;
}
styleArgumentText(str) {
return str;
}
styleSubcommandText(str) {
return str;
}
styleCommandText(str) {
return str;
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(cmd, helper) {
return Math.max(
helper.longestOptionTermLength(cmd, helper),
helper.longestGlobalOptionTermLength(cmd, helper),
helper.longestSubcommandTermLength(cmd, helper),
helper.longestArgumentTermLength(cmd, helper),
);
}
/**
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
*
* @param {string} str
* @returns {boolean}
*/
preformatted(str) {
return /\n[^\S\r\n]/.test(str);
}
/**
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
*
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
* TTT DDD DDDD
* DD DDD
*
* @param {string} term
* @param {number} termWidth
* @param {string} description
* @param {Help} helper
* @returns {string}
*/
formatItem(term, termWidth, description, helper) {
const itemIndent = 2;
const itemIndentStr = ' '.repeat(itemIndent);
if (!description) return itemIndentStr + term;
// Pad the term out to a consistent width, so descriptions are aligned.
const paddedTerm = term.padEnd(
termWidth + term.length - helper.displayWidth(term),
);
// Format the description.
const spacerWidth = 2; // between term and description
const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
let formattedDescription;
if (
remainingWidth < this.minWidthToWrap ||
helper.preformatted(description)
) {
formattedDescription = description;
} else {
const wrappedDescription = helper.boxWrap(description, remainingWidth);
formattedDescription = wrappedDescription.replace(
/\n/g,
'\n' + ' '.repeat(termWidth + spacerWidth),
);
}
// Construct and overall indent.
return (
itemIndentStr +
paddedTerm +
' '.repeat(spacerWidth) +
formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
);
}
/**
* Wrap a string at whitespace, preserving existing line breaks.
* Wrapping is skipped if the width is less than `minWidthToWrap`.
*
* @param {string} str
* @param {number} width
* @returns {string}
*/
boxWrap(str, width) {
if (width < this.minWidthToWrap) return str;
const rawLines = str.split(/\r\n|\n/);
// split up text by whitespace
const chunkPattern = /[\s]*[^\s]+/g;
const wrappedLines = [];
rawLines.forEach((line) => {
const chunks = line.match(chunkPattern);
if (chunks === null) {
wrappedLines.push('');
return;
}
let sumChunks = [chunks.shift()];
let sumWidth = this.displayWidth(sumChunks[0]);
chunks.forEach((chunk) => {
const visibleWidth = this.displayWidth(chunk);
// Accumulate chunks while they fit into width.
if (sumWidth + visibleWidth <= width) {
sumChunks.push(chunk);
sumWidth += visibleWidth;
return;
}
wrappedLines.push(sumChunks.join(''));
const nextChunk = chunk.trimStart(); // trim space at line break
sumChunks = [nextChunk];
sumWidth = this.displayWidth(nextChunk);
});
wrappedLines.push(sumChunks.join(''));
});
return wrappedLines.join('\n');
}
}
/**
* Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
*
* @param {string} str
* @returns {string}
* @package
*/
function stripColor(str) {
// eslint-disable-next-line no-control-regex
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
return str.replace(sgrPattern, '');
}
exports.Help = Help;
exports.stripColor = stripColor;
@@ -0,0 +1,367 @@
const { InvalidArgumentError } = require('./error.js');
class Option {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags, description) {
this.flags = flags;
this.description = description || '';
this.required = flags.includes('<'); // A value must be supplied when the option is specified.
this.optional = flags.includes('['); // A value is optional when the option is specified.
// variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
const optionFlags = splitOptionFlags(flags);
this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
this.long = optionFlags.longFlag;
this.negate = false;
if (this.long) {
this.negate = this.long.startsWith('--no-');
}
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.presetArg = undefined;
this.envVar = undefined;
this.parseArg = undefined;
this.hidden = false;
this.argChoices = undefined;
this.conflictsWith = [];
this.implied = undefined;
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Option}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
*
* @param {*} arg
* @return {Option}
*/
preset(arg) {
this.presetArg = arg;
return this;
}
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
*
* @param {(string | string[])} names
* @return {Option}
*/
conflicts(names) {
this.conflictsWith = this.conflictsWith.concat(names);
return this;
}
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*
* @param {object} impliedOptionValues
* @return {Option}
*/
implies(impliedOptionValues) {
let newImplied = impliedOptionValues;
if (typeof impliedOptionValues === 'string') {
// string is not documented, but easy mistake and we can do what user probably intended.
newImplied = { [impliedOptionValues]: true };
}
this.implied = Object.assign(this.implied || {}, newImplied);
return this;
}
/**
* Set environment variable to check for option value.
*
* An environment variable is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*
* @param {string} name
* @return {Option}
*/
env(name) {
this.envVar = name;
return this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(mandatory = true) {
this.mandatory = !!mandatory;
return this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(hide = true) {
this.hidden = !!hide;
return this;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
if (this.long) {
return this.long.replace(/^--/, '');
}
return this.short.replace(/^-/, '');
}
/**
* Return option name, in a camelcase format that can be used
* as an object attribute key.
*
* @return {string}
*/
attributeName() {
if (this.negate) {
return camelcase(this.name().replace(/^no-/, ''));
}
return camelcase(this.name());
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(arg) {
return this.short === arg || this.long === arg;
}
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*
* @return {boolean}
* @package
*/
isBoolean() {
return !this.required && !this.optional && !this.negate;
}
}
/**
* This class is to make it easier to work with dual options, without changing the existing
* implementation. We support separate dual options for separate positive and negative options,
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
* use cases, but is tricky for others where we want separate behaviours despite
* the single shared option value.
*/
class DualOptions {
/**
* @param {Option[]} options
*/
constructor(options) {
this.positiveOptions = new Map();
this.negativeOptions = new Map();
this.dualOptions = new Set();
options.forEach((option) => {
if (option.negate) {
this.negativeOptions.set(option.attributeName(), option);
} else {
this.positiveOptions.set(option.attributeName(), option);
}
});
this.negativeOptions.forEach((value, key) => {
if (this.positiveOptions.has(key)) {
this.dualOptions.add(key);
}
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(value, option) {
const optionKey = option.attributeName();
if (!this.dualOptions.has(optionKey)) return true;
// Use the value to deduce if (probably) came from the option.
const preset = this.negativeOptions.get(optionKey).presetArg;
const negativeValue = preset !== undefined ? preset : false;
return option.negate === (negativeValue === value);
}
}
/**
* Convert string from kebab-case to camelCase.
*
* @param {string} str
* @return {string}
* @private
*/
function camelcase(str) {
return str.split('-').reduce((str, word) => {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Split the short and long flag out of something like '-m,--mixed <value>'
*
* @private
*/
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
// short flag, single dash and single character
const shortFlagExp = /^-[^-]$/;
// long flag, double dash and at least one character
const longFlagExp = /^--[^-]/;
const flagParts = flags.split(/[ |,]+/).concat('guard');
// Normal is short and/or long.
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
// Long then short. Rarely used but fine.
if (!shortFlag && shortFlagExp.test(flagParts[0]))
shortFlag = flagParts.shift();
// Allow two long flags, like '--ws, --workspace'
// This is the supported way to have a shortish option flag.
if (!shortFlag && longFlagExp.test(flagParts[0])) {
shortFlag = longFlag;
longFlag = flagParts.shift();
}
// Check for unprocessed flag. Fail noisily rather than silently ignore.
if (flagParts[0].startsWith('-')) {
const unsupportedFlag = flagParts[0];
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
if (/^-[^-][^-]/.test(unsupportedFlag))
throw new Error(
`${baseError}
- a short flag is a single dash and a single character
- either use a single dash and a single character (for a short flag)
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
);
if (shortFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many short flags`);
if (longFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many long flags`);
throw new Error(`${baseError}
- unrecognised flag format`);
}
if (shortFlag === undefined && longFlag === undefined)
throw new Error(
`option creation failed due to no flags found in '${flags}'.`,
);
return { shortFlag, longFlag };
}
exports.Option = Option;
exports.DualOptions = DualOptions;
@@ -0,0 +1,101 @@
const maxDistance = 3;
function editDistance(a, b) {
// https://en.wikipedia.org/wiki/DamerauLevenshtein_distance
// Calculating optimal string alignment distance, no substring is edited more than once.
// (Simple implementation.)
// Quick early exit, return worst case.
if (Math.abs(a.length - b.length) > maxDistance)
return Math.max(a.length, b.length);
// distance between prefix substrings of a and b
const d = [];
// pure deletions turn a into empty string
for (let i = 0; i <= a.length; i++) {
d[i] = [i];
}
// pure insertions turn empty string into b
for (let j = 0; j <= b.length; j++) {
d[0][j] = j;
}
// fill matrix
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
let cost = 1;
if (a[i - 1] === b[j - 1]) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(
d[i - 1][j] + 1, // deletion
d[i][j - 1] + 1, // insertion
d[i - 1][j - 1] + cost, // substitution
);
// transposition
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
}
return d[a.length][b.length];
}
/**
* Find close matches, restricted to same number of edits.
*
* @param {string} word
* @param {string[]} candidates
* @returns {string}
*/
function suggestSimilar(word, candidates) {
if (!candidates || candidates.length === 0) return '';
// remove possible duplicates
candidates = Array.from(new Set(candidates));
const searchingOptions = word.startsWith('--');
if (searchingOptions) {
word = word.slice(2);
candidates = candidates.map((candidate) => candidate.slice(2));
}
let similar = [];
let bestDistance = maxDistance;
const minSimilarity = 0.4;
candidates.forEach((candidate) => {
if (candidate.length <= 1) return; // no one character guesses
const distance = editDistance(word, candidate);
const length = Math.max(word.length, candidate.length);
const similarity = (length - distance) / length;
if (similarity > minSimilarity) {
if (distance < bestDistance) {
// better edit distance, throw away previous worse matches
bestDistance = distance;
similar = [candidate];
} else if (distance === bestDistance) {
similar.push(candidate);
}
}
});
similar.sort((a, b) => a.localeCompare(b));
if (searchingOptions) {
similar = similar.map((candidate) => `--${candidate}`);
}
if (similar.length > 1) {
return `\n(Did you mean one of ${similar.join(', ')}?)`;
}
if (similar.length === 1) {
return `\n(Did you mean ${similar[0]}?)`;
}
return '';
}
exports.suggestSimilar = suggestSimilar;
@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}
@@ -0,0 +1,82 @@
{
"name": "commander",
"version": "13.1.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser",
"cli",
"argument",
"args",
"argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/tj/commander.js.git"
},
"scripts": {
"check": "npm run check:type && npm run check:lint && npm run check:format",
"check:format": "prettier --check .",
"check:lint": "eslint .",
"check:type": "npm run check:type:js && npm run check:type:ts",
"check:type:ts": "tsd && tsc -p tsconfig.ts.json",
"check:type:js": "tsc -p tsconfig.js.json",
"fix": "npm run fix:lint && npm run fix:format",
"fix:format": "prettier --write .",
"fix:lint": "eslint --fix .",
"test": "jest && npm run check:type:ts",
"test-all": "jest && npm run test-esm && npm run check",
"test-esm": "node ./tests/esm-imports-test.mjs"
},
"files": [
"index.js",
"lib/*.js",
"esm.mjs",
"typings/index.d.ts",
"typings/esm.d.mts",
"package-support.json"
],
"type": "commonjs",
"main": "./index.js",
"exports": {
".": {
"require": {
"types": "./typings/index.d.ts",
"default": "./index.js"
},
"import": {
"types": "./typings/esm.d.mts",
"default": "./esm.mjs"
},
"default": "./index.js"
},
"./esm.mjs": {
"types": "./typings/esm.d.mts",
"import": "./esm.mjs"
}
},
"devDependencies": {
"@eslint/js": "^9.4.0",
"@types/jest": "^29.2.4",
"@types/node": "^22.7.4",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.3.0",
"globals": "^15.7.0",
"jest": "^29.3.1",
"prettier": "^3.2.5",
"ts-jest": "^29.0.3",
"tsd": "^0.31.0",
"typescript": "^5.0.4",
"typescript-eslint": "^8.12.2"
},
"types": "typings/index.d.ts",
"engines": {
"node": ">=18"
},
"support": true
}
@@ -0,0 +1,3 @@
// Just reexport the types from cjs
// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.
export * from './index.js';
File diff suppressed because it is too large Load Diff
+64
View File
@@ -0,0 +1,64 @@
{
"name": "office-addin-dev-certs",
"version": "2.0.6",
"description": "For managing certificates when developing Office Add-ins.",
"main": "./lib/main.js",
"scripts": {
"build": "rimraf lib && concurrently \"tsc -p tsconfig.json\"",
"cli": "node lib/cli.js",
"lint": "office-addin-lint check",
"lint:fix": "office-addin-lint fix",
"prettier": "office-addin-lint prettier",
"start": "rimraf lib && concurrently \"npm run watch\"",
"test": "mocha -r ts-node/register test/**/*.ts",
"watch": "tsc -p tsconfig.json -w"
},
"author": "Office Dev",
"license": "MIT",
"bin": {
"office-addin-dev-certs": "./cli.js"
},
"keywords": [
"Office",
"add-in",
"localhost",
"SSL",
"https",
"certificates",
"keys",
"cert",
"development",
"secure",
"server"
],
"dependencies": {
"commander": "^13.0.0",
"fs-extra": "^11.2.0",
"mkcert": "^3.2.0",
"office-addin-cli": "^2.0.6",
"office-addin-usage-data": "^2.0.6"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/mkcert": "^1.2.2",
"@types/mocha": "^10.0.6",
"@types/node": "^14.17.2",
"@types/sinon": "^17.0.3",
"concurrently": "^9.0.0",
"mocha": "^11.0.0",
"office-addin-lint": "^3.0.6",
"rimraf": "^6.0.1",
"sinon": "^19.0.2",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
},
"repository": {
"type": "git",
"url": "https://github.com/OfficeDev/Office-Addin-Scripts"
},
"bugs": {
"url": "https://github.com/OfficeDev/Office-Addin-Scripts/issues"
},
"prettier": "office-addin-prettier-config",
"gitHead": "3023b9e22db5320008316d9eaf99993caa2e7a86"
}
+27
View File
@@ -0,0 +1,27 @@
if($args.Count -ne 2){
throw "Usage: install.ps1 <LocalMachine | CurrentUser> <CA-certificate-path>"
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
$machine = $args[0]
$caCertificatePath=$args[1]
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
Import-Certificate -CertStoreLocation cert:\\$machine\\Root ${caCertificatePath}
}
else{
# Legacy system support
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.import($caCertificatePath)
$store = new-object System.Security.Cryptography.X509Certificates.X509Store("Root", $machine)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
sudo mkdir -p /usr/local/share/ca-certificates/office-addin-dev-certs && sudo cp $1 /usr/local/share/ca-certificates/office-addin-dev-certs && sudo /usr/sbin/update-ca-certificates
elif [ -f "/usr/sbin/update-ca-trust" ]; then
sudo cp $1 /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt && sudo /usr/sbin/update-ca-trust
fi
+27
View File
@@ -0,0 +1,27 @@
if($args.Count -ne 2){
throw "Usage: uninstall.ps1 <LocalMachine | CurrentUser> <CA-certficate-name>"
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
$machine = $args[0]
$caCertificateName=$args[1]
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
Get-ChildItem cert:\\$machine\\Root | Where-Object { $_.IssuerName.Name -like "*CN=$caCertificateName*" } | Remove-Item
}
else{
# Legacy system support
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("root", $machine)
$store.Open("MaxAllowed")
$certs = $store.Certificates.Find("FindBySubjectName", $caCertificateName, $false)
foreach ($cert in $certs){
$store.Remove($cert)
}
$store.close()
}
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
hashes=$(security find-certificate -c "$1" -a -Z | grep SHA-1 | awk '{ print $NF }')
for hash in $hashes; do
security delete-certificate -Z $hash
done
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
sudo rm -r /usr/local/share/ca-certificates/office-addin-dev-certs/$1 && sudo /usr/sbin/update-ca-certificates --fresh
elif [ -f "/usr/sbin/update-ca-trust" ]; then
sudo rm -r /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt && sudo /usr/sbin/update-ca-trust
fi
+73
View File
@@ -0,0 +1,73 @@
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$CaCertificateName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$CaCertificatePath,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$LocalhostCertificatePath,
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]
$OutputMarker,
[switch]
$ReturnInvalidCertificate
)
# An optional output marker that can be used to find the beginning of this script's output
if ($OutputMarker) {
Write-Output $OutputMarker
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
$result = Get-ChildItem cert:\\CurrentUser\\Root | Where-Object Issuer -like "*CN=$CaCertificateName*"
if (!$ReturnInvalidCertificate) {
$result = $result | Where-Object { $_.NotAfter -gt (Get-Date).AddDays(1) }
if ($result -and ($result.Length -eq 1) -and (Test-Path $CaCertificatePath) -and (Test-Path $LocalhostCertificatePath)) {
# Check that CA certificate in store is the same as ca.crt
$caCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($CaCertificatePath)
$caThumbprint = $caCert.Thumbprint
$result = $result | Where-Object Thumbprint -eq $caThumbprint
if ($result) {
# Check that it matches the issuer of localhost.crt
$localhostCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($LocalhostCertificatePath)
$localhostChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
$localhostChain.Build($localhostCert) | Out-Null
$localhostTrustedIssuer = $localhostChain.ChainElements.Certificate | Where-Object { $_.Subject -eq $localhostCert.Issuer -and $_.Thumbprint -eq $caThumbprint }
if (!$localhostTrustedIssuer) {
$result = $null
}
}
}
else {
$result = $null
}
}
$result | Format-List
}
else{
# Legacy system support
Get-ChildItem cert:\\CurrentUser\\Root | Where-Object { $_.Subject -like "*CN=$CaCertificateName*"} | Where-Object { $_.NotAfter -gt (Get-Date).AddDays(1) } | Format-List
}
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
certs=$(security find-certificate -a -c "$1" -p)
while read line; do
if [[ "$line" == *"--BEGIN"* ]]; then
cert=$line
else
cert="$cert"$'\n'"$line"
if [[ "$line" == *"--END"* ]]; then
if [ 0 -lt $(echo "$cert" | openssl x509 -checkend 86400 | grep -c "will not expire") ]; then
echo "$cert"
fi
fi
fi
done <<< "$certs"
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
echo [ -f /usr/local/share/ca-certificates/office-addin-dev-certs/$1 ] && openssl x509 -in /usr/local/share/ca-certificates/office-addin-dev-certs/$1 -checkend 86400 -noout
elif [ -f "/usr/sbin/update-ca-trust" ]; then
echo [ -f /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt ] && openssl x509 -in /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt -checkend 86400 -noout
fi