sst
Version:
86 lines (85 loc) • 2.86 kB
JavaScript
import { env } from "process";
import { readFileSync } from "fs";
import crypto from "crypto";
const raw = {
// @ts-expect-error,
...globalThis.$SST_LINKS,
};
const environment = {
...env,
...globalThis.process?.env,
};
for (const [key, value] of Object.entries(environment)) {
if (key.startsWith("SST_RESOURCE_") && value) {
raw[key.slice("SST_RESOURCE_".length)] = JSON.parse(value);
}
}
// @ts-expect-error
if (env.SST_KEY_FILE && env.SST_KEY && !globalThis.SST_KEY_FILE_DATA) {
const key = Buffer.from(env.SST_KEY, "base64");
const encryptedData = readFileSync(env.SST_KEY_FILE);
const nonce = Buffer.alloc(12, 0);
const decipher = crypto.createDecipheriv("aes-256-gcm", key, nonce);
const authTag = encryptedData.subarray(-16);
const actualCiphertext = encryptedData.subarray(0, -16);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(actualCiphertext);
decrypted = Buffer.concat([decrypted, decipher.final()]);
const decryptedData = JSON.parse(decrypted.toString());
Object.assign(raw, decryptedData);
}
// @ts-expect-error
if (globalThis.SST_KEY_FILE_DATA) {
// @ts-expect-error
Object.assign(raw, globalThis.SST_KEY_FILE_DATA);
}
export function fromCloudflareEnv(input) {
for (let [key, value] of Object.entries(input)) {
if (typeof value === "string") {
try {
value = JSON.parse(value);
}
catch { }
}
raw[key] = value;
if (key.startsWith("SST_RESOURCE_")) {
raw[key.replace("SST_RESOURCE_", "")] = value;
}
}
}
export function wrapCloudflareHandler(handler) {
if (typeof handler === "function" && handler.hasOwnProperty("prototype")) {
return class extends handler {
constructor(ctx, env) {
fromCloudflareEnv(env);
super(ctx, env);
}
};
}
function wrap(fn) {
return function (req, env, ...rest) {
fromCloudflareEnv(env);
return fn(req, env, ...rest);
};
}
const result = {};
for (const [key, value] of Object.entries(handler)) {
result[key] = wrap(value);
}
return result;
}
export const Resource = new Proxy(raw, {
get(_target, prop) {
if (prop in raw) {
return raw[prop];
}
if (!env.SST_RESOURCE_App) {
throw new Error("It does not look like SST links are active. If this is in local development and you are not starting this process through the multiplexer, wrap your command with `sst dev -- <command>`");
}
let msg = `"${prop}" is not linked in your sst.config.ts`;
if (env.AWS_LAMBDA_FUNCTION_NAME) {
msg += ` to ${env.AWS_LAMBDA_FUNCTION_NAME}`;
}
throw new Error(msg);
},
});