Skip to content

Instantly share code, notes, and snippets.

@erossignon
Last active November 12, 2019 14:59
Show Gist options
  • Save erossignon/d6188c4518a04acb082887ef6433470d to your computer and use it in GitHub Desktop.
Save erossignon/d6188c4518a04acb082887ef6433470d to your computer and use it in GitHub Desktop.
server with hardcoded ip address in certifcate
// node --inspect-brk -r ts-node/register -r source-map-support test_server.ts
import * as path from "path";
import * as fs from "fs";
import { promisify } from "util";
import * as child_process from "child_process";
import {
makeApplicationUrn,
OPCUAServer,
OPCUAClient,
OPCUACertificateManager,
MessageSecurityMode,
SecurityPolicy,
} from "node-opcua";
import { main as createCertificate, execute } from "node-opcua-pki";
import { reject } from "async";
const ipAddress = "192.168.1.35";
const certificateFolder = path.join(__dirname, "certificates");
const PKIFolder = path.join(certificateFolder, "PKI");
const serverCertificate = path.join(certificateFolder, "server_certificate.pem");
const port = 4840;
const applicationUri = "urn:" + ipAddress + "-MyServer";
async function clientGetEndpoint() {
const client = OPCUAClient.create({
endpoint_must_exist: false,
});
await client.connect("opc.tcp://" + ipAddress + ":" + port);
const e = await client.getEndpoints();
console.log(e.toString());
await client.disconnect();
}
async function fileExists(path: string): Promise<boolean> {
return await new Promise((resolve, reject) =>
fs.access(path, fs.constants.F_OK, (err: Error | null) => resolve(!err))
);
}
async function folderExists(path: string): Promise<boolean> {
return await new Promise((resolve, reject) =>
fs.access(path, fs.constants.F_OK, (err: Error | null) => resolve(!err))
);
}
async function exec(cmd: string): Promise<void> {
console.log("Executing ", cmd);
const promise = new Promise((resolve, reject) => {
const child = child_process.exec(cmd, function (err) {
});
child.stdout.pipe(process.stdout);
child.on("close", function (code) {
console.log("done ... (" + code + ")");
if (code == 0) {
resolve();
} else {
reject(new Error("command ended with code " + code));
}
});
});
await promise;
}
async function createSelfSignedCertificate(ipAddress: string, serverCertificate: string) {
const args = [
"node", "node_modules/node-opcua-pki/bin/crypto_create_CA.js",
// command
"certificate",
// arguments
"-s", "-o", serverCertificate,
"--ip", ipAddress,
"-a", applicationUri
];
await exec(args.join(" "));
}
async function createServerCertificate() {
const certificateFolderExists = await fileExists(certificateFolder);
const serverCertificateExist = await fileExists(serverCertificate);
if (!certificateFolderExists || !serverCertificateExist) {
await createSelfSignedCertificate(ipAddress, serverCertificate);
console.log(" serverCertificate ", serverCertificate, "created");
}
}
(async () => {
try {
await createServerCertificate();
const serverCertificateManager = new OPCUACertificateManager({
automaticallyAcceptUnknownCertificate: true,
rootFolder: PKIFolder,
name: "pki"
});
const server = new OPCUAServer({
port,
allowAnonymous: true,
alternateHostname: [ipAddress],
serverInfo: {
applicationName: { text: "Mini NodeOPCUA Server", locale: "en" },
applicationUri,
productUri: "Mini NodeOPCUA-Server"
},
serverCertificateManager,
certificateFile: serverCertificate,
privateKeyFile: serverCertificateManager.privateKey,
securityModes: [MessageSecurityMode.None],
securityPolicies: [SecurityPolicy.None]
});
await server.initialize();
await server.start();
await clientGetEndpoint();
console.log("server certificate = ", server.certificateFile);
console.log("server key file = ", server.privateKeyFile);
const endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
console.log(" server is ready on ", endpointUrl);
console.log("CTRL+C to stop");
await exec(["openssl", "x509", "-in", serverCertificate, "-text"].join(" "));
let stopped = false;
process.on("SIGINT", async () => {
if (stopped) return;
console.log("shutting down ...")
stopped = true;
await server.shutdown();
console.log("... done..");
});
}
catch (err) {
console.log("err = ", err.message);
console.log(err);
process.exit(-1);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment