I'm trying to package my electron app, using electron-forge. In order to make the app available on macs, I need to codesign the app, which requires passing info such as appleId and app-specific-password in the package.json file.
How can I pass this information securely? (ie, not available to people who download the app)
If environmental variables are the way to go, I'm hoping to understand where I set the environmental variables (in a separate file? In the start command?) and how I access them in the package.json itself.
I'd appreciate any help to sort this out.
Details of what I've considered:
-The electron forge codesign documentation does not mention how to actually provide osx required details in a secure way. It does mention that it uses electron-notarize (among others) under the hood, and electron-notarize's documentation says: "Never hard code your password into your packaging scripts, use an environment variable at a minimum", but doesn't provide detail on how to do that.
-This stack overflow answer provides helpful info in terms of setting up a separate forge.config.js file, and then says you should "load your environment variables using process.env.YOUR_VARIABLE_NAME". It doesn't provide more detail--loading the environmental variables for a packaged app is what I'm trying to figure out here.
--This stack overflow answer mentions setting them manually, but doesn't mention how. It also mentions using the dotenv package--but I'd be surprised there's a separate package required for this task that is fundamental to any mac electron app.
I store them in an .env file in my project directory as follows:
APPLEID=your_id
APPLEIDPASS=your_password
In package.json I have a section:
"build": {
"productName": "PRODUCT",
"appId": "your app id",
"copyright": "Copyright",
"directories": {
"output": "build"
},
"afterSign": "scripts/notarize.js",
The afterSign points to a script scripts/notarize.js that will pull out the APPLEID and APPLEIDPASS using dotenv:
require('dotenv').config()
const { notarize } = require('electron-notarize')
exports.default = async function notarizing(context) {
const { electronPlatformName, appOutDir } = context
if (electronPlatformName !== 'darwin') {
return
}
const appName = context.packager.appInfo.productFilename;
return await notarize({
appBundleId: 'your app id',
appPath: `${appOutDir}/${appName}.app`,
appleId: process.env.APPLEID,
appleIdPassword: process.env.APPLEIDPASS
})
}
It's those 2 last lines with appleId and appleIdPassword that pull out the environment variables.
Never commit the .env file to, for example, github. To make sure: add .env to your .gitignore file. Also: the script/notarize.js app is not part of your app itself, this runs while you build your app.
I've been able to hear back from one of the maintainers of electron forge, who said the way to do it is:
Load the environmental variables in the build script itself. For example: $ VAR1=something VAR2=somethingelse npm run make.
Then, reference those variables as appropriate in the forge.config.js file that package.json refers to. Example reference syntax: process.env.VAR1
Related
I am trying to make a POC and I'm such making a really simple use-case.
In there, I use a src/lib/db.ts who, for our interest, contains this code
console.log(import.meta.env.MONGO_URI, import.meta.env.SSR);
giving
undefined true
Of course, my .env file contains a definition for MONGO_URI, I tried with VITE_MONGO_URI and could see the value.
I know a way to expose it is to use VITE_MONGO_URI but my point is exactly not to expose it on the client-side.
I checked and the file db.ts is not bundled with the client, even the import.meta.env.SSR being true shows that the bundler knows it's happening on the server.
Question: How to access my private environment variables server-side ?
EDIT: As specified by Shriji Kondan, the API for this purpose has been created now : here
You could use dotenv on the server side, assuming you are using node-adapter, you can have a file _constants.ts in your app
import 'dotenv/config';
export const MONGO_URI = process.env.MONGO_URI;
and then import this variable into your script.
It's not very awesome to put secrets on client-side code. It should be either utilities.ts with a performed action SUPER_SECRET_API_KEY="$ecret#p1Key" in .env file, then request it via in src/lib/utilities/utility.js as explained here :
import { SUPER_SECRET_API_KEY } from '$env/static/private';
export function performApiAction() {
const apiInstance = initialiseApi({key: SUPER_SECRET_API_KEY});
}
or from page.server.ts via form actions as stated here which is preferable way but it's more complex.
It's my first time using Electron JS and nodejs. I've built a small app that reads some records from a database and updates them. Everything is working fine. I have a config file with the database credentials but when I build a portable win app, I cannot figure out how to read the config file that I would like to place next to the exe. I would like to have easy access to the file, so I could run the same app on different databases.
Can anyone tell me if what I want is possible and how? I already tried to get the exe location but I couldn't. I also read a lot of topics here but nothing seems to solve my problem (I might be doing something wrong).
I'm using electron-builder to build my app.
Thanks in advance.
Edit #1
My Config file is
{
"user" :"X",
"password" :"X",
"server":"X",
"database":"X",
"options":
{
"trustedconnection": true,
"enableArithAbort" : true,
"trustServerCertificate": true
}
}
This is what I've and works when I run the project with npm start
const configRootPath = path.resolve(__dirname,'dbConfig.json');
dbConfig = JSON.parse(fs.readFileSync(configRootPath, { encoding: 'utf-8' }));
However, when I build it, the app is looking for the file in another location different from the one where the executable is.
Use of Electron's app.getPath(name) function will get you the path(s) you are after, irrespective of which OS (Operating System) you are using.
Unless your application writes your dbConfig.json file, it may be difficult for your user to understand exactly where they should place their database config file as each OS will run and store your application data in a different directory. You would need to be explicit to the user as to where to place their config file(s). Alternatively, your application could create the config file(s) on the user's behalf (automatically or through a html form) and save it to a location 'known' to the application.
A common place where application specific config files are stored is in the user's application data directory. With the application name automatically amended to the directory, it can be found as shown below.
const electronApp = require('electron').app;
let appUserDataPath = electronApp.getPath('userData');
console.log(appUserDataPath );
In your use case, the below would apply.
const electronApp = require('electron').app;
const nodeFs = require('fs');
const nodePath = require('path');
const configRootPath = nodePath.join(electronApp.getPath('userData'), 'dbConfig.json');
dbConfig = JSON.parse(nodeFs.readFileSync(configRootPath, 'utf-8'));
console.log(configRootPath);
console.log(dbConfig);
You can try electron-store to store config.
Electron doesn't have a built-in way to persist user preferences and other data. This module handles that for you, so you can focus on building your app. The data is saved in a JSON file named config.json in app.getPath('userData').
I have the issue I would like to automate via a script so tat .jnlp will be added as an allowable type of file , is there a command like or powershell or regedit that will add it?
The latest file types policies are published in the Chromium source code. You could clearly see that the danger_level of .jnlp type files is DANGEROUS. Therefor Edge will warn users that this file may harm their computers. Let users continue or discard the file.
If you ensure that the content(download file) on the site is safe, you can use this policy to specify the file types that are allowed to be downloaded continuously from a specific site: ExemptDomainFileTypePairsFromFileTypeDownloadWarnings.
Example:
[ { "file_extension": "jnlp", "domains": ["contoso.com"] }, { "file_extension": "exe", "domains": ["contoso.com"] }, { "file_extension": "swf", "domains": ["*"] } ]
If you want to achieve the same function through the registry, you can set it under this path: SOFTWARE\Policies\Microsoft\Edge\ExemptDomainFileTypePairsFromFileTypeDownloadWarnings
I'm using SendGrid(Node.js) for one of my personal projects. I followed the integration guide to set up my API KEY .env file as following:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
My question is... Every time before running the backend locally, I have to first run
source ./sendgrid.env
In order for the process.env.YOUR_API_KEY be acknowledged where the key is.
But after renamed the sendgrid.env file to just .env, I don't have to run source anymore.
This is how I call the API KEY
require('dotenv').config()
const { validationResult } = require('express-validator')
const Appointment = require('../models/Appointment')
const User = require('../models/User')
const sgMail = require('#sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
PS. I have set the dotenv config at the top of the file but still getting undefined until I changed the file name.
Does anyone know the reason or the logic behind this??
Thank you :)
If I am understanding it well enough. You have to change it to .env because by default require('dotenv').config() point to .env because the parenthesis of config are empty.
To follow the sendgrid way by calling your file sendgrid.env you would have to require('dotenv').config(sendgrid.env) and maybe, just require('dotenv').config(sendgrid) would be enough. Got to try it to know for sure. But at least from my understanding this is your answer.
I'm reading through electron and electron-builder docs, but I still do not quite understand what is the purpose of the buildResources folder?
Here's what a configuration doc for electron-builder says:
buildResources = build String - The path to build resources.
Kind of self-explanatory... But how or when they are involved in the build process, especially having that:
...build resources is not packed into the app. If you need to use some
files, e.g. as tray icon, please include required files explicitly
Can we simply put those icon files in an arbitrary folder and then copy over into the app/ manually (since we need to include buildResources manually anyway)?
TL;DR:
As far as I can tell from a quick glance at the source code, the buildResources folder is used to hold additional scripts, plugins, etc. that can be used by the package building software. Electron-builder doesn't generate the packages itself, it uses tools like NSIS.
Explanation:
I've had the same question and unfortunately find an answer for this isn't very straight-forward. The docs entry is pretty useless. I found out that someone asked about it in the GitHub issues but never got an answer.
I decided to dig in the code a bit myself to find out what it does. In NsisTargets.ts, you can see that the buildResources folder can contain custom includes and plugins for NSIS.
// NsisTargets.ts
taskManager.add(async () => {
const userPluginDir = path.join(packager.info.buildResourcesDir, pluginArch)
const stat = await statOrNull(userPluginDir)
if (stat != null && stat.isDirectory()) {
scriptGenerator.addPluginDir(pluginArch, userPluginDir)
}
})
// [...]
taskManager.add(async () => {
const customInclude = await packager.getResource(this.options.include, "installer.nsh")
if (customInclude != null) {
scriptGenerator.addIncludeDir(packager.info.buildResourcesDir)
scriptGenerator.include(customInclude)
}
})
and in pkg.ts it's used to load additional scripts to the pkg builder:
// pkg.ts
if (options.scripts != null) {
args.push("--scripts", path.resolve(this.packager.info.buildResourcesDir, options.scripts))
}
It appears as though buildResources can contain assets/scripts specifically used for the build process. That also explains why the contents of buildResources aren't included in the resulting app.asar file.
So, I'm going to say straight away that the documentation for this option is just awful.
Files included in buildResources will appear in the asar file which you can find documentation about on electron's website.
The option files will include files such as pictures which are not accessible in the asar file.
I.E.
given I have a folder called assets in my build folder I want to include with my app.
"files": [
"./build/**/*"
],
"directories": {
"buildResources": "assets"
}
This will put all folders inside build into the asar file, which you can then unpack by including,
"asarUnpack": "**/assets/*"
This will put the folder assets into the build folder in the app directory.