@norskvideo/ctl-product-template-schema 0.1.71 → 0.1.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@norskvideo/ctl-product-template-schema",
3
- "version": "0.1.71",
3
+ "version": "0.1.72",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,6 +40,10 @@
40
40
  "types": "./secret-references.d.ts",
41
41
  "default": "./secret-references.js"
42
42
  },
43
+ "./secrets": {
44
+ "types": "./secrets/index.d.ts",
45
+ "default": "./secrets/index.js"
46
+ },
43
47
  "./product-channels": {
44
48
  "types": "./product-channels.d.ts",
45
49
  "default": "./product-channels.js"
@@ -52,10 +56,18 @@
52
56
  "yaml": "^2.8.0",
53
57
  "zod": "4.6.7"
54
58
  },
59
+ "peerDependencies": {
60
+ "@aws-sdk/client-secrets-manager": "^3.0.0"
61
+ },
55
62
  "devDependencies": {
56
63
  "@types/bun": "latest",
57
64
  "@types/node": "^22.10.0"
58
65
  },
66
+ "peerDependenciesMeta": {
67
+ "@aws-sdk/client-secrets-manager": {
68
+ "optional": true
69
+ }
70
+ },
59
71
  "publishConfig": {
60
72
  "access": "public"
61
73
  }
@@ -0,0 +1,36 @@
1
+ import { type Result } from "@norskvideo/ctl-foundation";
2
+ import { z } from "zod";
3
+ import type { SecretProviders } from "./provider.js";
4
+ /** Names a configured provider may not take: the built-ins, plus `norsk`
5
+ * (resolved by norsk-ctl) and `plain` (what a literal is). */
6
+ export declare const RESERVED_PROVIDER_NAMES: readonly ["env", "file", "k8s", "aws", "norsk", "plain"];
7
+ export declare const SecretProvidersConfigSchema: z.ZodObject<{
8
+ fileDir: z.ZodOptional<z.ZodString>;
9
+ k8s: z.ZodOptional<z.ZodObject<{
10
+ root: z.ZodOptional<z.ZodString>;
11
+ }, z.core.$strict>>;
12
+ aws: z.ZodOptional<z.ZodObject<{
13
+ region: z.ZodOptional<z.ZodString>;
14
+ cacheTtlMs: z.ZodOptional<z.ZodNumber>;
15
+ }, z.core.$strict>>;
16
+ providers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
17
+ exec: z.ZodArray<z.ZodString>;
18
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
19
+ }, z.core.$strict>>>;
20
+ }, z.core.$strict>;
21
+ export type SecretProvidersConfig = z.infer<typeof SecretProvidersConfigSchema>;
22
+ export interface LoadSecretProvidersOptions {
23
+ env: Record<string, string | undefined>;
24
+ /** A config file. Missing is the same as empty; others being able to write
25
+ * it is refused, because it names commands that see every secret. */
26
+ path?: string;
27
+ /** Config text (YAML, so JSON too), as an environment variable carries it. */
28
+ inline?: string;
29
+ /** Where `file` reads when the config names no `fileDir`. Without either,
30
+ * there is no `file` provider. */
31
+ defaultFileDir?: string;
32
+ }
33
+ /** The providers to resolve with: `env` always, `file` where a directory is
34
+ * known, `k8s` and `aws` when configured, and any exec providers named. Read
35
+ * fresh on each call, so an edit needs no restart. */
36
+ export declare function loadSecretProviders(opts: LoadSecretProvidersOptions): Result<SecretProviders, string>;
@@ -0,0 +1,80 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { err, ok, tryResult } from "@norskvideo/ctl-foundation";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { z } from "zod";
5
+ import { awsSecretProvider } from "./providers/aws.js";
6
+ import { envSecretProvider } from "./providers/env.js";
7
+ import { execSecretProvider } from "./providers/exec.js";
8
+ import { fileSecretProvider } from "./providers/file.js";
9
+ import { k8sSecretProvider } from "./providers/k8s.js";
10
+ /** Names a configured provider may not take: the built-ins, plus `norsk`
11
+ * (resolved by norsk-ctl) and `plain` (what a literal is). */
12
+ export const RESERVED_PROVIDER_NAMES = ["env", "file", "k8s", "aws", "norsk", "plain"];
13
+ export const SecretProvidersConfigSchema = z.strictObject({
14
+ fileDir: z.string().min(1).optional(),
15
+ k8s: z.strictObject({ root: z.string().min(1).optional() }).optional(),
16
+ aws: z
17
+ .strictObject({
18
+ region: z.string().min(1).optional(),
19
+ cacheTtlMs: z.number().int().nonnegative().optional(),
20
+ })
21
+ .optional(),
22
+ providers: z
23
+ .record(z.string().regex(/^[a-z][a-z0-9-]*$/), z.strictObject({
24
+ exec: z.array(z.string().min(1)).min(1),
25
+ timeoutMs: z.number().int().positive().optional(),
26
+ }))
27
+ .optional(),
28
+ });
29
+ /** The providers to resolve with: `env` always, `file` where a directory is
30
+ * known, `k8s` and `aws` when configured, and any exec providers named. Read
31
+ * fresh on each call, so an edit needs no restart. */
32
+ export function loadSecretProviders(opts) {
33
+ const source = readConfig(opts);
34
+ if (source.status === "error")
35
+ return source;
36
+ const { config, where } = source.value;
37
+ const providers = { env: envSecretProvider(opts.env) };
38
+ const fileDir = config.fileDir ?? opts.defaultFileDir;
39
+ if (fileDir)
40
+ providers.file = fileSecretProvider(fileDir);
41
+ if (config.k8s)
42
+ providers.k8s = k8sSecretProvider(config.k8s);
43
+ if (config.aws)
44
+ providers.aws = awsSecretProvider(config.aws);
45
+ for (const [name, def] of Object.entries(config.providers ?? {})) {
46
+ if (RESERVED_PROVIDER_NAMES.includes(name)) {
47
+ return err(`secret provider config ${where} redefines the built-in provider '${name}'`);
48
+ }
49
+ providers[name] = execSecretProvider({ command: def.exec, ...(def.timeoutMs ? { timeoutMs: def.timeoutMs } : {}) });
50
+ }
51
+ return ok(providers);
52
+ }
53
+ function readConfig(opts) {
54
+ let text;
55
+ let where;
56
+ if (opts.inline !== undefined) {
57
+ text = opts.inline;
58
+ where = "(inline)";
59
+ }
60
+ else if (opts.path && existsSync(opts.path)) {
61
+ where = opts.path;
62
+ if ((statSync(opts.path).mode & 0o022) !== 0) {
63
+ return err(`secret provider config ${where} is writable by others than its owner; chmod go-w it`);
64
+ }
65
+ const read = tryResult(() => readFileSync(where, "utf-8"), (e) => (e instanceof Error ? e.message : String(e)));
66
+ if (read.status === "error")
67
+ return err(`secret provider config ${where} is unreadable: ${read.error}`);
68
+ text = read.value;
69
+ }
70
+ else {
71
+ return ok({ config: {}, where: "(none)" });
72
+ }
73
+ const raw = tryResult(() => parseYaml(text) ?? {}, (e) => (e instanceof Error ? e.message : String(e)));
74
+ if (raw.status === "error")
75
+ return err(`secret provider config ${where} is not valid YAML: ${raw.error}`);
76
+ const parsed = SecretProvidersConfigSchema.safeParse(raw.value);
77
+ if (!parsed.success)
78
+ return err(`secret provider config ${where} is invalid: ${z.prettifyError(parsed.error)}`);
79
+ return ok({ config: parsed.data, where });
80
+ }
@@ -0,0 +1,10 @@
1
+ import { type SecretResolver } from "./resolver.js";
2
+ export interface DelegateOptions {
3
+ url: string;
4
+ token: string;
5
+ fetch?: typeof fetch;
6
+ timeoutMs?: number;
7
+ }
8
+ /** Hands references to norsk-ctl's resolve endpoint and keeps literals in this
9
+ * process. Errors name each failing entry and ctl's reason, never a value. */
10
+ export declare function delegateResolver(opts: DelegateOptions): SecretResolver;
@@ -0,0 +1,62 @@
1
+ import { ok } from "@norskvideo/ctl-foundation";
2
+ import { isSecretReference } from "../secret-references.js";
3
+ import { unresolved, wrapAll } from "./resolver.js";
4
+ import { ResolveResponseSchema } from "./wire.js";
5
+ /** Hands references to norsk-ctl's resolve endpoint and keeps literals in this
6
+ * process. Errors name each failing entry and ctl's reason, never a value. */
7
+ export function delegateResolver(opts) {
8
+ const doFetch = opts.fetch ?? fetch;
9
+ return {
10
+ async resolve(entries, ctx) {
11
+ const references = [...new Set(Object.values(entries).filter(isSecretReference))];
12
+ if (references.length === 0)
13
+ return ok(wrapAll(entries));
14
+ const labels = () => Object.entries(entries)
15
+ .filter(([, v]) => isSecretReference(v))
16
+ .map(([k]) => k)
17
+ .join(", ");
18
+ const body = { references, ...(ctx?.purpose ? { purpose: ctx.purpose } : {}) };
19
+ let res;
20
+ try {
21
+ res = await doFetch(opts.url, {
22
+ method: "POST",
23
+ headers: { authorization: `Bearer ${opts.token}`, "content-type": "application/json" },
24
+ body: JSON.stringify(body),
25
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 15_000),
26
+ });
27
+ }
28
+ catch (e) {
29
+ const reason = `norsk-ctl's resolve endpoint is unreachable: ${e instanceof Error ? e.message : String(e)}`;
30
+ return unresolved(`cannot resolve the secret reference in ${labels()}: ${reason}`);
31
+ }
32
+ if (!res.ok) {
33
+ const reason = `norsk-ctl's resolve endpoint answered ${res.status}`;
34
+ return unresolved(`cannot resolve the secret reference in ${labels()}: ${reason}`);
35
+ }
36
+ const parsed = ResolveResponseSchema.safeParse(await res.json().catch(() => undefined));
37
+ if (!parsed.success) {
38
+ return unresolved(`cannot resolve the secret reference in ${labels()}: norsk-ctl's answer is malformed`);
39
+ }
40
+ const { values, errors } = parsed.data;
41
+ const resolved = { ...entries };
42
+ const failures = [];
43
+ for (const [label, value] of Object.entries(entries)) {
44
+ if (!isSecretReference(value))
45
+ continue;
46
+ const got = values[value];
47
+ if (errors[value] !== undefined)
48
+ failures.push(`${label} (${errors[value]})`);
49
+ else if (got === undefined)
50
+ failures.push(`${label} (norsk-ctl returned no value for it)`);
51
+ else if (got === "")
52
+ failures.push(`${label} (norsk-ctl resolved it to an empty value)`);
53
+ else
54
+ resolved[label] = got;
55
+ }
56
+ if (failures.length > 0) {
57
+ return unresolved(`could not resolve secret reference${failures.length > 1 ? "s" : ""}: ${failures.join("; ")}`);
58
+ }
59
+ return ok(wrapAll(resolved));
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,18 @@
1
+ import { type SecretResolver } from "./resolver.js";
2
+ export { isSecretReference, parseSecretReference, SECRET_PLACEHOLDER, SECRET_REFERENCE_PREFIX, type SecretReference, secretReference, } from "../secret-references.js";
3
+ export { type LoadSecretProvidersOptions, loadSecretProviders, RESERVED_PROVIDER_NAMES, type SecretProvidersConfig, SecretProvidersConfigSchema, } from "./config.js";
4
+ export { type DelegateOptions, delegateResolver } from "./delegate.js";
5
+ export { deobfuscate, isObfuscated, OBFUSCATED_PREFIX, obfuscate } from "./obfuscation.js";
6
+ export type { SecretProvider, SecretProviders, SecretResolutionError } from "./provider.js";
7
+ export { type AwsSecretProviderOptions, awsSecretProvider } from "./providers/aws.js";
8
+ export { envSecretProvider } from "./providers/env.js";
9
+ export { execSecretProvider } from "./providers/exec.js";
10
+ export { fileSecretProvider } from "./providers/file.js";
11
+ export { DEFAULT_K8S_SECRETS_ROOT, k8sSecretProvider } from "./providers/k8s.js";
12
+ export { localResolver, type ResolveContext, resolveSecretReferences, type SecretResolver } from "./resolver.js";
13
+ export { Secret } from "./secret.js";
14
+ export * from "./wire.js";
15
+ export declare const SECRET_PROVIDERS_ENV = "NORSK_SECRET_PROVIDERS";
16
+ export declare function createResolverFromEnv(env?: Record<string, string | undefined>): SecretResolver & {
17
+ mode: "delegate" | "local";
18
+ };
@@ -0,0 +1,44 @@
1
+ // Secret references, resolved by whatever needs the value (RFC 0011).
2
+ //
3
+ // An application calls createResolverFromEnv() once. Under norsk-ctl, which
4
+ // sets NORSK_SECRETS_URL and NORSK_SECRETS_TOKEN, every reference goes to ctl
5
+ // and is resolved with the providers on its host. Anywhere else (dev, a
6
+ // customer's Kubernetes) the providers come from NORSK_SECRET_PROVIDERS.
7
+ import { err, ok } from "@norskvideo/ctl-foundation";
8
+ import { loadSecretProviders } from "./config.js";
9
+ import { delegateResolver } from "./delegate.js";
10
+ import { localResolver } from "./resolver.js";
11
+ import { SECRETS_TOKEN_ENV, SECRETS_URL_ENV } from "./wire.js";
12
+ export { isSecretReference, parseSecretReference, SECRET_PLACEHOLDER, SECRET_REFERENCE_PREFIX, secretReference, } from "../secret-references.js";
13
+ export { loadSecretProviders, RESERVED_PROVIDER_NAMES, SecretProvidersConfigSchema, } from "./config.js";
14
+ export { delegateResolver } from "./delegate.js";
15
+ export { deobfuscate, isObfuscated, OBFUSCATED_PREFIX, obfuscate } from "./obfuscation.js";
16
+ export { awsSecretProvider } from "./providers/aws.js";
17
+ export { envSecretProvider } from "./providers/env.js";
18
+ export { execSecretProvider } from "./providers/exec.js";
19
+ export { fileSecretProvider } from "./providers/file.js";
20
+ export { DEFAULT_K8S_SECRETS_ROOT, k8sSecretProvider } from "./providers/k8s.js";
21
+ export { localResolver, resolveSecretReferences } from "./resolver.js";
22
+ export { Secret } from "./secret.js";
23
+ export * from "./wire.js";
24
+ export const SECRET_PROVIDERS_ENV = "NORSK_SECRET_PROVIDERS";
25
+ /** `norsk` secrets are held by norsk-ctl or norsk-mgr, so only ctl resolves them. */
26
+ const noNorskHere = async () => err("norsk: references are resolved by norsk-ctl, and there is no norsk-ctl here (NORSK_SECRETS_URL is not set)");
27
+ /** NORSK_SECRET_PROVIDERS is inline config when it looks like YAML or JSON
28
+ * rather than a path: it starts with '{' or holds a newline. */
29
+ const isInline = (v) => v.trimStart().startsWith("{") || v.includes("\n");
30
+ export function createResolverFromEnv(env = process.env) {
31
+ const url = env[SECRETS_URL_ENV];
32
+ const token = env[SECRETS_TOKEN_ENV];
33
+ if (url && token)
34
+ return { mode: "delegate", ...delegateResolver({ url, token }) };
35
+ const configured = env[SECRET_PROVIDERS_ENV];
36
+ const resolver = localResolver(() => {
37
+ const loaded = loadSecretProviders({
38
+ env,
39
+ ...(configured ? (isInline(configured) ? { inline: configured } : { path: configured }) : {}),
40
+ });
41
+ return loaded.status === "ok" ? ok({ norsk: noNorskHere, ...loaded.value }) : loaded;
42
+ });
43
+ return { mode: "local", ...resolver };
44
+ }
@@ -0,0 +1,6 @@
1
+ import { type Result } from "@norskvideo/ctl-foundation";
2
+ export declare const OBFUSCATED_PREFIX = "nsob:v1:";
3
+ export declare function isObfuscated(text: string): boolean;
4
+ export declare function obfuscate(value: string): string;
5
+ /** The value, or an error that never contains any of the text it was given. */
6
+ export declare function deobfuscate(text: string): Result<string, string>;
@@ -0,0 +1,42 @@
1
+ // The at-rest form of a secret held on disk by norsk: obfuscation, not
2
+ // encryption. The key derives from a constant in this file, so anyone with the
3
+ // code can reverse it. What it buys is that `cat`, `grep`, a paste into a
4
+ // ticket or an agent reading the file does not show the value; GCM's tag also
5
+ // rejects a damaged record. A later version whose key comes from a real key
6
+ // source takes the next version slot (RFC 0011 §3.4).
7
+ import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "node:crypto";
8
+ import { err, tryResult } from "@norskvideo/ctl-foundation";
9
+ export const OBFUSCATED_PREFIX = "nsob:v1:";
10
+ const CONSTANT = Buffer.from("norsk-secret-obfuscation-v1");
11
+ const SALT_BYTES = 16;
12
+ const NONCE_BYTES = 12;
13
+ const TAG_BYTES = 16;
14
+ const keyFor = (salt) => Buffer.from(hkdfSync("sha256", CONSTANT, salt, "nsob:v1", 32));
15
+ export function isObfuscated(text) {
16
+ return text.startsWith(OBFUSCATED_PREFIX);
17
+ }
18
+ export function obfuscate(value) {
19
+ const salt = randomBytes(SALT_BYTES);
20
+ const nonce = randomBytes(NONCE_BYTES);
21
+ const cipher = createCipheriv("aes-256-gcm", keyFor(salt), nonce);
22
+ const body = Buffer.concat([cipher.update(value, "utf-8"), cipher.final(), cipher.getAuthTag()]);
23
+ return `${OBFUSCATED_PREFIX}${[salt, nonce, body].map((b) => b.toString("base64url")).join(":")}`;
24
+ }
25
+ /** The value, or an error that never contains any of the text it was given. */
26
+ export function deobfuscate(text) {
27
+ if (!isObfuscated(text))
28
+ return err("not an obfuscated value");
29
+ const parts = text.slice(OBFUSCATED_PREFIX.length).split(":");
30
+ if (parts.length !== 3)
31
+ return err("malformed obfuscated value");
32
+ const [salt, nonce, body] = parts.map((p) => Buffer.from(p, "base64url"));
33
+ if (salt.length !== SALT_BYTES || nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) {
34
+ return err("malformed obfuscated value");
35
+ }
36
+ return tryResult(() => {
37
+ const decipher = createDecipheriv("aes-256-gcm", keyFor(salt), nonce);
38
+ decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));
39
+ const plain = Buffer.concat([decipher.update(body.subarray(0, body.length - TAG_BYTES)), decipher.final()]);
40
+ return plain.toString("utf-8");
41
+ }, () => "obfuscated value is damaged");
42
+ }
@@ -0,0 +1,11 @@
1
+ import type { Result } from "@norskvideo/ctl-foundation";
2
+ /** Turns a reference's key into its value. An error message is the provider's
3
+ * own reason and must never contain a value. */
4
+ export type SecretProvider = (key: string) => Promise<Result<string, string>>;
5
+ export type SecretProviders = Record<string, SecretProvider>;
6
+ export interface SecretResolutionError {
7
+ code: "SECRET_UNRESOLVED";
8
+ message: string;
9
+ }
10
+ /** A secret's single trailing newline is the editor's (or `echo`'s), not the secret's. */
11
+ export declare function dropTrailingNewline(text: string): string;
@@ -0,0 +1,4 @@
1
+ /** A secret's single trailing newline is the editor's (or `echo`'s), not the secret's. */
2
+ export function dropTrailingNewline(text) {
3
+ return text.replace(/\r?\n$/, "");
4
+ }
@@ -0,0 +1,19 @@
1
+ import { type Result } from "@norskvideo/ctl-foundation";
2
+ import type { SecretProvider } from "../provider.js";
3
+ type GetSecretString = (secretId: string) => Promise<Result<string, string>>;
4
+ export interface AwsSecretProviderOptions {
5
+ region?: string;
6
+ /** How long a fetched secret is reused; 0 fetches on every resolution. */
7
+ cacheTtlMs?: number;
8
+ /** Replaces the SDK call, for tests. */
9
+ getSecretString?: GetSecretString;
10
+ /** Replaces loading the SDK, for tests. */
11
+ loadSdk?: () => Promise<Result<GetSecretString, string>>;
12
+ now?: () => number;
13
+ }
14
+ /** AWS Secrets Manager. The key is a secret's name or ARN, optionally
15
+ * `#<field>` to take one field of a JSON secret. Credentials come from the SDK's
16
+ * default chain (an instance or pod role, the environment, a profile). The SDK
17
+ * is an optional peer dependency, loaded only when a reference needs it. */
18
+ export declare function awsSecretProvider(opts?: AwsSecretProviderOptions): SecretProvider;
19
+ export {};
@@ -0,0 +1,86 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { err, ok } from "@norskvideo/ctl-foundation";
10
+ const SDK_PACKAGE = "@aws-sdk/client-secrets-manager";
11
+ const DEFAULT_CACHE_TTL_MS = 30_000;
12
+ /** AWS Secrets Manager. The key is a secret's name or ARN, optionally
13
+ * `#<field>` to take one field of a JSON secret. Credentials come from the SDK's
14
+ * default chain (an instance or pod role, the environment, a profile). The SDK
15
+ * is an optional peer dependency, loaded only when a reference needs it. */
16
+ export function awsSecretProvider(opts = {}) {
17
+ const ttl = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
18
+ const now = opts.now ?? Date.now;
19
+ const cache = new Map();
20
+ let getter;
21
+ const fetchSecret = async (secretId) => {
22
+ const cached = cache.get(secretId);
23
+ if (cached && now() - cached.at < ttl)
24
+ return ok(cached.value);
25
+ getter ??= opts.getSecretString
26
+ ? Promise.resolve(ok(opts.getSecretString))
27
+ : (opts.loadSdk ?? (() => loadSdk(opts.region)))();
28
+ const get = await getter;
29
+ if (get.status === "error")
30
+ return err(`the aws provider needs ${SDK_PACKAGE} installed: ${get.error}`);
31
+ const got = await get.value(secretId);
32
+ if (got.status === "ok" && ttl > 0)
33
+ cache.set(secretId, { value: got.value, at: now() });
34
+ return got;
35
+ };
36
+ return async (key) => {
37
+ const hash = key.lastIndexOf("#");
38
+ const secretId = hash < 0 ? key : key.slice(0, hash);
39
+ const field = hash < 0 ? undefined : key.slice(hash + 1);
40
+ if (secretId === "" || field === "")
41
+ return err(`'${key}' is not <secret-id>[#<field>]`);
42
+ const got = await fetchSecret(secretId);
43
+ if (got.status === "error" || field === undefined)
44
+ return got;
45
+ return pickField(secretId, field, got.value);
46
+ };
47
+ }
48
+ function pickField(secretId, field, text) {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(text);
52
+ }
53
+ catch {
54
+ return err(`secret '${secretId}' is not JSON, so it has no field '${field}'`);
55
+ }
56
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
57
+ return err(`secret '${secretId}' is not a JSON object, so it has no field '${field}'`);
58
+ }
59
+ const value = parsed[field];
60
+ if (value === undefined)
61
+ return err(`secret '${secretId}' has no field '${field}'`);
62
+ return typeof value === "string" ? ok(value) : ok(JSON.stringify(value));
63
+ }
64
+ async function loadSdk(region) {
65
+ let sdk;
66
+ try {
67
+ sdk = (await import(__rewriteRelativeImportExtension(SDK_PACKAGE)));
68
+ }
69
+ catch (e) {
70
+ return err(e instanceof Error ? e.message : String(e));
71
+ }
72
+ const client = new sdk.SecretsManagerClient(region ? { region } : {});
73
+ return ok(async (secretId) => {
74
+ try {
75
+ const out = await client.send(new sdk.GetSecretValueCommand({ SecretId: secretId }));
76
+ if (out.SecretString !== undefined)
77
+ return ok(out.SecretString);
78
+ return err(`secret '${secretId}' is binary, not a string`);
79
+ }
80
+ catch (e) {
81
+ const name = e instanceof Error ? e.name : "error";
82
+ const message = e instanceof Error ? e.message : String(e);
83
+ return err(`${name}: ${message}`);
84
+ }
85
+ });
86
+ }
@@ -0,0 +1,2 @@
1
+ import type { SecretProvider } from "../provider.js";
2
+ export declare function envSecretProvider(env: Record<string, string | undefined>): SecretProvider;
@@ -0,0 +1,12 @@
1
+ import { err, ok } from "@norskvideo/ctl-foundation";
2
+ // NORSK_SECRET_* only, so a reference cannot lift the host's own credentials
3
+ // (AWS keys, the worker token) into something it hands them to.
4
+ const ENV_KEY = /^NORSK_SECRET_[A-Z0-9_]+$/;
5
+ export function envSecretProvider(env) {
6
+ return async (key) => {
7
+ if (!ENV_KEY.test(key))
8
+ return err(`'${key}' is not a NORSK_SECRET_* variable`);
9
+ const value = env[key];
10
+ return value === undefined ? err(`${key} is not set in the environment`) : ok(value);
11
+ };
12
+ }
@@ -0,0 +1,8 @@
1
+ import { type SecretProvider } from "../provider.js";
2
+ /** A command that prints the value: run without a shell, the key as its last
3
+ * argument. That one shape covers a cloud secret manager's CLI and a
4
+ * deployment's own decryptor without this code knowing either. */
5
+ export declare function execSecretProvider(opts: {
6
+ command: string[];
7
+ timeoutMs?: number;
8
+ }): SecretProvider;
@@ -0,0 +1,49 @@
1
+ import { spawn } from "node:child_process";
2
+ import { err, ok } from "@norskvideo/ctl-foundation";
3
+ import { dropTrailingNewline } from "../provider.js";
4
+ const DEFAULT_EXEC_TIMEOUT_MS = 10_000;
5
+ /** A command that prints the value: run without a shell, the key as its last
6
+ * argument. That one shape covers a cloud secret manager's CLI and a
7
+ * deployment's own decryptor without this code knowing either. */
8
+ export function execSecretProvider(opts) {
9
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
10
+ const [cmd, ...args] = opts.command;
11
+ return (key) => new Promise((resolve) => {
12
+ // Its own process group, so a timeout reaches whatever the command started:
13
+ // a script's children inherit its pipes and would otherwise hold them open.
14
+ const proc = spawn(cmd, [...args, key], { stdio: ["ignore", "pipe", "pipe"], detached: true });
15
+ const stdout = [];
16
+ const stderr = [];
17
+ let settled = false;
18
+ const settle = (r) => {
19
+ if (settled)
20
+ return;
21
+ settled = true;
22
+ clearTimeout(timer);
23
+ resolve(r);
24
+ };
25
+ // Settling on the timer rather than on close: a descendant that left the
26
+ // group can still hold the pipes, and the timeout must hold regardless.
27
+ const timer = setTimeout(() => {
28
+ try {
29
+ if (proc.pid !== undefined)
30
+ process.kill(-proc.pid, "SIGKILL");
31
+ }
32
+ catch {
33
+ proc.kill("SIGKILL");
34
+ }
35
+ settle(err(`${cmd} timed out after ${timeoutMs}ms`));
36
+ }, timeoutMs);
37
+ proc.stdout.on("data", (b) => stdout.push(b));
38
+ proc.stderr.on("data", (b) => stderr.push(b));
39
+ proc.on("error", (e) => settle(err(`could not run ${cmd}: ${e.message}`)));
40
+ proc.on("close", (code) => {
41
+ if (code !== 0) {
42
+ const reason = Buffer.concat(stderr).toString("utf-8").trim().split("\n")[0]?.slice(0, 200) || "no stderr";
43
+ settle(err(`${cmd} exited ${code}: ${reason}`));
44
+ return;
45
+ }
46
+ settle(ok(dropTrailingNewline(Buffer.concat(stdout).toString("utf-8"))));
47
+ });
48
+ });
49
+ }
@@ -0,0 +1,4 @@
1
+ import { type SecretProvider } from "../provider.js";
2
+ /** `<dir>/<key>`, file names only. A file holding the obfuscated form is read
3
+ * back as its value; any other file is its own value. */
4
+ export declare function fileSecretProvider(dir: string): SecretProvider;
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { err, ok, tryResult } from "@norskvideo/ctl-foundation";
4
+ import { deobfuscate, isObfuscated } from "../obfuscation.js";
5
+ import { dropTrailingNewline } from "../provider.js";
6
+ const FILE_KEY = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7
+ /** `<dir>/<key>`, file names only. A file holding the obfuscated form is read
8
+ * back as its value; any other file is its own value. */
9
+ export function fileSecretProvider(dir) {
10
+ return async (key) => {
11
+ if (!FILE_KEY.test(key)) {
12
+ return err(`'${key}' is not a secret file name (letters, digits, '.', '_', '-'; no directories)`);
13
+ }
14
+ const read = tryResult(() => readFileSync(join(dir, key), "utf-8"), () => `no readable secret '${key}' in ${dir}`);
15
+ if (read.status === "error")
16
+ return read;
17
+ const text = dropTrailingNewline(read.value);
18
+ if (!isObfuscated(text))
19
+ return ok(text);
20
+ const plain = deobfuscate(text);
21
+ return plain.status === "ok" ? plain : err(`secret '${key}' in ${dir}: ${plain.error}`);
22
+ };
23
+ }
@@ -0,0 +1,6 @@
1
+ import { type SecretProvider } from "../provider.js";
2
+ export declare const DEFAULT_K8S_SECRETS_ROOT = "/var/run/secrets/norsk";
3
+ /** `<secret>/<key>`, read from a Secret volume mounted at `<root>/<secret>`. */
4
+ export declare function k8sSecretProvider(opts?: {
5
+ root?: string;
6
+ }): SecretProvider;
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { err, ok, tryResult } from "@norskvideo/ctl-foundation";
4
+ import { dropTrailingNewline } from "../provider.js";
5
+ export const DEFAULT_K8S_SECRETS_ROOT = "/var/run/secrets/norsk";
6
+ // A Secret's name is a DNS subdomain; a key is letters, digits, '-', '_' and
7
+ // '.'. Neither may start with '.', which also rules out '..' and the volume's
8
+ // own '..data' entries.
9
+ const SECRET_NAME = /^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$/;
10
+ const SECRET_KEY = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
11
+ /** `<secret>/<key>`, read from a Secret volume mounted at `<root>/<secret>`. */
12
+ export function k8sSecretProvider(opts = {}) {
13
+ const root = opts.root ?? DEFAULT_K8S_SECRETS_ROOT;
14
+ return async (ref) => {
15
+ const parts = ref.split("/");
16
+ const [name, key] = parts;
17
+ if (parts.length !== 2 || !name || !key || !SECRET_NAME.test(name) || !SECRET_KEY.test(key)) {
18
+ return err(`'${ref}' is not <secret>/<key> (a Secret's name, then one of its keys)`);
19
+ }
20
+ const read = tryResult(() => readFileSync(join(root, name, key), "utf-8"), () => `no key '${ref}' under ${root} (is the Secret '${name}' mounted at ${join(root, name)}?)`);
21
+ return read.status === "ok" ? ok(dropTrailingNewline(read.value)) : read;
22
+ };
23
+ }
@@ -0,0 +1,21 @@
1
+ import { type Result } from "@norskvideo/ctl-foundation";
2
+ import type { SecretProviders, SecretResolutionError } from "./provider.js";
3
+ import { Secret } from "./secret.js";
4
+ export type ResolveContext = {
5
+ purpose?: string;
6
+ };
7
+ /** Something that resolves labelled values: each entry's label is what an
8
+ * error names (a launch parameter, "input arena-1 passphrase"). Literals come
9
+ * back as they went in, wrapped like the rest. */
10
+ export interface SecretResolver {
11
+ resolve(entries: Record<string, string>, ctx?: ResolveContext): Promise<Result<Record<string, Secret<string>>, SecretResolutionError>>;
12
+ }
13
+ /** Entries with every reference replaced by its value. Literals pass through,
14
+ * and a call with no reference never loads the providers, so a broken config
15
+ * costs only the calls that need it. Each distinct reference is resolved once.
16
+ * Every failing entry is named at once; no message carries a resolved value. */
17
+ export declare function resolveSecretReferences(entries: Record<string, string>, providers: () => Result<SecretProviders, string>): Promise<Result<Record<string, string>, SecretResolutionError>>;
18
+ export declare function unresolved(message: string): Result<never, SecretResolutionError>;
19
+ export declare function wrapAll(values: Record<string, string>): Record<string, Secret<string>>;
20
+ /** A resolver over providers held in this process. */
21
+ export declare function localResolver(providers: () => Result<SecretProviders, string>): SecretResolver;
@@ -0,0 +1,69 @@
1
+ import { err, ok } from "@norskvideo/ctl-foundation";
2
+ import { isSecretReference, parseSecretReference } from "../secret-references.js";
3
+ import { Secret } from "./secret.js";
4
+ /** Entries with every reference replaced by its value. Literals pass through,
5
+ * and a call with no reference never loads the providers, so a broken config
6
+ * costs only the calls that need it. Each distinct reference is resolved once.
7
+ * Every failing entry is named at once; no message carries a resolved value. */
8
+ export async function resolveSecretReferences(entries, providers) {
9
+ const referenced = Object.entries(entries).filter(([, v]) => isSecretReference(v));
10
+ if (referenced.length === 0)
11
+ return ok(entries);
12
+ const loaded = providers();
13
+ if (loaded.status === "error") {
14
+ return unresolved(`cannot resolve the secret reference in ${referenced.map(([k]) => k).join(", ")}: ${loaded.error}`);
15
+ }
16
+ const outcomes = new Map();
17
+ const outcomeOf = (value) => {
18
+ let pending = outcomes.get(value);
19
+ if (!pending) {
20
+ pending = resolveOne(value, loaded.value);
21
+ outcomes.set(value, pending);
22
+ }
23
+ return pending;
24
+ };
25
+ const resolved = { ...entries };
26
+ const failures = [];
27
+ for (const [label, value] of referenced) {
28
+ const got = await outcomeOf(value);
29
+ if (got.status === "error")
30
+ failures.push(`${label} (${got.error})`);
31
+ else
32
+ resolved[label] = got.value;
33
+ }
34
+ if (failures.length > 0) {
35
+ return unresolved(`could not resolve secret reference${failures.length > 1 ? "s" : ""}: ${failures.join("; ")}`);
36
+ }
37
+ return ok(resolved);
38
+ }
39
+ async function resolveOne(value, providers) {
40
+ const ref = parseSecretReference(value);
41
+ if (ref.status === "error")
42
+ return ref;
43
+ const provider = providers[ref.value.provider];
44
+ if (!provider) {
45
+ const known = Object.keys(providers).sort().join(", ") || "none";
46
+ return err(`no secret provider '${ref.value.provider}' on this host; it has: ${known}`);
47
+ }
48
+ const got = await provider(ref.value.key);
49
+ if (got.status === "error")
50
+ return err(`provider '${ref.value.provider}': ${got.error}`);
51
+ if (got.value === "")
52
+ return err(`provider '${ref.value.provider}' resolved it to an empty value`);
53
+ return got;
54
+ }
55
+ export function unresolved(message) {
56
+ return err({ code: "SECRET_UNRESOLVED", message });
57
+ }
58
+ export function wrapAll(values) {
59
+ return Object.fromEntries(Object.entries(values).map(([k, v]) => [k, new Secret(v)]));
60
+ }
61
+ /** A resolver over providers held in this process. */
62
+ export function localResolver(providers) {
63
+ return {
64
+ async resolve(entries) {
65
+ const got = await resolveSecretReferences(entries, providers);
66
+ return got.status === "ok" ? ok(wrapAll(got.value)) : got;
67
+ },
68
+ };
69
+ }
@@ -0,0 +1,11 @@
1
+ import { inspect } from "node:util";
2
+ /** A resolved secret. Printing, logging or serialising it shows `<secret>`;
3
+ * only `reveal()` gives the value, so every use of one is visible in code. */
4
+ export declare class Secret<T> {
5
+ #private;
6
+ constructor(value: T);
7
+ reveal(): T;
8
+ toString(): string;
9
+ toJSON(): string;
10
+ [inspect.custom](): string;
11
+ }
@@ -0,0 +1,22 @@
1
+ import { inspect } from "node:util";
2
+ import { SECRET_PLACEHOLDER } from "../secret-references.js";
3
+ /** A resolved secret. Printing, logging or serialising it shows `<secret>`;
4
+ * only `reveal()` gives the value, so every use of one is visible in code. */
5
+ export class Secret {
6
+ #value;
7
+ constructor(value) {
8
+ this.#value = value;
9
+ }
10
+ reveal() {
11
+ return this.#value;
12
+ }
13
+ toString() {
14
+ return SECRET_PLACEHOLDER;
15
+ }
16
+ toJSON() {
17
+ return SECRET_PLACEHOLDER;
18
+ }
19
+ [inspect.custom]() {
20
+ return SECRET_PLACEHOLDER;
21
+ }
22
+ }
@@ -0,0 +1,14 @@
1
+ import { z } from "zod";
2
+ export declare const SECRETS_URL_ENV = "NORSK_SECRETS_URL";
3
+ export declare const SECRETS_TOKEN_ENV = "NORSK_SECRETS_TOKEN";
4
+ export declare const ResolveRequestSchema: z.ZodObject<{
5
+ references: z.ZodArray<z.ZodString>;
6
+ purpose: z.ZodOptional<z.ZodString>;
7
+ }, z.core.$strict>;
8
+ export type ResolveRequest = z.infer<typeof ResolveRequestSchema>;
9
+ /** Every requested reference appears in exactly one of the two maps. */
10
+ export declare const ResolveResponseSchema: z.ZodObject<{
11
+ values: z.ZodRecord<z.ZodString, z.ZodString>;
12
+ errors: z.ZodRecord<z.ZodString, z.ZodString>;
13
+ }, z.core.$strict>;
14
+ export type ResolveResponse = z.infer<typeof ResolveResponseSchema>;
@@ -0,0 +1,16 @@
1
+ // The resolve endpoint's request and response (RFC 0011 §3.3), shared by the
2
+ // client an application uses and the endpoint norsk-ctl serves.
3
+ import { z } from "zod";
4
+ import { SECRET_REFERENCE_PREFIX } from "../secret-references.js";
5
+ export const SECRETS_URL_ENV = "NORSK_SECRETS_URL";
6
+ export const SECRETS_TOKEN_ENV = "NORSK_SECRETS_TOKEN";
7
+ export const ResolveRequestSchema = z.strictObject({
8
+ references: z.array(z.string().startsWith(SECRET_REFERENCE_PREFIX)).min(1).max(256),
9
+ /** What the caller wants them for, for errors and the audit; never a value. */
10
+ purpose: z.string().max(200).optional(),
11
+ });
12
+ /** Every requested reference appears in exactly one of the two maps. */
13
+ export const ResolveResponseSchema = z.strictObject({
14
+ values: z.record(z.string(), z.string()),
15
+ errors: z.record(z.string(), z.string()),
16
+ });