56 lines
1.9 KiB
JavaScript
56 lines
1.9 KiB
JavaScript
import crypto from "node:crypto";
|
|
import fs from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const serverDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
const repositoryRoot = path.dirname(serverDir);
|
|
const secretsPath = path.join(
|
|
repositoryRoot,
|
|
"sketches",
|
|
"arduino-uno-r4-wifi",
|
|
"wifi_matrix_status",
|
|
"arduino_secrets.h",
|
|
);
|
|
const payloadSecretsPath = path.join(
|
|
repositoryRoot,
|
|
"sketches",
|
|
"arduino-uno-r4-wifi",
|
|
"ds18b20_payload",
|
|
"arduino_secrets.h",
|
|
);
|
|
|
|
const secrets = await fs.readFile(secretsPath, "utf8");
|
|
const readDefine = (name) => {
|
|
const match = secrets.match(new RegExp(`^#define\\s+${name}\\s+"((?:\\\\.|[^"])*)"`, "m"));
|
|
if (!match) throw new Error(`${name} was not found in ${secretsPath}`);
|
|
return JSON.parse(`"${match[1]}"`);
|
|
};
|
|
|
|
const ssid = readDefine("SECRET_SSID");
|
|
const password = readDefine("SECRET_PASS");
|
|
const existingEnv = await fs.readFile(path.join(repositoryRoot, ".env"), "utf8").catch(() => "");
|
|
const existingToken = existingEnv.match(/^API_BEARER_TOKEN=(.+)$/m)?.[1]?.trim();
|
|
const apiToken = existingToken || crypto.randomBytes(32).toString("base64url");
|
|
const env = [
|
|
"HOST_PORT=8152",
|
|
"PUBLIC_DOMAIN=https://payloads.p20.dev",
|
|
`API_BEARER_TOKEN=${apiToken}`,
|
|
`WIFI_SSID=${JSON.stringify(ssid)}`,
|
|
`WIFI_PASSWORD=${JSON.stringify(password)}`,
|
|
"",
|
|
].join("\n");
|
|
|
|
const payloadSecrets = [
|
|
"#pragma once",
|
|
"",
|
|
"// Generated by npm --prefix server run configure. Do not commit.",
|
|
`#define SECRET_SSID ${JSON.stringify(ssid)}`,
|
|
`#define SECRET_PASS ${JSON.stringify(password)}`,
|
|
`#define SECRET_API_TOKEN ${JSON.stringify(apiToken)}`,
|
|
"",
|
|
].join("\n");
|
|
|
|
await fs.writeFile(path.join(repositoryRoot, ".env"), env, { mode: 0o600 });
|
|
await fs.writeFile(payloadSecretsPath, payloadSecrets, { mode: 0o600 });
|
|
console.log("Created .env and the DS18B20 payload sketch's local secret file.");
|