示例工程 12-ipc-anti-patterns

12-ipc-anti-patterns/demo-02-env-projection/env.ts

typescript · 1.0 KB

type Env = Record<string, string>;

const env: Env = {
  PATH: "/usr/bin:/bin",
  HOME: "/Users/alice",
  API_KEY: "sk-live-123",
  DB_PASSWORD: "hunter2",
  NODE_ENV: "production",
  LANG: "zh_CN.UTF-8",
};

const SECRET = /TOKEN|SECRET|PASSWORD|API_KEY|KEY/i;
const ALLOW = ["NODE_ENV", "LANG"];

function fullEnv(source: Env): Env {
  // 反模式:原样返回。
  return source;
}

function project(source: Env, keys: string[]): Env {
  const result: Env = {};
  for (const key of keys) {
    if (SECRET.test(key)) throw new Error(`SECRET_KEY_FORBIDDEN: ${key}`);
    const value = source[key];
    if (value !== undefined) result[key] = value;
  }
  return result;
}

const full = fullEnv(env);
const safe = project(env, ALLOW);
const serializedSafe = JSON.stringify(safe);
const leaked = SECRET.test(serializedSafe);

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      Object.keys(full).length === 6 &&
      Object.keys(safe).length === 2 &&
      !leaked,
    fullKeys: Object.keys(full).length,
    safeKeys: Object.keys(safe),
    leaked,
  }),
);