Skip to content

Instantly share code, notes, and snippets.

@madisonbullard
Last active August 2, 2024 04:00
Show Gist options
  • Save madisonbullard/f25bb5af65b2c13f4b2a19d7336154d7 to your computer and use it in GitHub Desktop.
Save madisonbullard/f25bb5af65b2c13f4b2a19d7336154d7 to your computer and use it in GitHub Desktop.
Copy your .env file to GitHub Repository Secrets using TypeScript
// Make sure dotenv and libsodium-wrappers are installed as dev dependencies
// Make sure GITHUB_ACCESS_TOKEN is declared in your .env file as a Fine-Grained Token with Secrets read/write access
import dotenv from 'dotenv';
import { readFileSync } from 'fs';
import sodium from 'libsodium-wrappers';
import path from 'path';
import { fileURLToPath } from 'url';
const baseUrl = 'https://api.github.com/repos/{USER}/{REPO}/actions/secrets';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const envFilePath = path.resolve(__dirname, '../relative/path/to/.env');
const envBuffer = readFileSync(envFilePath);
const envVars = dotenv.parse(envBuffer);
delete envVars.GITHUB_ACCESS_TOKEN;
console.log('Syncing env file to github');
const publicKeyRes = await fetch(`${baseUrl}/public-key`, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
const { key, key_id } = (await publicKeyRes.json()) as { key: string; key_id: string };
//Check if libsodium is ready and then proceed.
sodium.ready.then(async () => {
const promises = Object.entries(envVars).map(([secret_name, secret]) => {
// Convert the secret and key to a Uint8Array.
const binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL);
const binsec = sodium.from_string(secret);
// Encrypt the secret using libsodium
const encBytes = sodium.crypto_box_seal(binsec, binkey);
// Convert the encrypted Uint8Array to Base64
const output = sodium.to_base64(encBytes, sodium.base64_variants.ORIGINAL);
return fetch(`${baseUrl}/${secret_name}`, {
method: 'PUT',
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`,
'X-GitHub-Api-Version': '2022-11-28'
},
body: JSON.stringify({
key_id,
encrypted_value: output
})
});
});
const res = await Promise.all(promises);
res.forEach((r) => console.log(r.status));
});
export {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment