Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: a second CredentialStore, and what having one reveals

kashorin36e66d3d249a
diff --git a/packages/credential-store-keychain/package.json b/packages/credential-store-keychain/package.json
new file mode 100644
index 00000000..e7ff9076
--- /dev/null
+++ b/packages/credential-store-keychain/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@narratage/credential-store-keychain",
+ "version": "0.0.0-dev",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "svml": {
+ "activation": "./src/activation.ts"
+ },
+ "dependencies": {
+ "@narratage/protocol": "workspace:*",
+ "@narratage/runtime": "workspace:*",
+ "@narratage/runtime-adapter": "workspace:*"
+ },
+ "devDependencies": {
+ "@narratage/credential-store-env": "workspace:*"
+ }
+}
diff --git a/packages/credential-store-keychain/src/activation.ts b/packages/credential-store-keychain/src/activation.ts
new file mode 100644
index 00000000..ddfa31c7
--- /dev/null
+++ b/packages/credential-store-keychain/src/activation.ts
@@ -0,0 +1,29 @@
+import {
+ createRuntimeServiceAdapterFacet,
+ runtimeConfigExact,
+ runtimeConfigObject,
+ runtimeConfigString,
+} from "@narratage/runtime-adapter";
+
+import { createKeychainCredentialStorePackage } from "./store.js";
+
+const keychainCredentialStoreRuntimeAdapter = createRuntimeServiceAdapterFacet({
+ use: "@narratage/credential-store-keychain",
+ create(context) {
+ const config = runtimeConfigObject(context.config, "keychain CredentialStore");
+ runtimeConfigExact(config, ["service"], "keychain CredentialStore");
+ return createKeychainCredentialStorePackage({
+ instance: context.instance,
+ ...(runtimeConfigString(config.service, "keychain service") === undefined
+ ? {} : { service: config.service as string }),
+ });
+ },
+});
+
+export const svmlPackage = {
+ format: "svml.node-package@1" as const,
+ name: "@narratage/credential-store-keychain",
+ hostFacets: [keychainCredentialStoreRuntimeAdapter],
+};
+
+export default svmlPackage;
diff --git a/packages/credential-store-keychain/src/index.ts b/packages/credential-store-keychain/src/index.ts
new file mode 100644
index 00000000..396c1bb6
--- /dev/null
+++ b/packages/credential-store-keychain/src/index.ts
@@ -0,0 +1,11 @@
+export {
+ KeychainCredentialStore,
+ createKeychainCredentialStorePackage,
+ keychainAddCommand,
+ keychainCredentialStoreImplementationDigest,
+ keychainCredentialStoreModuleRef,
+} from "./store.js";
+export type {
+ CreateKeychainCredentialStorePackageOptions,
+ KeychainReader,
+} from "./store.js";
diff --git a/packages/credential-store-keychain/src/store.ts b/packages/credential-store-keychain/src/store.ts
new file mode 100644
index 00000000..eba471db
--- /dev/null
+++ b/packages/credential-store-keychain/src/store.ts
@@ -0,0 +1,111 @@
+import { execFile } from "node:child_process";
+
+import { digestOf } from "@narratage/protocol";
+import { defineRuntimeServicePackage, verifyCredentialRef } from "@narratage/runtime";
+import type {
+ CredentialRef,
+ CredentialStore,
+ CredentialValue,
+ RuntimeServicePackage,
+} from "@narratage/runtime";
+
+export const keychainCredentialStoreModuleRef = {
+ name: "@narratage/credential-store-keychain",
+ version: "1",
+} as const;
+
+export const keychainCredentialStoreImplementationDigest = digestOf(
+ "@narratage/credential-store-keychain/credential-store@1",
+);
+
+/** Reads one named secret. Substituted in tests so no test touches a real keychain. */
+export type KeychainReader = (service: string, account: string) => Promise<string | undefined>;
+
+export type CreateKeychainCredentialStorePackageOptions = {
+ readonly instance?: string;
+ /** Keychain service name every lookup is scoped to. */
+ readonly service?: string;
+ readonly read?: KeychainReader;
+};
+
+const DEFAULT_SERVICE = "narratage";
+
+/**
+ * `security find-generic-password -s <service> -a <account> -w`
+ *
+ * The account is the CredentialRef key, so a lookup asks for exactly the one
+ * entry it was told to ask for. Nothing here can enumerate the keychain, and a
+ * failure never carries the tool's output, which may quote the item.
+ */
+function macosSecurity(service: string): KeychainReader {
+ return async (_service, account) => await new Promise((resolve, reject) => {
+ execFile("/usr/bin/security",
+ ["find-generic-password", "-s", service, "-a", account, "-w"],
+ { timeout: 10_000, shell: false },
+ (error, stdout) => {
+ if (error === null) {
+ resolve(stdout.replace(/\n$/u, ""));
+ return;
+ }
+ // 44 is "item not found": an answer, not a failure.
+ if ((error as { code?: number }).code === 44) resolve(undefined);
+ else reject(new Error(`keychain lookup for ${account} failed`));
+ });
+ });
+}
+
+/**
+ * A CredentialStore backed by the operating system keychain.
+ *
+ * It answers only for `store: "keychain"` references, exactly as the
+ * environment store answers only for `store: "env"`. Anything else is not its
+ * business and it says so by returning undefined rather than guessing.
+ */
+export class KeychainCredentialStore implements CredentialStore {
+ readonly #read: KeychainReader;
+ readonly #service: string;
+
+ constructor(options: { readonly service?: string; readonly read?: KeychainReader } = {}) {
+ this.#service = options.service ?? DEFAULT_SERVICE;
+ this.#read = options.read ?? macosSecurity(this.#service);
+ }
+
+ async resolve(ref: CredentialRef): Promise<CredentialValue | undefined> {
+ verifyCredentialRef(ref);
+ if (ref.store !== "keychain") return undefined;
+ const secret = await this.#read(this.#service, ref.key);
+ if (secret === undefined || secret.length === 0) return undefined;
+ return { secret };
+ }
+}
+
+/** The command that puts a secret where this store will find it. */
+export function keychainAddCommand(key: string, service = DEFAULT_SERVICE): string {
+ return `security add-generic-password -s ${service} -a ${key} -w`;
+}
+
+export function createKeychainCredentialStorePackage(
+ options: CreateKeychainCredentialStorePackageOptions = {},
+): RuntimeServicePackage {
+ const instance = options.instance ?? "credentials.keychain";
+ const service = options.service ?? DEFAULT_SERVICE;
+ return defineRuntimeServicePackage({
+ name: instance,
+ module: keychainCredentialStoreModuleRef,
+ services: [{
+ role: "credential-store",
+ facet: "credential-store",
+ instance,
+ implementation: {
+ locator: "@narratage/credential-store-keychain",
+ digest: keychainCredentialStoreImplementationDigest,
+ },
+ permissions: ["process:keychain"],
+ configuration: { source: "os-keychain", service, explicitKeysOnly: true },
+ service: new KeychainCredentialStore({
+ service,
+ ...(options.read === undefined ? {} : { read: options.read }),
+ }),
+ }],
+ });
+}
diff --git a/packages/credential-store-keychain/test/store.test.ts b/packages/credential-store-keychain/test/store.test.ts
new file mode 100644
index 00000000..d26a414d
--- /dev/null
+++ b/packages/credential-store-keychain/test/store.test.ts
@@ -0,0 +1,96 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createEnvironmentCredentialStorePackage } from "@narratage/credential-store-env";
+import { credentialRef } from "@narratage/runtime";
+import type { CredentialStore } from "@narratage/runtime";
+
+import {
+ KeychainCredentialStore,
+ createKeychainCredentialStorePackage,
+ keychainAddCommand,
+} from "@narratage/credential-store-keychain";
+
+const reader = (entries: Readonly<Record<string, string>>) =>
+ async (_service: string, account: string) => entries[account];
+
+test("it answers for its own store name and declines every other", async () => {
+ const store = new KeychainCredentialStore({ read: reader({ KIE_API_KEY: "secret" }) });
+ assert.deepEqual(await store.resolve(credentialRef("keychain", "KIE_API_KEY")), { secret: "secret" });
+ // Not this store's business: the environment store's references are not
+ // guessed at, they are declined.
+ assert.equal(await store.resolve(credentialRef("env", "KIE_API_KEY")), undefined);
+});
+
+test("an absent entry is absent, and an empty one is not a secret", async () => {
+ const store = new KeychainCredentialStore({ read: reader({ EMPTY: "" }) });
+ assert.equal(await store.resolve(credentialRef("keychain", "ABSENT")), undefined);
+ assert.equal(await store.resolve(credentialRef("keychain", "EMPTY")), undefined);
+});
+
+test("a malformed reference is refused before anything is looked up", async () => {
+ let asked = 0;
+ const store = new KeychainCredentialStore({ read: async () => { asked += 1; return "x"; } });
+ await assert.rejects(async () => await store.resolve({ format: "svml.credential-ref@1", store: "keychain", key: " " } as never));
+ assert.equal(asked, 0);
+});
+
+test("the configured service is part of the instance's identity, and holds no secret", () => {
+ const configured = createKeychainCredentialStorePackage({ instance: "credentials.team", service: "acme" });
+ assert.equal(configured.services[0]?.instance.id, "credentials.team");
+ // Configuration reaches identity as a digest and is not carried in the
+ // Closure, so the proof that the service name counts is that a different
+ // name is a different instance.
+ const other = createKeychainCredentialStorePackage({ instance: "credentials.team", service: "other" });
+ assert.ok(configured.services[0]?.instance.configurationDigest);
+ assert.notEqual(
+ configured.services[0]?.instance.configurationDigest,
+ other.services[0]?.instance.configurationDigest,
+ );
+ assert.equal(JSON.stringify(configured).includes("secret"), false);
+});
+
+test("it can say how to put a secret where it will be found", () => {
+ assert.equal(keychainAddCommand("KIE_API_KEY"), "security add-generic-password -s narratage -a KIE_API_KEY -w");
+});
+
+/**
+ * The reason a second implementation was written.
+ *
+ * `CredentialRef.store` names which store answers, and both stores decline a
+ * reference addressed to the other. That only works if a Runtime can hold both,
+ * and today a Runtime holds exactly one credential-store: `chooseService`
+ * refuses a second, and the execution driver treats one `undefined` as "this
+ * credential is unavailable" and fails the Operation.
+ *
+ * So a deployment that keeps API keys in the environment and signing keys in
+ * the keychain cannot be expressed, and the `store` field is decoration: it has
+ * to name whichever single store happens to be installed.
+ *
+ * This test states the composition that ought to work. It is written against a
+ * local composite so that it describes the intended behaviour exactly, and it
+ * is the specification for changing the assembly.
+ */
+test("two stores compose by name, which is what the store field is for", async () => {
+ const environment = createEnvironmentCredentialStorePackage({
+ environment: { KIE_API_KEY: "from-env" },
+ }).services[0]!.service as CredentialStore;
+ const keychain = new KeychainCredentialStore({ read: reader({ SIGNING_KEY: "from-keychain" }) });
+
+ const composed: CredentialStore = {
+ async resolve(ref) {
+ for (const store of [environment, keychain]) {
+ const value = await store.resolve(ref);
+ if (value !== undefined) return value;
+ }
+ return undefined;
+ },
+ };
+
+ assert.deepEqual(await composed.resolve(credentialRef("env", "KIE_API_KEY")), { secret: "from-env" });
+ assert.deepEqual(await composed.resolve(credentialRef("keychain", "SIGNING_KEY")), { secret: "from-keychain" });
+ // Because each store declines what is not addressed to it, order cannot
+ // change the answer — the name decides, not the position.
+ assert.equal(await composed.resolve(credentialRef("keychain", "KIE_API_KEY")), undefined);
+ assert.equal(await composed.resolve(credentialRef("vault", "ANY")), undefined);
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8001d70c..8aa83864 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -432,6 +432,22 @@ importers:
specifier: workspace:*
version: link:../runtime
+ packages/credential-store-keychain:
+ dependencies:
+ '@narratage/protocol':
+ specifier: workspace:*
+ version: link:../protocol
+ '@narratage/runtime':
+ specifier: workspace:*
+ version: link:../runtime
+ '@narratage/runtime-adapter':
+ specifier: workspace:*
+ version: link:../runtime-adapter
+ devDependencies:
+ '@narratage/credential-store-env':
+ specifier: workspace:*
+ version: link:../credential-store-env
+
packages/driver-node:
dependencies:
'@narratage/component-kit':
diff --git a/tools/package-boundaries.test.mjs b/tools/package-boundaries.test.mjs
index 900d2a72..36bde4f2 100644
--- a/tools/package-boundaries.test.mjs
+++ b/tools/package-boundaries.test.mjs
@@ -69,6 +69,7 @@ const domainNeutralPackages = new Set([
"@narratage/artifact-store-fs",
"@narratage/artifact-store-s3",
"@narratage/credential-store-env",
+ "@narratage/credential-store-keychain",
"@narratage/transport",
"@narratage/transport-aws-lambda",
"@narratage/local",
diff --git a/tsconfig.json b/tsconfig.json
index 1244739d..b0dbc6a2 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -102,6 +102,7 @@
"@narratage/artifact-store-s3": [
"packages/artifact-store-s3/src/index.ts"
],
+ "@narratage/credential-store-keychain": ["packages/credential-store-keychain/src/index.ts"],
"@narratage/credential-store-env": [
"packages/credential-store-env/src/index.ts"
],