@i4ctime/q-ring 0.3.2 → 0.4.0
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/README.md +196 -6
- package/dist/{chunk-F4SPZ774.js → chunk-6IQ5SFLI.js} +298 -6
- package/dist/chunk-6IQ5SFLI.js.map +1 -0
- package/dist/{chunk-3WTTWJYU.js → chunk-IGNU622R.js} +337 -5
- package/dist/chunk-IGNU622R.js.map +1 -0
- package/dist/{dashboard-X3ONQFLV.js → dashboard-32PCZF7D.js} +2 -2
- package/dist/{dashboard-QQWKOOI5.js → dashboard-HVIQO6NT.js} +2 -2
- package/dist/index.js +675 -10
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +580 -9
- package/dist/mcp.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-3WTTWJYU.js.map +0 -1
- package/dist/chunk-F4SPZ774.js.map +0 -1
- /package/dist/{dashboard-QQWKOOI5.js.map → dashboard-32PCZF7D.js.map} +0 -0
- /package/dist/{dashboard-X3ONQFLV.js.map → dashboard-HVIQO6NT.js.map} +0 -0
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp.ts","../src/mcp/server.ts","../src/core/noise.ts","../src/utils/colors.ts","../src/core/agent.ts","../src/core/teleport.ts"],"sourcesContent":["import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createMcpServer } from \"./mcp/server.js\";\n\nconst server = createMcpServer();\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n getSecret,\n setSecret,\n deleteSecret,\n hasSecret,\n listSecrets,\n getEnvelope,\n entangleSecrets,\n exportSecrets,\n type KeyringOptions,\n} from \"../core/keyring.js\";\nimport { runHealthScan } from \"../core/agent.js\";\nimport { checkDecay, collapseValue } from \"../core/envelope.js\";\nimport { collapseEnvironment } from \"../core/collapse.js\";\nimport type { Scope } from \"../core/scope.js\";\nimport { queryAudit, detectAnomalies } from \"../core/observer.js\";\nimport {\n generateSecret,\n estimateEntropy,\n type NoiseFormat,\n} from \"../core/noise.js\";\nimport {\n tunnelCreate,\n tunnelRead,\n tunnelDestroy,\n tunnelList,\n} from \"../core/tunnel.js\";\nimport { teleportPack, teleportUnpack } from \"../core/teleport.js\";\n\nfunction text(t: string, isError = false) {\n return {\n content: [{ type: \"text\" as const, text: t }],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction opts(params: {\n scope?: string;\n projectPath?: string;\n env?: string;\n}): KeyringOptions {\n return {\n scope: params.scope as Scope | undefined,\n projectPath: params.projectPath ?? process.cwd(),\n env: params.env,\n source: \"mcp\",\n };\n}\n\nexport function createMcpServer(): McpServer {\n const server = new McpServer({\n name: \"q-ring\",\n version: \"0.2.0\",\n });\n\n const scopeSchema = z\n .enum([\"global\", \"project\"])\n .optional()\n .describe(\"Scope: global or project\");\n const projectPathSchema = z\n .string()\n .optional()\n .describe(\"Project root path for project-scoped secrets\");\n const envSchema = z\n .string()\n .optional()\n .describe(\"Environment for superposition collapse (e.g., dev, staging, prod)\");\n\n // ─── Core Tools ───\n\n server.tool(\n \"get_secret\",\n \"Retrieve a secret by key. Collapses superposition if the secret has multiple environment states. Records access in audit log (observer effect).\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n env: envSchema,\n },\n async (params) => {\n const value = getSecret(params.key, opts(params));\n if (value === null) return text(`Secret \"${params.key}\" not found`, true);\n return text(value);\n },\n );\n\n server.tool(\n \"list_secrets\",\n \"List all secret keys with quantum metadata (scope, decay status, superposition states, entanglement, access count). Values are never exposed.\",\n {\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const entries = listSecrets(opts(params));\n if (entries.length === 0) return text(\"No secrets found\");\n\n const lines = entries.map((e) => {\n const parts = [`[${e.scope}] ${e.key}`];\n\n if (e.envelope?.states) {\n parts.push(`states:[${Object.keys(e.envelope.states).join(\",\")}]`);\n }\n if (e.decay?.isExpired) {\n parts.push(\"EXPIRED\");\n } else if (e.decay?.isStale) {\n parts.push(`stale(${e.decay.lifetimePercent}%)`);\n }\n if (e.decay?.timeRemaining && !e.decay.isExpired) {\n parts.push(`ttl:${e.decay.timeRemaining}`);\n }\n if (e.envelope?.meta.entangled?.length) {\n parts.push(`entangled:${e.envelope.meta.entangled.length}`);\n }\n if (e.envelope && e.envelope.meta.accessCount > 0) {\n parts.push(`reads:${e.envelope.meta.accessCount}`);\n }\n\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"set_secret\",\n \"Store a secret with optional quantum metadata: TTL (decay), environment state (superposition), description, tags.\",\n {\n key: z.string().describe(\"The secret key name\"),\n value: z.string().describe(\"The secret value\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n env: z\n .string()\n .optional()\n .describe(\"If provided, sets the value for this specific environment (superposition)\"),\n ttlSeconds: z\n .number()\n .optional()\n .describe(\"Time-to-live in seconds (quantum decay)\"),\n description: z.string().optional().describe(\"Human-readable description\"),\n tags: z\n .array(z.string())\n .optional()\n .describe(\"Tags for organization\"),\n },\n async (params) => {\n const o = opts(params);\n\n if (params.env) {\n const existing = getEnvelope(params.key, o);\n const states = existing?.envelope?.states ?? {};\n states[params.env] = params.value;\n\n if (existing?.envelope?.value && !states[\"default\"]) {\n states[\"default\"] = existing.envelope.value;\n }\n\n setSecret(params.key, \"\", {\n ...o,\n states,\n defaultEnv: existing?.envelope?.defaultEnv ?? params.env,\n ttlSeconds: params.ttlSeconds,\n description: params.description,\n tags: params.tags,\n });\n\n return text(`[${params.scope ?? \"global\"}] ${params.key} set for env:${params.env}`);\n }\n\n setSecret(params.key, params.value, {\n ...o,\n ttlSeconds: params.ttlSeconds,\n description: params.description,\n tags: params.tags,\n });\n\n return text(`[${params.scope ?? \"global\"}] ${params.key} saved`);\n },\n );\n\n server.tool(\n \"delete_secret\",\n \"Remove a secret from the keyring.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const deleted = deleteSecret(params.key, opts(params));\n return text(\n deleted ? `Deleted \"${params.key}\"` : `Secret \"${params.key}\" not found`,\n !deleted,\n );\n },\n );\n\n server.tool(\n \"has_secret\",\n \"Check if a secret exists. Returns boolean. Never reveals the value. Respects decay — expired secrets return false.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n return text(hasSecret(params.key, opts(params)) ? \"true\" : \"false\");\n },\n );\n\n // ─── Quantum Tools ───\n\n server.tool(\n \"inspect_secret\",\n \"Show full quantum state of a secret: superposition states, decay status, entanglement links, access history. Never reveals the actual value.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const result = getEnvelope(params.key, opts(params));\n if (!result) return text(`Secret \"${params.key}\" not found`, true);\n\n const { envelope, scope } = result;\n const decay = checkDecay(envelope);\n\n const info: Record<string, unknown> = {\n key: params.key,\n scope,\n type: envelope.states ? \"superposition\" : \"collapsed\",\n created: envelope.meta.createdAt,\n updated: envelope.meta.updatedAt,\n accessCount: envelope.meta.accessCount,\n lastAccessed: envelope.meta.lastAccessedAt ?? \"never\",\n };\n\n if (envelope.states) {\n info.environments = Object.keys(envelope.states);\n info.defaultEnv = envelope.defaultEnv;\n }\n\n if (decay.timeRemaining) {\n info.decay = {\n expired: decay.isExpired,\n stale: decay.isStale,\n lifetimePercent: decay.lifetimePercent,\n timeRemaining: decay.timeRemaining,\n };\n }\n\n if (envelope.meta.entangled?.length) {\n info.entangled = envelope.meta.entangled;\n }\n\n if (envelope.meta.description) info.description = envelope.meta.description;\n if (envelope.meta.tags?.length) info.tags = envelope.meta.tags;\n\n return text(JSON.stringify(info, null, 2));\n },\n );\n\n server.tool(\n \"detect_environment\",\n \"Detect the current environment context (wavefunction collapse). Returns the detected environment and its source (NODE_ENV, git branch, project config, etc.).\",\n {\n projectPath: projectPathSchema,\n },\n async (params) => {\n const result = collapseEnvironment({\n projectPath: params.projectPath ?? process.cwd(),\n });\n\n if (!result) {\n return text(\n \"No environment detected. Set QRING_ENV, NODE_ENV, or create .q-ring.json\",\n );\n }\n\n return text(JSON.stringify(result, null, 2));\n },\n );\n\n server.tool(\n \"generate_secret\",\n \"Generate a cryptographic secret (quantum noise). Formats: hex, base64, alphanumeric, uuid, api-key, token, password. Optionally save directly to the keyring.\",\n {\n format: z\n .enum([\"hex\", \"base64\", \"alphanumeric\", \"uuid\", \"api-key\", \"token\", \"password\"])\n .optional()\n .default(\"api-key\")\n .describe(\"Output format\"),\n length: z.number().optional().describe(\"Length in bytes or characters\"),\n prefix: z.string().optional().describe(\"Prefix for api-key/token format\"),\n saveAs: z.string().optional().describe(\"If provided, save the generated secret with this key name\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n },\n async (params) => {\n const secret = generateSecret({\n format: params.format as NoiseFormat,\n length: params.length,\n prefix: params.prefix,\n });\n\n if (params.saveAs) {\n setSecret(params.saveAs, secret, {\n ...opts(params),\n description: `Generated ${params.format} secret`,\n });\n const entropy = estimateEntropy(secret);\n return text(\n `Generated and saved as \"${params.saveAs}\" (${params.format}, ~${entropy} bits entropy)`,\n );\n }\n\n return text(secret);\n },\n );\n\n server.tool(\n \"entangle_secrets\",\n \"Create a quantum entanglement between two secrets. When the source is rotated/updated, the target automatically receives the same value.\",\n {\n sourceKey: z.string().describe(\"Source secret key\"),\n targetKey: z.string().describe(\"Target secret key\"),\n sourceScope: scopeSchema.default(\"global\"),\n targetScope: scopeSchema.default(\"global\"),\n sourceProjectPath: z.string().optional(),\n targetProjectPath: z.string().optional(),\n },\n async (params) => {\n entangleSecrets(\n params.sourceKey,\n {\n scope: params.sourceScope as Scope,\n projectPath: params.sourceProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n params.targetKey,\n {\n scope: params.targetScope as Scope,\n projectPath: params.targetProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n );\n\n return text(`Entangled: ${params.sourceKey} <-> ${params.targetKey}`);\n },\n );\n\n // ─── Tunneling Tools ───\n\n server.tool(\n \"tunnel_create\",\n \"Create an ephemeral secret that exists only in memory (quantum tunneling). Never persisted to disk. Optional TTL and max-reads for self-destruction.\",\n {\n value: z.string().describe(\"The secret value\"),\n ttlSeconds: z.number().optional().describe(\"Auto-expire after N seconds\"),\n maxReads: z.number().optional().describe(\"Self-destruct after N reads\"),\n },\n async (params) => {\n const id = tunnelCreate(params.value, {\n ttlSeconds: params.ttlSeconds,\n maxReads: params.maxReads,\n });\n return text(id);\n },\n );\n\n server.tool(\n \"tunnel_read\",\n \"Read an ephemeral tunneled secret by ID. May self-destruct if max-reads is reached.\",\n {\n id: z.string().describe(\"Tunnel ID\"),\n },\n async (params) => {\n const value = tunnelRead(params.id);\n if (value === null) {\n return text(`Tunnel \"${params.id}\" not found or expired`, true);\n }\n return text(value);\n },\n );\n\n server.tool(\n \"tunnel_list\",\n \"List active tunneled secrets (IDs and metadata only, never values).\",\n {},\n async () => {\n const tunnels = tunnelList();\n if (tunnels.length === 0) return text(\"No active tunnels\");\n\n const lines = tunnels.map((t) => {\n const parts = [t.id];\n parts.push(`reads:${t.accessCount}`);\n if (t.maxReads) parts.push(`max:${t.maxReads}`);\n if (t.expiresAt) {\n const rem = Math.max(0, Math.floor((t.expiresAt - Date.now()) / 1000));\n parts.push(`expires:${rem}s`);\n }\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"tunnel_destroy\",\n \"Immediately destroy a tunneled secret.\",\n {\n id: z.string().describe(\"Tunnel ID\"),\n },\n async (params) => {\n const destroyed = tunnelDestroy(params.id);\n return text(\n destroyed ? `Destroyed ${params.id}` : `Tunnel \"${params.id}\" not found`,\n !destroyed,\n );\n },\n );\n\n // ─── Teleportation Tools ───\n\n server.tool(\n \"teleport_pack\",\n \"Pack secrets into an AES-256-GCM encrypted bundle for sharing between machines (quantum teleportation).\",\n {\n keys: z\n .array(z.string())\n .optional()\n .describe(\"Specific keys to pack (all if omitted)\"),\n passphrase: z.string().describe(\"Encryption passphrase\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const o = opts(params);\n const entries = listSecrets(o);\n\n const secrets: { key: string; value: string; scope?: string }[] = [];\n for (const entry of entries) {\n if (params.keys && !params.keys.includes(entry.key)) continue;\n const value = getSecret(entry.key, { ...o, scope: entry.scope });\n if (value !== null) {\n secrets.push({ key: entry.key, value, scope: entry.scope });\n }\n }\n\n if (secrets.length === 0) return text(\"No secrets to pack\", true);\n\n const bundle = teleportPack(secrets, params.passphrase);\n return text(bundle);\n },\n );\n\n server.tool(\n \"teleport_unpack\",\n \"Decrypt and import secrets from a teleport bundle.\",\n {\n bundle: z.string().describe(\"Base64-encoded encrypted bundle\"),\n passphrase: z.string().describe(\"Decryption passphrase\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n dryRun: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Preview without importing\"),\n },\n async (params) => {\n try {\n const payload = teleportUnpack(params.bundle, params.passphrase);\n\n if (params.dryRun) {\n const preview = payload.secrets\n .map((s) => `${s.key} [${s.scope ?? \"global\"}]`)\n .join(\"\\n\");\n return text(`Would import ${payload.secrets.length} secrets:\\n${preview}`);\n }\n\n const o = opts(params);\n for (const s of payload.secrets) {\n setSecret(s.key, s.value, o);\n }\n\n return text(`Imported ${payload.secrets.length} secret(s) from teleport bundle`);\n } catch {\n return text(\"Failed to unpack: wrong passphrase or corrupted bundle\", true);\n }\n },\n );\n\n // ─── Observer / Audit Tools ───\n\n server.tool(\n \"audit_log\",\n \"Query the audit log for secret access history (observer effect). Shows who accessed what and when.\",\n {\n key: z.string().optional().describe(\"Filter by key\"),\n action: z\n .enum([\"read\", \"write\", \"delete\", \"list\", \"export\", \"generate\", \"entangle\", \"tunnel\", \"teleport\", \"collapse\"])\n .optional()\n .describe(\"Filter by action\"),\n limit: z.number().optional().default(20).describe(\"Max events to return\"),\n },\n async (params) => {\n const events = queryAudit({\n key: params.key,\n action: params.action,\n limit: params.limit,\n });\n\n if (events.length === 0) return text(\"No audit events found\");\n\n const lines = events.map((e) => {\n const parts = [e.timestamp, e.action];\n if (e.key) parts.push(e.key);\n if (e.scope) parts.push(`[${e.scope}]`);\n if (e.env) parts.push(`env:${e.env}`);\n if (e.detail) parts.push(e.detail);\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"detect_anomalies\",\n \"Scan for anomalous secret access patterns: burst reads, unusual-hour access. Returns findings and recommendations.\",\n {\n key: z.string().optional().describe(\"Check anomalies for a specific key\"),\n },\n async (params) => {\n const anomalies = detectAnomalies(params.key);\n if (anomalies.length === 0) return text(\"No anomalies detected\");\n\n const lines = anomalies.map(\n (a) => `[${a.type}] ${a.description}`,\n );\n return text(lines.join(\"\\n\"));\n },\n );\n\n // ─── Health ───\n\n server.tool(\n \"health_check\",\n \"Run a comprehensive health check on all secrets: decay status, staleness, anomalies, entropy assessment.\",\n {\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const entries = listSecrets(opts(params));\n const anomalies = detectAnomalies();\n\n let healthy = 0;\n let stale = 0;\n let expired = 0;\n let noDecay = 0;\n const issues: string[] = [];\n\n for (const entry of entries) {\n if (!entry.decay?.timeRemaining) {\n noDecay++;\n continue;\n }\n if (entry.decay.isExpired) {\n expired++;\n issues.push(`EXPIRED: ${entry.key}`);\n } else if (entry.decay.isStale) {\n stale++;\n issues.push(\n `STALE: ${entry.key} (${entry.decay.lifetimePercent}%, ${entry.decay.timeRemaining} left)`,\n );\n } else {\n healthy++;\n }\n }\n\n const summary = [\n `Secrets: ${entries.length} total`,\n `Healthy: ${healthy} | Stale: ${stale} | Expired: ${expired} | No decay: ${noDecay}`,\n `Anomalies: ${anomalies.length}`,\n ];\n\n if (issues.length > 0) {\n summary.push(\"\", \"Issues:\", ...issues);\n }\n if (anomalies.length > 0) {\n summary.push(\n \"\",\n \"Anomalies:\",\n ...anomalies.map((a) => `[${a.type}] ${a.description}`),\n );\n }\n\n return text(summary.join(\"\\n\"));\n },\n );\n\n // ─── Status Dashboard ───\n\n let dashboardInstance: { port: number; close: () => void } | null = null;\n\n server.tool(\n \"status_dashboard\",\n \"Launch the quantum status dashboard — a local web page showing live health, decay timers, superposition states, entanglement graph, tunnels, audit log, and anomaly alerts. Returns the URL to open in a browser.\",\n {\n port: z.number().optional().default(9876).describe(\"Port to serve on\"),\n },\n async (params) => {\n if (dashboardInstance) {\n return text(`Dashboard already running at http://127.0.0.1:${dashboardInstance.port}`);\n }\n\n const { startDashboardServer } = await import(\"../core/dashboard.js\");\n dashboardInstance = startDashboardServer({ port: params.port });\n\n return text(`Dashboard started at http://127.0.0.1:${dashboardInstance.port}\\nOpen this URL in a browser to see live quantum status.`);\n },\n );\n\n // ─── Agent ───\n\n server.tool(\n \"agent_scan\",\n \"Run an autonomous agent health scan: checks decay, staleness, anomalies, and optionally auto-rotates expired secrets. Returns a structured report.\",\n {\n autoRotate: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Auto-rotate expired secrets with generated values\"),\n projectPaths: z\n .array(z.string())\n .optional()\n .describe(\"Project paths to monitor\"),\n },\n async (params) => {\n const report = runHealthScan({\n autoRotate: params.autoRotate,\n projectPaths: params.projectPaths ?? [process.cwd()],\n });\n return text(JSON.stringify(report, null, 2));\n },\n );\n\n return server;\n}\n","/**\n * Quantum Noise: cryptographic secret generation.\n * Generates high-entropy values in common formats.\n */\n\nimport { randomBytes, randomInt } from \"node:crypto\";\n\nexport type NoiseFormat =\n | \"hex\"\n | \"base64\"\n | \"alphanumeric\"\n | \"uuid\"\n | \"api-key\"\n | \"token\"\n | \"password\";\n\nexport interface NoiseOptions {\n format?: NoiseFormat;\n /** Length in bytes (for hex/base64) or characters (for alphanumeric/password) */\n length?: number;\n /** Prefix for api-key format (e.g., \"sk-\", \"pk-\") */\n prefix?: string;\n}\n\nconst ALPHA_NUM =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst PASSWORD_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{}|;:,.<>?\";\n\nfunction randomString(charset: string, length: number): string {\n let result = \"\";\n for (let i = 0; i < length; i++) {\n result += charset[randomInt(charset.length)];\n }\n return result;\n}\n\nexport function generateSecret(opts: NoiseOptions = {}): string {\n const format = opts.format ?? \"api-key\";\n\n switch (format) {\n case \"hex\": {\n const len = opts.length ?? 32;\n return randomBytes(len).toString(\"hex\");\n }\n\n case \"base64\": {\n const len = opts.length ?? 32;\n return randomBytes(len).toString(\"base64url\");\n }\n\n case \"alphanumeric\": {\n const len = opts.length ?? 32;\n return randomString(ALPHA_NUM, len);\n }\n\n case \"uuid\": {\n const bytes = randomBytes(16);\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1\n const hex = bytes.toString(\"hex\");\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20, 32),\n ].join(\"-\");\n }\n\n case \"api-key\": {\n const prefix = opts.prefix ?? \"qr_\";\n const len = opts.length ?? 48;\n return prefix + randomString(ALPHA_NUM, len);\n }\n\n case \"token\": {\n const prefix = opts.prefix ?? \"\";\n const len = opts.length ?? 64;\n return prefix + randomBytes(len).toString(\"base64url\");\n }\n\n case \"password\": {\n const len = opts.length ?? 24;\n let pw = randomString(PASSWORD_CHARS, len);\n\n // Guarantee at least one of each class\n const hasUpper = /[A-Z]/.test(pw);\n const hasLower = /[a-z]/.test(pw);\n const hasDigit = /[0-9]/.test(pw);\n const hasSpecial = /[^A-Za-z0-9]/.test(pw);\n\n if (!hasUpper) pw = replaceAt(pw, randomInt(len), randomString(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", 1));\n if (!hasLower) pw = replaceAt(pw, randomInt(len), randomString(\"abcdefghijklmnopqrstuvwxyz\", 1));\n if (!hasDigit) pw = replaceAt(pw, randomInt(len), randomString(\"0123456789\", 1));\n if (!hasSpecial) pw = replaceAt(pw, randomInt(len), randomString(\"!@#$%^&*()-_=+\", 1));\n\n return pw;\n }\n\n default:\n return randomBytes(32).toString(\"hex\");\n }\n}\n\nfunction replaceAt(str: string, index: number, char: string): string {\n return str.slice(0, index) + char + str.slice(index + 1);\n}\n\n/**\n * Estimate the entropy of a secret in bits.\n */\nexport function estimateEntropy(secret: string): number {\n const charsets = [\n { regex: /[a-z]/, size: 26 },\n { regex: /[A-Z]/, size: 26 },\n { regex: /[0-9]/, size: 10 },\n { regex: /[^A-Za-z0-9]/, size: 32 },\n ];\n\n let poolSize = 0;\n for (const { regex, size } of charsets) {\n if (regex.test(secret)) poolSize += size;\n }\n\n return poolSize > 0 ? Math.floor(Math.log2(poolSize) * secret.length) : 0;\n}\n","/**\n * Minimal ANSI color helpers. No dependencies.\n */\n\nconst enabled = process.stdout.isTTY !== false && !process.env.NO_COLOR;\n\nfunction wrap(code: string, text: string): string {\n return enabled ? `\\x1b[${code}m${text}\\x1b[0m` : text;\n}\n\nexport const c = {\n bold: (t: string) => wrap(\"1\", t),\n dim: (t: string) => wrap(\"2\", t),\n italic: (t: string) => wrap(\"3\", t),\n underline: (t: string) => wrap(\"4\", t),\n\n red: (t: string) => wrap(\"31\", t),\n green: (t: string) => wrap(\"32\", t),\n yellow: (t: string) => wrap(\"33\", t),\n blue: (t: string) => wrap(\"34\", t),\n magenta: (t: string) => wrap(\"35\", t),\n cyan: (t: string) => wrap(\"36\", t),\n white: (t: string) => wrap(\"37\", t),\n gray: (t: string) => wrap(\"90\", t),\n\n bgRed: (t: string) => wrap(\"41\", t),\n bgGreen: (t: string) => wrap(\"42\", t),\n bgYellow: (t: string) => wrap(\"43\", t),\n bgBlue: (t: string) => wrap(\"44\", t),\n bgMagenta: (t: string) => wrap(\"45\", t),\n bgCyan: (t: string) => wrap(\"46\", t),\n};\n\nexport function scopeColor(scope: string): string {\n return scope === \"project\" ? c.cyan(scope) : c.blue(scope);\n}\n\nexport function decayIndicator(percent: number, expired: boolean): string {\n if (expired) return c.bgRed(c.white(\" EXPIRED \"));\n if (percent >= 90) return c.red(`[decay ${percent}%]`);\n if (percent >= 75) return c.yellow(`[decay ${percent}%]`);\n if (percent > 0) return c.green(`[decay ${percent}%]`);\n return \"\";\n}\n\nexport function envBadge(env: string): string {\n switch (env) {\n case \"prod\":\n return c.bgRed(c.white(` ${env} `));\n case \"staging\":\n return c.bgYellow(c.white(` ${env} `));\n case \"dev\":\n return c.bgGreen(c.white(` ${env} `));\n case \"test\":\n return c.bgBlue(c.white(` ${env} `));\n default:\n return c.bgMagenta(c.white(` ${env} `));\n }\n}\n\nexport const SYMBOLS = {\n check: enabled ? \"\\u2713\" : \"[ok]\",\n cross: enabled ? \"\\u2717\" : \"[x]\",\n arrow: enabled ? \"\\u2192\" : \"->\",\n dot: enabled ? \"\\u2022\" : \"*\",\n lock: enabled ? \"\\u{1f512}\" : \"[locked]\",\n key: enabled ? \"\\u{1f511}\" : \"[key]\",\n link: enabled ? \"\\u{1f517}\" : \"[link]\",\n warning: enabled ? \"\\u26a0\\ufe0f\" : \"[!]\",\n clock: enabled ? \"\\u23f0\" : \"[time]\",\n shield: enabled ? \"\\u{1f6e1}\\ufe0f\" : \"[shield]\",\n zap: enabled ? \"\\u26a1\" : \"[zap]\",\n eye: enabled ? \"\\u{1f441}\\ufe0f\" : \"[eye]\",\n ghost: enabled ? \"\\u{1f47b}\" : \"[ghost]\",\n package: enabled ? \"\\u{1f4e6}\" : \"[pkg]\",\n sparkle: enabled ? \"\\u2728\" : \"[*]\",\n} as const;\n","/**\n * Quantum Agent: autonomous background monitor for secret health.\n *\n * Runs as a long-lived process that periodically:\n * - Checks for expired/stale secrets (decay monitoring)\n * - Detects access anomalies (observer analysis)\n * - Logs health reports\n * - Can trigger rotation callbacks\n *\n * Designed to run as `qring agent` or be invoked by the MCP server.\n */\n\nimport { listSecrets, getEnvelope, setSecret, type KeyringOptions } from \"./keyring.js\";\nimport { checkDecay, type QuantumEnvelope } from \"./envelope.js\";\nimport { detectAnomalies, logAudit, queryAudit } from \"./observer.js\";\nimport { generateSecret } from \"./noise.js\";\nimport { findEntangled } from \"./entanglement.js\";\nimport { c, SYMBOLS, decayIndicator } from \"../utils/colors.js\";\n\nexport interface AgentConfig {\n /** Check interval in seconds (default: 60) */\n intervalSeconds: number;\n /** Auto-rotate expired secrets with generated values */\n autoRotate: boolean;\n /** Project paths to monitor */\n projectPaths: string[];\n /** Verbose output */\n verbose: boolean;\n}\n\nexport interface AgentReport {\n timestamp: string;\n totalSecrets: number;\n healthy: number;\n stale: number;\n expired: number;\n anomalies: number;\n rotated: string[];\n warnings: string[];\n}\n\nfunction defaultConfig(): AgentConfig {\n return {\n intervalSeconds: 60,\n autoRotate: false,\n projectPaths: [process.cwd()],\n verbose: false,\n };\n}\n\nexport function runHealthScan(config: Partial<AgentConfig> = {}): AgentReport {\n const cfg = { ...defaultConfig(), ...config };\n\n const report: AgentReport = {\n timestamp: new Date().toISOString(),\n totalSecrets: 0,\n healthy: 0,\n stale: 0,\n expired: 0,\n anomalies: 0,\n rotated: [],\n warnings: [],\n };\n\n // Scan global scope\n const globalEntries = listSecrets({ scope: \"global\", source: \"agent\" });\n\n // Scan project scopes\n const projectEntries = cfg.projectPaths.flatMap((pp) =>\n listSecrets({ scope: \"project\", projectPath: pp, source: \"agent\" }),\n );\n\n const allEntries = [...globalEntries, ...projectEntries];\n report.totalSecrets = allEntries.length;\n\n for (const entry of allEntries) {\n if (!entry.envelope) continue;\n\n const decay = checkDecay(entry.envelope);\n\n if (decay.isExpired) {\n report.expired++;\n report.warnings.push(\n `EXPIRED: ${entry.key} [${entry.scope}] — expired ${decay.timeRemaining}`,\n );\n\n if (cfg.autoRotate) {\n const newValue = generateSecret({ format: \"api-key\" });\n setSecret(entry.key, newValue, {\n scope: entry.scope,\n projectPath: cfg.projectPaths[0],\n source: \"agent\",\n });\n report.rotated.push(entry.key);\n logAudit({\n action: \"write\",\n key: entry.key,\n scope: entry.scope,\n source: \"agent\",\n detail: \"auto-rotated by agent (expired)\",\n });\n }\n } else if (decay.isStale) {\n report.stale++;\n report.warnings.push(\n `STALE: ${entry.key} [${entry.scope}] — ${decay.lifetimePercent}% lifetime, ${decay.timeRemaining} remaining`,\n );\n } else {\n report.healthy++;\n }\n }\n\n // Check for anomalies\n const anomalies = detectAnomalies();\n report.anomalies = anomalies.length;\n for (const a of anomalies) {\n report.warnings.push(`ANOMALY [${a.type}]: ${a.description}`);\n }\n\n return report;\n}\n\nfunction formatReport(report: AgentReport, verbose: boolean): string {\n const lines: string[] = [];\n\n lines.push(\n `${c.bold(`${SYMBOLS.shield} q-ring agent scan`)} ${c.dim(report.timestamp)}`,\n );\n lines.push(\n ` ${c.dim(\"secrets:\")} ${report.totalSecrets} ${c.green(`${SYMBOLS.check} ${report.healthy}`)} ${c.yellow(`${SYMBOLS.warning} ${report.stale}`)} ${c.red(`${SYMBOLS.cross} ${report.expired}`)} ${c.dim(`anomalies: ${report.anomalies}`)}`,\n );\n\n if (report.rotated.length > 0) {\n lines.push(\n ` ${c.cyan(`${SYMBOLS.zap} auto-rotated:`)} ${report.rotated.join(\", \")}`,\n );\n }\n\n if (verbose && report.warnings.length > 0) {\n lines.push(\"\");\n for (const w of report.warnings) {\n if (w.startsWith(\"EXPIRED\")) lines.push(` ${c.red(w)}`);\n else if (w.startsWith(\"STALE\")) lines.push(` ${c.yellow(w)}`);\n else if (w.startsWith(\"ANOMALY\")) lines.push(` ${c.magenta(w)}`);\n else lines.push(` ${w}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Run the agent as a continuous background monitor.\n */\nexport async function startAgent(config: Partial<AgentConfig> = {}): Promise<void> {\n const cfg = { ...defaultConfig(), ...config };\n\n console.log(\n `${c.bold(`${SYMBOLS.zap} q-ring agent started`)} ${c.dim(`(interval: ${cfg.intervalSeconds}s, auto-rotate: ${cfg.autoRotate})`)}`,\n );\n console.log(\n c.dim(` monitoring: global + ${cfg.projectPaths.length} project(s)`),\n );\n console.log();\n\n const scan = () => {\n const report = runHealthScan(cfg);\n console.log(formatReport(report, cfg.verbose));\n\n if (report.warnings.length > 0 || cfg.verbose) {\n console.log();\n }\n };\n\n // Initial scan\n scan();\n\n // Continuous monitoring\n const interval = setInterval(scan, cfg.intervalSeconds * 1000);\n\n // Graceful shutdown\n const shutdown = () => {\n clearInterval(interval);\n console.log(`\\n${c.dim(\"q-ring agent stopped\")}`);\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // Keep alive\n await new Promise(() => {});\n}\n","/**\n * Quantum Teleportation: securely share/transfer secrets between machines.\n *\n * Generates encrypted bundles that can be shared via any channel.\n * The recipient decrypts with a shared passphrase (out-of-band exchange).\n * Uses AES-256-GCM with PBKDF2-derived keys.\n */\n\nimport {\n randomBytes,\n createCipheriv,\n createDecipheriv,\n pbkdf2Sync,\n} from \"node:crypto\";\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst KEY_LENGTH = 32;\nconst IV_LENGTH = 16;\nconst SALT_LENGTH = 32;\nconst TAG_LENGTH = 16;\nconst PBKDF2_ITERATIONS = 100000;\n\nexport interface TeleportBundle {\n /** Format version */\n v: 1;\n /** Base64-encoded encrypted payload */\n data: string;\n /** Base64-encoded salt for key derivation */\n salt: string;\n /** Base64-encoded initialization vector */\n iv: string;\n /** Base64-encoded auth tag */\n tag: string;\n /** ISO timestamp of creation */\n createdAt: string;\n /** Number of secrets in the bundle */\n count: number;\n}\n\nexport interface TeleportPayload {\n secrets: { key: string; value: string; scope?: string }[];\n exportedAt: string;\n exportedBy?: string;\n}\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, \"sha512\");\n}\n\n/**\n * Pack secrets into an encrypted teleport bundle.\n */\nexport function teleportPack(\n secrets: { key: string; value: string; scope?: string }[],\n passphrase: string,\n): string {\n const payload: TeleportPayload = {\n secrets,\n exportedAt: new Date().toISOString(),\n };\n\n const plaintext = JSON.stringify(payload);\n const salt = randomBytes(SALT_LENGTH);\n const iv = randomBytes(IV_LENGTH);\n const key = deriveKey(passphrase, salt);\n\n const cipher = createCipheriv(ALGORITHM, key, iv);\n const encrypted = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n\n const bundle: TeleportBundle = {\n v: 1,\n data: encrypted.toString(\"base64\"),\n salt: salt.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n createdAt: new Date().toISOString(),\n count: secrets.length,\n };\n\n return Buffer.from(JSON.stringify(bundle)).toString(\"base64\");\n}\n\n/**\n * Unpack and decrypt a teleport bundle.\n */\nexport function teleportUnpack(\n encoded: string,\n passphrase: string,\n): TeleportPayload {\n const bundleJson = Buffer.from(encoded, \"base64\").toString(\"utf8\");\n const bundle: TeleportBundle = JSON.parse(bundleJson);\n\n if (bundle.v !== 1) {\n throw new Error(`Unsupported teleport bundle version: ${bundle.v}`);\n }\n\n const salt = Buffer.from(bundle.salt, \"base64\");\n const iv = Buffer.from(bundle.iv, \"base64\");\n const tag = Buffer.from(bundle.tag, \"base64\");\n const encrypted = Buffer.from(bundle.data, \"base64\");\n const key = deriveKey(passphrase, salt);\n\n const decipher = createDecipheriv(ALGORITHM, key, iv);\n decipher.setAuthTag(tag);\n\n const decrypted = Buffer.concat([\n decipher.update(encrypted),\n decipher.final(),\n ]);\n\n return JSON.parse(decrypted.toString(\"utf8\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;A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AC3B,YAAY,OAAO;AAAA,QACnB,cAAc,OAAO,gBAAgB,CAAC,QAAQ,IAAI,CAAC;AAAA,MACrD,CAAC;AACD,aAAO,KAAK,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,IAC7C;AAAA,EACF;AAEA,SAAOA;AACT;;;AD7oBA,IAAM,SAAS,gBAAgB;AAC/B,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["opts","randomBytes","randomBytes","server"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/mcp/server.ts","../src/core/noise.ts","../src/utils/colors.ts","../src/core/agent.ts","../src/core/teleport.ts","../src/core/import.ts","../src/core/validate.ts"],"sourcesContent":["import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createMcpServer } from \"./mcp/server.js\";\n\nconst server = createMcpServer();\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n getSecret,\n setSecret,\n deleteSecret,\n hasSecret,\n listSecrets,\n getEnvelope,\n entangleSecrets,\n disentangleSecrets,\n exportSecrets,\n type KeyringOptions,\n} from \"../core/keyring.js\";\nimport { runHealthScan } from \"../core/agent.js\";\nimport { checkDecay, collapseValue } from \"../core/envelope.js\";\nimport { collapseEnvironment, readProjectConfig } from \"../core/collapse.js\";\nimport type { Scope } from \"../core/scope.js\";\nimport { queryAudit, detectAnomalies } from \"../core/observer.js\";\nimport {\n generateSecret,\n estimateEntropy,\n type NoiseFormat,\n} from \"../core/noise.js\";\nimport {\n tunnelCreate,\n tunnelRead,\n tunnelDestroy,\n tunnelList,\n} from \"../core/tunnel.js\";\nimport { teleportPack, teleportUnpack } from \"../core/teleport.js\";\nimport { importDotenv, parseDotenv } from \"../core/import.js\";\nimport { validateSecret, registry as providerRegistry } from \"../core/validate.js\";\nimport {\n registerHook,\n removeHook,\n listHooks as listAllHooks,\n type HookType,\n type HookAction,\n} from \"../core/hooks.js\";\n\nfunction text(t: string, isError = false) {\n return {\n content: [{ type: \"text\" as const, text: t }],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction opts(params: {\n scope?: string;\n projectPath?: string;\n env?: string;\n}): KeyringOptions {\n return {\n scope: params.scope as Scope | undefined,\n projectPath: params.projectPath ?? process.cwd(),\n env: params.env,\n source: \"mcp\",\n };\n}\n\nexport function createMcpServer(): McpServer {\n const server = new McpServer({\n name: \"q-ring\",\n version: \"0.2.0\",\n });\n\n const scopeSchema = z\n .enum([\"global\", \"project\"])\n .optional()\n .describe(\"Scope: global or project\");\n const projectPathSchema = z\n .string()\n .optional()\n .describe(\"Project root path for project-scoped secrets\");\n const envSchema = z\n .string()\n .optional()\n .describe(\"Environment for superposition collapse (e.g., dev, staging, prod)\");\n\n // ─── Core Tools ───\n\n server.tool(\n \"get_secret\",\n \"Retrieve a secret by key. Collapses superposition if the secret has multiple environment states. Records access in audit log (observer effect).\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n env: envSchema,\n },\n async (params) => {\n const value = getSecret(params.key, opts(params));\n if (value === null) return text(`Secret \"${params.key}\" not found`, true);\n return text(value);\n },\n );\n\n server.tool(\n \"list_secrets\",\n \"List all secret keys with quantum metadata (scope, decay status, superposition states, entanglement, access count). Values are never exposed. Supports filtering by tag, expiry state, and key pattern.\",\n {\n scope: scopeSchema,\n projectPath: projectPathSchema,\n tag: z.string().optional().describe(\"Filter by tag\"),\n expired: z.boolean().optional().describe(\"Show only expired secrets\"),\n stale: z.boolean().optional().describe(\"Show only stale secrets (75%+ decay)\"),\n filter: z.string().optional().describe(\"Glob pattern on key name (e.g., 'API_*')\"),\n },\n async (params) => {\n let entries = listSecrets(opts(params));\n\n if (params.tag) {\n entries = entries.filter((e) =>\n e.envelope?.meta.tags?.includes(params.tag!),\n );\n }\n if (params.expired) {\n entries = entries.filter((e) => e.decay?.isExpired);\n }\n if (params.stale) {\n entries = entries.filter(\n (e) => e.decay?.isStale && !e.decay?.isExpired,\n );\n }\n if (params.filter) {\n const regex = new RegExp(\n \"^\" + params.filter.replace(/\\*/g, \".*\") + \"$\",\n \"i\",\n );\n entries = entries.filter((e) => regex.test(e.key));\n }\n if (entries.length === 0) return text(\"No secrets found\");\n\n const lines = entries.map((e) => {\n const parts = [`[${e.scope}] ${e.key}`];\n\n if (e.envelope?.states) {\n parts.push(`states:[${Object.keys(e.envelope.states).join(\",\")}]`);\n }\n if (e.decay?.isExpired) {\n parts.push(\"EXPIRED\");\n } else if (e.decay?.isStale) {\n parts.push(`stale(${e.decay.lifetimePercent}%)`);\n }\n if (e.decay?.timeRemaining && !e.decay.isExpired) {\n parts.push(`ttl:${e.decay.timeRemaining}`);\n }\n if (e.envelope?.meta.entangled?.length) {\n parts.push(`entangled:${e.envelope.meta.entangled.length}`);\n }\n if (e.envelope && e.envelope.meta.accessCount > 0) {\n parts.push(`reads:${e.envelope.meta.accessCount}`);\n }\n\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"set_secret\",\n \"Store a secret with optional quantum metadata: TTL (decay), environment state (superposition), description, tags.\",\n {\n key: z.string().describe(\"The secret key name\"),\n value: z.string().describe(\"The secret value\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n env: z\n .string()\n .optional()\n .describe(\"If provided, sets the value for this specific environment (superposition)\"),\n ttlSeconds: z\n .number()\n .optional()\n .describe(\"Time-to-live in seconds (quantum decay)\"),\n description: z.string().optional().describe(\"Human-readable description\"),\n tags: z\n .array(z.string())\n .optional()\n .describe(\"Tags for organization\"),\n rotationFormat: z\n .enum([\"hex\", \"base64\", \"alphanumeric\", \"uuid\", \"api-key\", \"token\", \"password\"])\n .optional()\n .describe(\"Format for auto-rotation when this secret expires\"),\n rotationPrefix: z\n .string()\n .optional()\n .describe(\"Prefix for auto-rotation (e.g. 'sk-')\"),\n },\n async (params) => {\n const o = opts(params);\n\n if (params.env) {\n const existing = getEnvelope(params.key, o);\n const states = existing?.envelope?.states ?? {};\n states[params.env] = params.value;\n\n if (existing?.envelope?.value && !states[\"default\"]) {\n states[\"default\"] = existing.envelope.value;\n }\n\n setSecret(params.key, \"\", {\n ...o,\n states,\n defaultEnv: existing?.envelope?.defaultEnv ?? params.env,\n ttlSeconds: params.ttlSeconds,\n description: params.description,\n tags: params.tags,\n rotationFormat: params.rotationFormat,\n rotationPrefix: params.rotationPrefix,\n });\n\n return text(`[${params.scope ?? \"global\"}] ${params.key} set for env:${params.env}`);\n }\n\n setSecret(params.key, params.value, {\n ...o,\n ttlSeconds: params.ttlSeconds,\n description: params.description,\n tags: params.tags,\n rotationFormat: params.rotationFormat,\n rotationPrefix: params.rotationPrefix,\n });\n\n return text(`[${params.scope ?? \"global\"}] ${params.key} saved`);\n },\n );\n\n server.tool(\n \"delete_secret\",\n \"Remove a secret from the keyring.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const deleted = deleteSecret(params.key, opts(params));\n return text(\n deleted ? `Deleted \"${params.key}\"` : `Secret \"${params.key}\" not found`,\n !deleted,\n );\n },\n );\n\n server.tool(\n \"has_secret\",\n \"Check if a secret exists. Returns boolean. Never reveals the value. Respects decay — expired secrets return false.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n return text(hasSecret(params.key, opts(params)) ? \"true\" : \"false\");\n },\n );\n\n server.tool(\n \"export_secrets\",\n \"Export secrets as .env or JSON format. Collapses superposition. Supports filtering by specific keys or tags.\",\n {\n format: z\n .enum([\"env\", \"json\"])\n .optional()\n .default(\"env\")\n .describe(\"Output format\"),\n keys: z\n .array(z.string())\n .optional()\n .describe(\"Only export these specific key names\"),\n tags: z\n .array(z.string())\n .optional()\n .describe(\"Only export secrets with any of these tags\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n env: envSchema,\n },\n async (params) => {\n const output = exportSecrets({\n ...opts(params),\n format: params.format as \"env\" | \"json\",\n keys: params.keys,\n tags: params.tags,\n });\n\n if (!output.trim()) return text(\"No secrets matched the filters\", true);\n return text(output);\n },\n );\n\n server.tool(\n \"import_dotenv\",\n \"Import secrets from .env file content. Parses standard dotenv syntax (comments, quotes, multiline escapes) and stores each key/value pair in q-ring.\",\n {\n content: z.string().describe(\"The .env file content to parse and import\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n skipExisting: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Skip keys that already exist in q-ring\"),\n dryRun: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Preview what would be imported without saving\"),\n },\n async (params) => {\n const result = importDotenv(params.content, {\n scope: params.scope as \"global\" | \"project\",\n projectPath: params.projectPath ?? process.cwd(),\n source: \"mcp\",\n skipExisting: params.skipExisting,\n dryRun: params.dryRun,\n });\n\n const lines = [\n params.dryRun ? \"Dry run — no changes made\" : `Imported ${result.imported.length} secret(s)`,\n ];\n\n if (result.imported.length > 0) {\n lines.push(`Keys: ${result.imported.join(\", \")}`);\n }\n if (result.skipped.length > 0) {\n lines.push(`Skipped (existing): ${result.skipped.join(\", \")}`);\n }\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"check_project\",\n \"Validate project secrets against the .q-ring.json manifest. Returns which required secrets are present, missing, expired, or stale. Use this to verify project readiness.\",\n {\n projectPath: projectPathSchema,\n },\n async (params) => {\n const projectPath = params.projectPath ?? process.cwd();\n const config = readProjectConfig(projectPath);\n\n if (!config?.secrets || Object.keys(config.secrets).length === 0) {\n return text(\"No secrets manifest found in .q-ring.json\", true);\n }\n\n const results: Record<string, unknown>[] = [];\n let presentCount = 0;\n let missingCount = 0;\n let expiredCount = 0;\n let staleCount = 0;\n\n for (const [key, manifest] of Object.entries(config.secrets)) {\n const result = getEnvelope(key, { projectPath, source: \"mcp\" });\n\n if (!result) {\n const status = manifest.required !== false ? \"missing\" : \"optional_missing\";\n if (manifest.required !== false) missingCount++;\n results.push({ key, status, required: manifest.required !== false, description: manifest.description });\n continue;\n }\n\n const decay = checkDecay(result.envelope);\n\n if (decay.isExpired) {\n expiredCount++;\n results.push({ key, status: \"expired\", timeRemaining: decay.timeRemaining, description: manifest.description });\n } else if (decay.isStale) {\n staleCount++;\n results.push({ key, status: \"stale\", lifetimePercent: decay.lifetimePercent, timeRemaining: decay.timeRemaining, description: manifest.description });\n } else {\n presentCount++;\n results.push({ key, status: \"ok\", description: manifest.description });\n }\n }\n\n const summary = {\n total: Object.keys(config.secrets).length,\n present: presentCount,\n missing: missingCount,\n expired: expiredCount,\n stale: staleCount,\n ready: missingCount === 0 && expiredCount === 0,\n secrets: results,\n };\n\n return text(JSON.stringify(summary, null, 2));\n },\n );\n\n server.tool(\n \"env_generate\",\n \"Generate .env file content from the project manifest (.q-ring.json). Resolves each declared secret from q-ring, collapses superposition, and returns .env formatted output. Warns about missing or expired secrets.\",\n {\n projectPath: projectPathSchema,\n env: envSchema,\n },\n async (params) => {\n const projectPath = params.projectPath ?? process.cwd();\n const config = readProjectConfig(projectPath);\n\n if (!config?.secrets || Object.keys(config.secrets).length === 0) {\n return text(\"No secrets manifest found in .q-ring.json\", true);\n }\n\n const lines: string[] = [];\n const warnings: string[] = [];\n\n for (const [key, manifest] of Object.entries(config.secrets)) {\n const value = getSecret(key, {\n projectPath,\n env: params.env,\n source: \"mcp\",\n });\n\n if (value === null) {\n if (manifest.required !== false) {\n warnings.push(`MISSING (required): ${key}`);\n }\n lines.push(`# ${key}=`);\n continue;\n }\n\n const result = getEnvelope(key, { projectPath, source: \"mcp\" });\n if (result) {\n const decay = checkDecay(result.envelope);\n if (decay.isExpired) warnings.push(`EXPIRED: ${key}`);\n else if (decay.isStale) warnings.push(`STALE: ${key}`);\n }\n\n const escaped = value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\");\n lines.push(`${key}=\"${escaped}\"`);\n }\n\n const output = lines.join(\"\\n\");\n const result = warnings.length > 0\n ? `${output}\\n\\n# Warnings:\\n${warnings.map((w) => `# ${w}`).join(\"\\n\")}`\n : output;\n\n return text(result);\n },\n );\n\n // ─── Quantum Tools ───\n\n server.tool(\n \"inspect_secret\",\n \"Show full quantum state of a secret: superposition states, decay status, entanglement links, access history. Never reveals the actual value.\",\n {\n key: z.string().describe(\"The secret key name\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const result = getEnvelope(params.key, opts(params));\n if (!result) return text(`Secret \"${params.key}\" not found`, true);\n\n const { envelope, scope } = result;\n const decay = checkDecay(envelope);\n\n const info: Record<string, unknown> = {\n key: params.key,\n scope,\n type: envelope.states ? \"superposition\" : \"collapsed\",\n created: envelope.meta.createdAt,\n updated: envelope.meta.updatedAt,\n accessCount: envelope.meta.accessCount,\n lastAccessed: envelope.meta.lastAccessedAt ?? \"never\",\n };\n\n if (envelope.states) {\n info.environments = Object.keys(envelope.states);\n info.defaultEnv = envelope.defaultEnv;\n }\n\n if (decay.timeRemaining) {\n info.decay = {\n expired: decay.isExpired,\n stale: decay.isStale,\n lifetimePercent: decay.lifetimePercent,\n timeRemaining: decay.timeRemaining,\n };\n }\n\n if (envelope.meta.entangled?.length) {\n info.entangled = envelope.meta.entangled;\n }\n\n if (envelope.meta.description) info.description = envelope.meta.description;\n if (envelope.meta.tags?.length) info.tags = envelope.meta.tags;\n\n return text(JSON.stringify(info, null, 2));\n },\n );\n\n server.tool(\n \"detect_environment\",\n \"Detect the current environment context (wavefunction collapse). Returns the detected environment and its source (NODE_ENV, git branch, project config, etc.).\",\n {\n projectPath: projectPathSchema,\n },\n async (params) => {\n const result = collapseEnvironment({\n projectPath: params.projectPath ?? process.cwd(),\n });\n\n if (!result) {\n return text(\n \"No environment detected. Set QRING_ENV, NODE_ENV, or create .q-ring.json\",\n );\n }\n\n return text(JSON.stringify(result, null, 2));\n },\n );\n\n server.tool(\n \"generate_secret\",\n \"Generate a cryptographic secret (quantum noise). Formats: hex, base64, alphanumeric, uuid, api-key, token, password. Optionally save directly to the keyring.\",\n {\n format: z\n .enum([\"hex\", \"base64\", \"alphanumeric\", \"uuid\", \"api-key\", \"token\", \"password\"])\n .optional()\n .default(\"api-key\")\n .describe(\"Output format\"),\n length: z.number().optional().describe(\"Length in bytes or characters\"),\n prefix: z.string().optional().describe(\"Prefix for api-key/token format\"),\n saveAs: z.string().optional().describe(\"If provided, save the generated secret with this key name\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n },\n async (params) => {\n const secret = generateSecret({\n format: params.format as NoiseFormat,\n length: params.length,\n prefix: params.prefix,\n });\n\n if (params.saveAs) {\n setSecret(params.saveAs, secret, {\n ...opts(params),\n description: `Generated ${params.format} secret`,\n });\n const entropy = estimateEntropy(secret);\n return text(\n `Generated and saved as \"${params.saveAs}\" (${params.format}, ~${entropy} bits entropy)`,\n );\n }\n\n return text(secret);\n },\n );\n\n server.tool(\n \"entangle_secrets\",\n \"Create a quantum entanglement between two secrets. When the source is rotated/updated, the target automatically receives the same value.\",\n {\n sourceKey: z.string().describe(\"Source secret key\"),\n targetKey: z.string().describe(\"Target secret key\"),\n sourceScope: scopeSchema.default(\"global\"),\n targetScope: scopeSchema.default(\"global\"),\n sourceProjectPath: z.string().optional(),\n targetProjectPath: z.string().optional(),\n },\n async (params) => {\n entangleSecrets(\n params.sourceKey,\n {\n scope: params.sourceScope as Scope,\n projectPath: params.sourceProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n params.targetKey,\n {\n scope: params.targetScope as Scope,\n projectPath: params.targetProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n );\n\n return text(`Entangled: ${params.sourceKey} <-> ${params.targetKey}`);\n },\n );\n\n server.tool(\n \"disentangle_secrets\",\n \"Remove a quantum entanglement between two secrets. They will no longer synchronize on rotation.\",\n {\n sourceKey: z.string().describe(\"Source secret key\"),\n targetKey: z.string().describe(\"Target secret key\"),\n sourceScope: scopeSchema.default(\"global\"),\n targetScope: scopeSchema.default(\"global\"),\n sourceProjectPath: z.string().optional(),\n targetProjectPath: z.string().optional(),\n },\n async (params) => {\n disentangleSecrets(\n params.sourceKey,\n {\n scope: params.sourceScope as Scope,\n projectPath: params.sourceProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n params.targetKey,\n {\n scope: params.targetScope as Scope,\n projectPath: params.targetProjectPath ?? process.cwd(),\n source: \"mcp\",\n },\n );\n\n return text(`Disentangled: ${params.sourceKey} </> ${params.targetKey}`);\n },\n );\n\n // ─── Tunneling Tools ───\n\n server.tool(\n \"tunnel_create\",\n \"Create an ephemeral secret that exists only in memory (quantum tunneling). Never persisted to disk. Optional TTL and max-reads for self-destruction.\",\n {\n value: z.string().describe(\"The secret value\"),\n ttlSeconds: z.number().optional().describe(\"Auto-expire after N seconds\"),\n maxReads: z.number().optional().describe(\"Self-destruct after N reads\"),\n },\n async (params) => {\n const id = tunnelCreate(params.value, {\n ttlSeconds: params.ttlSeconds,\n maxReads: params.maxReads,\n });\n return text(id);\n },\n );\n\n server.tool(\n \"tunnel_read\",\n \"Read an ephemeral tunneled secret by ID. May self-destruct if max-reads is reached.\",\n {\n id: z.string().describe(\"Tunnel ID\"),\n },\n async (params) => {\n const value = tunnelRead(params.id);\n if (value === null) {\n return text(`Tunnel \"${params.id}\" not found or expired`, true);\n }\n return text(value);\n },\n );\n\n server.tool(\n \"tunnel_list\",\n \"List active tunneled secrets (IDs and metadata only, never values).\",\n {},\n async () => {\n const tunnels = tunnelList();\n if (tunnels.length === 0) return text(\"No active tunnels\");\n\n const lines = tunnels.map((t) => {\n const parts = [t.id];\n parts.push(`reads:${t.accessCount}`);\n if (t.maxReads) parts.push(`max:${t.maxReads}`);\n if (t.expiresAt) {\n const rem = Math.max(0, Math.floor((t.expiresAt - Date.now()) / 1000));\n parts.push(`expires:${rem}s`);\n }\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"tunnel_destroy\",\n \"Immediately destroy a tunneled secret.\",\n {\n id: z.string().describe(\"Tunnel ID\"),\n },\n async (params) => {\n const destroyed = tunnelDestroy(params.id);\n return text(\n destroyed ? `Destroyed ${params.id}` : `Tunnel \"${params.id}\" not found`,\n !destroyed,\n );\n },\n );\n\n // ─── Teleportation Tools ───\n\n server.tool(\n \"teleport_pack\",\n \"Pack secrets into an AES-256-GCM encrypted bundle for sharing between machines (quantum teleportation).\",\n {\n keys: z\n .array(z.string())\n .optional()\n .describe(\"Specific keys to pack (all if omitted)\"),\n passphrase: z.string().describe(\"Encryption passphrase\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const o = opts(params);\n const entries = listSecrets(o);\n\n const secrets: { key: string; value: string; scope?: string }[] = [];\n for (const entry of entries) {\n if (params.keys && !params.keys.includes(entry.key)) continue;\n const value = getSecret(entry.key, { ...o, scope: entry.scope });\n if (value !== null) {\n secrets.push({ key: entry.key, value, scope: entry.scope });\n }\n }\n\n if (secrets.length === 0) return text(\"No secrets to pack\", true);\n\n const bundle = teleportPack(secrets, params.passphrase);\n return text(bundle);\n },\n );\n\n server.tool(\n \"teleport_unpack\",\n \"Decrypt and import secrets from a teleport bundle.\",\n {\n bundle: z.string().describe(\"Base64-encoded encrypted bundle\"),\n passphrase: z.string().describe(\"Decryption passphrase\"),\n scope: scopeSchema.default(\"global\"),\n projectPath: projectPathSchema,\n dryRun: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Preview without importing\"),\n },\n async (params) => {\n try {\n const payload = teleportUnpack(params.bundle, params.passphrase);\n\n if (params.dryRun) {\n const preview = payload.secrets\n .map((s) => `${s.key} [${s.scope ?? \"global\"}]`)\n .join(\"\\n\");\n return text(`Would import ${payload.secrets.length} secrets:\\n${preview}`);\n }\n\n const o = opts(params);\n for (const s of payload.secrets) {\n setSecret(s.key, s.value, o);\n }\n\n return text(`Imported ${payload.secrets.length} secret(s) from teleport bundle`);\n } catch {\n return text(\"Failed to unpack: wrong passphrase or corrupted bundle\", true);\n }\n },\n );\n\n // ─── Observer / Audit Tools ───\n\n server.tool(\n \"audit_log\",\n \"Query the audit log for secret access history (observer effect). Shows who accessed what and when.\",\n {\n key: z.string().optional().describe(\"Filter by key\"),\n action: z\n .enum([\"read\", \"write\", \"delete\", \"list\", \"export\", \"generate\", \"entangle\", \"tunnel\", \"teleport\", \"collapse\"])\n .optional()\n .describe(\"Filter by action\"),\n limit: z.number().optional().default(20).describe(\"Max events to return\"),\n },\n async (params) => {\n const events = queryAudit({\n key: params.key,\n action: params.action,\n limit: params.limit,\n });\n\n if (events.length === 0) return text(\"No audit events found\");\n\n const lines = events.map((e) => {\n const parts = [e.timestamp, e.action];\n if (e.key) parts.push(e.key);\n if (e.scope) parts.push(`[${e.scope}]`);\n if (e.env) parts.push(`env:${e.env}`);\n if (e.detail) parts.push(e.detail);\n return parts.join(\" | \");\n });\n\n return text(lines.join(\"\\n\"));\n },\n );\n\n server.tool(\n \"detect_anomalies\",\n \"Scan for anomalous secret access patterns: burst reads, unusual-hour access. Returns findings and recommendations.\",\n {\n key: z.string().optional().describe(\"Check anomalies for a specific key\"),\n },\n async (params) => {\n const anomalies = detectAnomalies(params.key);\n if (anomalies.length === 0) return text(\"No anomalies detected\");\n\n const lines = anomalies.map(\n (a) => `[${a.type}] ${a.description}`,\n );\n return text(lines.join(\"\\n\"));\n },\n );\n\n // ─── Health ───\n\n server.tool(\n \"health_check\",\n \"Run a comprehensive health check on all secrets: decay status, staleness, anomalies, entropy assessment.\",\n {\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const entries = listSecrets(opts(params));\n const anomalies = detectAnomalies();\n\n let healthy = 0;\n let stale = 0;\n let expired = 0;\n let noDecay = 0;\n const issues: string[] = [];\n\n for (const entry of entries) {\n if (!entry.decay?.timeRemaining) {\n noDecay++;\n continue;\n }\n if (entry.decay.isExpired) {\n expired++;\n issues.push(`EXPIRED: ${entry.key}`);\n } else if (entry.decay.isStale) {\n stale++;\n issues.push(\n `STALE: ${entry.key} (${entry.decay.lifetimePercent}%, ${entry.decay.timeRemaining} left)`,\n );\n } else {\n healthy++;\n }\n }\n\n const summary = [\n `Secrets: ${entries.length} total`,\n `Healthy: ${healthy} | Stale: ${stale} | Expired: ${expired} | No decay: ${noDecay}`,\n `Anomalies: ${anomalies.length}`,\n ];\n\n if (issues.length > 0) {\n summary.push(\"\", \"Issues:\", ...issues);\n }\n if (anomalies.length > 0) {\n summary.push(\n \"\",\n \"Anomalies:\",\n ...anomalies.map((a) => `[${a.type}] ${a.description}`),\n );\n }\n\n return text(summary.join(\"\\n\"));\n },\n );\n\n // ─── Validation Tools ───\n\n server.tool(\n \"validate_secret\",\n \"Test if a secret is actually valid with its target service (e.g., OpenAI, Stripe, GitHub). Uses provider auto-detection based on key prefixes, or accepts an explicit provider name. Never logs the secret value.\",\n {\n key: z.string().describe(\"The secret key name\"),\n provider: z.string().optional().describe(\"Force a specific provider (openai, stripe, github, aws, http)\"),\n scope: scopeSchema,\n projectPath: projectPathSchema,\n },\n async (params) => {\n const value = getSecret(params.key, opts(params));\n if (value === null) return text(`Secret \"${params.key}\" not found`, true);\n\n const envelope = getEnvelope(params.key, opts(params));\n const provHint = params.provider ?? envelope?.envelope.meta.provider;\n\n const result = await validateSecret(value, { provider: provHint });\n return text(JSON.stringify(result, null, 2));\n },\n );\n\n server.tool(\n \"list_providers\",\n \"List all available validation providers for secret liveness testing.\",\n {},\n async () => {\n const providers = providerRegistry.listProviders().map((p) => ({\n name: p.name,\n description: p.description,\n prefixes: p.prefixes ?? [],\n }));\n return text(JSON.stringify(providers, null, 2));\n },\n );\n\n // ─── Hook Tools ───\n\n server.tool(\n \"register_hook\",\n \"Register a webhook/callback that fires when a secret is updated, deleted, or rotated. Supports shell commands, HTTP webhooks, and process signals.\",\n {\n type: z.enum([\"shell\", \"http\", \"signal\"]).describe(\"Hook type\"),\n key: z.string().optional().describe(\"Trigger on exact key match\"),\n keyPattern: z.string().optional().describe(\"Trigger on key glob pattern (e.g. DB_*)\"),\n tag: z.string().optional().describe(\"Trigger on secrets with this tag\"),\n scope: z.enum([\"global\", \"project\"]).optional().describe(\"Trigger only for this scope\"),\n actions: z.array(z.enum([\"write\", \"delete\", \"rotate\"])).optional().default([\"write\", \"delete\", \"rotate\"]).describe(\"Which actions trigger this hook\"),\n command: z.string().optional().describe(\"Shell command to execute (for shell type)\"),\n url: z.string().optional().describe(\"URL to POST to (for http type)\"),\n signalTarget: z.string().optional().describe(\"Process name or PID (for signal type)\"),\n signalName: z.string().optional().default(\"SIGHUP\").describe(\"Signal to send (for signal type)\"),\n description: z.string().optional().describe(\"Human-readable description\"),\n },\n async (params) => {\n if (!params.key && !params.keyPattern && !params.tag) {\n return text(\"At least one match criterion required: key, keyPattern, or tag\", true);\n }\n\n const entry = registerHook({\n type: params.type as HookType,\n match: {\n key: params.key,\n keyPattern: params.keyPattern,\n tag: params.tag,\n scope: params.scope as \"global\" | \"project\" | undefined,\n action: params.actions as HookAction[],\n },\n command: params.command,\n url: params.url,\n signal: params.signalTarget ? { target: params.signalTarget, signal: params.signalName } : undefined,\n description: params.description,\n enabled: true,\n });\n\n return text(JSON.stringify(entry, null, 2));\n },\n );\n\n server.tool(\n \"list_hooks\",\n \"List all registered secret change hooks with their match criteria, type, and status.\",\n {},\n async () => {\n const hooks = listAllHooks();\n if (hooks.length === 0) return text(\"No hooks registered\");\n return text(JSON.stringify(hooks, null, 2));\n },\n );\n\n server.tool(\n \"remove_hook\",\n \"Remove a registered hook by ID.\",\n {\n id: z.string().describe(\"Hook ID to remove\"),\n },\n async (params) => {\n const removed = removeHook(params.id);\n return text(\n removed ? `Removed hook ${params.id}` : `Hook \"${params.id}\" not found`,\n !removed,\n );\n },\n );\n\n // ─── Status Dashboard ───\n\n let dashboardInstance: { port: number; close: () => void } | null = null;\n\n server.tool(\n \"status_dashboard\",\n \"Launch the quantum status dashboard — a local web page showing live health, decay timers, superposition states, entanglement graph, tunnels, audit log, and anomaly alerts. Returns the URL to open in a browser.\",\n {\n port: z.number().optional().default(9876).describe(\"Port to serve on\"),\n },\n async (params) => {\n if (dashboardInstance) {\n return text(`Dashboard already running at http://127.0.0.1:${dashboardInstance.port}`);\n }\n\n const { startDashboardServer } = await import(\"../core/dashboard.js\");\n dashboardInstance = startDashboardServer({ port: params.port });\n\n return text(`Dashboard started at http://127.0.0.1:${dashboardInstance.port}\\nOpen this URL in a browser to see live quantum status.`);\n },\n );\n\n // ─── Agent ───\n\n server.tool(\n \"agent_scan\",\n \"Run an autonomous agent health scan: checks decay, staleness, anomalies, and optionally auto-rotates expired secrets. Returns a structured report.\",\n {\n autoRotate: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Auto-rotate expired secrets with generated values\"),\n projectPaths: z\n .array(z.string())\n .optional()\n .describe(\"Project paths to monitor\"),\n },\n async (params) => {\n const report = runHealthScan({\n autoRotate: params.autoRotate,\n projectPaths: params.projectPaths ?? [process.cwd()],\n });\n return text(JSON.stringify(report, null, 2));\n },\n );\n\n return server;\n}\n","/**\n * Quantum Noise: cryptographic secret generation.\n * Generates high-entropy values in common formats.\n */\n\nimport { randomBytes, randomInt } from \"node:crypto\";\n\nexport type NoiseFormat =\n | \"hex\"\n | \"base64\"\n | \"alphanumeric\"\n | \"uuid\"\n | \"api-key\"\n | \"token\"\n | \"password\";\n\nexport interface NoiseOptions {\n format?: NoiseFormat;\n /** Length in bytes (for hex/base64) or characters (for alphanumeric/password) */\n length?: number;\n /** Prefix for api-key format (e.g., \"sk-\", \"pk-\") */\n prefix?: string;\n}\n\nconst ALPHA_NUM =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst PASSWORD_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{}|;:,.<>?\";\n\nfunction randomString(charset: string, length: number): string {\n let result = \"\";\n for (let i = 0; i < length; i++) {\n result += charset[randomInt(charset.length)];\n }\n return result;\n}\n\nexport function generateSecret(opts: NoiseOptions = {}): string {\n const format = opts.format ?? \"api-key\";\n\n switch (format) {\n case \"hex\": {\n const len = opts.length ?? 32;\n return randomBytes(len).toString(\"hex\");\n }\n\n case \"base64\": {\n const len = opts.length ?? 32;\n return randomBytes(len).toString(\"base64url\");\n }\n\n case \"alphanumeric\": {\n const len = opts.length ?? 32;\n return randomString(ALPHA_NUM, len);\n }\n\n case \"uuid\": {\n const bytes = randomBytes(16);\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1\n const hex = bytes.toString(\"hex\");\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20, 32),\n ].join(\"-\");\n }\n\n case \"api-key\": {\n const prefix = opts.prefix ?? \"qr_\";\n const len = opts.length ?? 48;\n return prefix + randomString(ALPHA_NUM, len);\n }\n\n case \"token\": {\n const prefix = opts.prefix ?? \"\";\n const len = opts.length ?? 64;\n return prefix + randomBytes(len).toString(\"base64url\");\n }\n\n case \"password\": {\n const len = opts.length ?? 24;\n let pw = randomString(PASSWORD_CHARS, len);\n\n // Guarantee at least one of each class\n const hasUpper = /[A-Z]/.test(pw);\n const hasLower = /[a-z]/.test(pw);\n const hasDigit = /[0-9]/.test(pw);\n const hasSpecial = /[^A-Za-z0-9]/.test(pw);\n\n if (!hasUpper) pw = replaceAt(pw, randomInt(len), randomString(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", 1));\n if (!hasLower) pw = replaceAt(pw, randomInt(len), randomString(\"abcdefghijklmnopqrstuvwxyz\", 1));\n if (!hasDigit) pw = replaceAt(pw, randomInt(len), randomString(\"0123456789\", 1));\n if (!hasSpecial) pw = replaceAt(pw, randomInt(len), randomString(\"!@#$%^&*()-_=+\", 1));\n\n return pw;\n }\n\n default:\n return randomBytes(32).toString(\"hex\");\n }\n}\n\nfunction replaceAt(str: string, index: number, char: string): string {\n return str.slice(0, index) + char + str.slice(index + 1);\n}\n\n/**\n * Estimate the entropy of a secret in bits.\n */\nexport function estimateEntropy(secret: string): number {\n const charsets = [\n { regex: /[a-z]/, size: 26 },\n { regex: /[A-Z]/, size: 26 },\n { regex: /[0-9]/, size: 10 },\n { regex: /[^A-Za-z0-9]/, size: 32 },\n ];\n\n let poolSize = 0;\n for (const { regex, size } of charsets) {\n if (regex.test(secret)) poolSize += size;\n }\n\n return poolSize > 0 ? Math.floor(Math.log2(poolSize) * secret.length) : 0;\n}\n","/**\n * Minimal ANSI color helpers. No dependencies.\n */\n\nconst enabled = process.stdout.isTTY !== false && !process.env.NO_COLOR;\n\nfunction wrap(code: string, text: string): string {\n return enabled ? `\\x1b[${code}m${text}\\x1b[0m` : text;\n}\n\nexport const c = {\n bold: (t: string) => wrap(\"1\", t),\n dim: (t: string) => wrap(\"2\", t),\n italic: (t: string) => wrap(\"3\", t),\n underline: (t: string) => wrap(\"4\", t),\n\n red: (t: string) => wrap(\"31\", t),\n green: (t: string) => wrap(\"32\", t),\n yellow: (t: string) => wrap(\"33\", t),\n blue: (t: string) => wrap(\"34\", t),\n magenta: (t: string) => wrap(\"35\", t),\n cyan: (t: string) => wrap(\"36\", t),\n white: (t: string) => wrap(\"37\", t),\n gray: (t: string) => wrap(\"90\", t),\n\n bgRed: (t: string) => wrap(\"41\", t),\n bgGreen: (t: string) => wrap(\"42\", t),\n bgYellow: (t: string) => wrap(\"43\", t),\n bgBlue: (t: string) => wrap(\"44\", t),\n bgMagenta: (t: string) => wrap(\"45\", t),\n bgCyan: (t: string) => wrap(\"46\", t),\n};\n\nexport function scopeColor(scope: string): string {\n return scope === \"project\" ? c.cyan(scope) : c.blue(scope);\n}\n\nexport function decayIndicator(percent: number, expired: boolean): string {\n if (expired) return c.bgRed(c.white(\" EXPIRED \"));\n if (percent >= 90) return c.red(`[decay ${percent}%]`);\n if (percent >= 75) return c.yellow(`[decay ${percent}%]`);\n if (percent > 0) return c.green(`[decay ${percent}%]`);\n return \"\";\n}\n\nexport function envBadge(env: string): string {\n switch (env) {\n case \"prod\":\n return c.bgRed(c.white(` ${env} `));\n case \"staging\":\n return c.bgYellow(c.white(` ${env} `));\n case \"dev\":\n return c.bgGreen(c.white(` ${env} `));\n case \"test\":\n return c.bgBlue(c.white(` ${env} `));\n default:\n return c.bgMagenta(c.white(` ${env} `));\n }\n}\n\nexport const SYMBOLS = {\n check: enabled ? \"\\u2713\" : \"[ok]\",\n cross: enabled ? \"\\u2717\" : \"[x]\",\n arrow: enabled ? \"\\u2192\" : \"->\",\n dot: enabled ? \"\\u2022\" : \"*\",\n lock: enabled ? \"\\u{1f512}\" : \"[locked]\",\n key: enabled ? \"\\u{1f511}\" : \"[key]\",\n link: enabled ? \"\\u{1f517}\" : \"[link]\",\n warning: enabled ? \"\\u26a0\\ufe0f\" : \"[!]\",\n clock: enabled ? \"\\u23f0\" : \"[time]\",\n shield: enabled ? \"\\u{1f6e1}\\ufe0f\" : \"[shield]\",\n zap: enabled ? \"\\u26a1\" : \"[zap]\",\n eye: enabled ? \"\\u{1f441}\\ufe0f\" : \"[eye]\",\n ghost: enabled ? \"\\u{1f47b}\" : \"[ghost]\",\n package: enabled ? \"\\u{1f4e6}\" : \"[pkg]\",\n sparkle: enabled ? \"\\u2728\" : \"[*]\",\n} as const;\n","/**\n * Quantum Agent: autonomous background monitor for secret health.\n *\n * Runs as a long-lived process that periodically:\n * - Checks for expired/stale secrets (decay monitoring)\n * - Detects access anomalies (observer analysis)\n * - Logs health reports\n * - Can trigger rotation callbacks\n *\n * Designed to run as `qring agent` or be invoked by the MCP server.\n */\n\nimport { listSecrets, getEnvelope, setSecret, type KeyringOptions } from \"./keyring.js\";\nimport { checkDecay, type QuantumEnvelope } from \"./envelope.js\";\nimport { detectAnomalies, logAudit, queryAudit } from \"./observer.js\";\nimport { generateSecret } from \"./noise.js\";\nimport { findEntangled } from \"./entanglement.js\";\nimport { fireHooks } from \"./hooks.js\";\nimport { c, SYMBOLS, decayIndicator } from \"../utils/colors.js\";\n\nexport interface AgentConfig {\n /** Check interval in seconds (default: 60) */\n intervalSeconds: number;\n /** Auto-rotate expired secrets with generated values */\n autoRotate: boolean;\n /** Project paths to monitor */\n projectPaths: string[];\n /** Verbose output */\n verbose: boolean;\n}\n\nexport interface AgentReport {\n timestamp: string;\n totalSecrets: number;\n healthy: number;\n stale: number;\n expired: number;\n anomalies: number;\n rotated: string[];\n warnings: string[];\n}\n\nfunction defaultConfig(): AgentConfig {\n return {\n intervalSeconds: 60,\n autoRotate: false,\n projectPaths: [process.cwd()],\n verbose: false,\n };\n}\n\nexport function runHealthScan(config: Partial<AgentConfig> = {}): AgentReport {\n const cfg = { ...defaultConfig(), ...config };\n\n const report: AgentReport = {\n timestamp: new Date().toISOString(),\n totalSecrets: 0,\n healthy: 0,\n stale: 0,\n expired: 0,\n anomalies: 0,\n rotated: [],\n warnings: [],\n };\n\n // Scan global scope\n const globalEntries = listSecrets({ scope: \"global\", source: \"agent\" });\n\n // Scan project scopes\n const projectEntries = cfg.projectPaths.flatMap((pp) =>\n listSecrets({ scope: \"project\", projectPath: pp, source: \"agent\" }),\n );\n\n const allEntries = [...globalEntries, ...projectEntries];\n report.totalSecrets = allEntries.length;\n\n for (const entry of allEntries) {\n if (!entry.envelope) continue;\n\n const decay = checkDecay(entry.envelope);\n\n if (decay.isExpired) {\n report.expired++;\n report.warnings.push(\n `EXPIRED: ${entry.key} [${entry.scope}] — expired ${decay.timeRemaining}`,\n );\n\n if (cfg.autoRotate) {\n const fmt = (entry.envelope?.meta.rotationFormat ?? \"api-key\") as import(\"./noise.js\").NoiseFormat;\n const prefix = entry.envelope?.meta.rotationPrefix;\n const newValue = generateSecret({ format: fmt, prefix });\n setSecret(entry.key, newValue, {\n scope: entry.scope,\n projectPath: cfg.projectPaths[0],\n source: \"agent\",\n });\n report.rotated.push(entry.key);\n logAudit({\n action: \"write\",\n key: entry.key,\n scope: entry.scope,\n source: \"agent\",\n detail: \"auto-rotated by agent (expired)\",\n });\n fireHooks({\n action: \"rotate\",\n key: entry.key,\n scope: entry.scope,\n timestamp: new Date().toISOString(),\n source: \"agent\",\n }, entry.envelope?.meta.tags).catch(() => {});\n }\n } else if (decay.isStale) {\n report.stale++;\n report.warnings.push(\n `STALE: ${entry.key} [${entry.scope}] — ${decay.lifetimePercent}% lifetime, ${decay.timeRemaining} remaining`,\n );\n } else {\n report.healthy++;\n }\n }\n\n // Check for anomalies\n const anomalies = detectAnomalies();\n report.anomalies = anomalies.length;\n for (const a of anomalies) {\n report.warnings.push(`ANOMALY [${a.type}]: ${a.description}`);\n }\n\n return report;\n}\n\nfunction formatReport(report: AgentReport, verbose: boolean): string {\n const lines: string[] = [];\n\n lines.push(\n `${c.bold(`${SYMBOLS.shield} q-ring agent scan`)} ${c.dim(report.timestamp)}`,\n );\n lines.push(\n ` ${c.dim(\"secrets:\")} ${report.totalSecrets} ${c.green(`${SYMBOLS.check} ${report.healthy}`)} ${c.yellow(`${SYMBOLS.warning} ${report.stale}`)} ${c.red(`${SYMBOLS.cross} ${report.expired}`)} ${c.dim(`anomalies: ${report.anomalies}`)}`,\n );\n\n if (report.rotated.length > 0) {\n lines.push(\n ` ${c.cyan(`${SYMBOLS.zap} auto-rotated:`)} ${report.rotated.join(\", \")}`,\n );\n }\n\n if (verbose && report.warnings.length > 0) {\n lines.push(\"\");\n for (const w of report.warnings) {\n if (w.startsWith(\"EXPIRED\")) lines.push(` ${c.red(w)}`);\n else if (w.startsWith(\"STALE\")) lines.push(` ${c.yellow(w)}`);\n else if (w.startsWith(\"ANOMALY\")) lines.push(` ${c.magenta(w)}`);\n else lines.push(` ${w}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Run the agent as a continuous background monitor.\n */\nexport async function startAgent(config: Partial<AgentConfig> = {}): Promise<void> {\n const cfg = { ...defaultConfig(), ...config };\n\n console.log(\n `${c.bold(`${SYMBOLS.zap} q-ring agent started`)} ${c.dim(`(interval: ${cfg.intervalSeconds}s, auto-rotate: ${cfg.autoRotate})`)}`,\n );\n console.log(\n c.dim(` monitoring: global + ${cfg.projectPaths.length} project(s)`),\n );\n console.log();\n\n const scan = () => {\n const report = runHealthScan(cfg);\n console.log(formatReport(report, cfg.verbose));\n\n if (report.warnings.length > 0 || cfg.verbose) {\n console.log();\n }\n };\n\n // Initial scan\n scan();\n\n // Continuous monitoring\n const interval = setInterval(scan, cfg.intervalSeconds * 1000);\n\n // Graceful shutdown\n const shutdown = () => {\n clearInterval(interval);\n console.log(`\\n${c.dim(\"q-ring agent stopped\")}`);\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // Keep alive\n await new Promise(() => {});\n}\n","/**\n * Quantum Teleportation: securely share/transfer secrets between machines.\n *\n * Generates encrypted bundles that can be shared via any channel.\n * The recipient decrypts with a shared passphrase (out-of-band exchange).\n * Uses AES-256-GCM with PBKDF2-derived keys.\n */\n\nimport {\n randomBytes,\n createCipheriv,\n createDecipheriv,\n pbkdf2Sync,\n} from \"node:crypto\";\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst KEY_LENGTH = 32;\nconst IV_LENGTH = 16;\nconst SALT_LENGTH = 32;\nconst TAG_LENGTH = 16;\nconst PBKDF2_ITERATIONS = 100000;\n\nexport interface TeleportBundle {\n /** Format version */\n v: 1;\n /** Base64-encoded encrypted payload */\n data: string;\n /** Base64-encoded salt for key derivation */\n salt: string;\n /** Base64-encoded initialization vector */\n iv: string;\n /** Base64-encoded auth tag */\n tag: string;\n /** ISO timestamp of creation */\n createdAt: string;\n /** Number of secrets in the bundle */\n count: number;\n}\n\nexport interface TeleportPayload {\n secrets: { key: string; value: string; scope?: string }[];\n exportedAt: string;\n exportedBy?: string;\n}\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, \"sha512\");\n}\n\n/**\n * Pack secrets into an encrypted teleport bundle.\n */\nexport function teleportPack(\n secrets: { key: string; value: string; scope?: string }[],\n passphrase: string,\n): string {\n const payload: TeleportPayload = {\n secrets,\n exportedAt: new Date().toISOString(),\n };\n\n const plaintext = JSON.stringify(payload);\n const salt = randomBytes(SALT_LENGTH);\n const iv = randomBytes(IV_LENGTH);\n const key = deriveKey(passphrase, salt);\n\n const cipher = createCipheriv(ALGORITHM, key, iv);\n const encrypted = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n\n const bundle: TeleportBundle = {\n v: 1,\n data: encrypted.toString(\"base64\"),\n salt: salt.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n createdAt: new Date().toISOString(),\n count: secrets.length,\n };\n\n return Buffer.from(JSON.stringify(bundle)).toString(\"base64\");\n}\n\n/**\n * Unpack and decrypt a teleport bundle.\n */\nexport function teleportUnpack(\n encoded: string,\n passphrase: string,\n): TeleportPayload {\n const bundleJson = Buffer.from(encoded, \"base64\").toString(\"utf8\");\n const bundle: TeleportBundle = JSON.parse(bundleJson);\n\n if (bundle.v !== 1) {\n throw new Error(`Unsupported teleport bundle version: ${bundle.v}`);\n }\n\n const salt = Buffer.from(bundle.salt, \"base64\");\n const iv = Buffer.from(bundle.iv, \"base64\");\n const tag = Buffer.from(bundle.tag, \"base64\");\n const encrypted = Buffer.from(bundle.data, \"base64\");\n const key = deriveKey(passphrase, salt);\n\n const decipher = createDecipheriv(ALGORITHM, key, iv);\n decipher.setAuthTag(tag);\n\n const decrypted = Buffer.concat([\n decipher.update(encrypted),\n decipher.final(),\n ]);\n\n return JSON.parse(decrypted.toString(\"utf8\"));\n}\n","/**\n * Import module: parse .env files and bulk-store secrets into q-ring.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { setSecret, hasSecret, type SetSecretOptions } from \"./keyring.js\";\n\nexport interface ImportOptions {\n scope?: \"global\" | \"project\";\n projectPath?: string;\n env?: string;\n source?: \"cli\" | \"mcp\" | \"agent\" | \"api\";\n skipExisting?: boolean;\n dryRun?: boolean;\n}\n\nexport interface ImportResult {\n imported: string[];\n skipped: string[];\n total: number;\n}\n\n/**\n * Parse .env content into key-value pairs.\n * Handles comments, blank lines, quoted values, and basic multiline.\n */\nexport function parseDotenv(content: string): Map<string, string> {\n const result = new Map<string, string>();\n const lines = content.split(/\\r?\\n/);\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n\n if (!line || line.startsWith(\"#\")) continue;\n\n const eqIdx = line.indexOf(\"=\");\n if (eqIdx === -1) continue;\n\n const key = line.slice(0, eqIdx).trim();\n let value = line.slice(eqIdx + 1).trim();\n\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n value = value\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\r\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\\\\\/g, \"\\\\\")\n .replace(/\\\\\"/g, '\"');\n\n if (value.includes(\"#\") && !line.includes('\"') && !line.includes(\"'\")) {\n value = value.split(\"#\")[0].trim();\n }\n\n if (key) result.set(key, value);\n }\n\n return result;\n}\n\n/**\n * Import secrets from a .env file path or raw content string.\n */\nexport function importDotenv(\n filePathOrContent: string,\n options: ImportOptions = {},\n): ImportResult {\n let content: string;\n\n try {\n content = readFileSync(filePathOrContent, \"utf8\");\n } catch {\n content = filePathOrContent;\n }\n\n const pairs = parseDotenv(content);\n const result: ImportResult = {\n imported: [],\n skipped: [],\n total: pairs.size,\n };\n\n for (const [key, value] of pairs) {\n if (options.skipExisting && hasSecret(key, {\n scope: options.scope,\n projectPath: options.projectPath,\n source: options.source ?? \"cli\",\n })) {\n result.skipped.push(key);\n continue;\n }\n\n if (options.dryRun) {\n result.imported.push(key);\n continue;\n }\n\n const setOpts: SetSecretOptions = {\n scope: options.scope ?? \"global\",\n projectPath: options.projectPath ?? process.cwd(),\n source: options.source ?? \"cli\",\n };\n\n setSecret(key, value, setOpts);\n result.imported.push(key);\n }\n\n return result;\n}\n","/**\n * Secret Liveness Validation: test if a secret is actually valid\n * with its target service using a pluggable provider system.\n */\n\nimport { request as httpsRequest } from \"node:https\";\nimport { request as httpRequest } from \"node:http\";\n\nexport interface ValidationResult {\n valid: boolean;\n status: \"valid\" | \"invalid\" | \"error\" | \"unknown\";\n message: string;\n latencyMs: number;\n provider: string;\n}\n\nexport interface Provider {\n name: string;\n description: string;\n /** Prefixes that auto-detect to this provider */\n prefixes?: string[];\n validate(value: string): Promise<ValidationResult>;\n}\n\nfunction makeRequest(\n url: string,\n headers: Record<string, string>,\n timeoutMs = 10000,\n): Promise<{ statusCode: number; body: string }> {\n return new Promise((resolve, reject) => {\n const parsedUrl = new URL(url);\n const reqFn = parsedUrl.protocol === \"https:\" ? httpsRequest : httpRequest;\n const req = reqFn(\n url,\n { method: \"GET\", headers, timeout: timeoutMs },\n (res) => {\n let body = \"\";\n res.on(\"data\", (chunk) => (body += chunk));\n res.on(\"end\", () =>\n resolve({ statusCode: res.statusCode ?? 0, body }),\n );\n },\n );\n req.on(\"error\", reject);\n req.on(\"timeout\", () => {\n req.destroy();\n reject(new Error(\"Request timed out\"));\n });\n req.end();\n });\n}\n\nexport class ProviderRegistry {\n private providers = new Map<string, Provider>();\n\n register(provider: Provider): void {\n this.providers.set(provider.name, provider);\n }\n\n get(name: string): Provider | undefined {\n return this.providers.get(name);\n }\n\n detectProvider(\n value: string,\n hints?: { provider?: string; prefix?: string },\n ): Provider | undefined {\n if (hints?.provider) {\n return this.providers.get(hints.provider);\n }\n\n for (const provider of this.providers.values()) {\n if (provider.prefixes) {\n for (const pfx of provider.prefixes) {\n if (value.startsWith(pfx)) return provider;\n }\n }\n }\n\n return undefined;\n }\n\n listProviders(): Provider[] {\n return [...this.providers.values()];\n }\n}\n\n// ─── Built-in Providers ───\n\nconst openaiProvider: Provider = {\n name: \"openai\",\n description: \"OpenAI API key validation\",\n prefixes: [\"sk-\"],\n async validate(value: string): Promise<ValidationResult> {\n const start = Date.now();\n try {\n const { statusCode } = await makeRequest(\n \"https://api.openai.com/v1/models?limit=1\",\n {\n Authorization: `Bearer ${value}`,\n \"User-Agent\": \"q-ring-validator/1.0\",\n },\n );\n const latencyMs = Date.now() - start;\n\n if (statusCode === 200)\n return { valid: true, status: \"valid\", message: \"API key is valid\", latencyMs, provider: \"openai\" };\n if (statusCode === 401)\n return { valid: false, status: \"invalid\", message: \"Invalid or revoked API key\", latencyMs, provider: \"openai\" };\n if (statusCode === 429)\n return { valid: true, status: \"error\", message: \"Rate limited — key may be valid\", latencyMs, provider: \"openai\" };\n return { valid: false, status: \"error\", message: `Unexpected status ${statusCode}`, latencyMs, provider: \"openai\" };\n } catch (err) {\n return { valid: false, status: \"error\", message: `${err instanceof Error ? err.message : \"Network error\"}`, latencyMs: Date.now() - start, provider: \"openai\" };\n }\n },\n};\n\nconst stripeProvider: Provider = {\n name: \"stripe\",\n description: \"Stripe API key validation\",\n prefixes: [\"sk_live_\", \"sk_test_\", \"rk_live_\", \"rk_test_\", \"pk_live_\", \"pk_test_\"],\n async validate(value: string): Promise<ValidationResult> {\n const start = Date.now();\n try {\n const { statusCode } = await makeRequest(\n \"https://api.stripe.com/v1/balance\",\n {\n Authorization: `Bearer ${value}`,\n \"User-Agent\": \"q-ring-validator/1.0\",\n },\n );\n const latencyMs = Date.now() - start;\n\n if (statusCode === 200)\n return { valid: true, status: \"valid\", message: \"API key is valid\", latencyMs, provider: \"stripe\" };\n if (statusCode === 401)\n return { valid: false, status: \"invalid\", message: \"Invalid or revoked API key\", latencyMs, provider: \"stripe\" };\n if (statusCode === 429)\n return { valid: true, status: \"error\", message: \"Rate limited — key may be valid\", latencyMs, provider: \"stripe\" };\n return { valid: false, status: \"error\", message: `Unexpected status ${statusCode}`, latencyMs, provider: \"stripe\" };\n } catch (err) {\n return { valid: false, status: \"error\", message: `${err instanceof Error ? err.message : \"Network error\"}`, latencyMs: Date.now() - start, provider: \"stripe\" };\n }\n },\n};\n\nconst githubProvider: Provider = {\n name: \"github\",\n description: \"GitHub token validation\",\n prefixes: [\"ghp_\", \"gho_\", \"ghu_\", \"ghs_\", \"ghr_\", \"github_pat_\"],\n async validate(value: string): Promise<ValidationResult> {\n const start = Date.now();\n try {\n const { statusCode } = await makeRequest(\n \"https://api.github.com/user\",\n {\n Authorization: `token ${value}`,\n \"User-Agent\": \"q-ring-validator/1.0\",\n Accept: \"application/vnd.github+json\",\n },\n );\n const latencyMs = Date.now() - start;\n\n if (statusCode === 200)\n return { valid: true, status: \"valid\", message: \"Token is valid\", latencyMs, provider: \"github\" };\n if (statusCode === 401)\n return { valid: false, status: \"invalid\", message: \"Invalid or expired token\", latencyMs, provider: \"github\" };\n if (statusCode === 403)\n return { valid: false, status: \"invalid\", message: \"Token lacks required permissions\", latencyMs, provider: \"github\" };\n if (statusCode === 429)\n return { valid: true, status: \"error\", message: \"Rate limited — token may be valid\", latencyMs, provider: \"github\" };\n return { valid: false, status: \"error\", message: `Unexpected status ${statusCode}`, latencyMs, provider: \"github\" };\n } catch (err) {\n return { valid: false, status: \"error\", message: `${err instanceof Error ? err.message : \"Network error\"}`, latencyMs: Date.now() - start, provider: \"github\" };\n }\n },\n};\n\nconst awsProvider: Provider = {\n name: \"aws\",\n description: \"AWS access key validation (checks key format only — full STS validation requires secret key + region)\",\n prefixes: [\"AKIA\", \"ASIA\"],\n async validate(value: string): Promise<ValidationResult> {\n const start = Date.now();\n const latencyMs = Date.now() - start;\n\n if (/^(AKIA|ASIA)[A-Z0-9]{16}$/.test(value)) {\n return { valid: true, status: \"unknown\", message: \"Valid AWS access key format (STS validation requires secret key)\", latencyMs, provider: \"aws\" };\n }\n return { valid: false, status: \"invalid\", message: \"Invalid AWS access key format\", latencyMs, provider: \"aws\" };\n },\n};\n\nconst httpProvider: Provider = {\n name: \"http\",\n description: \"Generic HTTP endpoint validation\",\n async validate(value: string, url?: string): Promise<ValidationResult> {\n const start = Date.now();\n\n if (!url) {\n return { valid: false, status: \"unknown\", message: \"No validation URL configured\", latencyMs: 0, provider: \"http\" };\n }\n\n try {\n const { statusCode } = await makeRequest(url, {\n Authorization: `Bearer ${value}`,\n \"User-Agent\": \"q-ring-validator/1.0\",\n });\n const latencyMs = Date.now() - start;\n\n if (statusCode >= 200 && statusCode < 300)\n return { valid: true, status: \"valid\", message: `Endpoint returned ${statusCode}`, latencyMs, provider: \"http\" };\n if (statusCode === 401 || statusCode === 403)\n return { valid: false, status: \"invalid\", message: `Authentication failed (${statusCode})`, latencyMs, provider: \"http\" };\n return { valid: false, status: \"error\", message: `Unexpected status ${statusCode}`, latencyMs, provider: \"http\" };\n } catch (err) {\n return { valid: false, status: \"error\", message: `${err instanceof Error ? err.message : \"Network error\"}`, latencyMs: Date.now() - start, provider: \"http\" };\n }\n },\n};\n\nexport const registry = new ProviderRegistry();\nregistry.register(openaiProvider);\nregistry.register(stripeProvider);\nregistry.register(githubProvider);\nregistry.register(awsProvider);\nregistry.register(httpProvider);\n\n/**\n * Validate a secret value against its detected or specified provider.\n */\nexport async function validateSecret(\n value: string,\n opts?: { provider?: string; validationUrl?: string },\n): Promise<ValidationResult> {\n const provider = opts?.provider\n ? registry.get(opts.provider)\n : registry.detectProvider(value);\n\n if (!provider) {\n return {\n valid: false,\n status: \"unknown\",\n message: \"No provider detected — set a provider in the manifest or secret metadata\",\n latencyMs: 0,\n provider: \"none\",\n };\n }\n\n if (provider.name === \"http\" && opts?.validationUrl) {\n return (provider as any).validate(value, opts.validationUrl);\n }\n\n return provider.validate(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,4BAA4B;;;ACArC,SAAS,iBAAiB;AAC1B,SAAS,SAAS;;;ACIlB,SAAS,aAAa,iBAAiB;AAmBvC,IAAM,YACJ;AACF,IAAM,iBACJ;AAEF,SAAS,aA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,gBAAgB;AAC/B,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["opts","randomBytes","randomBytes","opts","server","result"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/envelope.ts","../src/core/collapse.ts","../src/core/observer.ts","../src/core/entanglement.ts","../src/core/keyring.ts","../src/utils/hash.ts","../src/core/scope.ts","../src/core/tunnel.ts"],"sourcesContent":["/**\n * Quantum Envelope: the storage format for all q-ring secrets.\n *\n * Instead of storing raw strings, every secret is wrapped in an envelope\n * that carries quantum metadata: environment states (superposition),\n * TTL/expiry (decay), entanglement links, and access tracking (observer).\n */\n\nexport type Environment = string; // \"dev\" | \"staging\" | \"prod\" | custom\n\nexport interface EntanglementLink {\n /** Service name of the entangled scope */\n service: string;\n /** Key name in the entangled scope */\n key: string;\n}\n\nexport interface SecretMetadata {\n createdAt: string;\n updatedAt: string;\n /** ISO timestamp when this secret expires (quantum decay) */\n expiresAt?: string;\n /** TTL in seconds from creation/update */\n ttlSeconds?: number;\n /** Human-readable description */\n description?: string;\n /** Tags for organization */\n tags?: string[];\n /** Entanglement links to other secrets */\n entangled?: EntanglementLink[];\n /** Total number of times this secret has been read */\n accessCount: number;\n /** ISO timestamp of last read */\n lastAccessedAt?: string;\n /** Whether this secret is ephemeral (tunneling - not persisted to keyring) */\n ephemeral?: boolean;\n}\n\nexport interface QuantumEnvelope {\n /** Schema version for forward compatibility */\n v: 1;\n /** Simple value (when not in superposition) */\n value?: string;\n /** Superposition: environment-keyed values */\n states?: Record<Environment, string>;\n /** Default environment to collapse to when no context is available */\n defaultEnv?: Environment;\n /** Quantum metadata */\n meta: SecretMetadata;\n}\n\nexport function createEnvelope(\n value: string,\n opts?: Partial<Pick<QuantumEnvelope, \"states\" | \"defaultEnv\">> & {\n description?: string;\n tags?: string[];\n ttlSeconds?: number;\n expiresAt?: string;\n entangled?: EntanglementLink[];\n },\n): QuantumEnvelope {\n const now = new Date().toISOString();\n\n let expiresAt = opts?.expiresAt;\n if (!expiresAt && opts?.ttlSeconds) {\n expiresAt = new Date(Date.now() + opts.ttlSeconds * 1000).toISOString();\n }\n\n return {\n v: 1,\n value: opts?.states ? undefined : value,\n states: opts?.states,\n defaultEnv: opts?.defaultEnv,\n meta: {\n createdAt: now,\n updatedAt: now,\n expiresAt,\n ttlSeconds: opts?.ttlSeconds,\n description: opts?.description,\n tags: opts?.tags,\n entangled: opts?.entangled,\n accessCount: 0,\n },\n };\n}\n\nexport function parseEnvelope(raw: string): QuantumEnvelope | null {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && parsed.v === 1) {\n return parsed as QuantumEnvelope;\n }\n } catch {\n // Not a quantum envelope - legacy raw string\n }\n return null;\n}\n\n/**\n * Wrap a legacy raw string value into a quantum envelope.\n * Used for backward compatibility with secrets stored before the envelope format.\n */\nexport function wrapLegacy(rawValue: string): QuantumEnvelope {\n const now = new Date().toISOString();\n return {\n v: 1,\n value: rawValue,\n meta: {\n createdAt: now,\n updatedAt: now,\n accessCount: 0,\n },\n };\n}\n\nexport function serializeEnvelope(envelope: QuantumEnvelope): string {\n return JSON.stringify(envelope);\n}\n\n/**\n * Resolve the concrete value from a quantum envelope.\n * If in superposition, collapses based on the provided environment.\n */\nexport function collapseValue(\n envelope: QuantumEnvelope,\n env?: Environment,\n): string | null {\n if (envelope.states) {\n const targetEnv = env ?? envelope.defaultEnv;\n if (targetEnv && envelope.states[targetEnv]) {\n return envelope.states[targetEnv];\n }\n // If no env match, try default, then return null\n if (envelope.defaultEnv && envelope.states[envelope.defaultEnv]) {\n return envelope.states[envelope.defaultEnv];\n }\n // Last resort: return the first state\n const keys = Object.keys(envelope.states);\n if (keys.length > 0) {\n return envelope.states[keys[0]];\n }\n return null;\n }\n\n return envelope.value ?? null;\n}\n\nexport interface DecayStatus {\n isExpired: boolean;\n isStale: boolean;\n /** Percentage of lifetime elapsed (0-100+) */\n lifetimePercent: number;\n /** Seconds remaining until expiry, or negative if expired */\n secondsRemaining: number | null;\n /** Human-readable time remaining */\n timeRemaining: string | null;\n}\n\nexport function checkDecay(envelope: QuantumEnvelope): DecayStatus {\n if (!envelope.meta.expiresAt) {\n return {\n isExpired: false,\n isStale: false,\n lifetimePercent: 0,\n secondsRemaining: null,\n timeRemaining: null,\n };\n }\n\n const now = Date.now();\n const expires = new Date(envelope.meta.expiresAt).getTime();\n const created = new Date(envelope.meta.createdAt).getTime();\n const totalLifetime = expires - created;\n const elapsed = now - created;\n const remaining = expires - now;\n\n const lifetimePercent =\n totalLifetime > 0 ? Math.round((elapsed / totalLifetime) * 100) : 100;\n\n const secondsRemaining = Math.floor(remaining / 1000);\n\n let timeRemaining: string | null = null;\n if (remaining > 0) {\n const days = Math.floor(remaining / 86400000);\n const hours = Math.floor((remaining % 86400000) / 3600000);\n const minutes = Math.floor((remaining % 3600000) / 60000);\n\n if (days > 0) timeRemaining = `${days}d ${hours}h`;\n else if (hours > 0) timeRemaining = `${hours}h ${minutes}m`;\n else timeRemaining = `${minutes}m`;\n } else {\n timeRemaining = \"expired\";\n }\n\n return {\n isExpired: remaining <= 0,\n isStale: lifetimePercent >= 75,\n lifetimePercent,\n secondsRemaining,\n timeRemaining,\n };\n}\n\n/**\n * Record an access event on the envelope (observer effect).\n * Returns a new envelope with updated access metadata.\n */\nexport function recordAccess(envelope: QuantumEnvelope): QuantumEnvelope {\n return {\n ...envelope,\n meta: {\n ...envelope.meta,\n accessCount: envelope.meta.accessCount + 1,\n lastAccessedAt: new Date().toISOString(),\n },\n };\n}\n","/**\n * Wavefunction Collapse: auto-detect the current environment context.\n *\n * Resolution order (first match wins):\n * 1. Explicit --env flag\n * 2. QRING_ENV environment variable\n * 3. NODE_ENV environment variable\n * 4. Git branch heuristics (main/master → prod, develop → dev, staging → staging)\n * 5. .q-ring.json project config\n * 6. Default environment from the envelope\n */\n\nimport { execSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Environment } from \"./envelope.js\";\n\nconst BRANCH_ENV_MAP: Record<string, Environment> = {\n main: \"prod\",\n master: \"prod\",\n production: \"prod\",\n develop: \"dev\",\n development: \"dev\",\n dev: \"dev\",\n staging: \"staging\",\n stage: \"staging\",\n test: \"test\",\n testing: \"test\",\n};\n\nfunction detectGitBranch(cwd?: string): string | null {\n try {\n const branch = execSync(\"git rev-parse --abbrev-ref HEAD\", {\n cwd: cwd ?? process.cwd(),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n encoding: \"utf8\",\n timeout: 3000,\n }).trim();\n return branch || null;\n } catch {\n return null;\n }\n}\n\nexport interface ProjectConfig {\n env?: Environment;\n defaultEnv?: Environment;\n branchMap?: Record<string, Environment>;\n}\n\nfunction readProjectConfig(projectPath?: string): ProjectConfig | null {\n const configPath = join(projectPath ?? process.cwd(), \".q-ring.json\");\n try {\n if (existsSync(configPath)) {\n return JSON.parse(readFileSync(configPath, \"utf8\"));\n }\n } catch {\n // invalid config\n }\n return null;\n}\n\nexport interface CollapseContext {\n /** Explicitly provided environment */\n explicit?: Environment;\n /** Project path for git/config detection */\n projectPath?: string;\n}\n\nexport interface CollapseResult {\n env: Environment;\n source:\n | \"explicit\"\n | \"QRING_ENV\"\n | \"NODE_ENV\"\n | \"git-branch\"\n | \"project-config\"\n | \"default\";\n}\n\nexport function collapseEnvironment(\n ctx: CollapseContext = {},\n): CollapseResult | null {\n if (ctx.explicit) {\n return { env: ctx.explicit, source: \"explicit\" };\n }\n\n const qringEnv = process.env.QRING_ENV;\n if (qringEnv) {\n return { env: qringEnv, source: \"QRING_ENV\" };\n }\n\n const nodeEnv = process.env.NODE_ENV;\n if (nodeEnv) {\n const mapped = mapEnvName(nodeEnv);\n return { env: mapped, source: \"NODE_ENV\" };\n }\n\n const config = readProjectConfig(ctx.projectPath);\n if (config?.env) {\n return { env: config.env, source: \"project-config\" };\n }\n\n const branch = detectGitBranch(ctx.projectPath);\n if (branch) {\n const branchMap = { ...BRANCH_ENV_MAP, ...config?.branchMap };\n const mapped = branchMap[branch];\n if (mapped) {\n return { env: mapped, source: \"git-branch\" };\n }\n }\n\n if (config?.defaultEnv) {\n return { env: config.defaultEnv, source: \"project-config\" };\n }\n\n return null;\n}\n\nfunction mapEnvName(raw: string): Environment {\n const lower = raw.toLowerCase();\n if (lower === \"production\") return \"prod\";\n if (lower === \"development\") return \"dev\";\n return lower;\n}\n","/**\n * Observer Effect: every secret read/write/delete is logged.\n * Audit trail stored at ~/.config/q-ring/audit.jsonl\n *\n * The act of observation changes the state — each access increments\n * the envelope's access counter and records a timestamp.\n */\n\nimport { existsSync, mkdirSync, appendFileSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport type AuditAction =\n | \"read\"\n | \"write\"\n | \"delete\"\n | \"list\"\n | \"export\"\n | \"generate\"\n | \"entangle\"\n | \"tunnel\"\n | \"teleport\"\n | \"collapse\";\n\nexport interface AuditEvent {\n timestamp: string;\n action: AuditAction;\n key?: string;\n scope?: string;\n env?: string;\n source: \"cli\" | \"mcp\" | \"agent\" | \"api\";\n /** Additional context */\n detail?: string;\n /** Process ID for tracking */\n pid: number;\n}\n\nfunction getAuditDir(): string {\n const dir = join(homedir(), \".config\", \"q-ring\");\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n return dir;\n}\n\nfunction getAuditPath(): string {\n return join(getAuditDir(), \"audit.jsonl\");\n}\n\nexport function logAudit(event: Omit<AuditEvent, \"timestamp\" | \"pid\">): void {\n const full: AuditEvent = {\n ...event,\n timestamp: new Date().toISOString(),\n pid: process.pid,\n };\n\n try {\n appendFileSync(getAuditPath(), JSON.stringify(full) + \"\\n\");\n } catch {\n // audit logging should never crash the app\n }\n}\n\nexport interface AuditQuery {\n key?: string;\n action?: AuditAction;\n since?: string;\n limit?: number;\n}\n\nexport function queryAudit(query: AuditQuery = {}): AuditEvent[] {\n const path = getAuditPath();\n if (!existsSync(path)) return [];\n\n try {\n const lines = readFileSync(path, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim());\n\n let events: AuditEvent[] = lines\n .map((line) => {\n try {\n return JSON.parse(line) as AuditEvent;\n } catch {\n return null;\n }\n })\n .filter((e): e is AuditEvent => e !== null);\n\n if (query.key) {\n events = events.filter((e) => e.key === query.key);\n }\n if (query.action) {\n events = events.filter((e) => e.action === query.action);\n }\n if (query.since) {\n const since = new Date(query.since).getTime();\n events = events.filter(\n (e) => new Date(e.timestamp).getTime() >= since,\n );\n }\n\n events.sort(\n (a, b) =>\n new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),\n );\n\n if (query.limit) {\n events = events.slice(0, query.limit);\n }\n\n return events;\n } catch {\n return [];\n }\n}\n\nexport interface AccessAnomaly {\n type: \"burst\" | \"unusual-hour\" | \"new-source\";\n description: string;\n events: AuditEvent[];\n}\n\n/**\n * Detect anomalous access patterns in the audit log.\n */\nexport function detectAnomalies(key?: string): AccessAnomaly[] {\n const recent = queryAudit({\n key,\n action: \"read\",\n since: new Date(Date.now() - 3600000).toISOString(), // last hour\n });\n\n const anomalies: AccessAnomaly[] = [];\n\n // Burst detection: more than 50 reads of the same key in an hour\n if (key && recent.length > 50) {\n anomalies.push({\n type: \"burst\",\n description: `${recent.length} reads of \"${key}\" in the last hour`,\n events: recent.slice(0, 10),\n });\n }\n\n // Unusual hour detection: access between 1am-5am local time\n const nightAccess = recent.filter((e) => {\n const hour = new Date(e.timestamp).getHours();\n return hour >= 1 && hour < 5;\n });\n\n if (nightAccess.length > 0) {\n anomalies.push({\n type: \"unusual-hour\",\n description: `${nightAccess.length} access(es) during unusual hours (1am-5am)`,\n events: nightAccess,\n });\n }\n\n return anomalies;\n}\n","/**\n * Quantum Entanglement: link secrets across projects.\n * When one entangled secret is rotated, all linked copies update.\n *\n * Entanglement is stored as metadata in the envelope. The entanglement\n * registry at ~/.config/q-ring/entanglement.json provides a reverse\n * lookup: given a secret, find all its entangled partners.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport interface EntanglementPair {\n /** Source: service/key */\n source: { service: string; key: string };\n /** Target: service/key */\n target: { service: string; key: string };\n /** When this entanglement was created */\n createdAt: string;\n}\n\ninterface EntanglementRegistry {\n pairs: EntanglementPair[];\n}\n\nfunction getRegistryPath(): string {\n const dir = join(homedir(), \".config\", \"q-ring\");\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n return join(dir, \"entanglement.json\");\n}\n\nfunction loadRegistry(): EntanglementRegistry {\n const path = getRegistryPath();\n if (!existsSync(path)) {\n return { pairs: [] };\n }\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return { pairs: [] };\n }\n}\n\nfunction saveRegistry(registry: EntanglementRegistry): void {\n writeFileSync(getRegistryPath(), JSON.stringify(registry, null, 2));\n}\n\nexport function entangle(\n source: { service: string; key: string },\n target: { service: string; key: string },\n): void {\n const registry = loadRegistry();\n\n const exists = registry.pairs.some(\n (p) =>\n p.source.service === source.service &&\n p.source.key === source.key &&\n p.target.service === target.service &&\n p.target.key === target.key,\n );\n\n if (!exists) {\n registry.pairs.push({\n source,\n target,\n createdAt: new Date().toISOString(),\n });\n // Bidirectional: add reverse link too\n registry.pairs.push({\n source: target,\n target: source,\n createdAt: new Date().toISOString(),\n });\n saveRegistry(registry);\n }\n}\n\nexport function disentangle(\n source: { service: string; key: string },\n target: { service: string; key: string },\n): void {\n const registry = loadRegistry();\n registry.pairs = registry.pairs.filter(\n (p) =>\n !(\n (p.source.service === source.service &&\n p.source.key === source.key &&\n p.target.service === target.service &&\n p.target.key === target.key) ||\n (p.source.service === target.service &&\n p.source.key === target.key &&\n p.target.service === source.service &&\n p.target.key === source.key)\n ),\n );\n saveRegistry(registry);\n}\n\n/**\n * Find all entangled partners for a given secret.\n */\nexport function findEntangled(\n source: { service: string; key: string },\n): { service: string; key: string }[] {\n const registry = loadRegistry();\n return registry.pairs\n .filter(\n (p) =>\n p.source.service === source.service && p.source.key === source.key,\n )\n .map((p) => p.target);\n}\n\n/**\n * List all entanglement pairs.\n */\nexport function listEntanglements(): EntanglementPair[] {\n return loadRegistry().pairs;\n}\n","import { Entry, findCredentials } from \"@napi-rs/keyring\";\nimport {\n resolveScope,\n globalService,\n projectService,\n type Scope,\n} from \"./scope.js\";\nimport {\n type QuantumEnvelope,\n type Environment,\n createEnvelope,\n parseEnvelope,\n wrapLegacy,\n serializeEnvelope,\n collapseValue,\n checkDecay,\n recordAccess,\n type DecayStatus,\n type EntanglementLink,\n} from \"./envelope.js\";\nimport { collapseEnvironment, type CollapseContext } from \"./collapse.js\";\nimport { logAudit, type AuditAction } from \"./observer.js\";\nimport { findEntangled, entangle as entangleLink } from \"./entanglement.js\";\n\nexport interface SecretEntry {\n key: string;\n scope: Scope;\n value?: string;\n envelope?: QuantumEnvelope;\n decay?: DecayStatus;\n}\n\nexport interface KeyringOptions {\n scope?: Scope;\n projectPath?: string;\n /** Environment for superposition collapse */\n env?: Environment;\n /** Audit source */\n source?: \"cli\" | \"mcp\" | \"agent\" | \"api\";\n /** Skip audit logging (for internal polling like the dashboard) */\n silent?: boolean;\n}\n\nexport interface SetSecretOptions extends KeyringOptions {\n /** Environment states for superposition */\n states?: Record<Environment, string>;\n /** Default environment */\n defaultEnv?: Environment;\n /** TTL in seconds (quantum decay) */\n ttlSeconds?: number;\n /** Expiry timestamp */\n expiresAt?: string;\n /** Description */\n description?: string;\n /** Tags */\n tags?: string[];\n}\n\nfunction readEnvelope(service: string, key: string): QuantumEnvelope | null {\n const entry = new Entry(service, key);\n const raw = entry.getPassword();\n if (raw === null) return null;\n\n const envelope = parseEnvelope(raw);\n return envelope ?? wrapLegacy(raw);\n}\n\nfunction writeEnvelope(\n service: string,\n key: string,\n envelope: QuantumEnvelope,\n): void {\n const entry = new Entry(service, key);\n entry.setPassword(serializeEnvelope(envelope));\n}\n\nfunction resolveEnv(opts: KeyringOptions): Environment | undefined {\n if (opts.env) return opts.env;\n const result = collapseEnvironment({ projectPath: opts.projectPath });\n return result?.env;\n}\n\n/**\n * Retrieve a secret by key, with scope resolution and superposition collapse.\n * Records the access in the audit log (observer effect).\n */\nexport function getSecret(\n key: string,\n opts: KeyringOptions = {},\n): string | null {\n const scopes = resolveScope(opts);\n const env = resolveEnv(opts);\n const source = opts.source ?? \"cli\";\n\n for (const { service, scope } of scopes) {\n const envelope = readEnvelope(service, key);\n if (!envelope) continue;\n\n // Check decay\n const decay = checkDecay(envelope);\n if (decay.isExpired) {\n logAudit({\n action: \"read\",\n key,\n scope,\n source,\n detail: \"blocked: secret expired (quantum decay)\",\n });\n continue;\n }\n\n // Collapse superposition\n const value = collapseValue(envelope, env);\n if (value === null) continue;\n\n // Observer effect: record access and persist\n const updated = recordAccess(envelope);\n writeEnvelope(service, key, updated);\n\n logAudit({ action: \"read\", key, scope, env, source });\n\n return value;\n }\n\n return null;\n}\n\n/**\n * Get the full envelope for a secret (for inspection, no value extraction).\n */\nexport function getEnvelope(\n key: string,\n opts: KeyringOptions = {},\n): { envelope: QuantumEnvelope; scope: Scope } | null {\n const scopes = resolveScope(opts);\n\n for (const { service, scope } of scopes) {\n const envelope = readEnvelope(service, key);\n if (envelope) return { envelope, scope };\n }\n\n return null;\n}\n\n/**\n * Store a secret with quantum metadata.\n */\nexport function setSecret(\n key: string,\n value: string,\n opts: SetSecretOptions = {},\n): void {\n const scope = opts.scope ?? \"global\";\n const scopes = resolveScope({ ...opts, scope });\n const { service } = scopes[0];\n const source = opts.source ?? \"cli\";\n\n // Check if there's an existing envelope to preserve metadata\n const existing = readEnvelope(service, key);\n\n let envelope: QuantumEnvelope;\n\n if (opts.states) {\n envelope = createEnvelope(\"\", {\n states: opts.states,\n defaultEnv: opts.defaultEnv,\n description: opts.description,\n tags: opts.tags,\n ttlSeconds: opts.ttlSeconds,\n expiresAt: opts.expiresAt,\n entangled: existing?.meta.entangled,\n });\n } else {\n envelope = createEnvelope(value, {\n description: opts.description,\n tags: opts.tags,\n ttlSeconds: opts.ttlSeconds,\n expiresAt: opts.expiresAt,\n entangled: existing?.meta.entangled,\n });\n }\n\n // Preserve access count from existing\n if (existing) {\n envelope.meta.createdAt = existing.meta.createdAt;\n envelope.meta.accessCount = existing.meta.accessCount;\n }\n\n writeEnvelope(service, key, envelope);\n logAudit({ action: \"write\", key, scope, source });\n\n // Propagate to entangled secrets\n const entangled = findEntangled({ service, key });\n for (const target of entangled) {\n try {\n const targetEnvelope = readEnvelope(target.service, target.key);\n if (targetEnvelope) {\n if (opts.states) {\n targetEnvelope.states = opts.states;\n } else {\n targetEnvelope.value = value;\n }\n targetEnvelope.meta.updatedAt = new Date().toISOString();\n writeEnvelope(target.service, target.key, targetEnvelope);\n logAudit({\n action: \"entangle\",\n key: target.key,\n scope: \"global\",\n source,\n detail: `propagated from ${key}`,\n });\n }\n } catch {\n // entangled target may not exist\n }\n }\n}\n\n/**\n * Delete a secret from the specified scope (or both if unscoped).\n */\nexport function deleteSecret(\n key: string,\n opts: KeyringOptions = {},\n): boolean {\n const scopes = resolveScope(opts);\n const source = opts.source ?? \"cli\";\n let deleted = false;\n\n for (const { service, scope } of scopes) {\n const entry = new Entry(service, key);\n try {\n if (entry.deleteCredential()) {\n deleted = true;\n logAudit({ action: \"delete\", key, scope, source });\n }\n } catch {\n // not found\n }\n }\n\n return deleted;\n}\n\n/**\n * Check whether a secret exists in any applicable scope.\n */\nexport function hasSecret(\n key: string,\n opts: KeyringOptions = {},\n): boolean {\n const scopes = resolveScope(opts);\n\n for (const { service } of scopes) {\n const envelope = readEnvelope(service, key);\n if (envelope) {\n const decay = checkDecay(envelope);\n if (!decay.isExpired) return true;\n }\n }\n\n return false;\n}\n\n/**\n * List all secrets across applicable scopes with quantum metadata.\n */\nexport function listSecrets(opts: KeyringOptions = {}): SecretEntry[] {\n const source = opts.source ?? \"cli\";\n const services: { service: string; scope: Scope }[] = [];\n\n if (!opts.scope || opts.scope === \"global\") {\n services.push({ service: globalService(), scope: \"global\" });\n }\n\n if ((!opts.scope || opts.scope === \"project\") && opts.projectPath) {\n services.push({\n service: projectService(opts.projectPath),\n scope: \"project\",\n });\n }\n\n const results: SecretEntry[] = [];\n const seen = new Set<string>();\n\n for (const { service, scope } of services) {\n try {\n const credentials = findCredentials(service);\n for (const cred of credentials) {\n const id = `${scope}:${cred.account}`;\n if (seen.has(id)) continue;\n seen.add(id);\n\n const envelope = parseEnvelope(cred.password) ?? wrapLegacy(cred.password);\n const decay = checkDecay(envelope);\n\n results.push({\n key: cred.account,\n scope,\n envelope,\n decay,\n });\n }\n } catch {\n // keyring unavailable\n }\n }\n\n if (!opts.silent) {\n logAudit({ action: \"list\", source });\n }\n\n return results.sort((a, b) => a.key.localeCompare(b.key));\n}\n\n/**\n * Export all secrets with their values (for .env or JSON export).\n * Collapses superposition based on detected environment.\n */\nexport function exportSecrets(\n opts: KeyringOptions & { format?: \"env\" | \"json\" } = {},\n): string {\n const format = opts.format ?? \"env\";\n const env = resolveEnv(opts);\n const entries = listSecrets(opts);\n const source = opts.source ?? \"cli\";\n\n const merged = new Map<string, string>();\n\n const globalEntries = entries.filter((e) => e.scope === \"global\");\n const projectEntries = entries.filter((e) => e.scope === \"project\");\n\n for (const entry of [...globalEntries, ...projectEntries]) {\n if (entry.envelope) {\n const decay = checkDecay(entry.envelope);\n if (decay.isExpired) continue;\n\n const value = collapseValue(entry.envelope, env);\n if (value !== null) {\n merged.set(entry.key, value);\n }\n }\n }\n\n logAudit({ action: \"export\", source, detail: `format=${format}` });\n\n if (format === \"json\") {\n const obj: Record<string, string> = {};\n for (const [key, value] of merged) {\n obj[key] = value;\n }\n return JSON.stringify(obj, null, 2);\n }\n\n const lines: string[] = [];\n for (const [key, value] of merged) {\n const escaped = value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\");\n lines.push(`${key}=\"${escaped}\"`);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Create an entanglement between two secrets.\n */\nexport function entangleSecrets(\n sourceKey: string,\n sourceOpts: KeyringOptions,\n targetKey: string,\n targetOpts: KeyringOptions,\n): void {\n const sourceScopes = resolveScope({ ...sourceOpts, scope: sourceOpts.scope ?? \"global\" });\n const targetScopes = resolveScope({ ...targetOpts, scope: targetOpts.scope ?? \"global\" });\n\n const source = { service: sourceScopes[0].service, key: sourceKey };\n const target = { service: targetScopes[0].service, key: targetKey };\n\n entangleLink(source, target);\n logAudit({\n action: \"entangle\",\n key: sourceKey,\n source: sourceOpts.source ?? \"cli\",\n detail: `entangled with ${targetKey}`,\n });\n}\n","import { createHash } from \"node:crypto\";\n\nexport function hashProjectPath(projectPath: string): string {\n return createHash(\"sha256\").update(projectPath).digest(\"hex\").slice(0, 12);\n}\n","import { hashProjectPath } from \"../utils/hash.js\";\n\nconst SERVICE_PREFIX = \"q-ring\";\n\nexport type Scope = \"global\" | \"project\";\n\nexport interface ResolvedScope {\n scope: Scope;\n service: string;\n projectPath?: string;\n}\n\nexport function globalService(): string {\n return `${SERVICE_PREFIX}:global`;\n}\n\nexport function projectService(projectPath: string): string {\n const hash = hashProjectPath(projectPath);\n return `${SERVICE_PREFIX}:project:${hash}`;\n}\n\nexport function resolveScope(opts: {\n scope?: Scope;\n projectPath?: string;\n}): ResolvedScope[] {\n const { scope, projectPath } = opts;\n\n if (scope === \"global\") {\n return [{ scope: \"global\", service: globalService() }];\n }\n\n if (scope === \"project\") {\n if (!projectPath) {\n throw new Error(\"Project path is required for project scope\");\n }\n return [\n { scope: \"project\", service: projectService(projectPath), projectPath },\n ];\n }\n\n // No explicit scope: return project-first for resolution (project overrides global)\n if (projectPath) {\n return [\n { scope: \"project\", service: projectService(projectPath), projectPath },\n { scope: \"global\", service: globalService() },\n ];\n }\n\n return [{ scope: \"global\", service: globalService() }];\n}\n\nexport function parseServiceName(service: string): ResolvedScope {\n if (service === globalService()) {\n return { scope: \"global\", service };\n }\n\n if (service.startsWith(`${SERVICE_PREFIX}:project:`)) {\n return { scope: \"project\", service };\n }\n\n return { scope: \"global\", service };\n}\n","/**\n * Quantum Tunneling: ephemeral secrets that exist only in memory.\n *\n * Tunneled secrets are never persisted to the OS keyring. They live\n * in a process-scoped in-memory store with optional auto-expiry.\n * Useful for passing secrets between agents without touching disk.\n */\n\ninterface TunnelEntry {\n value: string;\n createdAt: number;\n expiresAt?: number;\n accessCount: number;\n /** Max number of reads before auto-destruct */\n maxReads?: number;\n}\n\nconst tunnelStore = new Map<string, TunnelEntry>();\n\nlet cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\nfunction ensureCleanup(): void {\n if (cleanupInterval) return;\n cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [id, entry] of tunnelStore) {\n if (entry.expiresAt && now >= entry.expiresAt) {\n tunnelStore.delete(id);\n }\n }\n if (tunnelStore.size === 0 && cleanupInterval) {\n clearInterval(cleanupInterval);\n cleanupInterval = null;\n }\n }, 5000);\n\n // Don't prevent process exit\n if (cleanupInterval && typeof cleanupInterval === \"object\" && \"unref\" in cleanupInterval) {\n cleanupInterval.unref();\n }\n}\n\nexport interface TunnelOptions {\n /** TTL in seconds */\n ttlSeconds?: number;\n /** Self-destruct after N reads */\n maxReads?: number;\n}\n\n/**\n * Create a tunneled (ephemeral) secret. Returns a tunnel ID.\n */\nexport function tunnelCreate(\n value: string,\n opts: TunnelOptions = {},\n): string {\n const id = `tun_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;\n const now = Date.now();\n\n tunnelStore.set(id, {\n value,\n createdAt: now,\n expiresAt: opts.ttlSeconds ? now + opts.ttlSeconds * 1000 : undefined,\n accessCount: 0,\n maxReads: opts.maxReads,\n });\n\n ensureCleanup();\n return id;\n}\n\n/**\n * Read a tunneled secret by ID. Returns null if expired or not found.\n * Each read increments the access counter; auto-destructs after maxReads.\n */\nexport function tunnelRead(id: string): string | null {\n const entry = tunnelStore.get(id);\n if (!entry) return null;\n\n if (entry.expiresAt && Date.now() >= entry.expiresAt) {\n tunnelStore.delete(id);\n return null;\n }\n\n entry.accessCount++;\n\n if (entry.maxReads && entry.accessCount >= entry.maxReads) {\n const value = entry.value;\n tunnelStore.delete(id);\n return value;\n }\n\n return entry.value;\n}\n\n/**\n * Destroy a tunneled secret immediately.\n */\nexport function tunnelDestroy(id: string): boolean {\n return tunnelStore.delete(id);\n}\n\n/**\n * List all active tunnel IDs (never exposes values).\n */\nexport function tunnelList(): {\n id: string;\n createdAt: number;\n expiresAt?: number;\n accessCount: number;\n maxReads?: number;\n}[] {\n const now = Date.now();\n const result: ReturnType<typeof tunnelList> = [];\n\n for (const [id, entry] of tunnelStore) {\n if (entry.expiresAt && now >= entry.expiresAt) {\n tunnelStore.delete(id);\n continue;\n }\n result.push({\n id,\n createdAt: entry.createdAt,\n expiresAt: entry.expiresAt,\n accessCount: entry.accessCount,\n maxReads: entry.maxReads,\n });\n }\n\n return result;\n}\n"],"mappings":";;;AAmDO,SAAS,eACd,OACA,MAOiB;AACjB,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AAEnC,MAAI,YAAY,MAAM;AACtB,MAAI,CAAC,aAAa,MAAM,YAAY;AAClC,gBAAY,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,aAAa,GAAI,EAAE,YAAY;AAAA,EACxE;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,MAAM,SAAS,SAAY;AAAA,IAClC,QAAQ,MAAM;AAAA,IACd,YAAY,MAAM;AAAA,IAClB,MAAM;AAAA,MACJ,WAAW;AAAA,MACX,WAAW;AAAA,MACX;AAAA,MACA,YAAY,MAAM;AAAA,MAClB,aAAa,MAAM;AAAA,MACnB,MAAM,MAAM;AAAA,MACZ,WAAW,MAAM;AAAA,MACjB,aAAa;AAAA,IACf;AAAA,EACF;AACF;AAEO,SAAS,cAAc,KAAqC;AACjE,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,QAAI,UAAU,OAAO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