feat(credential-sharing): implement the Credential Sharing OpenSpec (M1-M3)

New @logicsrc/plugin-credential-sharing: a provider-neutral secret-sync engine
with env/.env, Doppler, Railway, and GitHub Secrets adapters behind one
CredentialProvider contract.

- engine: inspect -> diff -> plan -> approve -> sync -> rollback -> audit/export
- dry-run is the default for sync; --approve writes; destructive changes gated
- fingerprint-based diffs (salted SHA-256); raw values never printed or stored in
  plans/runs/audit; rollback pre-image kept in a 0600 .logicsrc vault (gitignored)
- github-secrets is write-only for values (sealed-box via libsodium), so it cannot
  be a sync source or value-restoring rollback target
- CLI: real `logicsrc credentials <providers|inspect|diff|plan|approve|sync|
  rollback|audit|export>` (replaces the prior stub)
- 4 JSON schemas registered in @logicsrc/validators
- flip logicsrc.com/credential-sharing band from coming-soon to available
- 37 tests pass; full env->env lifecycle verified; artifacts schema-validate

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-06-27 15:24:30 +00:00
parent 6e7f44612a
commit cf73fe5af2
30 changed files with 1849 additions and 38 deletions

View file

@ -0,0 +1,75 @@
import { keysFromValues } from "../fingerprint.js";
import { httpJson, requireEnv } from "./http.js";
import type { CredentialEndpoint, CredentialProvider, CredentialValueBag, CredentialWriteResult } from "../types.js";
const DOPPLER_API = "https://api.doppler.com/v3";
function auth(): string {
const token = requireEnv("DOPPLER_TOKEN", "Create a Doppler service token and export it as DOPPLER_TOKEN.");
return `Bearer ${token}`;
}
function scopeQuery(endpoint: CredentialEndpoint): string {
const params = new URLSearchParams();
if (endpoint.project) params.set("project", endpoint.project);
if (endpoint.config) params.set("config", endpoint.config);
const qs = params.toString();
return qs ? `?${qs}` : "";
}
interface DopplerSecretsResponse {
secrets: Record<string, { raw?: string; computed?: string }>;
}
async function fetchSecrets(endpoint: CredentialEndpoint): Promise<CredentialValueBag> {
const data = await httpJson<DopplerSecretsResponse>(`${DOPPLER_API}/configs/config/secrets${scopeQuery(endpoint)}`, {
headers: { Authorization: auth(), accept: "application/json" },
expect: "Doppler list secrets"
});
const out: CredentialValueBag = {};
for (const [name, value] of Object.entries(data.secrets ?? {})) {
out[name] = value.raw ?? value.computed ?? "";
}
return out;
}
export const dopplerProvider: CredentialProvider = {
id: "doppler",
name: "Doppler",
description: "Sync project/config scoped secrets.",
capabilities: { readValues: true, readNames: true, write: true, delete: true, rollback: true, audit: false },
authRequirements: ["DOPPLER_TOKEN"],
status: "available",
async inspect(endpoint) {
const values = await fetchSecrets(endpoint);
return { provider: "doppler", endpoint, valuesReadable: true, keys: keysFromValues(values), inspectedAt: new Date().toISOString() };
},
async readValues(endpoint, keys) {
const values = await fetchSecrets(endpoint);
return Object.fromEntries(keys.filter((k) => k in values).map((k) => [k, values[k]]));
},
async write({ endpoint, upserts, deletes, dryRun }) {
const results: CredentialWriteResult[] = [
...Object.keys(upserts).map((key) => ({ key, applied: !dryRun })),
...deletes.map((key) => ({ key, applied: !dryRun }))
];
if (dryRun) {
return results;
}
// Doppler deletes a secret when its value is set to null.
const secrets: Record<string, string | null> = { ...upserts };
for (const key of deletes) {
secrets[key] = null;
}
await httpJson(`${DOPPLER_API}/configs/config/secrets`, {
method: "POST",
headers: { Authorization: auth(), "content-type": "application/json" },
body: JSON.stringify({ project: endpoint.project, config: endpoint.config, secrets }),
expect: "Doppler update secrets"
});
return results;
}
};

View file

@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { parseEnv, applyEnv } from "./env.js";
describe("env provider parsing", () => {
it("parses plain, quoted, and exported lines and ignores comments", () => {
const body = ["# comment", "A=1", 'B="two words"', "export C=three", "", "D='quoted'"].join("\n");
expect(parseEnv(body)).toEqual({ A: "1", B: "two words", C: "three", D: "quoted" });
});
it("decodes escaped newlines inside double quotes", () => {
expect(parseEnv('KEY="line1\\nline2"')).toEqual({ KEY: "line1\nline2" });
});
});
describe("env provider merge", () => {
it("updates existing keys in place and appends new ones", () => {
const body = "# header\nA=1\nB=2\n";
const next = applyEnv(body, { A: "10", C: "3" }, []);
expect(next).toBe("# header\nA=10\nB=2\nC=3\n");
});
it("removes deleted keys but preserves comments", () => {
const body = "# header\nA=1\nB=2\n";
expect(applyEnv(body, {}, ["B"])).toBe("# header\nA=1\n");
});
it("quotes values that need it", () => {
expect(applyEnv("", { A: "two words" }, [])).toBe('A="two words"\n');
});
});

View file

@ -0,0 +1,142 @@
import { readFileSync, writeFileSync, existsSync } from "node:fs";
import { resolve } from "node:path";
import { keysFromValues } from "../fingerprint.js";
import type { CredentialEndpoint, CredentialProvider, CredentialValueBag, CredentialWriteResult } from "../types.js";
const QUOTED = /^(['"])(.*)\1$/s;
/** Parse a `.env` file body into a value bag. Supports quotes and `export` prefixes. */
export function parseEnv(body: string): CredentialValueBag {
const out: CredentialValueBag = {};
for (const rawLine of body.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith("#")) {
continue;
}
const withoutExport = line.startsWith("export ") ? line.slice("export ".length) : line;
const eq = withoutExport.indexOf("=");
if (eq === -1) {
continue;
}
const key = withoutExport.slice(0, eq).trim();
if (!key) {
continue;
}
let value = withoutExport.slice(eq + 1).trim();
const quoted = QUOTED.exec(value);
if (quoted) {
value = quoted[2];
if (quoted[1] === '"') {
value = value.replace(/\\n/g, "\n").replace(/\\"/g, '"');
}
}
out[key] = value;
}
return out;
}
function needsQuoting(value: string): boolean {
return /[\s#'"=]|^$/.test(value) || value.includes("\n");
}
function serializeValue(value: string): string {
if (!needsQuoting(value)) {
return value;
}
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
}
/** Merge upserts/deletes into an existing `.env` body, preserving comments and order. */
export function applyEnv(body: string, upserts: CredentialValueBag, deletes: string[]): string {
const deleteSet = new Set(deletes);
const remaining = new Map(Object.entries(upserts));
const lines = body.split(/\r?\n/);
const output: string[] = [];
for (const rawLine of lines) {
const trimmed = rawLine.trim();
if (!trimmed || trimmed.startsWith("#")) {
output.push(rawLine);
continue;
}
const withoutExport = trimmed.startsWith("export ") ? trimmed.slice("export ".length) : trimmed;
const eq = withoutExport.indexOf("=");
const key = eq === -1 ? "" : withoutExport.slice(0, eq).trim();
if (key && deleteSet.has(key)) {
continue;
}
if (key && remaining.has(key)) {
output.push(`${key}=${serializeValue(remaining.get(key) as string)}`);
remaining.delete(key);
continue;
}
output.push(rawLine);
}
if (remaining.size > 0) {
// Drop the blank line(s) a trailing newline left behind so new keys append cleanly.
while (output.length > 0 && output[output.length - 1].trim() === "") {
output.pop();
}
for (const [key, value] of remaining) {
output.push(`${key}=${serializeValue(value)}`);
}
}
let result = output.join("\n");
if (!result.endsWith("\n")) {
result += "\n";
}
return result;
}
function endpointPath(endpoint: CredentialEndpoint): string {
return resolve(process.cwd(), endpoint.path ?? ".env");
}
function readBody(endpoint: CredentialEndpoint): string {
const file = endpointPath(endpoint);
return existsSync(file) ? readFileSync(file, "utf8") : "";
}
export const envProvider: CredentialProvider = {
id: "env",
name: "Local .env file",
description: "Read, diff, redact, and write local environment files.",
capabilities: { readValues: true, readNames: true, write: true, delete: true, rollback: true, audit: false },
authRequirements: [],
status: "available",
async inspect(endpoint) {
const values = parseEnv(readBody(endpoint));
return {
provider: "env",
endpoint,
valuesReadable: true,
keys: keysFromValues(values),
inspectedAt: new Date().toISOString()
};
},
async readValues(endpoint, keys) {
const values = parseEnv(readBody(endpoint));
return Object.fromEntries(keys.filter((k) => k in values).map((k) => [k, values[k]]));
},
async write({ endpoint, upserts, deletes, dryRun }) {
const results: CredentialWriteResult[] = [
...Object.keys(upserts).map((key) => ({ key, applied: !dryRun })),
...deletes.map((key) => ({ key, applied: !dryRun }))
];
if (dryRun) {
return results;
}
const next = applyEnv(readBody(endpoint), upserts, deletes);
writeFileSync(endpointPath(endpoint), next, { mode: 0o600 });
return results;
},
async rollback({ endpoint, preImage, dryRun }) {
return this.write({ endpoint, upserts: preImage, deletes: [], dryRun });
}
};

View file

@ -0,0 +1,116 @@
import { keysFromNames } from "../fingerprint.js";
import { httpJson, requireEnv } from "./http.js";
import type { CredentialEndpoint, CredentialProvider, CredentialWriteResult } from "../types.js";
const GITHUB_API = "https://api.github.com";
function headers(): Record<string, string> {
const token = requireEnv("GITHUB_TOKEN", "Export a GitHub token with secrets:write scope as GITHUB_TOKEN.");
return {
Authorization: `Bearer ${token}`,
accept: "application/vnd.github+json",
"x-github-api-version": "2022-11-28"
};
}
/**
* Resolve the Actions-secrets base path for an endpoint.
* repo (default): project=owner, service=repo
* org: scope="org", project=org
* environment: scope="environment", project=owner, service=repo, config=environment
*/
function basePath(endpoint: CredentialEndpoint): string {
const scope = endpoint.scope ?? "repo";
if (scope === "org") {
if (!endpoint.project) throw new Error('GitHub org secrets need project=<org>.');
return `/orgs/${endpoint.project}/actions/secrets`;
}
if (!endpoint.project || !endpoint.service) {
throw new Error('GitHub repo secrets need project=<owner> and service=<repo>.');
}
if (scope === "environment") {
if (!endpoint.config) throw new Error('GitHub environment secrets need config=<environment>.');
return `/repos/${endpoint.project}/${endpoint.service}/environments/${endpoint.config}/secrets`;
}
return `/repos/${endpoint.project}/${endpoint.service}/actions/secrets`;
}
interface SecretsList {
secrets: Array<{ name: string; updated_at?: string }>;
}
interface PublicKey {
key_id: string;
key: string;
}
async function sealValue(value: string, publicKeyB64: string): Promise<string> {
const sodiumModule = (await import("libsodium-wrappers")) as unknown as { default?: SodiumLike } & SodiumLike;
const sodium: SodiumLike = sodiumModule.default ?? sodiumModule;
await sodium.ready;
const key = sodium.from_base64(publicKeyB64, sodium.base64_variants.ORIGINAL);
const sealed = sodium.crypto_box_seal(sodium.from_string(value), key);
return sodium.to_base64(sealed, sodium.base64_variants.ORIGINAL);
}
interface SodiumLike {
ready: Promise<void>;
base64_variants: { ORIGINAL: number };
from_base64(input: string, variant: number): Uint8Array;
to_base64(input: Uint8Array, variant: number): string;
from_string(input: string): Uint8Array;
crypto_box_seal(message: Uint8Array, publicKey: Uint8Array): Uint8Array;
}
export const githubSecretsProvider: CredentialProvider = {
id: "github-secrets",
name: "GitHub Secrets",
description: "Sync repository, organization, and environment secrets.",
// GitHub never returns secret values — names only. So values are not readable
// and a github-secrets endpoint cannot be a sync source or a rollback target.
capabilities: { readValues: false, readNames: true, write: true, delete: true, rollback: false, audit: false },
authRequirements: ["GITHUB_TOKEN"],
status: "available",
async inspect(endpoint) {
const list = await httpJson<SecretsList>(`${GITHUB_API}${basePath(endpoint)}?per_page=100`, {
headers: headers(),
expect: "GitHub list secrets"
});
const keys = keysFromNames((list.secrets ?? []).map((s) => s.name));
for (const secret of list.secrets ?? []) {
const key = keys.find((k) => k.name === secret.name);
if (key) key.lastModifiedAt = secret.updated_at;
}
return { provider: "github-secrets", endpoint, valuesReadable: false, keys, inspectedAt: new Date().toISOString() };
},
async write({ endpoint, upserts, deletes, dryRun }) {
const results: CredentialWriteResult[] = [
...Object.keys(upserts).map((key) => ({ key, applied: !dryRun })),
...deletes.map((key) => ({ key, applied: !dryRun }))
];
if (dryRun) {
return results;
}
const base = basePath(endpoint);
const visibility = endpoint.scope === "org" ? { visibility: "all" as const } : {};
let publicKey: PublicKey | undefined;
if (Object.keys(upserts).length > 0) {
publicKey = await httpJson<PublicKey>(`${GITHUB_API}${base}/public-key`, { headers: headers(), expect: "GitHub public key" });
}
for (const [name, value] of Object.entries(upserts)) {
const encrypted_value = await sealValue(value, (publicKey as PublicKey).key);
await httpJson(`${GITHUB_API}${base}/${name}`, {
method: "PUT",
headers: { ...headers(), "content-type": "application/json" },
body: JSON.stringify({ encrypted_value, key_id: (publicKey as PublicKey).key_id, ...visibility }),
expect: `GitHub put secret ${name}`
});
}
for (const name of deletes) {
await httpJson(`${GITHUB_API}${base}/${name}`, { method: "DELETE", headers: headers(), expect: `GitHub delete secret ${name}` });
}
return results;
}
};

View file

@ -0,0 +1,23 @@
/** Minimal fetch helper shared by the network credential providers. */
export function requireEnv(name: string, hint: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing ${name}. ${hint}`);
}
return value;
}
export async function httpJson<T>(
url: string,
init: RequestInit & { expect?: string } = {}
): Promise<T> {
const response = await fetch(url, init);
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(`${init.expect ?? "Request"} failed: ${response.status} ${response.statusText} ${body.slice(0, 300)}`.trim());
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}

View file

@ -0,0 +1,25 @@
import type { CredentialProvider, CredentialProviderManifest } from "../types.js";
import { envProvider } from "./env.js";
import { dopplerProvider } from "./doppler.js";
import { railwayProvider } from "./railway.js";
import { githubSecretsProvider } from "./github-secrets.js";
export const credentialProviders: CredentialProvider[] = [envProvider, dopplerProvider, railwayProvider, githubSecretsProvider];
export const credentialProviderRegistry: Map<string, CredentialProvider> = new Map(
credentialProviders.map((provider) => [provider.id, provider])
);
export function listCredentialProviderManifests(): CredentialProviderManifest[] {
return credentialProviders.map(({ id, name, description, capabilities, authRequirements, status }) => ({
id,
name,
description,
capabilities,
authRequirements,
status
}));
}
export { envProvider, dopplerProvider, railwayProvider, githubSecretsProvider };
export { parseEnv, applyEnv } from "./env.js";

View file

@ -0,0 +1,88 @@
import { keysFromValues } from "../fingerprint.js";
import { httpJson, requireEnv } from "./http.js";
import type { CredentialEndpoint, CredentialProvider, CredentialValueBag, CredentialWriteResult } from "../types.js";
const RAILWAY_API = "https://backboard.railway.app/graphql/v2";
function auth(): string {
const token = requireEnv("RAILWAY_TOKEN", "Create a Railway account/project token and export it as RAILWAY_TOKEN.");
return `Bearer ${token}`;
}
/** Railway addresses variables by project/environment(/service). project=projectId, config=environmentId, service=serviceId. */
function scope(endpoint: CredentialEndpoint): { projectId: string; environmentId: string; serviceId?: string } {
if (!endpoint.project || !endpoint.config) {
throw new Error('Railway endpoint needs project (projectId) and config (environmentId), e.g. --to-project <projectId> --to-config <environmentId>.');
}
return { projectId: endpoint.project, environmentId: endpoint.config, serviceId: endpoint.service };
}
async function gql<T>(query: string, variables: Record<string, unknown>, expect: string): Promise<T> {
const data = await httpJson<{ data?: T; errors?: Array<{ message: string }> }>(RAILWAY_API, {
method: "POST",
headers: { Authorization: auth(), "content-type": "application/json" },
body: JSON.stringify({ query, variables }),
expect
});
if (data.errors?.length) {
throw new Error(`${expect} failed: ${data.errors.map((e) => e.message).join("; ")}`);
}
return data.data as T;
}
async function fetchVariables(endpoint: CredentialEndpoint): Promise<CredentialValueBag> {
const { projectId, environmentId, serviceId } = scope(endpoint);
const data = await gql<{ variables: Record<string, string> }>(
`query Variables($projectId: String!, $environmentId: String!, $serviceId: String) {
variables(projectId: $projectId, environmentId: $environmentId, serviceId: $serviceId)
}`,
{ projectId, environmentId, serviceId },
"Railway list variables"
);
return data.variables ?? {};
}
export const railwayProvider: CredentialProvider = {
id: "railway",
name: "Railway",
description: "Sync service variables.",
capabilities: { readValues: true, readNames: true, write: true, delete: true, rollback: true, audit: false },
authRequirements: ["RAILWAY_TOKEN"],
status: "available",
async inspect(endpoint) {
const values = await fetchVariables(endpoint);
return { provider: "railway", endpoint, valuesReadable: true, keys: keysFromValues(values), inspectedAt: new Date().toISOString() };
},
async readValues(endpoint, keys) {
const values = await fetchVariables(endpoint);
return Object.fromEntries(keys.filter((k) => k in values).map((k) => [k, values[k]]));
},
async write({ endpoint, upserts, deletes, dryRun }) {
const results: CredentialWriteResult[] = [
...Object.keys(upserts).map((key) => ({ key, applied: !dryRun })),
...deletes.map((key) => ({ key, applied: !dryRun }))
];
if (dryRun) {
return results;
}
const { projectId, environmentId, serviceId } = scope(endpoint);
for (const [name, value] of Object.entries(upserts)) {
await gql(
`mutation Upsert($input: VariableUpsertInput!) { variableUpsert(input: $input) }`,
{ input: { projectId, environmentId, serviceId, name, value } },
`Railway upsert ${name}`
);
}
for (const name of deletes) {
await gql(
`mutation Delete($input: VariableDeleteInput!) { variableDelete(input: $input) }`,
{ input: { projectId, environmentId, serviceId, name } },
`Railway delete ${name}`
);
}
return results;
}
};