/** * Build-time credential stamp (issue #3836): sealed allowlist of literal * credential keys a package may resolve, plus dependency stamp pins. Publish * fails closed on non-literal or unstampable use. Fleet seal (`0014`) and * convert (`0015`) fill missing slots and descriptions. A stored stamp limits * every run of that package to its declared slots (ADR 0068, 2026-10-16). */ import { canonicalJsonStringify } from '@kody-internal/shared/canonical-json.ts' import { sha256Hex } from '@kody-internal/shared/sha256.ts' import { shouldStoreArtifactBlobAsLatin1 } from '#universal/package-file-media.ts' import { isPlainJavaScriptModule, plainJavaScriptTypeSyntaxAdvice, } from '#worker/module-source.ts' import { type AstNode, constantsWithoutShadows, forEachScannableModule, shareModulePasses, getNodeName, isPackageAppAssetPath, listScannableModulePaths, parseModule, readPackageAppAssetsDirectory, readModuleParseError, resolveStringExpression, scannableModuleFilePattern, scannableModuleWalk, unwrapExpression, walkAst, } from '#worker/credentials/module-placeholder-scan.ts' import { isVaultCredentialUsePlacement, mergePackageCredentialScans, scanPackageCredentials, type PackageCredentialScan, } from '#worker/credentials/credential-inventory-scan.ts' import { normalizeSecretProviderNeedId, secretProviderSlotExample, } from '#worker/credentials/credential-needs.ts' import type { ResolvedSecretProviderSlots } from '#worker/credentials/secret-provider-slots.ts' import type { PackageCodemodFinding } from '#worker/package-codemods/types.ts' import { inferCredentialNames, loadModuleNameSummary, type ModuleNameSummary, type StoredModuleNameSummary, storeModuleNameSummary, summarizeModuleNames, } from '#worker/package-codemods/codemods/0013-infer-credential-names.ts' import { getPackageAppClientEntryPath, getPackageAppEntryPath, listPackageSubscriptions, normalizePackageWorkspacePath, parseAuthoredPackageJson, } from '#worker/package-registry/manifest.ts' import { credentialSlotPrefixCoversName, credentialSlotPrefixKindValues, packageCredentialSlotKindValues, secretProviderSlotKind, packageCredentialSlotNamePattern, type AuthoredPackageJson, type PackageCredentialKind, type PackageCredentialSlotKind, type PackageCredentialSlot, } from '#worker/package-registry/types.ts' import { collectDynamicImportExpressionNodes, type ModuleImportNodesCache, } from '#worker/package-runtime/import-specifiers.ts' import { collectReachableSourceFilePaths } from '#worker/package-runtime/module-graph-workspace.ts' import { collectPublishedPackageArtifactTargets } from '#worker/package-runtime/package-artifact-targets.ts' import { detectLegacyCredentialPatternsCodemod, legacyCredentialPatternFromMessage, type LegacyCredentialPattern, scanModuleCredentialReferences, } from '#worker/package-codemods/codemods/0010-detect-legacy-credential-patterns.ts' export const credentialStampVersion = 1 as const export const credentialStampFileName = 'credential-stamp.json' /** * Size above which a prebuilt client or static asset module is left out of * the stamp walks. Larger prebuilt client bundles (e.g. * @kentcdodds/world-builder's ~1.7MB `public/client/main.js`) reset the * Durable Object CPU budget when parsed. The size never decides whether a * module may be left out: only its path does * ({@link isClientAssetCredentialStampPath}). UTF-8 byte length. */ export const credentialStampMaxModuleScanBytes = 256 * 1024 const credentialStampUtf8Encoder = new TextEncoder() export function measureCredentialStampModuleBytes(source: string): number { return credentialStampUtf8Encoder.encode(source).byteLength } /** Directory names that hold build output, wherever they sit in a package. */ const buildOutputDirectoryNames = new Set(['dist', 'build', 'out', '.output']) /** * The directory of the declared `kody.app.client` entry, or null when there * is none or the entry sits at the package root. */ function readPackageAppClientDirectory(manifestSource: string | undefined) { if (manifestSource == null) return null let parsed: unknown try { parsed = JSON.parse(manifestSource) } catch { return null } const app = (parsed as { kody?: { app?: { client?: unknown } } } | null)?.kody ?.app const client = app?.client const entry = typeof client === 'string' ? client : typeof (client as { entry?: unknown } | null | undefined)?.entry === 'string' ? (client as { entry: string }).entry : null if (!entry?.trim()) return null let normalized: string try { normalized = normalizePackageWorkspacePath(entry.trim()) } catch { return null } const lastSlash = normalized.lastIndexOf('/') return lastSlash > 0 ? normalized.slice(0, lastSlash) : null } /** * Whether `path` is somewhere only the browser or a build tool reads: under * the declared `kody.app.assets` directory, under the directory of the * declared `kody.app.client` entry (when no server module lives there), or * under a build output directory. */ function isClientAssetCredentialStampPath( path: string, directories: { assets: string | null client: string | null }, ) { if (isPackageAppAssetPath(path, directories.assets)) return true if (directories.client != null && path.startsWith(`${directories.client}/`)) { return true } return path .split('/') .slice(0, -1) .some((segment) => buildOutputDirectoryNames.has(segment)) } /** * Drop oversized prebuilt client and static asset modules from a package * file map before stamp planning / sealing. A module is dropped only when * its path says it is client or build output * ({@link isClientAssetCredentialStampPath}) and no server runtime root * reaches it (`serverPaths`, from {@link collectServerRuntimeModulePaths}). * Every other module is walked whatever its size, so a module that cannot * be walked fails the check with its path instead of being skipped. Returns * `files` itself when nothing is dropped so the credential scans of one * check share one module index. */ export function omitOversizedClientCredentialStampModules( files: Record, serverPaths: ReadonlySet, ): Record { const manifestSource = files[packageManifestPath] const clientDirectory = readPackageAppClientDirectory(manifestSource) const directories = { assets: readPackageAppAssetsDirectory(manifestSource), // A directory that also holds server modules is not a client directory. client: clientDirectory != null && ![...serverPaths].some((path) => path.startsWith(`${clientDirectory}/`)) ? clientDirectory : null, } const oversized = Object.entries(files).filter( ([path, content]) => !serverPaths.has(path) && scannableModuleFilePattern.test(path) && isClientAssetCredentialStampPath(path, directories) && measureCredentialStampModuleBytes(content) > credentialStampMaxModuleScanBytes, ) if (oversized.length === 0) return files const next = { ...files } for (const [path] of oversized) delete next[path] return next } export type CredentialDepStamp = { packageId: string publishedCommit: string stampHash: string } export type CredentialStamp = { version: typeof credentialStampVersion keys: Array depStamps: Array stampHash: string } /** True for a credential-stamp.json blob stored at publish or backfill. */ export function isStoredCredentialStamp( value: unknown, ): value is CredentialStamp { if (value == null || typeof value !== 'object' || Array.isArray(value)) { return false } const record = value as Record return ( record.version === credentialStampVersion && typeof record.stampHash === 'string' && Array.isArray(record.keys) && record.keys.every((key) => typeof key === 'string') && Array.isArray(record.depStamps) && record.depStamps.every(isCredentialDepStamp) ) } function isCredentialDepStamp(value: unknown): value is CredentialDepStamp { if (value == null || typeof value !== 'object' || Array.isArray(value)) { return false } const record = value as Record return ( typeof record.packageId === 'string' && typeof record.publishedCommit === 'string' && typeof record.stampHash === 'string' ) } export type CredentialStampGateFailure = { code: | 'non_literal' | 'unstampable_pattern' | 'server_eval' | 'missing_description' | 'invalid_key' | 'credential_named' path?: string /** Agent-facing fix instructions; never include credential values. */ message: string } export type CredentialStampScan = { /** Sorted unique literal keys this package's own source stamps. */ keys: Array failures: Array /** Keys present in `kody.credentials` but not in the stamp (stale). */ staleManifestKeys: Array /** Literal `kody.mcp` server names sealed as `kind: "mcp"` slots. */ mcpKeys: Array /** Literal `secretJwtSign` private-key secret names. */ jwtSignKeys: Array /** Literal integration / createAuthenticatedFetch account names. */ oauthKeys: Array /** The credential inventory of the scanned modules, with sites. */ scan: PackageCredentialScan /** * Every 0010 legacy-pattern finding of the scanned modules. * Remove when: issue #3836 phase 3 enforces credential stamps on every package. */ legacyFindings: Array } /** * A slot the `0014` seal codemod / stamp backfill can write without * overwriting an existing description. */ export type CredentialStampSealSlot = { key: string description: string kind?: PackageCredentialSlotKind } export type CredentialStampSealPlan = { keys: Array /** Slots to insert or fill (existing descriptions are never overwritten). */ updates: Array /** Stamp keys that still need a human description. */ uninferableKeys: Array /** Gate failures that block sealing (excludes missing_description for keys in updates). */ blockingFailures: Array staleManifestKeys: Array /** True when keys are stamped, every key has a description, and nothing blocks. */ sealReady: boolean } const packageManifestPath = 'package.json' /** * 0010 labels that cannot be sealed into a stamp allowlist. `kody.mcp` stays * off this list: {@link scanLiteralMcpServerKeys} stamps literal server names * and fails dynamic access. Non-literal names, `|scope=`, * packageSecrets.get, and plain http still fail closed. Manifest-only * `kody.secretMounts` is a compat finding: publish may keep it for stale * static dependents, and it does not fail this gate. * Remove when: issue #3836 phase 3 enforces credential stamps on every package. */ const unstampableLegacyPatterns = new Set([ 'computed secret', 'computed integration', '|scope=', 'packageSecrets.get', 'plain http', ]) const credentialFunctionNames = new Set(['credential', 'credentials']) function isPlainObject(value: unknown): value is Record { return value != null && typeof value === 'object' && !Array.isArray(value) } const packageCredentialKinds: ReadonlySet = new Set( packageCredentialSlotKindValues, ) type ManifestCredentialSlot = { description: string | null kind?: PackageCredentialSlotKind provider?: string package?: string multiple?: boolean /** As written; only `true` is valid, and only on a name-filled kind. */ prefix?: unknown } function readManifestCredentialSlots( manifestSource: string | undefined, ): Record { if (manifestSource == null) return {} let parsed: unknown try { parsed = JSON.parse(manifestSource) } catch { return {} } if (!isPlainObject(parsed) || !isPlainObject(parsed.kody)) return {} const credentials = parsed.kody.credentials if (!isPlainObject(credentials)) return {} const slots: Record = {} for (const [name, slot] of Object.entries(credentials)) { if (!isPlainObject(slot)) continue const description = typeof slot.description === 'string' && slot.description.trim().length > 0 ? slot.description.trim() : null const declared: ManifestCredentialSlot = { description } if ( typeof slot.kind === 'string' && packageCredentialKinds.has(slot.kind) ) { declared.kind = slot.kind as PackageCredentialSlotKind } if (typeof slot.provider === 'string' && slot.provider.trim().length > 0) { declared.provider = slot.provider } if (typeof slot.package === 'string') declared.package = slot.package.trim() if (typeof slot.multiple === 'boolean') declared.multiple = slot.multiple if (Object.hasOwn(slot, 'prefix')) declared.prefix = slot.prefix slots[name] = declared } return slots } function toInventorySlots( slots: Record, ): Record | undefined { const out: Record = {} for (const [name, slot] of Object.entries(slots)) { if (slot.description == null) continue out[name] = { description: slot.description, ...(slot.kind ? { kind: slot.kind } : {}), ...(slot.provider ? { provider: slot.provider } : {}), ...(slot.multiple != null ? { multiple: slot.multiple } : {}), ...(slot.prefix === true ? { prefix: true as const } : {}), } } return Object.keys(out).length > 0 ? out : undefined } function slotDescription( slots: Record, key: string, ): string | null { return slots[key]?.description ?? null } type CredentialBindings = { functions: Set runtimeObjects: Set } function collectCredentialBindings(body: Array): CredentialBindings { const functions = new Set() const runtimeObjects = new Set(['kody']) for (const node of body) { if (node.type !== 'ImportDeclaration') continue if (getNodeName(node.source) !== 'kody:runtime') continue for (const specifier of node.specifiers ?? []) { const local = getNodeName(specifier.local) if (!local) continue if ( specifier.type === 'ImportDefaultSpecifier' || specifier.type === 'ImportNamespaceSpecifier' ) { runtimeObjects.add(local) continue } const imported = getNodeName(specifier.imported) if (specifier.type === 'ImportSpecifier' && imported === 'kody') { runtimeObjects.add(local) } if (imported && credentialFunctionNames.has(imported)) { functions.add(local) } } } return { functions, runtimeObjects } } /** * Property name of a member expression: `obj.lit`, `obj?.lit`, `obj['lit']`, * `obj?.['lit']`, and template literals without expressions (`obj[\`lit\`]`). */ function memberPropertyName(node: AstNode | undefined): string | null { if ( node?.type !== 'MemberExpression' && node?.type !== 'OptionalMemberExpression' ) { return null } if (node.computed === true) { const property = node.property if (property?.type === 'StringLiteral' || property?.type === 'Literal') { return getNodeName(property) } return templateLiteralStaticText(property) } return getNodeName(node.property) } /** * `credential` / `credentials` as an imported binding or as * `kody.credential` / `kody['credential']` on a tracked runtime object. */ function isCredentialFunctionValue( node: AstNode | undefined, bindings: CredentialBindings, ): boolean { if (node?.type === 'Identifier') { return bindings.functions.has(getNodeName(node) ?? '') } if ( node?.type !== 'MemberExpression' && node?.type !== 'OptionalMemberExpression' ) { return false } if (node.object?.type !== 'Identifier') return false if (!bindings.runtimeObjects.has(getNodeName(node.object) ?? '')) { return false } const property = memberPropertyName(node) return property != null && credentialFunctionNames.has(property) } function isCredentialCallee( callee: AstNode | undefined, bindings: CredentialBindings, ) { return isCredentialFunctionValue(callee, bindings) } function isCredentialNamedMember( node: AstNode | undefined, bindings: CredentialBindings, ): boolean { if ( node?.type !== 'MemberExpression' && node?.type !== 'OptionalMemberExpression' ) { return false } if (memberPropertyName(node) !== 'named') return false return isCredentialFunctionValue(node.object, bindings) } /** `credential.visitor(key)`: a literal key read on the visitor's grant. */ function isCredentialVisitorMember( node: AstNode | undefined, bindings: CredentialBindings, ): boolean { if ( node?.type !== 'MemberExpression' && node?.type !== 'OptionalMemberExpression' ) { return false } if (memberPropertyName(node) !== 'visitor') return false return isCredentialFunctionValue(node.object, bindings) } function isCalledMember(node: AstNode, parent: AstNode | undefined) { return Boolean( parent && (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.callee === node, ) } function isNonReferenceName(node: AstNode, parent: AstNode) { if (parent.computed === true) return false if ( parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression' ) { return parent.property === node } if ( parent.type === 'Property' || parent.type === 'ObjectProperty' || parent.type === 'MethodDefinition' || parent.type === 'PropertyDefinition' ) { return ( parent.key === node && (parent as { shorthand?: boolean }).shorthand !== true ) } return false } /** * TypeScript nodes whose children can hold runtime expressions. Every other * `TS*` node is a type (alias, interface, annotation, type arguments, `typeof` * query, …) and is erased before the code runs. */ const runtimeTypeScriptNodeTypes = new Set([ 'TSAsExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', 'TSNonNullExpression', 'TSInstantiationExpression', 'TSEnumDeclaration', 'TSEnumBody', 'TSEnumMember', 'TSModuleDeclaration', 'TSModuleBlock', 'TSExportAssignment', 'TSImportEqualsDeclaration', 'TSParameterProperty', ]) /** * A reference that is erased before the code runs: inside a type, under an * ambient `declare`, or in a type-only export. Such a reference cannot hand * the credential function to anything at run time. */ export function isErasedTypePosition(ancestors: ReadonlyArray) { for (const ancestor of ancestors) { if ( ancestor.type.startsWith('TS') && !runtimeTypeScriptNodeTypes.has(ancestor.type) ) { return true } if ((ancestor as { declare?: unknown }).declare === true) return true if ( (ancestor.type === 'ExportNamedDeclaration' || ancestor.type === 'ExportSpecifier' || ancestor.type === 'TSImportEqualsDeclaration') && ((ancestor as { exportKind?: unknown }).exportKind === 'type' || (ancestor as { importKind?: unknown }).importKind === 'type') ) { return true } } return false } /** `typeof credential` in a runtime expression reads a string, not the value. */ export function isRuntimeTypeofOperand( node: AstNode, parent: AstNode | undefined, ) { return ( parent?.type === 'UnaryExpression' && parent.operator === 'typeof' && parent.argument === node ) } /** * `import c = kody.credential` is a runtime alias, but its qualified name is a * `TS*` node that {@link isErasedTypePosition} would otherwise skip. */ function isRuntimeImportEqualsOfRuntime( node: AstNode, bindings: CredentialBindings, ) { if (node.type !== 'TSImportEqualsDeclaration') return false if ((node as { importKind?: unknown }).importKind === 'type') return false let reference = node.moduleReference as AstNode | undefined let firstMember: AstNode | undefined while (reference?.type === 'TSQualifiedName') { firstMember = reference.right as AstNode | undefined reference = reference.left as AstNode | undefined } if (reference?.type !== 'Identifier' || firstMember == null) return false const name = getNodeName(reference) ?? '' if (bindings.functions.has(name)) return true return ( bindings.runtimeObjects.has(name) && credentialFunctionNames.has(getNodeName(firstMember) ?? '') ) } function isVisitorCallOrTypeof(visitor: AstNode, parent: AstNode | undefined) { return ( isCalledMember(visitor, parent) || isRuntimeTypeofOperand(visitor, parent) ) } type KeyScan = { key: (key: string) => void computed: () => void named: () => void indirect: () => void } function scanParsedCredentialKeys( parsed: AstNode, constants: ReadonlyMap, scan: KeyScan, ) { const bindings = collectCredentialBindings(parsed.program?.body ?? []) walkAst(parsed, (node, ancestors) => { if (isRuntimeImportEqualsOfRuntime(node, bindings)) { scan.indirect() return } if ( node.type === 'CallExpression' || node.type === 'OptionalCallExpression' ) { if (isCredentialNamedMember(node.callee, bindings)) { scan.named() return } if ( isCredentialCallee(node.callee, bindings) || isCredentialVisitorMember(node.callee, bindings) ) { const key = resolveStringExpression( node.arguments?.[0], constantsWithoutShadows(constants, ancestors), ) if (key == null) scan.computed() else scan.key(key) return } } if ( (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') && isCredentialNamedMember(node, bindings) ) { const parent = ancestors.at(-1) const called = parent && (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.callee === node if (!called) scan.named() return } // `kody.credential.bind(kody)`, `const get = kody.credential`, etc. — // any non-call use of the credential function value escapes the stamp. if ( (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') && isCredentialFunctionValue(node, bindings) ) { const parent = ancestors.at(-1) if ( isRuntimeTypeofOperand(node, parent) || isErasedTypePosition(ancestors) ) { return } const called = parent && (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.callee === node const namedAccess = parent && (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && parent.object === node && memberPropertyName(parent) === 'named' const visitorCall = parent != null && parent.object === node && isCredentialVisitorMember(parent, bindings) && isVisitorCallOrTypeof(parent, ancestors.at(-2)) if (!called && !namedAccess && !visitorCall) scan.indirect() return } if ( (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') && isCredentialVisitorMember(node, bindings) ) { const parent = ancestors.at(-1) if ( !isCalledMember(node, parent) && !isRuntimeTypeofOperand(node, parent) && !isErasedTypePosition(ancestors) ) { scan.indirect() } return } if (node.type !== 'Identifier') return if (!bindings.functions.has(getNodeName(node) ?? '')) return const parent = ancestors.at(-1) if (!parent || parent.type.startsWith('Import')) return if (isNonReferenceName(node, parent)) return if (isRuntimeTypeofOperand(node, parent)) return if (isErasedTypePosition(ancestors)) return const isCallee = (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.callee === node const isNamedAccess = (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && parent.object === node && memberPropertyName(parent) === 'named' if (isNamedAccess) { scan.named() return } const isVisitorCall = isCredentialVisitorMember(parent, bindings) && parent.object === node && isVisitorCallOrTypeof(parent, ancestors.at(-2)) if (!isCallee && !isVisitorCall) scan.indirect() }) } const textCredentialCallPattern = /\b(?:credentials?|credential\s*(?:\?\.|\.)\s*visitor)\s*\(\s*(?:(['"`])([^'"`$\\]*)\1)?/g function scanUnparsedCredentialKeys(source: string, scan: KeyScan) { if (!/\bkody:runtime\b|\bkody\s*(?:\?\.|\.)\s*credentials?\b/.test(source)) { return } if (/\bcredentials?\s*(?:\?\.|\.)\s*named\b/.test(source)) { scan.named() } for (const match of source.matchAll(textCredentialCallPattern)) { if (match[2] == null) scan.computed() else scan.key(match[2]) } } const unparsedCredentialMentionPattern = /\b(?:credentials?|kody)\b/ /** * Report every server-runtime JavaScript parse failure. For other module * types, report failures that mention credential, credentials, or kody. */ async function unparsedServerModuleFailure( path: string, source: string, ): Promise { const plainJavaScript = isPlainJavaScriptModule(path) if (!plainJavaScript && !unparsedCredentialMentionPattern.test(source)) return null const parseError = (await readModuleParseError(source, path)) ?? 'unknown parse error' return { code: 'non_literal', path, message: `${path}: server-runtime module could not be parsed (${parseError}), so publish cannot check how it uses credential, credentials, or kody. ${plainJavaScript ? `Fix the syntax error. ${plainJavaScriptTypeSyntaxAdvice}` : 'Fix the syntax error, or rewrite the module in syntax TypeScript accepts.'}`, } } /** * Shared agent-facing fix for unstampable / non-literal credential use * (issue #3836 publish gate). Kent's pattern: fixed declared slots plus a * call map from each run to those slots — never a runtime-chosen name in * package source. */ export const credentialStampConversionFixGuidance = 'Fix: declare every need with a real description in kody.credentials. Call credential("SLOT") or credentials("SLOT") with its literal key, or use a name-filled placeholder or createAuthenticatedFetch whose name matches a declared slot (a "prefix": true slot also covers "SLOT-"). Callers can select a stable ID in the execute credentials call map ({ "SLOT": { "id": "credential-id" } }), with CLI --credential SLOT=id:credential-id, or with a stored mapping.' /** * Fix for a credential name built at run time: a hand-written slot it * matches, by key or by a `prefix: true` slot's `-` prefix. */ export const runTimeNameFixGuidance = 'Fix: declare each name it can build in kody.credentials with a real description. A slot covers its exact key; add "prefix": true (no kind, or kind "secret" or "oauth") to also cover "-" names, e.g. "kody": { "credentials": { "exampleApiKey": { "description": "Example API key; account work uses exampleApiKey-work.", "prefix": true } } }. A name a caller passes (account, secretName) must match a declared slot when it is used, or the run is refused.' function nonLiteralFixMessage(kind: string) { return `${kind} Publish cannot stamp a credential whose name is only known at run time. ${credentialStampConversionFixGuidance}` } /** * Server-runtime module paths for the eval rule: every published artifact * entry except `app-client`, plus modules reachable from those entries. * Modules shared with the UI graph follow the server rule. */ export async function collectServerRuntimeModulePaths( files: Record, ): Promise> { return new Set( [...(await collectServerRuntimeSourcePaths(files))].filter((path) => scannableModuleFilePattern.test(path), ), ) } async function collectServerRuntimeSourcePaths( files: Record, ): Promise> { const manifestSource = files[packageManifestPath] if (manifestSource == null) return new Set() let manifest: AuthoredPackageJson try { manifest = parseAuthoredPackageJson({ content: manifestSource, mode: 'published', }) } catch { return new Set() } const rootPackage = { manifest, prefix: '', } const serverEntries = new Set() for (const target of collectPublishedPackageArtifactTargets(manifest)) { if (target.bundleKind === 'app-client') continue serverEntries.add(normalizePackageWorkspacePath(target.entryPoint)) } const appEntry = getPackageAppEntryPath(manifest) if (appEntry) serverEntries.add(appEntry) for (const subscription of listPackageSubscriptions(manifest)) { serverEntries.add(normalizePackageWorkspacePath(subscription.handler)) } // `main` / `module` are not on AuthoredPackageJson; read them from the // raw manifest. `browser` and kody.app.client stay UI-only roots. let rawManifest: unknown try { rawManifest = JSON.parse(manifestSource) } catch { rawManifest = null } if (isPlainObject(rawManifest)) { for (const field of ['main', 'module'] as const) { const value = rawManifest[field] if (typeof value === 'string' && value.trim()) { serverEntries.add(normalizePackageWorkspacePath(value)) } } } getPackageAppClientEntryPath(manifest) // Reachability alone keeps unreferenced static assets (multi-MB client // bundles under kody.app.assets) off this set. Do not drop assets by // directory prefix: a server import of an asset module must still follow // the server_eval rule and stay stamp-scanned via listScannableModulePaths. const serverReachable = new Set() // About 100 entries share most modules; parse each module once. const importNodesCache: ModuleImportNodesCache = new Map() for (const entry of serverEntries) { for (const path of await collectReachableSourceFilePaths({ files, entryPoint: entry, rootPackage, importNodesCache, })) { serverReachable.add(path) } } return serverReachable } /** * Keep the scanner's executable source, including assets reached by either * runtime graph, but not files used only by the static asset server. */ export async function credentialScanWorkingFiles( files: Record, ): Promise> { const assetsDirectory = readPackageAppAssetsDirectory( files[packageManifestPath], ) const paths = Object.keys(files) const hasAssets = paths.some((path) => isPackageAppAssetPath(path, assetsDirectory), ) const runtime = hasAssets ? await collectServerRuntimeSourcePaths(files) : new Set() if (hasAssets) { for (const path of await listScannableModulePaths(files)) runtime.add(path) } const kept = paths.filter((path) => { if (path === packageManifestPath) return true if (runtime.has(path)) return true if (isPackageAppAssetPath(path, assetsDirectory)) return false // Dependency pinning also recognizes static imports in files whose // extension is not JS or TS. Keep them and potential graph edges. return ( scannableModuleFilePattern.test(path) || (!files[path]!.includes('\0') && !shouldStoreArtifactBlobAsLatin1(path) && /\b(?:import|export|require)\b/.test(files[path]!)) ) }) return kept.length === paths.length ? files : Object.fromEntries(kept.map((path) => [path, files[path]!])) } const globalObjectNames = new Set(['globalThis', 'window', 'global', 'self']) function templateLiteralStaticText(node: AstNode | undefined): string | null { if (node?.type !== 'TemplateLiteral') return null if ((node.expressions?.length ?? 0) > 0) return null const quasi = node.quasis?.[0] if (!quasi) return null const value = quasi.value as | { cooked?: string | null; raw?: string } | undefined if (typeof value?.cooked === 'string') return value.cooked if (typeof value?.raw === 'string') return value.raw return getNodeName(quasi) } /** * True when `node` is `eval` / `Function`, or a member access that ends in * those names (`globalThis.eval`, `window['Function']`, `new globalThis.Function`). * Call-form `Function("…")()` is covered the same way as `new Function`. * Parenthesized / TS-wrapped callees are unwrapped first. */ function isEvalOrFunctionTarget(node: AstNode | null | undefined): boolean { const target = unwrapExpression(node ?? undefined) if (!target) return false if (target.type === 'Identifier') { const name = getNodeName(target) return name === 'eval' || name === 'Function' } if ( target.type === 'MemberExpression' || target.type === 'OptionalMemberExpression' ) { if (target.computed === true) { const prop = unwrapExpression(target.property) const literal = prop?.type === 'Literal' || prop?.type === 'StringLiteral' ? typeof prop.value === 'string' ? prop.value : null : templateLiteralStaticText(prop) if (literal != null) return literal === 'eval' || literal === 'Function' // Fail closed on globalThis[expr] / window[name] — property is not a // static literal, so publish cannot prove it is not eval/Function. const object = unwrapExpression(target.object) return globalObjectNames.has(getNodeName(object) ?? '') } const name = getNodeName(target.property) return name === 'eval' || name === 'Function' } return false } const serverEvalTextFallbackPattern = /\b(?:globalThis|window|global|self)\s*(?:\?\.)?\s*(?:\.\s*(?:eval|Function)\b|\[\s*['"](?:eval|Function)['"]\s*\])|\beval\s*\(|\b(?:new\s+)?Function\s*\(|\bimport\s*\(\s*[^'"`]/ function isParenthesized(node: AstNode) { return ( (node.extra as { parenthesized?: boolean } | undefined)?.parenthesized === true ) } // The fixed function body only returns the global object; no code comes from data. function isGlobalThisLookupCall(node: AstNode, parent: AstNode | undefined) { const target = node.callee const body = node.arguments?.[0] return ( parent?.type === 'CallExpression' && parent.callee === node && parent.arguments?.length === 0 && parent.optional !== true && parent.typeParameters == null && parent.typeArguments == null && node.type === 'CallExpression' && node.optional !== true && node.typeParameters == null && node.typeArguments == null && !isParenthesized(node) && target?.type === 'Identifier' && target.name === 'Function' && !isParenthesized(target) && node.arguments?.length === 1 && (body?.type === 'Literal' || body?.type === 'StringLiteral') && body.value === 'return this' && !isParenthesized(body) ) } async function scanServerEvalFailures( files: Record, serverPaths: ReadonlySet, ): Promise> { const failures: Array = [] const visit = async (path: string, parsed: AstNode | null) => { const source = files[path] if (source == null) return if (!parsed) { if (serverEvalTextFallbackPattern.test(source)) { failures.push({ code: 'server_eval', path, message: `${path}: unparseable server-runtime code looks like it uses eval, Function, or import() with a non-literal specifier. The exact Function("return this")() lookup is allowed only in parseable code. Resolve computed imports in the build (use static imports or tree-shake the loader), or move the code into a kody.app.client entry not imported by the server.`, }) } return } let foundEval = false walkAst(parsed, (node, ancestors) => { if (foundEval) return if ( (node.type === 'CallExpression' || node.type === 'OptionalCallExpression' || node.type === 'NewExpression') && isEvalOrFunctionTarget(node.callee) && !isGlobalThisLookupCall(node, ancestors.at(-1)) ) { foundEval = true } }) const dynamicImports = await collectDynamicImportExpressionNodes( source, isPlainJavaScriptModule(path) ? { filePath: path } : undefined, ) const hasNonLiteralImport = dynamicImports.some( (node) => node.literalSpecifier == null, ) if (foundEval || hasNonLiteralImport) { failures.push({ code: 'server_eval', path, message: `${path}: server-runtime code must not use eval, new Function, Function(...) (except the exact Function("return this")() lookup), or import() with a non-literal specifier. Resolve computed imports in the build (use static imports or tree-shake the loader), or move the code into a kody.app.client entry not imported by the server.`, }) } } await forEachScannableModule( files, async (path, parsed) => { if (serverPaths.has(path)) await visit(path, parsed) }, { sorted: true }, ) // Server-reachable modules the runtime walk does not list. const walk = await scannableModuleWalk(files) for (const path of [...serverPaths].sort()) { if (walk.listed.has(path) || !walk.visits(path) || files[path] == null) { continue } await visit(path, await parseModule(files[path], path)) } return failures.sort(compareFailurePaths) } /** * Collect literal `kody.mcp.SERVER` / `kody.mcp["SERVER"]` names and fail on * dynamic access (`kody.mcp[variable]`, `const { mcp } = kody` then computed). */ export async function scanLiteralMcpServerKeys( files: Record, serverPaths?: ReadonlySet, ): Promise<{ keys: Array failures: Array }> { files = omitOversizedClientCredentialStampModules( files, serverPaths ?? (await collectServerRuntimeModulePaths(files)), ) const keys = new Set() const failures: Array = [] const declaredMcpKeys = declaredMcpCredentialKeys( readManifestCredentialSlots(files[packageManifestPath]), ) await forEachScannableModule(files, (path, parsed, constants) => { const source = files[path]! if (!parsed) { if ( /\bkody\s*(?:\?\.|\.)\s*mcp\b|\bkody\s*\[\s*['"`]mcp['"`]/.test(source) ) { failures.push({ code: 'non_literal', path, message: `${path}: kody.mcp access could not be parsed. Call kody.mcp.SERVER (or kody.mcp["SERVER"]) with a literal server name, and declare a kind "mcp" slot for each server.`, }) } return } const body = parsed.program?.body ?? [] const kodyAliases = new Set(['kody']) const mcpAliases = createMcpAliasTable() for (const node of body) { if (node.type !== 'ImportDeclaration') continue if (getNodeName(node.source) !== 'kody:runtime') continue for (const specifier of node.specifiers ?? []) { const local = getNodeName(specifier.local) if (!local) continue if ( specifier.type === 'ImportDefaultSpecifier' || specifier.type === 'ImportNamespaceSpecifier' ) { kodyAliases.add(local) continue } if ( specifier.type === 'ImportSpecifier' && getNodeName(specifier.imported) === 'kody' ) { kodyAliases.add(local) } } } walkAst(parsed, (node, ancestors) => { if (node.type === 'VariableDeclarator') { // `const mcp = kody.mcp` / `const mcp = runtime.mcp` if ( node.id?.type === 'Identifier' && node.init && isKodyMcpRoot(node.init, kodyAliases, mcpAliases, ancestors) ) { const local = getNodeName(node.id) if (local) registerMcpAlias(mcpAliases, local, node, ancestors) } if ( node.id?.type === 'ObjectPattern' && node.init?.type === 'Identifier' && kodyAliases.has(getNodeName(node.init) ?? '') ) { for (const property of node.id.properties ?? []) { if (property.type !== 'ObjectProperty') continue if (property.computed === true) { failures.push({ code: 'non_literal', path, message: `${path}: destructuring kody must use literal property names (including mcp). Rewrite to a literal binding.`, }) continue } if (getNodeName(property.key) !== 'mcp') continue const value = property.value as AstNode | undefined if (value?.type === 'Identifier') { const local = getNodeName(value) if (local) { registerMcpAlias(mcpAliases, local, node, ancestors) } continue } if (value?.type === 'ObjectPattern') { // `const { mcp: { linear } } = kody` collectLiteralMcpServersFromObjectPattern({ pattern: value, path, keys, failures, }) continue } failures.push({ code: 'non_literal', path, message: `${path}: destructuring kody.mcp must bind a simple local name (then mcp.SERVER) or a literal server ObjectPattern.`, }) } } if ( node.id?.type === 'ObjectPattern' && node.init && isKodyMcpRoot(node.init, kodyAliases, mcpAliases, ancestors) ) { collectLiteralMcpServersFromObjectPattern({ pattern: node.id, path, keys, failures, }) } return } if ( node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression' ) { const server = mcpServerFromMember( node, kodyAliases, mcpAliases, constantsWithoutShadows(constants, ancestors), declaredMcpKeys, ancestors, ) if (server === null) { failures.push({ code: 'non_literal', path, message: `${path}: kody.mcp was accessed with a non-literal server name. Use kody.mcp.SERVER or kody.mcp["SERVER"] and declare a kind "mcp" slot for each server.`, }) return } if (server !== undefined) { if (packageCredentialSlotNamePattern.test(server)) keys.add(server) else { failures.push({ code: 'invalid_key', path, message: `${path}: MCP server "${server}" is not a valid kody.credentials key. Rename the attached server or declare it under a valid slot key.`, }) } return } } // Fail closed when a bare kody.mcp / mcp alias escapes as a value // (passed to a call, returned, stored in a container, …) instead of // a literal member access or supported alias/destructure binding. if (!isKodyMcpRoot(node, kodyAliases, mcpAliases, ancestors)) return const parent = ancestors.at(-1) if (!parent) return if (parent.type.startsWith('Import')) return if (isNonReferenceName(node, parent)) return if ( (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && parent.object === node ) { return } if (parent.type === 'VariableDeclarator') { // Binding site (`const mcp = …`) or supported init (`= kody.mcp` // / `= { linear } = kody.mcp`). if (parent.id === node || parent.init === node) return } if ( (parent.type === 'ObjectProperty' || parent.type === 'Property') && parent.value === node ) { // Destructuring binding: `const { mcp } = kody` / `const { linear } = kody.mcp`. return } failures.push({ code: 'non_literal', path, message: `${path}: kody.mcp escaped as a value. Keep MCP access as literal kody.mcp.SERVER (or a local alias used only as mcp.SERVER) and declare each server as a kind "mcp" kody.credentials slot.`, }) }) }) return { keys: [...keys].sort(), failures: dedupeFailures(failures) } } type McpAliasTable = { moduleNames: Set /** Every registered alias name, so non-alias identifiers skip the scope walk. */ names: Set declarators: Array<{ node: AstNode; name: string }> } function createMcpAliasTable(): McpAliasTable { return { moduleNames: new Set(), names: new Set(), declarators: [] } } function isNestedBindingScope(type: string): boolean { switch (type) { case 'FunctionDeclaration': case 'FunctionExpression': case 'ArrowFunctionExpression': case 'ClassMethod': case 'ClassPrivateMethod': case 'ObjectMethod': case 'ClassDeclaration': case 'ClassExpression': case 'BlockStatement': case 'CatchClause': case 'ForStatement': case 'ForOfStatement': case 'ForInStatement': case 'SwitchCase': return true default: return false } } function isModuleScopeAncestors(ancestors: ReadonlyArray): boolean { return !ancestors.some((ancestor) => isNestedBindingScope(ancestor.type)) } function firstMatchingBindingInStatements( statements: ReadonlyArray, name: string, ): { declarator: AstNode | null } | null { for (const statement of statements) { if (statement.type === 'VariableDeclaration') { for (const declarator of statement.declarations ?? []) { if (collectBindingNamesFromPattern(declarator.id).includes(name)) { return { declarator } } } } if ( (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') && getNodeName(statement.id) === name ) { return { declarator: null } } } return null } /** * Innermost binding of `name` visible at `ancestors`. A VariableDeclarator * binding can be a registered MCP alias; params and other bindings shadow. */ function innermostBindingOfName( name: string, ancestors: ReadonlyArray, ): { declarator: AstNode | null } | null { for (let index = ancestors.length - 1; index >= 0; index -= 1) { const ancestor = ancestors[index]! if (ancestor.type === 'Program') break if ( isFunctionLikeAstNode(ancestor) || ancestor.type === 'ClassPrivateMethod' ) { if ( (ancestor.type === 'FunctionDeclaration' || ancestor.type === 'FunctionExpression') && getNodeName(ancestor.id) === name ) { return { declarator: null } } if (functionParamNames(ancestor).includes(name)) { return { declarator: null } } } if ( ancestor.type === 'ClassExpression' && getNodeName(ancestor.id) === name ) { return { declarator: null } } if ( ancestor.type === 'CatchClause' && collectBindingNamesFromPattern(ancestor.param).includes(name) ) { return { declarator: null } } if ( ancestor.type === 'ForOfStatement' || ancestor.type === 'ForInStatement' ) { const left = ancestor.left if (left?.type === 'VariableDeclaration') { for (const declarator of left.declarations ?? []) { if (collectBindingNamesFromPattern(declarator.id).includes(name)) { return { declarator } } } } else if (collectBindingNamesFromPattern(left).includes(name)) { return { declarator: null } } } if (ancestor.type === 'ForStatement' && ancestor.init) { if (ancestor.init.type === 'VariableDeclaration') { for (const declarator of ancestor.init.declarations ?? []) { if (collectBindingNamesFromPattern(declarator.id).includes(name)) { return { declarator } } } } } if (ancestor.type === 'SwitchCase' && Array.isArray(ancestor.consequent)) { const found = firstMatchingBindingInStatements(ancestor.consequent, name) if (found) return found } if (ancestor.type === 'BlockStatement' && Array.isArray(ancestor.body)) { const found = firstMatchingBindingInStatements(ancestor.body, name) if (found) return found } } return null } function registerMcpAlias( table: McpAliasTable, name: string, declarator: AstNode, ancestors: ReadonlyArray, ) { table.declarators.push({ node: declarator, name }) table.names.add(name) if (isModuleScopeAncestors(ancestors)) table.moduleNames.add(name) } function isActiveMcpAlias( name: string, ancestors: ReadonlyArray, table: McpAliasTable, ): boolean { // The scan asks this for every identifier in every module. A name that was // never registered as an alias cannot be one, whatever its scope, so skip // the ancestor walk (it made the stamp scan several times slower on large // packages). if (!table.names.has(name)) return false const binding = innermostBindingOfName(name, ancestors) if (binding == null) return table.moduleNames.has(name) if (binding.declarator == null) return false return table.declarators.some( (entry) => entry.node === binding.declarator && entry.name === name, ) } function isKodyMcpRoot( node: AstNode, kodyAliases: Set, mcpAliases: McpAliasTable, ancestors: ReadonlyArray = [], ): boolean { if (node.type === 'Identifier') { const name = getNodeName(node) return name != null && isActiveMcpAlias(name, ancestors, mcpAliases) } if ( node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression' ) { return false } if (node.object?.type !== 'Identifier') return false if (!kodyAliases.has(getNodeName(node.object) ?? '')) return false return memberPropertyName(node) === 'mcp' } function declaredMcpCredentialKeys( slots: Record, ): ReadonlySet { const keys = new Set() for (const [name, slot] of Object.entries(slots)) { if (slot.kind === 'mcp') keys.add(name) } return keys } function isFunctionLikeAstNode(node: AstNode): boolean { return ( node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' || node.type === 'ObjectMethod' || node.type === 'ClassMethod' ) } /** * Local binding names from one function parameter pattern (identifier, * `{ cm }` / `{ client: cm }`, or those with defaults). Used so loose * `cm.mcp` on a destructured helper param counts like a direct `cm` param. */ function collectBindingNamesFromPattern( pattern: AstNode | undefined, ): Array { if (!pattern) return [] if (pattern.type === 'Identifier') { const name = getNodeName(pattern) return name ? [name] : [] } if (pattern.type === 'AssignmentPattern') { return collectBindingNamesFromPattern(pattern.left) } if (pattern.type === 'RestElement' || pattern.type === 'RestProperty') { return collectBindingNamesFromPattern(pattern.argument) } if (pattern.type === 'ArrayPattern') { const names: Array = [] for (const element of pattern.elements ?? []) { if (!element) continue names.push(...collectBindingNamesFromPattern(element)) } return names } if (pattern.type === 'ObjectPattern') { const names: Array = [] for (const property of pattern.properties ?? []) { if (property.type === 'RestElement' || property.type === 'RestProperty') { names.push(...collectBindingNamesFromPattern(property.argument)) continue } if (property.type !== 'ObjectProperty') continue // Shorthand `{ cm }` binds via key; `{ client: cm }` via value. const value = property.value as AstNode | undefined const binding = value?.type === 'AssignmentPattern' ? value.left : (value ?? property.key) names.push(...collectBindingNamesFromPattern(binding)) } return names } return [] } function functionParamNames(node: AstNode): Array { const names: Array = [] for (const param of node.params ?? []) { names.push(...collectBindingNamesFromPattern(param)) } return names } /** * True when `name` is a parameter of an enclosing function (inner-to-outer). * Used so loose `cm.mcp?.['home']` on a helper parameter counts, while * unrelated `settings.mcp.home` data does not. */ function isEnclosingFunctionParameter( name: string, ancestors: ReadonlyArray, ): boolean { for (let index = ancestors.length - 1; index >= 0; index -= 1) { const ancestor = ancestors[index] if (!ancestor || !isFunctionLikeAstNode(ancestor)) continue if (functionParamNames(ancestor).includes(name)) return true } return false } /** * `cm.mcp` / `cm?.mcp` / `cm['mcp']` when `cm` is an enclosing function * parameter (not a known kody/mcp alias). Used only to mark already-declared * MCP slots as used (kasa helpers); never seals new keys or fails the gate. */ function isLooseDeclaredMcpRoot( node: AstNode, kodyAliases: Set, mcpAliases: McpAliasTable, ancestors: ReadonlyArray, ): boolean { if ( node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression' ) { return false } if (memberPropertyName(node) !== 'mcp') return false if (node.object?.type !== 'Identifier') return false const objectName = getNodeName(node.object) if (objectName == null) return false if ( kodyAliases.has(objectName) || isActiveMcpAlias(objectName, ancestors, mcpAliases) ) { return false } if (innermostBindingOfName(objectName, ancestors)?.declarator != null) { return false } return isEnclosingFunctionParameter(objectName, ancestors) } function collectLiteralMcpServersFromObjectPattern(input: { pattern: AstNode path: string keys: Set failures: Array }) { for (const property of input.pattern.properties ?? []) { if (property.type === 'RestElement' || property.type === 'RestProperty') { input.failures.push({ code: 'non_literal', path: input.path, message: `${input.path}: destructuring kody.mcp with a rest element cannot be stamped. Bind each server by literal name (const { linear } = kody.mcp) or use kody.mcp.SERVER.`, }) continue } if (property.type !== 'ObjectProperty') { input.failures.push({ code: 'non_literal', path: input.path, message: `${input.path}: destructuring kody.mcp must use literal server names. Declare each server as a kind "mcp" kody.credentials slot.`, }) continue } if (property.computed === true) { input.failures.push({ code: 'non_literal', path: input.path, message: `${input.path}: destructuring kody.mcp must use literal server names. Declare each server as a kind "mcp" kody.credentials slot.`, }) continue } const server = getNodeName(property.key) if (server && packageCredentialSlotNamePattern.test(server)) { input.keys.add(server) } else { input.failures.push({ code: 'non_literal', path: input.path, message: `${input.path}: destructuring kody.mcp must use literal server names. Declare each server as a kind "mcp" kody.credentials slot.`, }) } } } /** * Literal server name from `kody.mcp.SERVER` / `mcp.SERVER` / `kody.mcp[NAME]` * when NAME is a module const string, or null when the access is dynamic, or * undefined when the node is not an mcp server access. */ function literalMcpServerName( node: AstNode, constants: ReadonlyMap, ): string | null { if (node.computed === true) { const literal = memberPropertyName(node) if (literal != null) return literal if (node.property) { return resolveStringExpression(node.property, constants) } return null } return memberPropertyName(node) } function mcpServerFromMember( node: AstNode, kodyAliases: Set, mcpAliases: McpAliasTable, constants: ReadonlyMap = new Map(), declaredMcpKeys: ReadonlySet = new Set(), ancestors: ReadonlyArray = [], ): string | null | undefined { if ( node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression' ) { return undefined } if (isKodyMcpRoot(node, kodyAliases, mcpAliases, ancestors)) { // Bare `kody.mcp` / `mcp` root — wait for a child member when present. return undefined } if ( node.object && isKodyMcpRoot(node.object, kodyAliases, mcpAliases, ancestors) ) { const server = literalMcpServerName(node, constants) // `kody.mcp?.[CANVA_MCP_NAME]` when CANVA_MCP_NAME = 'canva' at module // scope — same as credential("KEY") const folding. Dynamic → fail. return server } // Helpers like kasa's `cm.mcp?.['home']` on a function parameter: count a // literal server only when that slot is already declared kind "mcp". // Unrelated locals such as `settings.mcp.home` are ignored even if `home` // is declared. if ( node.object && isLooseDeclaredMcpRoot(node.object, kodyAliases, mcpAliases, ancestors) ) { const server = literalMcpServerName(node, constants) if (server != null && declaredMcpKeys.has(server)) return server return undefined } return undefined } /** * Infer a description for a stamp key from how the package uses it. Prefer * specific MCP / OAuth / signing wording; fall back to a factual use sentence * for other literal keys (never the empty "Describe what … is for." placeholder * the publish gate rejects). */ export function inferCredentialStampDescription(input: { key: string kind?: PackageCredentialSlotKind mcp?: boolean jwtSign?: boolean oauth?: boolean }): string { if (input.mcp || input.kind === 'mcp') { return `Calls tools on the attached MCP server "${input.key}".` } if (input.jwtSign || input.kind === 'signing') { return `Signs tokens with the "${input.key}" signing credential.` } if (input.oauth || input.kind === 'oauth') { return `OAuth access for ${input.key}.` } if (input.kind === 'login') { return `Login exchange for ${input.key}.` } if (input.kind === 'url') { return `URL credential for ${input.key}.` } return `Used by this package as credential "${input.key}".` } /** * Plan seal updates: add missing slots / descriptions where inferable, and * list blocking failures / uninferable keys that need an agent or owner. */ export async function planCredentialStampSeal( files: Record, ): Promise { const scanned = await scanCredentialStamp(files) const slots = readManifestCredentialSlots(files[packageManifestPath]) const mcpKeySet = new Set(scanned.mcpKeys) const jwtKeySet = new Set(scanned.jwtSignKeys) const oauthKeySet = new Set(scanned.oauthKeys) const updates: Array = [] const uninferableKeys: Array = [] const kindMismatches: Array = [] for (const key of scanned.keys) { const existing = slots[key] const inferredKind: PackageCredentialKind | undefined = mcpKeySet.has(key) ? 'mcp' : oauthKeySet.has(key) ? 'oauth' : // secretJwtSign resolves a Key/secret by name — do not force kind // "signing" (that is for credential(key).sign()). undefined if (existing?.description != null) { if ( inferredKind === 'mcp' && existing.kind != null && existing.kind !== 'mcp' ) { kindMismatches.push({ code: 'unstampable_pattern', message: `kody.credentials slot for an MCP server is declared with kind "${existing.kind}" instead of "mcp". Change the kind to "mcp" (or omit kind only for fetch-capable credentials that are not MCP servers).`, }) continue } if (inferredKind === 'mcp' && existing.kind == null) { updates.push({ key, description: existing.description, kind: 'mcp', }) } continue } const kind = existing?.kind ?? inferredKind updates.push({ key, description: inferCredentialStampDescription({ key, kind, mcp: mcpKeySet.has(key), jwtSign: jwtKeySet.has(key), oauth: oauthKeySet.has(key), }), ...(kind ? { kind } : {}), }) } const blockingFailures = [ ...scanned.failures.filter( (failure) => failure.code !== 'missing_description', ), ...kindMismatches, ] const sealReady = blockingFailures.length === 0 && scanned.keys.every((key) => { const existing = slots[key]?.description if (existing != null) return true return updates.some((update) => update.key === key) }) return { keys: scanned.keys, updates, uninferableKeys, blockingFailures, staleManifestKeys: scanned.staleManifestKeys, sealReady, } } /** * Apply {@link planCredentialStampSeal} updates into package.json without * overwriting existing descriptions. */ export function applyCredentialStampSealPlan( files: Record, plan: CredentialStampSealPlan, ): { files: Record; changed: boolean } { if (plan.updates.length === 0) { return { files, changed: false } } const source = files[packageManifestPath] if (source == null) return { files, changed: false } let parsed: unknown try { parsed = JSON.parse(source) } catch { return { files, changed: false } } if (!isPlainObject(parsed)) return { files, changed: false } const kody = isPlainObject(parsed.kody) ? { ...parsed.kody } : {} const existing = isPlainObject(kody.credentials) ? { ...kody.credentials } : {} let changed = false for (const update of plan.updates) { const prior = isPlainObject(existing[update.key]) ? { ...(existing[update.key] as Record) } : {} const priorDescription = typeof prior.description === 'string' && prior.description.trim().length > 0 ? prior.description.trim() : null const next: Record = { ...prior } let slotChanged = false if (priorDescription == null) { next.description = update.description slotChanged = true } if (update.kind && prior.kind == null) { next.kind = update.kind slotChanged = true } if (!slotChanged) continue existing[update.key] = next changed = true } if (!changed) return { files, changed: false } const indent = detectJsonIndent(source) const nextSource = `${JSON.stringify( { ...parsed, kody: { ...kody, credentials: existing } }, null, indent, )}\n` return { files: { ...files, [packageManifestPath]: nextSource }, changed: true, } } /** * What the module walks of a credential stamp scan found, before sealing. * Plain data with nothing derived across modules, so the results of walks * over disjoint sets of modules merge into the result for all of them. */ export type CredentialStampPasses = { scan: PackageCredentialScan /** Valid literal keys from credential helpers and named references. */ keys: Array oauthKeys: Array moduleFailures: Array mcp: { keys: Array; failures: Array } legacyFindings: Array serverEvalFailures: Array /** * What each parsed module's run-time-built credential names can be, for * checking them against hand-written `kody.credentials` slots. */ nameSummaries: Array<{ path: string; summary: StoredModuleNameSummary }> } /** * Walk the modules of `files` for a credential stamp. `files` must already * be without oversized client modules * ({@link omitOversizedClientCredentialStampModules}). * When the file map adopted a module plan, only that plan's modules are * walked; {@link mergeCredentialStampPasses} joins the parts. */ export async function collectCredentialStampPasses( files: Record, serverPaths: ReadonlySet, ): Promise { const keys = new Set() const oauthKeys = new Set() const slots = readManifestCredentialSlots(files[packageManifestPath]) const moduleFailures: Array = [] const nameSummaries: CredentialStampPasses['nameSummaries'] = [] // One parse of each module serves every scan below. const [scan, , , mcp, legacyFindings, serverEvalFailures] = await shareModulePasses(files, [ // Sites ride along so the publish check reads its request-placement // hits from this scan instead of walking every module again. () => scanPackageCredentials({ files, slots: toInventorySlots(slots), sites: true, }), () => scanModuleCredentialReferences(files, (_path) => ({ add: () => {}, named: (name, kind) => { if (packageCredentialSlotNamePattern.test(name)) { keys.add(name) if (kind === 'integration') oauthKeys.add(name) } }, // Non-literal helper args are refused via 0010 unstampable patterns. computed: () => {}, // Vault placeholders are gated from inventory placements below: only // request / credential-mapped sites fail the stamp. Display strings // (status example/help fields) are not credential uses. unnamed: () => {}, })), () => forEachScannableModule(files, async (path, parsed, constants) => { if (!parsed && serverPaths.has(path)) { const failure = await unparsedServerModuleFailure( path, files[path]!, ) if (failure) moduleFailures.push(failure) } const keyScan: KeyScan = { key: (key) => { if (packageCredentialSlotNamePattern.test(key)) keys.add(key) else { moduleFailures.push({ code: 'invalid_key', path, message: `${path}: credential("${key}") is not a valid kody.credentials key. Rename it.`, }) } }, computed: () => { moduleFailures.push({ code: 'non_literal', path, message: nonLiteralFixMessage( `${path}: credential() / credentials() / credential.visitor() was called with a non-literal key. Call it with a literal key, e.g. credential.visitor("SLOT") for a need each visitor supplies.`, ), }) }, named: () => { moduleFailures.push({ code: 'credential_named', path, message: `${path}: credential.named() is only for ad hoc execute and unshared personal-org packages (not stamped). ${credentialStampConversionFixGuidance}`, }) }, indirect: () => { moduleFailures.push({ code: 'non_literal', path, message: `${path}: passes credential/credentials around instead of calling it with a literal key. Call credential("SLOT"), credentials("SLOT"), or credential.visitor("SLOT") directly. Type-only uses are fine: for a client type, import type { KodyCredentialClient } from "kody:runtime" (or write typeof credential inside a type). ${credentialStampConversionFixGuidance}`, }) }, } if (parsed) scanParsedCredentialKeys(parsed, constants, keyScan) else scanUnparsedCredentialKeys(files[path]!, keyScan) }), () => scanLiteralMcpServerKeys(files, serverPaths), () => detectLegacyCredentialPatternsCodemod.detect(files, { packageName: '', }), () => scanServerEvalFailures(files, serverPaths), () => forEachScannableModule(files, (path, parsed, constants) => { if (!parsed) return const summary = summarizeModuleNames(parsed, constants) nameSummaries.push({ path, summary: storeModuleNameSummary(summary) }) }), ]) return { scan, keys: [...keys].sort(), oauthKeys: [...oauthKeys].sort(), moduleFailures, mcp, legacyFindings, serverEvalFailures, nameSummaries: nameSummaries.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0, ), } } function compareFailurePaths( left: CredentialStampGateFailure, right: CredentialStampGateFailure, ) { const leftPath = left.path ?? '' const rightPath = right.path ?? '' return leftPath < rightPath ? -1 : leftPath > rightPath ? 1 : 0 } /** * Join the 0010 findings of walks over disjoint module sets, given in sorted * module order. Every part reports the manifest findings; one of each stays. */ export function mergeLegacyCredentialFindings( parts: ReadonlyArray>, ): Array { const seen = new Set() const findings: Array = [] for (const finding of parts.flat()) { const key = JSON.stringify([finding.path ?? null, finding.message]) if (seen.has(key)) continue seen.add(key) findings.push(finding) } return findings.sort((left, right) => (left.path ?? '').localeCompare(right.path ?? ''), ) } /** * Join the passes of walks over disjoint module sets, given in sorted module * order, into what one walk over all of them returns. */ export function mergeCredentialStampPasses( parts: ReadonlyArray, ): CredentialStampPasses { return { scan: mergePackageCredentialScans(parts.map((part) => part.scan)), keys: [...new Set(parts.flatMap((part) => part.keys))].sort(), oauthKeys: [...new Set(parts.flatMap((part) => part.oauthKeys))].sort(), moduleFailures: parts.flatMap((part) => part.moduleFailures), mcp: { keys: [...new Set(parts.flatMap((part) => part.mcp.keys))].sort(), failures: dedupeFailures(parts.flatMap((part) => part.mcp.failures)), }, legacyFindings: mergeLegacyCredentialFindings( parts.map((part) => part.legacyFindings), ), serverEvalFailures: parts .flatMap((part) => part.serverEvalFailures) .sort(compareFailurePaths), nameSummaries: parts.flatMap((part) => part.nameSummaries), } } /** * Scan package source for stampable literal credential keys and publish-time * gate failures (non-literal uses, unstampable legacy patterns, server eval). * Remove when: #1909 phase 4 drops `package_kody_id_redirects`. */ export async function scanCredentialStamp( files: Record, options: { /** From {@link resolveSecretProviderSlots}; unresolved slots seal nothing. */ secretProviders?: ResolvedSecretProviderSlots } = {}, ): Promise { const serverPaths = await collectServerRuntimeModulePaths(files) files = omitOversizedClientCredentialStampModules(files, serverPaths) return sealCredentialStamp( files[packageManifestPath], await collectCredentialStampPasses(files, serverPaths), options, ) } /** * Turn the module passes of a whole tree into its stamp: the sorted keys and * the gate failures, checked against the manifest's `kody.credentials`. */ export function sealCredentialStamp( manifestSource: string | undefined, passes: CredentialStampPasses, options: { secretProviders?: ResolvedSecretProviderSlots } = {}, ): CredentialStampScan { const { scan, moduleFailures, mcp, legacyFindings, serverEvalFailures } = passes const keys = new Set(passes.keys) const oauthKeys = new Set(passes.oauthKeys) const failures: Array = [] const slots = readManifestCredentialSlots(manifestSource) for (const reference of scan.references) { // Package and session scopes are refused via the 0010 unstampable // pattern list. `|scope=user` is the caller's own secret by name. if (reference.scope != null && reference.scope !== 'user') continue if (packageCredentialSlotNamePattern.test(reference.name)) { keys.add(reference.name) if (reference.nameKind === 'integration') oauthKeys.add(reference.name) } else { failures.push({ code: 'invalid_key', message: `Credential name "${reference.name}" is not a valid kody.credentials key (letter, then letters/numbers/dots/underscores/hyphens; max 64). Rename it and use the new literal key.`, }) } } const jwtSignKeys: Array = [] for (const name of scan.jwtSignSecretNames) { if (packageCredentialSlotNamePattern.test(name)) { keys.add(name) jwtSignKeys.push(name) } else { failures.push({ code: 'invalid_key', message: `secretJwtSign name "${name}" is not a valid kody.credentials key. Rename it to a valid literal key and declare it with a description.`, }) } } if (scan.jwtSignCalls > scan.jwtSignSecretNames.length) { failures.push({ code: 'non_literal', message: nonLiteralFixMessage( 'secretJwtSign was called with a non-literal private_key_secret_name.', ), }) } // A vault use seals only through a described kind "secret-provider" slot // for its literal provider id. Refs stay governed by per-package grants. const providerSlots = secretProviderSlotKeysByProvider( slots, options.secretProviders, ) const undeclaredProviders = new Set() const vaultUses = scan.vaultUses.filter((use) => isVaultCredentialUsePlacement(use.placement), ) for (const use of vaultUses) { const provider = normalizeSecretProviderNeedId(use.provider) const slotKeys = providerSlots.get(provider) if (slotKeys) for (const key of slotKeys) keys.add(key) else undeclaredProviders.add(provider) } // Fail closed on a vault use the scanner read no provider id from. const unreadVaultUse = scan.vaultPlacements.filter(isVaultCredentialUsePlacement).length > vaultUses.length if (undeclaredProviders.size > 0 || unreadVaultUse) { failures.push({ code: 'unstampable_pattern', message: vaultPlaceholderFixMessage( [...undeclaredProviders].sort(), slots, options.secretProviders, ), }) } failures.push(...(options.secretProviders?.failures ?? [])) failures.push(...moduleFailures) for (const key of mcp.keys) keys.add(key) failures.push(...mcp.failures) const handWritten = checkRunTimeCredentialNames({ slots, passes, computedPaths: computedNamePaths(legacyFindings), }) for (const key of handWritten.keys) keys.add(key) failures.push(...handWritten.failures) for (const finding of legacyFindings) { const pattern = legacyCredentialPatternFromMessage(finding.message) if (pattern == null || !unstampableLegacyPatterns.has(pattern)) continue if (isComputedNamePattern(pattern)) continue failures.push({ code: 'unstampable_pattern', ...(finding.path ? { path: finding.path } : {}), message: `${finding.path ?? 'package'}: ${finding.message} This pattern cannot be sealed into the credential stamp, so publish fails. ${unstampablePatternFix(pattern)}`, }) } failures.push(...serverEvalFailures) const sortedKeys = [...keys].sort() const staleManifestKeys = Object.keys(slots) .filter((key) => !keys.has(key)) .sort() const missingDescriptions = sortedKeys.filter( (key) => slotDescription(slots, key) == null, ) if (missingDescriptions.length > 0) { failures.push({ code: 'missing_description', message: missingDescriptionMessage(missingDescriptions, slots), }) } return { keys: sortedKeys, failures: dedupeFailures(failures), staleManifestKeys, mcpKeys: mcp.keys, jwtSignKeys: [...jwtSignKeys].sort(), oauthKeys: [...oauthKeys].sort(), scan, legacyFindings, } } type ComputedNameKind = 'secret' | 'integration' function isComputedNamePattern(pattern: LegacyCredentialPattern) { return pattern === 'computed secret' || pattern === 'computed integration' } /** Modules that build a credential name at run time, with the kinds built. */ function computedNamePaths(findings: ReadonlyArray) { const paths = new Map>() for (const finding of findings) { const pattern = legacyCredentialPatternFromMessage(finding.message) if (pattern == null || !isComputedNamePattern(pattern)) continue const path = finding.path ?? 'package' const kinds = paths.get(path) ?? new Set() kinds.add(pattern === 'computed integration' ? 'integration' : 'secret') paths.set(path, kinds) } return paths } /** The slot kinds a name-filled use of each kind resolves through. */ const nameFillingSlotKinds: Record> = { secret: new Set(['secret']), integration: new Set(['oauth']), } type HandWrittenSlot = { key: string; prefix: boolean } /** * The hand-written slots that can fill a name of `kind`: described, a valid * key, no kind or the kind the name resolves to, and `prefix` only as * `true` on a kind it applies to. Others are reported as malformed. */ function nameFillingSlots( slots: Record, kind: ComputedNameKind, ) { const filling: Array = [] for (const [key, slot] of Object.entries(slots)) { if (slot.description == null) continue if (!packageCredentialSlotNamePattern.test(key)) continue if (slot.kind != null && !nameFillingSlotKinds[kind].has(slot.kind)) continue if (slot.prefix !== undefined && slot.prefix !== true) continue filling.push({ key, prefix: slot.prefix === true }) } return filling } function malformedSlotFailures(slots: Record) { const failures: Array = [] const prefixKinds: ReadonlyArray = credentialSlotPrefixKindValues for (const [key, slot] of Object.entries(slots)) { if (slot.prefix === undefined) continue if (slot.prefix !== true) { failures.push({ code: 'invalid_key', message: `kody.credentials "${key}" sets prefix to something other than true. Write "prefix": true to cover "${key}-" names, or remove it.`, }) } else if (slot.kind != null && !prefixKinds.includes(slot.kind)) { failures.push({ code: 'invalid_key', message: `kody.credentials "${key}" sets prefix: true with kind "${slot.kind}". prefix applies only to a slot with no kind, or kind "secret" or "oauth".`, }) } } return failures } /** The slot that covers `name` the way the run-time check does, if any. */ function coveringSlot(name: string, slots: ReadonlyArray) { const exact = slots.find((slot) => slot.key === name) if (exact) return exact let covering: HandWrittenSlot | null = null for (const slot of slots) { if (!slot.prefix || !credentialSlotPrefixCoversName(slot.key, name)) { continue } if (!covering || slot.key.length > covering.key.length) covering = slot } return covering } /** A prefix slot covering every `-` name. */ function coveringPrefixSlot( head: string, slots: ReadonlyArray, ) { return ( slots.find((slot) => slot.prefix && slot.key === head) ?? coveringSlot( head, slots.filter((slot) => slot.prefix && slot.key !== head), ) ) } /** * Check each credential name a module builds at run time against the * hand-written `kody.credentials` slots. Every name the source says it can * be (literal defaults, `-` conventions) must match a slot's * key, or a `prefix: true` slot's `-` prefix. A name its callers pass * in is checked the same way when it is used: an undeclared name is refused * at run time. */ function checkRunTimeCredentialNames(input: { slots: Record passes: CredentialStampPasses computedPaths: ReadonlyMap> }) { const { slots, passes, computedPaths } = input const keys = new Set() const failures = malformedSlotFailures(slots) if (computedPaths.size === 0) return { keys, failures } const summaries = new Map( passes.nameSummaries.map(({ path, summary }) => [ path, loadModuleNameSummary(summary), ]), ) for (const [path, kinds] of computedPaths) { for (const kind of kinds) { const filling = nameFillingSlots(slots, kind) const uncoveredExact = new Set() const uncoveredPrefix = new Set() for (const site of summaries.get(path)?.sites ?? []) { if (site.kind !== kind) continue const inferred = inferCredentialNames(site.value, path, summaries) for (const name of inferred.exact) { const slot = coveringSlot(name, filling) if (slot) keys.add(slot.key) else uncoveredExact.add(name) } for (const head of inferred.prefix) { const slot = coveringPrefixSlot(head, filling) if (slot) keys.add(slot.key) else uncoveredPrefix.add(head) } } if (filling.length === 0) { failures.push({ code: 'unstampable_pattern', path, message: `${path}: builds ${kind === 'integration' ? 'an integration' : 'a secret'} name at run time, and kody.credentials declares no slot it can match. ${runTimeNameFixGuidance}`, }) continue } if (uncoveredExact.size + uncoveredPrefix.size > 0) { const names = [ ...[...uncoveredExact].sort().map((name) => `"${name}"`), ...[...uncoveredPrefix].sort().map((head) => `"${head}-"`), ] failures.push({ code: 'unstampable_pattern', path, message: `${path}: builds ${kind === 'integration' ? 'an integration' : 'a secret'} name at run time that can be ${names.join(', ')}, and no kody.credentials slot matches ${names.length === 1 ? 'it' : 'them'}. ${runTimeNameFixGuidance}`, }) continue } // Names its callers pass are checked against these slots at run time. for (const slot of filling) keys.add(slot.key) } } return { keys, failures } } /** * Slot keys by the provider id their package declares. Only slots that are * described secret-provider slots in this manifest and that resolved count. */ function secretProviderSlotKeysByProvider( slots: Record, resolved: ResolvedSecretProviderSlots | undefined, ) { const byProvider = new Map>() for (const [key, slot] of Object.entries(slots)) { if (slot.kind !== secretProviderSlotKind || slot.description == null) { continue } if (!packageCredentialSlotNamePattern.test(key)) continue const provider = resolved?.ids[key] if (provider == null) continue byProvider.set(provider, [...(byProvider.get(provider) ?? []), key]) } return byProvider } function vaultPlaceholderFixMessage( providers: ReadonlyArray, slots: Record, resolved: ResolvedSecretProviderSlots | undefined, ) { const which = providers.length > 0 ? ` for provider id${providers.length === 1 ? '' : 's'} ${providers.map((id) => `"${id}"`).join(', ')}` : '' const declared = Object.entries(slots) .filter(([, slot]) => slot.kind === secretProviderSlotKind) .map(([key, slot]) => { const id = resolved?.ids[key] return `${key} (package "${slot.package ?? ''}"${id ? `, provider id "${id}"` : ', unresolved'})` }) const declaredNote = declared.length > 0 ? ` Declared secret-provider slots: ${declared.join('; ')}.` : '' return `A vault placeholder {{secret/provider:ref}}${which} appears in a request or credential-mapped site (fetch URL, header, query, path, body, signing key, SDK option, call argument, or an object, array, or helper return that can feed one) and no declared provider package serves that provider id.${declaredNote} Declare a kody.credentials slot with kind "secret-provider" that names the saved provider package whose kody.secretProvider.id matches, for example:\n\n"kody": {\n "credentials": {\n ${secretProviderSlotExample()}\n }\n}\n\nThe placeholder's provider id must be literal. Each ref still needs a per-package grant on the secret-providers page (resourceLock kind "secret_provider"). Placeholders only in values returned from status(), help(), docs(), or usage() are display text and do not block the stamp.` } function unstampablePatternFix(pattern: LegacyCredentialPattern): string { switch (pattern) { case 'computed secret': case 'computed integration': return runTimeNameFixGuidance case '|scope=': return `Remove |scope=package and |scope=session (and any helper scope option); |scope=user is fine. Prefer a declared kody.credentials need filled by an org Key or by a Key bound to this same package (package Keys fill that package's needs when the name matches or they are the only match). ${credentialStampConversionFixGuidance}` case 'secretMounts': return `Keep kody.secretMounts entries that stale static dependents still read (check static_dependents). Delete a mount only once no stale dependent reads it. Removing a mount or deleting its secret breaks those dependents. New code uses a kody.credentials slot, not packageSecrets.get. ${credentialStampConversionFixGuidance}` case 'packageSecrets.get': return `Replace packageSecrets.get with credential("SLOT") or {{secret:SLOT}}. ${credentialStampConversionFixGuidance}` case 'plain http': return 'Use https:// for any request that carries a credential placeholder.' case 'kody.mcp': case 'literal secret': case 'webhook secretName': return `Declare the name as a fixed kody.credentials slot with a description, and keep the call site literal. Callers pick among credentials with the execute credentials call map or a stored/trigger mapping.` default: { const exhaustive: never = pattern return `Unhandled pattern: ${String(exhaustive)}` } } } function missingDescriptionMessage( missing: ReadonlyArray, slots: Record, ) { const example = Object.fromEntries( missing.map((name) => { const existing = slots[name] return [ name, { ...(existing?.kind ? { kind: existing.kind } : {}), ...(existing?.provider ? { provider: existing.provider } : {}), description: `Describe what ${name} is for.`, }, ] }), ) return `Credential stamp keys missing a description in kody.credentials: ${missing.join(', ')}. Placeholder descriptions are not allowed — write what each credential is for in package.json, then publish again. Example:\n\n"kody": {\n "credentials": ${JSON.stringify(example, null, 2).replace(/\n/g, '\n ')}\n}\n\nPublish seals every stamped key into kody.credentials and never overwrites a description you already wrote.` } function dedupeFailures(failures: Array) { const seen = new Set() const out: Array = [] for (const failure of failures) { const id = `${failure.code}:${failure.path ?? ''}:${failure.message}` if (seen.has(id)) continue seen.add(id) out.push(failure) } return out } /** * Add stamp keys missing from `kody.credentials` without touching existing * descriptions. New keys are inserted without a description so the publish * gate can require a real one (no placeholders). */ export function mergeCredentialStampIntoManifestFiles( files: Record, keys: ReadonlyArray, ): { files: Record; addedKeys: Array } { const source = files[packageManifestPath] if (source == null || keys.length === 0) { return { files, addedKeys: [] } } let parsed: unknown try { parsed = JSON.parse(source) } catch { return { files, addedKeys: [] } } if (!isPlainObject(parsed)) return { files, addedKeys: [] } const kody = isPlainObject(parsed.kody) ? { ...parsed.kody } : {} const existing = isPlainObject(kody.credentials) ? { ...kody.credentials } : {} const addedKeys: Array = [] for (const key of keys) { if (Object.hasOwn(existing, key)) continue existing[key] = {} addedKeys.push(key) } if (addedKeys.length === 0) return { files, addedKeys: [] } const indent = detectJsonIndent(source) const next = `${JSON.stringify( { ...parsed, kody: { ...kody, credentials: existing } }, null, indent, )}\n` return { files: { ...files, [packageManifestPath]: next }, addedKeys, } } function detectJsonIndent(source: string) { const match = source.match(/\n([ \t]+)"/) return match?.[1] ?? '\t' } /** Content hash over sorted keys and dependency stamp pins. */ export async function computeCredentialStampHash(input: { keys: ReadonlyArray depStamps: ReadonlyArray }): Promise { const payload = { keys: [...input.keys].sort(), depStamps: [...input.depStamps] .map((dep) => ({ packageId: dep.packageId, publishedCommit: dep.publishedCommit, stampHash: dep.stampHash, })) .sort((left, right) => left.packageId.localeCompare(right.packageId)), } return sha256Hex(canonicalJsonStringify(payload)) } export async function buildCredentialStamp(input: { keys: ReadonlyArray depStamps?: ReadonlyArray }): Promise { const keys = [...input.keys].sort() const depStamps = [...(input.depStamps ?? [])].sort((left, right) => left.packageId.localeCompare(right.packageId), ) const stampHash = await computeCredentialStampHash({ keys, depStamps }) return { version: credentialStampVersion, keys, depStamps, stampHash, } }