@tinycloud/mcp 0.8.4-beta.6 → 0.8.4-beta.7

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/server.ts","../src/tools.ts","../src/results.ts","../src/logging.ts","../src/schemas.ts","../package.json","../src/version.ts","../src/http.ts","../src/oauth.ts","../src/token-status.ts","../src/remote-store.ts","../src/native-auth.ts"],"sourcesContent":["import { basename } from \"node:path\";\n\nimport { resolveInvocationProfileName } from \"@tinycloud/operations/profile\";\n\nimport { serveTinyCloudMcp, MCP_VERSION } from \"./server.js\";\n\nexport interface ParsedCliOptions {\n readonly profile?: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n readonly help: boolean;\n readonly version: boolean;\n}\n\nconst HELP = `TinyCloud delegated operations MCP server\n\nUsage: tinycloud-mcp [options]\n\nOptions:\n --profile <name> Pin the TinyCloud profile for this process\n --allow-owner-profile Allow data execution for an explicitly selected owner profile\n --help Show this help\n --version Show the package version\n`;\n\nexport function parseCliOptions(arguments_: readonly string[]): ParsedCliOptions {\n let profile: string | undefined;\n let explicitProfile = false;\n let allowOwnerProfile = false;\n let help = false;\n let version = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === \"--help\" || argument === \"-h\") {\n help = true;\n continue;\n }\n if (argument === \"--version\" || argument === \"-v\") {\n version = true;\n continue;\n }\n if (argument === \"--allow-owner-profile\") {\n allowOwnerProfile = true;\n continue;\n }\n if (argument === \"--profile\") {\n const value = arguments_[index + 1];\n if (value === undefined || value.startsWith(\"-\") || value.trim().length === 0) {\n throw new Error(\"--profile requires a non-empty profile name.\");\n }\n profile = value;\n explicitProfile = true;\n index += 1;\n continue;\n }\n if (argument?.startsWith(\"--profile=\")) {\n const value = argument.slice(\"--profile=\".length);\n if (value.trim().length === 0) throw new Error(\"--profile requires a non-empty profile name.\");\n profile = value;\n explicitProfile = true;\n continue;\n }\n throw new Error(`Unknown option: ${argument}`);\n }\n\n return { profile, explicitProfile, allowOwnerProfile, help, version };\n}\n\nexport async function main(arguments_: readonly string[] = process.argv.slice(2)): Promise<number> {\n let options: ParsedCliOptions;\n try {\n options = parseCliOptions(arguments_);\n } catch (error) {\n process.stderr.write(\"[tinycloud-mcp] Invalid command line.\\n\");\n return 2;\n }\n\n if (options.help) {\n process.stdout.write(HELP);\n return 0;\n }\n if (options.version) {\n process.stdout.write(`${MCP_VERSION}\\n`);\n return 0;\n }\n\n let profile: string;\n try {\n profile = await resolveInvocationProfileName(options.profile);\n } catch {\n process.stderr.write(\"[tinycloud-mcp] Could not select a profile.\\n\");\n return 2;\n }\n\n // The selected profile is now a value captured by the server closure. Every\n // operation receives it explicitly and cannot re-read TC_PROFILE/config.\n serveTinyCloudMcp({\n profile,\n explicitProfile: options.explicitProfile,\n allowOwnerProfile: options.allowOwnerProfile,\n });\n return 0;\n}\n\nfunction isDirectInvocation(): boolean {\n const argv = process.argv[1];\n if (argv === undefined) return false;\n return basename(argv) === \"cli.js\" || basename(argv) === \"cli.cjs\" || basename(argv) === \"tinycloud-mcp\";\n}\n\nif (isDirectInvocation()) {\n void main().then((code) => {\n if (code !== 0) process.exitCode = code;\n }).catch(() => {\n process.stderr.write(\"[tinycloud-mcp] Startup failed.\\n\");\n process.exitCode = 1;\n });\n}\n","import { McpServer } from \"@modelcontextprotocol/server\";\nimport { serveStdio, type StdioServerHandle } from \"@modelcontextprotocol/server/stdio\";\n\nimport { createJsonSchemaValidator, registerTinyCloudTools, type McpStartupSelection } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nexport const MCP_SERVER_NAME = \"tinycloud-mcp\";\nexport { MCP_VERSION } from \"./version.js\";\n/** The stdio server is always the local surface. */\nexport type LocalMcpSelection = Omit<McpStartupSelection, \"surface\">;\n\nexport function createTinyCloudMcpServer(selection: LocalMcpSelection): McpServer {\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n { jsonSchemaValidator: validator },\n );\n registerTinyCloudTools(server, { ...selection, surface: \"local\" }, validator);\n return server;\n}\n\n/** Start the only supported MCP transport: local stdio. */\nexport function serveTinyCloudMcp(selection: LocalMcpSelection): StdioServerHandle {\n return serveStdio(\n () => createTinyCloudMcpServer(selection),\n { onerror: () => writeBoundedDiagnostic(\"MCP transport error\") },\n );\n}\n\nfunction writeBoundedDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp] ${message}\\n`);\n}\n","import { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { fromJsonSchema, type McpServer, type ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport { AjvJsonSchemaValidator } from \"@modelcontextprotocol/server/validators/ajv\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nimport { toMcpToolResult, type McpToolResult } from \"./results.js\";\nimport { logToolCall } from \"./logging.js\";\nimport { toMcpJsonSchema } from \"./schemas.js\";\n\nexport const TOOL_NAMES = [\n \"tinycloud_status\",\n \"tinycloud_auth_status\",\n \"tinycloud_auth_capabilities\",\n \"tinycloud_auth_request\",\n \"tinycloud_auth_import\",\n \"tinycloud_account_spaces_list\",\n \"tinycloud_account_applications_list\",\n \"tinycloud_kv_list\",\n \"tinycloud_kv_get\",\n \"tinycloud_kv_head\",\n \"tinycloud_kv_put\",\n \"tinycloud_kv_delete\",\n \"tinycloud_knowledge_list\",\n \"tinycloud_knowledge_read\",\n \"tinycloud_sql_schema_inspect\",\n \"tinycloud_sql_query\",\n \"tinycloud_sql_execute\",\n \"tinycloud_secrets_get\",\n \"tinycloud_secrets_status\",\n \"tinycloud_apps_context\",\n \"tinycloud_apps_read\",\n \"tinycloud_apps_write\",\n \"tinycloud_apps_query\",\n] as const;\n\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\n/** Private stdio/hosted surfaces and the restricted public plugin. */\nexport type McpSurface = \"local\" | \"hosted\" | \"public\";\n\nexport interface McpStartupSelection {\n /** Which server registers the tools; bindings not on this surface are skipped. */\n readonly surface: McpSurface;\n readonly profile: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n /** Absolute TinyCloud home used to isolate one hosted principal. */\n readonly stateRoot?: string;\n /** Optional allowlist for surfaces whose grant is narrower than hosted OAuth. */\n readonly allowedTools?: readonly ToolName[];\n /** Check node authority only when an operation needs the account. */\n readonly beforeOperation?: () => Promise<void>;\n /** Hosted transports may attach a browser approval URL to canonical results. */\n readonly transformOperationResult?: (result: unknown, invocation: McpOperationInvocation) => Promise<unknown>;\n}\n\nexport interface McpOperationInvocation {\n readonly operationId: string;\n readonly operationVersion: number;\n readonly input: unknown;\n}\n\nexport interface McpInvocationTarget {\n readonly profile: string;\n readonly allowOwnerProfile?: true;\n readonly stateRoot?: string;\n}\n\n/** Project one startup selection into the only owner-sensitive target shape. */\nexport function invocationTargetForMcp(\n selection: Omit<McpStartupSelection, \"surface\">,\n): McpInvocationTarget {\n return {\n profile: selection.profile,\n ...(selection.explicitProfile && selection.allowOwnerProfile\n ? { allowOwnerProfile: true }\n : {}),\n ...(selection.stateRoot === undefined ? {} : { stateRoot: selection.stateRoot }),\n };\n}\n\ninterface CatalogOperation {\n readonly id: string;\n readonly version: number;\n readonly title: string;\n readonly description: string;\n readonly input: Record<string, unknown>;\n readonly result: Record<string, unknown>;\n}\n\ninterface OperationsCatalog {\n readonly stableErrors: readonly string[];\n readonly operations: readonly CatalogOperation[];\n}\n\n// The require anchor is this module, never the consumer entrypoint. In ESM\n// tsup preserves import.meta.url; in CJS it rewrites the same module-relative\n// anchor to the generated __filename, so both formats stay in MCP's package\n// dependency boundary.\nconst packageRequire = createRequire(\n typeof __dirname === \"string\" ? join(__dirname, \"tools.cjs\") : import.meta.url,\n);\nconst generatedCatalog = packageRequire(\n \"@tinycloud/operations/operations.json\",\n) as OperationsCatalog;\nconst stableErrorCodes: Readonly<Record<string, true>> = Object.fromEntries(\n generatedCatalog.stableErrors.map((code) => [code, true as const]),\n);\n\nexport interface ToolBinding {\n readonly name: ToolName;\n readonly operationId: string;\n readonly operationVersion: number;\n readonly readOnlyHint: boolean;\n readonly idempotentHint: boolean;\n readonly destructiveHint: boolean;\n readonly openWorldHint: boolean;\n /** Surfaces that register this tool; omitted means private local and hosted surfaces only. */\n readonly surfaces?: readonly McpSurface[];\n}\n\nconst PRIVATE_SURFACES: readonly McpSurface[] = [\"local\", \"hosted\"];\n\n/** The surfaces a binding is registered on. */\nexport function bindingSurfaces(binding: ToolBinding): readonly McpSurface[] {\n return binding.surfaces ?? PRIVATE_SURFACES;\n}\n\nexport const TOOL_BINDINGS: readonly ToolBinding[] = [\n {\n name: \"tinycloud_status\",\n operationId: \"tinycloud.status.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_status\",\n operationId: \"tinycloud.auth.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_capabilities\",\n operationId: \"tinycloud.auth.capabilities\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_request\",\n operationId: \"tinycloud.auth.request\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_import\",\n operationId: \"tinycloud.auth.import\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n // Hosted delegations must arrive through the owner/request-bound OpenKey callback,\n // not a caller-supplied import artifact.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_account_spaces_list\",\n operationId: \"tinycloud.account.spaces.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_account_applications_list\",\n operationId: \"tinycloud.account.applications.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_list\",\n operationId: \"tinycloud.kv.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_get\",\n operationId: \"tinycloud.kv.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_head\",\n operationId: \"tinycloud.kv.head\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_put\",\n operationId: \"tinycloud.kv.put\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_delete\",\n operationId: \"tinycloud.kv.delete\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_knowledge_list\",\n operationId: \"tinycloud.knowledge.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_knowledge_read\",\n operationId: \"tinycloud.knowledge.read\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_schema_inspect\",\n operationId: \"tinycloud.sql.schema.inspect\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_query\",\n operationId: \"tinycloud.sql.query\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_execute\",\n operationId: \"tinycloud.sql.execute\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_get\",\n operationId: \"tinycloud.secrets.get\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_status\",\n operationId: \"tinycloud.secrets.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n // Hosted has no persistent reauthorization path for a revoked session\n // yet (TC-896), so status is local/stdio only.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_apps_context\",\n operationId: \"tinycloud.apps.context\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_read\",\n operationId: \"tinycloud.apps.read\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_write\",\n operationId: \"tinycloud.apps.write\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_query\",\n operationId: \"tinycloud.apps.query\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n] as const;\n\n// Project once per process; never mutate the catalog shared with non-MCP consumers.\nconst definitions = new Map(generatedCatalog.operations.map((operation) => [\n `${operation.id}@${operation.version}`,\n {\n ...operation,\n input: toMcpJsonSchema(operation.input),\n result: toMcpJsonSchema(operation.result),\n },\n]));\n\nexport function createJsonSchemaValidator(): AjvJsonSchemaValidator {\n return new AjvJsonSchemaValidator();\n}\n\nexport function registerTinyCloudTools(\n server: McpServer,\n selection: McpStartupSelection,\n validator: AjvJsonSchemaValidator,\n): void {\n const bindings = TOOL_BINDINGS.filter((binding) =>\n bindingSurfaces(binding).includes(selection.surface) &&\n (selection.allowedTools === undefined || selection.allowedTools.includes(binding.name)));\n for (const binding of bindings) {\n const operation = definitions.get(`${binding.operationId}@${binding.operationVersion}`);\n if (operation === undefined) {\n throw new Error(`Generated operations catalog is missing ${binding.operationId}@${binding.operationVersion}.`);\n }\n\n const inputSchema = fromJsonSchema(\n operation.input as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const outputSchema = fromJsonSchema(\n operation.result as unknown as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const annotations: ToolAnnotations = {\n readOnlyHint: binding.readOnlyHint,\n idempotentHint: binding.idempotentHint,\n destructiveHint: binding.destructiveHint,\n openWorldHint: binding.openWorldHint,\n };\n\n server.registerTool(\n binding.name,\n {\n title: operation.title,\n description: operation.description,\n inputSchema,\n outputSchema,\n annotations,\n },\n async (input: unknown): Promise<McpToolResult> => {\n const startedAt = performance.now();\n const metrics = { replayedGrants: 0 };\n let code = \"INTERNAL_ERROR\";\n try {\n await selection.beforeOperation?.();\n const result = await invokeOperation(\n binding.operationId,\n binding.operationVersion,\n invocationTargetForMcp(selection),\n input,\n metrics,\n );\n const projected = selection.transformOperationResult === undefined\n ? result\n : await selection.transformOperationResult(result, {\n operationId: binding.operationId,\n operationVersion: binding.operationVersion,\n input,\n });\n const response = toMcpToolResult(projected, bindings, {\n surface: selection.surface === \"local\" ? \"local\" : \"hosted\",\n readOnly: binding.readOnlyHint,\n operationId: binding.operationId,\n });\n code = outcomeCode(response.structuredContent);\n return response;\n } finally {\n if (selection.surface !== \"local\") {\n logToolCall(binding.name, code, startedAt, metrics.replayedGrants);\n }\n }\n },\n );\n }\n}\n\nfunction outcomeCode(result: McpToolResult[\"structuredContent\"]): string {\n if (result.status === \"error\") {\n const error = result.error as { code?: unknown } | undefined;\n return typeof error?.code === \"string\" && Object.hasOwn(stableErrorCodes, error.code) ? error.code : \"INTERNAL_ERROR\";\n }\n if (result.status !== \"ok\") return result.status;\n const output = result.output as { outcome?: unknown; ops?: readonly { outcome?: unknown }[] } | undefined;\n if (output?.outcome === \"COPY_PARTIAL\") return \"COPY_PARTIAL\";\n if (Array.isArray(output?.ops) && output.ops.some((op) => op.outcome !== \"ok\")) return \"PARTIAL\";\n return \"ok\";\n}\n\nexport function toolBindingsForTest(): readonly ToolBinding[] {\n return TOOL_BINDINGS;\n}\n","/** MCP preserves the canonical envelope; hosted clients also receive readable JSON. */\nexport interface CanonicalOperationResult {\n readonly status: \"ok\" | \"authority_required\" | \"setup_required\" | \"error\";\n readonly [key: string]: unknown;\n}\n\nexport interface McpToolResult extends CallToolResult {\n readonly content: [{ readonly type: \"text\"; readonly text: string }];\n readonly structuredContent: CanonicalOperationResult;\n}\n\n/** The binding fields needed to name the tool that runs an operation. */\nexport interface RecoveryToolBinding {\n readonly name: string;\n readonly operationId: string;\n}\n\nexport interface McpToolResultOptions {\n readonly surface?: \"hosted\" | \"local\";\n readonly readOnly?: boolean;\n /** Trusted operation identity from the tool binding, not operation output. */\n readonly operationId?: string;\n}\n\nexport function toMcpToolResult(\n result: unknown,\n bindings: readonly RecoveryToolBinding[] = [],\n options: McpToolResultOptions = {},\n): McpToolResult {\n let canonical: CanonicalOperationResult = isCanonicalOperationResult(result)\n ? withRecoveryTool(result, bindings)\n : {\n status: \"error\",\n operation: {},\n context: {},\n error: { code: \"INTERNAL_ERROR\" },\n };\n let serialized: string | undefined;\n if (options.surface === \"hosted\") {\n serialized = JSON.stringify(canonical);\n if (\n (options.readOnly === true ||\n options.operationId === \"tinycloud.apps.context\" ||\n options.operationId === \"tinycloud.apps.query\") &&\n serialized.length > 100_000\n ) {\n const sql = options.operationId?.startsWith(\"tinycloud.sql.\") ||\n options.operationId === \"tinycloud.apps.query\";\n canonical = {\n status: \"error\",\n operation: canonical.operation,\n context: canonical.context,\n error: {\n code: sql ? \"SQL_RESULT_LIMIT_EXCEEDED\" : \"KV_RESPONSE_TOO_LARGE\",\n message: sql\n ? \"The result exceeds 100,000 characters. Select fewer columns or rows, add a WHERE filter or a smaller LIMIT, or aggregate the data.\"\n : \"The result exceeds 100,000 characters. Request fewer keys, narrow the prefix, or use a smaller page size.\",\n retryable: false,\n },\n };\n serialized = JSON.stringify(canonical);\n }\n }\n\n return {\n content: [{\n type: \"text\",\n text: resultSummary(canonical.status) +\n (serialized !== undefined && !(options.operationId === \"tinycloud.secrets.get\" && canonical.status === \"ok\")\n ? `\\n${serialized}` : \"\"),\n }],\n structuredContent: canonical,\n };\n}\n\n/**\n * A redacted `complete_migration` recovery names an operation; MCP clients\n * call tools, so name the bound tool. `tool` comes from the code-owned binding\n * table only, never from operation data, and is added after redaction. An\n * operationId with no binding gets no `tool`.\n */\nfunction withRecoveryTool(\n result: CanonicalOperationResult,\n bindings: readonly RecoveryToolBinding[],\n): CanonicalOperationResult {\n if (result.status !== \"error\") return result;\n // The kernel's redaction already constrained `error.details.recovery` to a\n // safe recovery object; only its discriminant and operationId are read here.\n const error = result.error as\n | { readonly details?: { readonly recovery?: { readonly action?: unknown; readonly operationId?: unknown } } }\n | undefined;\n const recovery = error?.details?.recovery;\n if (recovery?.action !== \"complete_migration\") return result;\n const binding = bindings.find((candidate) => candidate.operationId === recovery.operationId);\n if (binding === undefined) return result;\n return {\n ...result,\n error: { ...error, details: { ...error?.details, recovery: { ...recovery, tool: binding.name } } },\n };\n}\n\n/** The canonical envelope immediately before MCP protocol serialization. */\nexport function canonicalMcpAdapterResult(result: unknown): CanonicalOperationResult {\n return toMcpToolResult(result).structuredContent;\n}\n\nfunction isCanonicalOperationResult(value: unknown): value is CanonicalOperationResult {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const status = (value as { status?: unknown }).status;\n return status === \"ok\" ||\n status === \"authority_required\" ||\n status === \"setup_required\" ||\n status === \"error\";\n}\n\nfunction resultSummary(status: CanonicalOperationResult[\"status\"]): string {\n switch (status) {\n case \"ok\":\n return \"TinyCloud operation completed; use the structured result.\";\n case \"authority_required\":\n return \"TinyCloud authority is required; use the structured request and approval action.\";\n case \"setup_required\":\n return \"TinyCloud setup is required; use the structured setup action.\";\n case \"error\":\n return \"TinyCloud operation failed; use the structured error.\";\n }\n}\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n","/** Only code-owned tool names/codes and numeric counters reach this sink. */\nexport function logToolCall(\n tool: string,\n code: string,\n startedAt: number,\n replayedGrants: number,\n): void {\n process.stderr.write(`${JSON.stringify({\n tool,\n code,\n durationMs: Math.max(0, Math.round(performance.now() - startedAt)),\n replayedGrants,\n })}\\n`);\n}\n","type JsonSchema = boolean | Record<string, unknown>;\n\nconst DRAFT_7 = \"http://json-schema.org/draft-07/schema#\";\nconst DRAFT_2020_12 = \"https://json-schema.org/draft/2020-12/schema\";\nconst schemaMaps = new Set([\"properties\", \"patternProperties\", \"definitions\", \"$defs\"]);\nconst schemaArrays = new Set([\"allOf\", \"anyOf\", \"oneOf\"]);\nconst schemaValues = new Set([\n \"additionalProperties\", \"items\", \"contains\", \"propertyNames\", \"not\", \"if\", \"then\", \"else\",\n]);\n\n/** Project the catalog's shared Draft-07/2020-12 vocabulary without changing its validation rules. */\nexport function toMcpJsonSchema(schema: Record<string, unknown>): Record<string, unknown>;\nexport function toMcpJsonSchema(schema: JsonSchema): JsonSchema;\nexport function toMcpJsonSchema(schema: JsonSchema): JsonSchema {\n if (typeof schema === \"boolean\") return schema;\n // These forms need a semantic migration, not just a dialect declaration. The\n // generated catalog does not use them; fail closed if that contract changes.\n if (Array.isArray(schema.items) || \"additionalItems\" in schema || \"dependencies\" in schema ||\n (\"$ref\" in schema && Object.keys(schema).some((key) => key !== \"$ref\"))) {\n throw new Error(\"The operations schema needs a semantic migration to JSON Schema 2020-12.\");\n }\n\n const projected: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === \"$schema\") {\n if (value !== DRAFT_7) throw new Error(`Unsupported operations schema dialect: ${String(value)}.`);\n projected[key] = DRAFT_2020_12;\n } else if (schemaMaps.has(key)) {\n projected[key] = Object.fromEntries(Object.entries(value as Record<string, JsonSchema>)\n .map(([name, child]) => [name, toMcpJsonSchema(child)]));\n } else if (schemaArrays.has(key)) {\n projected[key] = (value as JsonSchema[]).map(toMcpJsonSchema);\n } else if (schemaValues.has(key)) {\n projected[key] = toMcpJsonSchema(value as JsonSchema);\n } else {\n // Descriptions, defaults, examples and const/enum values are data, not schemas.\n projected[key] = value;\n }\n }\n return projected;\n}\n","{\n \"name\": \"@tinycloud/mcp\",\n \"version\": \"0.8.4-beta.6\",\n \"description\": \"TinyCloud delegated operations MCP server\",\n \"keywords\": [\n \"tinycloud\",\n \"mcp\",\n \"model-context-protocol\",\n \"agents\",\n \"delegation\",\n \"ucan\",\n \"kv\",\n \"sqlite\"\n ],\n \"author\": \"TinyCloud, Inc.\",\n \"license\": \"EGPL\",\n \"type\": \"module\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"tinycloud-mcp\": \"./bin/tinycloud-mcp\",\n \"tinycloud-mcp-http\": \"./bin/tinycloud-mcp-http\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./server\": {\n \"types\": \"./dist/server.d.ts\",\n \"import\": \"./dist/server.js\",\n \"require\": \"./dist/server.cjs\"\n },\n \"./tools\": {\n \"types\": \"./dist/tools.d.ts\",\n \"import\": \"./dist/tools.js\",\n \"require\": \"./dist/tools.cjs\"\n },\n \"./results\": {\n \"types\": \"./dist/results.d.ts\",\n \"import\": \"./dist/results.js\",\n \"require\": \"./dist/results.cjs\"\n },\n \"./http\": {\n \"types\": \"./dist/http.d.ts\",\n \"import\": \"./dist/http.js\",\n \"require\": \"./dist/http.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"bin\",\n \"generated\",\n \"skills\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"test\": \"bun run build && bun scripts/test.ts && bun run check:generated\",\n \"test:stdio\": \"bun run build && bun test src/stdio.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"start:http\": \"node dist/http-cli.js\",\n \"generate\": \"bun scripts/generate.ts\",\n \"check:generated\": \"bun scripts/generate.ts --check\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/node\": \"2.0.0-beta.5\",\n \"@modelcontextprotocol/server\": \"2.0.0-beta.5\",\n \"@tinycloud/node-sdk\": \"3.9.0-beta.6\",\n \"@tinycloud/node-sdk-wasm\": \"1.7.8\",\n \"@tinycloud/operations\": \"0.7.8-beta.6\",\n \"jose\": \"6.2.4\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"2.0.0-beta.5\",\n \"@types/node\": \"^20\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"^5.9.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/TinyCloudLabs/js-sdk\"\n },\n \"homepage\": \"https://docs.tinycloud.xyz/cli/mcp\"\n}\n","import packageMetadata from \"../package.json\";\n\nexport const MCP_VERSION = packageMetadata.version;\n","import { join } from \"node:path\";\n\nimport {\n McpServer,\n createMcpHandler,\n fromJsonSchema,\n getOAuthProtectedResourceMetadataUrl,\n hostHeaderValidationResponse,\n oauthMetadataResponse,\n requireBearerAuth,\n type AuthInfo,\n type OAuthMetadata,\n} from \"@modelcontextprotocol/server\";\nimport { RUNTIME_DELEGATION_REJECTIONS } from \"@tinycloud/node-sdk\";\n\nimport { createOpenKeyTokenVerifier } from \"./oauth.js\";\nimport { createTokenStatusChecker, type TokenStatusChecker, type TokenStatusConfig } from \"./token-status.js\";\nimport { logToolCall } from \"./logging.js\";\nimport {\n ApprovalOwnerMismatchError,\n ApprovalRequestError,\n ApprovalStageError,\n NativeGrantValidationError,\n RemoteTenantStore,\n type RemoteStoreConfig,\n} from \"./remote-store.js\";\nimport {\n MAX_NATIVE_GRANT_BODY_BYTES,\n NATIVE_GRANT_EXPIRED,\n NATIVE_GRANT_MAX_LIFETIME_SECONDS,\n NATIVE_GRANT_REJECTED,\n NATIVE_GRANT_REQUIRED,\n NATIVE_GRANT_VALIDATION_UNAVAILABLE,\n NATIVE_OWNER_DID_HEADER,\n NATIVE_SERVICE_UNAUTHORIZED,\n NATIVE_SERVICE_UNAVAILABLE,\n NATIVE_SERVICE_CREDENTIAL_HEADER,\n serviceCredentialMatches,\n} from \"./native-auth.js\";\nimport { MCP_SERVER_NAME } from \"./server.js\";\nimport { createJsonSchemaValidator, registerTinyCloudTools } from \"./tools.js\";\nimport type { McpOperationInvocation } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nconst REQUIRED_SCOPE = \"tinycloud:mcp\";\nconst LOCAL_CLI_PACKAGE = [\"@tinycloud\", \"cli\"].join(\"/\");\nconst LOCAL_MCP_PACKAGE = [\"@tinycloud\", \"mcp\"].join(\"/\");\n\nexport interface HostedMcpConfig extends RemoteStoreConfig {\n readonly oauthMetadata: OAuthMetadata;\n readonly allowedOrigins?: readonly string[];\n /**\n * OpenKey token introspection client (`TC_MCP_INTROSPECTION_URL` and client\n * credentials). The hosted server always sets this; without it only the\n * signed token claims are checked.\n */\n readonly introspection?: Omit<TokenStatusConfig, \"resourceUrl\">;\n}\n\nexport interface HostedMcpApp {\n readonly fetch: (request: Request) => Promise<Response>;\n readonly close: () => Promise<void>;\n}\n\nexport function createHostedMcpApp(config: HostedMcpConfig): HostedMcpApp {\n if (config.nativeServiceCredential !== undefined &&\n Buffer.byteLength(config.nativeServiceCredential, \"utf8\") < 32) {\n throw new Error(\"TC_MCP_NATIVE_SERVICE_CREDENTIAL must contain at least 32 bytes.\");\n }\n const resourceUrl = canonicalResourceUrl(config.publicUrl);\n const pluginUrl = new URL(\"./chatgpt/mcp\", resourceUrl);\n const statusFor = (resource: URL): TokenStatusChecker | undefined =>\n config.introspection === undefined\n ? undefined\n : createTokenStatusChecker({ ...config.introspection, resourceUrl: resource.toString() });\n const hosted = createHostedSurface(config, resourceUrl, \"hosted\", statusFor(resourceUrl));\n const plugin = createHostedSurface({\n ...config,\n nativeServiceCredential: undefined,\n stateDir: join(config.stateDir, \"chatgpt\"),\n approvalPath: new URL(\"./connect\", pluginUrl).pathname,\n }, pluginUrl, \"public\", statusFor(pluginUrl));\n const pluginPaths: Record<string, true> = {\n [pluginUrl.pathname]: true,\n [new URL(\"./connect\", pluginUrl).pathname]: true,\n [new URL(\"./connect/callback\", pluginUrl).pathname]: true,\n [new URL(getOAuthProtectedResourceMetadataUrl(pluginUrl)).pathname]: true,\n };\n return {\n fetch: (request) => (pluginPaths[new URL(request.url).pathname] === true ? plugin : hosted).fetch(request),\n close: async () => {\n await Promise.all([hosted.close(), plugin.close()]);\n },\n };\n}\n\nfunction createHostedSurface(\n config: HostedMcpConfig,\n resourceUrl: URL,\n surface: \"hosted\" | \"public\",\n tokenStatus: TokenStatusChecker | undefined,\n): HostedMcpApp {\n const connectPath = config.approvalPath ?? \"/connect\";\n const callbackPath = `${connectPath}/callback`;\n const issuer = String(config.oauthMetadata.issuer);\n const jwksUri = String(config.oauthMetadata.jwks_uri);\n const verifier = createOpenKeyTokenVerifier({\n issuer,\n audience: resourceUrl.toString(),\n jwksUri,\n requiredScope: REQUIRED_SCOPE,\n ...(tokenStatus === undefined ? {} : { tokenStatus }),\n });\n const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);\n const authenticate = requireBearerAuth({\n verifier,\n requiredScopes: [REQUIRED_SCOPE],\n resourceMetadataUrl,\n });\n const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });\n const nativeServiceIdentityEnabled = surface === \"hosted\" && config.nativeServiceCredential !== undefined;\n if (nativeServiceIdentityEnabled) void store.nativeServiceIdentity().catch(() => undefined);\n const handler = createMcpHandler(async ({ authInfo }) => {\n const nativeOwner = typeof authInfo?.extra?.nativeOwnerDid === \"string\"\n ? authInfo.extra.nativeOwnerDid\n : undefined;\n const identity = nativeOwner === undefined\n ? oauthIdentity(authInfo)\n : { subject: `native:${nativeOwner}`, ownerDids: [nativeOwner] };\n const { subject, ownerDids } = identity;\n const stateRoot = nativeOwner === undefined\n ? await store.initializeTenant(subject)\n : store.nativeTenantStateRoot(nativeOwner);\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n {\n jsonSchemaValidator: validator,\n instructions: nativeOwner === undefined\n ? surface === \"public\"\n ? \"Use TinyCloud only for the user's requested task. Call tinycloud_connect first. If an operation returns authority_required, present approval.url and wait for the user's approval before retrying. If approval is declined, stop that operation. For personal records, call tinycloud_apps_context first. Never request or store passwords, API keys, authentication codes, government identifiers, payment-card data, or protected health information.\"\n : \"Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged. For personal records such as weight, workouts, goals or todos, call tinycloud_apps_context first.\"\n : \"Use only the user's requested connector-transcript data. The signed TinyCloud grant authorizes read-only SQL and transcript KV reads.\",\n },\n );\n registerTinyCloudTools(server, {\n surface,\n profile: \"agent\",\n explicitProfile: true,\n allowOwnerProfile: false,\n stateRoot,\n ...(nativeOwner === undefined ? {} : {\n allowedTools: [\"tinycloud_sql_query\", \"tinycloud_kv_get\"] as const,\n }),\n beforeOperation: nativeOwner === undefined\n ? () => store.validateTenant(subject, ownerDids)\n : () => store.assertNativeGrantActive(nativeOwner),\n ...(nativeOwner === undefined ? {\n transformOperationResult: (result: unknown, invocation: McpOperationInvocation) =>\n store.decorateAuthorityResult(subject, ownerDids, result, invocation),\n } : {}),\n }, validator);\n if (nativeOwner === undefined) registerConnectTool(server, validator, store, identity, surface);\n return server;\n }, {\n legacy: \"stateless\",\n onerror: () => writeDiagnostic(\"MCP request failed\"),\n });\n\n const metadataOptions = {\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: resourceUrl,\n serviceDocumentationUrl: new URL(\"https://docs.tinycloud.xyz/cli/mcp\"),\n scopesSupported: [REQUIRED_SCOPE],\n resourceName: surface === \"public\" ? \"TinyCloud personal records\" : \"TinyCloud hosted MCP\",\n };\n const allowedHosts = [resourceUrl.hostname];\n\n return {\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname !== \"/healthz\") {\n const hostFailure = hostHeaderValidationResponse(request, allowedHosts);\n if (hostFailure !== undefined) return hostFailure;\n }\n if (url.pathname === \"/.well-known/oauth-protected-resource\" && surface === \"hosted\") {\n const metadataUrl = new URL(getOAuthProtectedResourceMetadataUrl(resourceUrl));\n const metadataRequest = new Request(metadataUrl.toString(), {\n method: request.method,\n headers: request.headers,\n });\n const response = oauthMetadataResponse(metadataRequest, metadataOptions);\n if (response !== undefined) return withBearerMethodsSupported(response);\n }\n const metadata = oauthMetadataResponse(request, metadataOptions);\n if (metadata !== undefined) {\n return surface === \"hosted\" ? withBearerMethodsSupported(metadata) : metadata;\n }\n if (url.pathname === \"/.well-known/ai-catalog.json\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n return publicMetadataCors(Response.json({\n specVersion: \"1.0\",\n host: {\n displayName: \"TinyCloud, Inc.\",\n identifier: \"https://mcp.tinycloud.xyz\",\n documentationUrl: \"https://docs.tinycloud.xyz/cli/mcp\",\n },\n entries: [{\n identifier: \"urn:air:tinycloud.xyz:mcp:tinycloud-mcp\",\n displayName: \"TinyCloud MCP\",\n type: \"application/json\",\n description: \"Hosted Streamable HTTP MCP server for delegated TinyCloud operations.\",\n url: new URL(\"/.well-known/mcp/server-card.json\", resourceUrl).toString(),\n representativeQueries: [\n \"How do I connect to TinyCloud's hosted MCP server?\",\n \"Which endpoint provides TinyCloud's delegated MCP operations?\",\n \"How can I connect to TinyCloud MCP using local stdio?\",\n ],\n }],\n }, {\n headers: {\n \"cache-control\": \"public, max-age=300\",\n \"content-type\": \"application/json; charset=utf-8\",\n },\n }), request);\n }\n\n if (url.pathname === \"/.well-known/poppy.json\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n return publicMetadataCors(Response.json({\n protocol_version: \"0.1\",\n organization: {\n name: \"TinyCloud, Inc.\",\n domain: resourceUrl.hostname,\n },\n web: {},\n }, {\n headers: {\n \"cache-control\": \"public, max-age=300\",\n \"content-type\": \"application/json; charset=utf-8\",\n },\n }), request);\n }\n if (url.pathname === \"/auth.md\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n const issuerUrl = new URL(issuer);\n const authorizationServerMetadataUrl = new URL(\n `/.well-known/oauth-authorization-server${issuerUrl.pathname}`,\n issuerUrl.origin,\n );\n const registrationEndpoint = config.oauthMetadata.registration_endpoint;\n const registrationNote = typeof registrationEndpoint === \"string\"\n ? `OpenKey's OAuth \\`registration_endpoint\\` is ${registrationEndpoint}; it registers OAuth clients, not TinyCloud users or agents.`\n : \"The authorization server does not advertise an OAuth client registration endpoint.\";\n const authDoc = [\n \"# TinyCloud MCP auth.md\",\n \"\",\n `Protected resource: ${resourceUrl}.`,\n \"\",\n \"Send an OAuth access token in the `Authorization: Bearer` header.\",\n \"\",\n `Protected Resource Metadata: ${new URL(\"/.well-known/oauth-protected-resource\", resourceUrl)}.`,\n `Authorization server issuer: ${issuer}.`,\n `Authorization server metadata: ${authorizationServerMetadataUrl}.`,\n `Scope: \\`${REQUIRED_SCOPE}\\`.`,\n \"\",\n \"Hosted access uses OpenKey OAuth.\",\n registrationNote,\n \"TinyCloud does not host an Auth.md agent-enrollment or user-registration endpoint for this service.\",\n \"No `agent_auth` registration block is published because no agent-registration endpoint is available.\",\n \"\",\n `Local stdio is a separate option configured with \\`${LOCAL_CLI_PACKAGE}\\` and \\`${LOCAL_MCP_PACKAGE}\\`.`,\n \"\",\n \"Connection steps: https://docs.tinycloud.xyz/cli/mcp\",\n ].join(\"\\n\") + \"\\n\";\n return publicMetadataCors(publicText(authDoc, \"text/markdown; charset=utf-8\"), request);\n }\n if (url.pathname === \"/robots.txt\" && surface === \"hosted\") {\n return request.method === \"GET\"\n ? publicText(`User-agent: *\\nAllow: /\\nSitemap: ${new URL(\"/sitemap.xml\", resourceUrl)}\\nAgentmap: ${new URL(\"/.well-known/ai-catalog.json\", resourceUrl)}\\n`, \"text/plain; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if ((url.pathname === \"/mcp/server-card\" || url.pathname === \"/.well-known/mcp/server-card.json\") && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n const identity = nativeServiceIdentityEnabled\n ? await store.nativeServiceIdentity().catch(() => undefined)\n : undefined;\n const card: Record<string, unknown> = {\n $schema: \"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json\",\n name: `xyz.tinycloud/${MCP_SERVER_NAME}`,\n title: \"TinyCloud MCP\",\n version: MCP_VERSION,\n description: \"MCP server for delegated TinyCloud operations.\",\n websiteUrl: \"https://docs.tinycloud.xyz/cli/mcp\",\n repository: { source: \"github\", url: \"https://github.com/TinyCloudLabs/js-sdk\", subfolder: \"packages/mcp\" },\n remotes: [{ type: \"streamable-http\", url: resourceUrl.toString() }],\n };\n if (identity !== undefined) {\n card[\"x-tinycloud-native-auth\"] = {\n serviceDid: identity.serviceDid,\n serviceDidField: \"x-tinycloud-native-auth.serviceDid\",\n grantEndpoint: {\n method: \"POST\",\n path: \"/native/grant\",\n body: { delegation: \"serialized PortableDelegation JSON string\" },\n },\n serviceCredentialHeader: NATIVE_SERVICE_CREDENTIAL_HEADER,\n serviceCredentialEnv: \"TC_MCP_NATIVE_SERVICE_CREDENTIAL\",\n ownerDidHeader: NATIVE_OWNER_DID_HEADER,\n maxGrantLifetimeSeconds: NATIVE_GRANT_MAX_LIFETIME_SECONDS,\n acceptedCapabilities: [\n { service: \"tinycloud.sql\", space: \"applications\", path: \"xyz.tinycloud.tinychat/connectors\", actions: [\"tinycloud.sql/read\"] },\n { service: \"tinycloud.kv\", space: \"applications\", path: \"xyz.tinycloud.tinychat/connectors/\", actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"] },\n ],\n tools: [\"tinycloud_sql_query\", \"tinycloud_kv_get\"],\n errors: {\n required: NATIVE_GRANT_REQUIRED,\n expired: NATIVE_GRANT_EXPIRED,\n rejected: NATIVE_GRANT_REJECTED,\n serviceUnauthorized: NATIVE_SERVICE_UNAUTHORIZED,\n serviceUnavailable: NATIVE_SERVICE_UNAVAILABLE,\n validationUnavailable: NATIVE_GRANT_VALIDATION_UNAVAILABLE,\n },\n };\n }\n return publicMetadataCors(Response.json(card, {\n headers: { \"cache-control\": \"public, max-age=300\" },\n }), request);\n }\n if (url.pathname === \"/llms.txt\" && surface === \"hosted\") {\n return request.method === \"GET\"\n ? publicText(`# TinyCloud MCP\\n\\nHosted Streamable HTTP endpoint: https://mcp.tinycloud.xyz/mcp (OpenKey OAuth).\\n\\nConnection documentation: https://docs.tinycloud.xyz/cli/mcp\\n\\nLocal alternative: install ${LOCAL_CLI_PACKAGE} and ${LOCAL_MCP_PACKAGE}, then set up tinycloud-mcp as a stdio server in your MCP client.\\n`, \"text/plain; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === \"/sitemap.xml\" && surface === \"hosted\") {\n const sitemap = `<?xml version=\"1.0\" encoding=\"UTF-8\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"><url><loc>${new URL(\"/\", resourceUrl)}</loc></url></urlset>`;\n return request.method === \"GET\"\n ? publicText(sitemap, \"application/xml; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === \"/\" && surface === \"hosted\") {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return methodNotAllowed(\"GET, HEAD\");\n const markdown = request.headers.get(\"accept\")?.includes(\"text/markdown\") ?? false;\n const content = markdown\n ? `# TinyCloud MCP\\n\\nHosted endpoint: <https://mcp.tinycloud.xyz/mcp> (Streamable HTTP, OpenKey OAuth).\\n\\n[Connection documentation](https://docs.tinycloud.xyz/cli/mcp).\\n\\nLocal alternative: install \\`${LOCAL_CLI_PACKAGE}\\` and \\`${LOCAL_MCP_PACKAGE}\\` and connect the \\`tinycloud-mcp\\` stdio server.\\n`\n : `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><link rel=\"ai-catalog\" href=\"/.well-known/ai-catalog.json\"><title>TinyCloud MCP</title></head><main><h1>TinyCloud MCP</h1><p>Hosted MCP endpoint: <code>https://mcp.tinycloud.xyz/mcp</code> (Streamable HTTP, OpenKey OAuth).</p><p><a href=\"https://docs.tinycloud.xyz/cli/mcp\">Connection documentation</a></p><p>Local alternative: install <code>${LOCAL_CLI_PACKAGE}</code> and <code>${LOCAL_MCP_PACKAGE}</code> and connect the <code>tinycloud-mcp</code> stdio server.</p></main></html>`;\n const headers = new Headers({\n \"content-type\": markdown ? \"text/markdown; charset=utf-8\" : \"text/html; charset=utf-8\",\n \"cache-control\": \"public, max-age=300\",\n \"content-security-policy\": \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n \"x-content-type-options\": \"nosniff\",\n vary: \"Accept\",\n });\n headers.set(\n \"link\",\n `<${new URL(\"/mcp/server-card\", resourceUrl)}>; rel=\"describedby\"; type=\"application/json\", <https://docs.tinycloud.xyz/cli/mcp>; rel=\"service-doc\"`,\n );\n return new Response(request.method === \"HEAD\" ? null : content, { headers });\n }\n if (url.pathname === \"/healthz\") {\n return request.method === \"GET\"\n ? json({ ok: true })\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === connectPath) {\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n try {\n const destination = await store.approvalRedirect(requiredState(url));\n return Response.redirect(destination, 302);\n } catch {\n if (request.headers.get(\"accept\")?.includes(\"text/html\")) {\n return new Response(\n \"<!doctype html><html lang=\\\"en\\\"><meta charset=\\\"utf-8\\\"><meta name=\\\"viewport\\\" content=\\\"width=device-width,initial-scale=1\\\"><title>TinyCloud approval unavailable</title><main><h1>This approval link is unavailable</h1><p>It may have expired or already been used. No new approval was accepted through this link.</p><p>Return to the conversation that requested access. In ChatGPT, select @TinyCloud and ask it to continue your original request. If access is still needed, it can provide a fresh approval link.</p><p>If you declined access, no further approval is required. Never paste passwords, codes or approval links into support messages.</p></main></html>\",\n {\n status: 400,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n vary: \"Accept\",\n },\n },\n );\n }\n return json({ error: \"The approval link is invalid or expired.\" }, 400);\n }\n }\n if (url.pathname === callbackPath) {\n if (request.method === \"OPTIONS\") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n const originFailure = validateCallbackOrigin(request, config.openkeyHost);\n if (originFailure !== undefined) return callbackCors(originFailure, config.openkeyHost);\n try {\n await store.completeApproval(requiredState(url), request);\n return callbackCors(json({ success: true }), config.openkeyHost);\n } catch (error) {\n // Only fixed server-authored text reaches OpenKey; callback input is never echoed.\n if (error instanceof ApprovalOwnerMismatchError) {\n return callbackCors(json({ error: error.message, code: \"approval_owner_mismatch\" }, 403), config.openkeyHost);\n }\n // Stage, code, reason and detail are identifiers, never callback, delegation or node text.\n const stage = error instanceof ApprovalStageError ? error.stage : \"unknown\";\n const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code)\n ? error.code\n : \"UNKNOWN\";\n const reason = !(error instanceof ApprovalStageError) || error.reason === undefined\n ? undefined\n : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? \"unknown\";\n // Only the server log says which state, tenant or body check failed;\n // the response stays uniform so a caller cannot probe a state.\n const detail = error instanceof ApprovalRequestError ? error.detail : \"none\";\n writeDiagnostic(\n `connect callback rejected: stage=${stage} code=${code}${reason === undefined ? \"\" : ` reason=${reason}`} detail=${detail}`,\n );\n return callbackCors(\n json({\n error: stage,\n code,\n ...(reason === undefined ? {} : { reason }),\n message: \"TinyCloud could not accept this delegation.\",\n }, 400),\n config.openkeyHost,\n );\n }\n }\n if (url.pathname === \"/native/grant\" && surface === \"hosted\") {\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n if (request.headers.has(\"origin\")) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (config.nativeServiceCredential === undefined) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n if (!serviceCredentialMatches(\n request.headers.get(NATIVE_SERVICE_CREDENTIAL_HEADER),\n config.nativeServiceCredential,\n )) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (!request.headers.get(\"content-type\")?.toLowerCase().startsWith(\"application/json\")) {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n const bodyText = await readBoundedBodyText(request, MAX_NATIVE_GRANT_BODY_BYTES);\n if (bodyText === undefined) return json({ error: NATIVE_GRANT_REJECTED }, 401);\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body) || !(\"delegation\" in body)) {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n const grantBody = body as { delegation?: unknown };\n if (Object.keys(body).length !== 1 || typeof grantBody.delegation !== \"string\") {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n try {\n const accepted = await store.acceptNativeGrant(grantBody.delegation);\n return json({\n ownerDid: accepted.ownerDid,\n serviceDid: accepted.serviceDid,\n expiresAt: accepted.expiresAt,\n }, 201);\n } catch (error) {\n return nativeGrantErrorResponse(error);\n }\n }\n if (url.pathname === resourceUrl.pathname && surface === \"hosted\" &&\n (request.headers.has(NATIVE_SERVICE_CREDENTIAL_HEADER) || request.headers.has(NATIVE_OWNER_DID_HEADER))) {\n if (config.nativeServiceCredential === undefined) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n if (!serviceCredentialMatches(\n request.headers.get(NATIVE_SERVICE_CREDENTIAL_HEADER),\n config.nativeServiceCredential,\n )) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (request.headers.has(\"origin\")) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n const ownerHeader = request.headers.get(NATIVE_OWNER_DID_HEADER);\n if (ownerHeader === null || ownerHeader.length === 0) {\n return json({ error: NATIVE_GRANT_REQUIRED }, 401);\n }\n const grant = await store.nativeGrantForOwner(ownerHeader);\n if (grant.status !== \"ok\") {\n const status = grant.status === \"unavailable\" ? 503 : 401;\n const code = grant.status === \"required\"\n ? NATIVE_GRANT_REQUIRED\n : grant.status === \"expired\"\n ? NATIVE_GRANT_EXPIRED\n : grant.status === \"unavailable\"\n ? NATIVE_GRANT_VALIDATION_UNAVAILABLE\n : NATIVE_GRANT_REJECTED;\n return json({ error: code }, status);\n }\n return handler.fetch(request, {\n authInfo: {\n token: \"native-service\",\n clientId: \"tinycloud-native\",\n scopes: [],\n extra: { nativeOwnerDid: grant.ownerDid },\n } as AuthInfo,\n });\n }\n if (url.pathname !== resourceUrl.pathname) return json({ error: \"Not found\" }, 404);\n const originFailure = validateOrigin(request, config.allowedOrigins);\n if (originFailure !== undefined) return originFailure;\n const auth = await authenticate(request);\n if (auth instanceof Response) return auth;\n return handler.fetch(request, { authInfo: auth });\n },\n close: () => handler.close(),\n };\n}\n\nfunction registerConnectTool(\n server: McpServer,\n validator: ReturnType<typeof createJsonSchemaValidator>,\n store: RemoteTenantStore,\n identity: OAuthIdentity,\n surface: \"hosted\" | \"public\",\n): void {\n const inputSchema = fromJsonSchema({ type: \"object\", properties: {}, additionalProperties: false }, validator);\n const outputSchema = fromJsonSchema({\n type: \"object\",\n properties: {\n connected: { type: \"boolean\" },\n ...(surface === \"hosted\" ? { sessionDid: { type: \"string\" } } : {}),\n approvalUrl: { type: \"string\", format: \"uri\" },\n expiresAt: { type: \"string\", format: \"date-time\" },\n },\n required: surface === \"hosted\" ? [\"connected\", \"sessionDid\"] : [\"connected\"],\n additionalProperties: false,\n }, validator);\n server.registerTool(\n \"tinycloud_connect\",\n {\n title: \"Connect TinyCloud\",\n description: \"Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.\",\n inputSchema,\n outputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n },\n async () => {\n const startedAt = performance.now();\n let code = \"INTERNAL_ERROR\";\n let text: string;\n try {\n const status = await store.connectStatus(identity.subject, identity.ownerDids);\n if (status.connected) {\n code = \"ok\";\n text = \"TinyCloud is connected.\";\n } else if (status.approvalUrl === undefined) {\n code = \"unavailable\";\n text = \"TinyCloud is unavailable. Call this tool again shortly.\";\n } else {\n code = \"authority_required\";\n text = `TinyCloud approval is required. Open ${status.approvalUrl}, then call this tool again. This link expires at ${status.expiresAt}.`;\n }\n const visibleStatus = surface === \"hosted\" ? status : {\n connected: status.connected,\n ...(status.approvalUrl === undefined ? {} : { approvalUrl: status.approvalUrl }),\n ...(status.expiresAt === undefined ? {} : { expiresAt: status.expiresAt }),\n };\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: visibleStatus,\n };\n } finally {\n logToolCall(\"tinycloud_connect\", code, startedAt, 0);\n }\n },\n );\n}\n\ninterface OAuthIdentity {\n readonly subject: string;\n readonly ownerDids: string[];\n}\n\nfunction oauthIdentity(authInfo: AuthInfo | undefined): OAuthIdentity {\n const subject = authInfo?.extra?.subject;\n if (typeof subject !== \"string\" || subject.length === 0) {\n throw new Error(\"The authenticated MCP request has no OpenKey subject.\");\n }\n const ownerDids = authInfo?.extra?.ownerDids;\n if (!Array.isArray(ownerDids) || ownerDids.length === 0 ||\n !ownerDids.every((did) => typeof did === \"string\")) {\n throw new Error(\"The authenticated MCP request has no OpenKey owner identity.\");\n }\n return { subject, ownerDids };\n}\n\nfunction canonicalResourceUrl(url: URL): URL {\n const resource = new URL(url);\n resource.hash = \"\";\n resource.search = \"\";\n resource.pathname = resource.pathname.replace(/\\/+$/, \"\") || \"/mcp\";\n if (resource.pathname === \"/\") resource.pathname = \"/mcp\";\n return resource;\n}\n\nfunction requiredState(url: URL): string {\n const state = url.searchParams.get(\"state\");\n if (state === null) throw new ApprovalRequestError(\"state_missing\", \"Missing approval state.\");\n if (state.length > 512) throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n return state;\n}\n\nfunction validateOrigin(request: Request, allowed: readonly string[] | undefined): Response | undefined {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return undefined;\n const allowlist = allowed ?? [];\n return allowlist.includes(origin) ? undefined : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction validateCallbackOrigin(request: Request, openkeyHost: string): Response | undefined {\n const origin = request.headers.get(\"origin\");\n return origin === null || origin === new URL(openkeyHost).origin\n ? undefined\n : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction callbackCors(response: Response, openkeyHost: string): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", new URL(openkeyHost).origin);\n headers.set(\"access-control-allow-methods\", \"POST, OPTIONS\");\n headers.set(\"access-control-allow-headers\", \"content-type\");\n headers.set(\"vary\", \"Origin\");\n return new Response(response.body, { status: response.status, headers });\n}\n\nasync function readBoundedBodyText(request: Request, maxBytes: number): Promise<string | undefined> {\n const contentLength = request.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedLength = Number(contentLength);\n if (Number.isFinite(parsedLength) && parsedLength > maxBytes) return undefined;\n }\n if (request.body === null) return \"\";\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString(\"utf8\");\n}\n\nfunction nativeGrantErrorResponse(error: unknown): Response {\n if (!(error instanceof NativeGrantValidationError)) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n const unavailable = error.code === NATIVE_GRANT_VALIDATION_UNAVAILABLE ||\n error.code === NATIVE_SERVICE_UNAVAILABLE;\n return json({ error: error.code }, unavailable ? 503 : 401);\n}\n\nfunction json(value: unknown, status = 200): Response {\n return Response.json(value, { status, headers: { \"cache-control\": \"no-store\" } });\n}\n\n\nasync function withBearerMethodsSupported(response: Response): Promise<Response> {\n if (response.status === 204 || response.body === null) return response;\n const metadata = await response.json() as Record<string, unknown>;\n const headers = new Headers(response.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n return new Response(JSON.stringify({ ...metadata, bearer_methods_supported: [\"header\"] }), {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nfunction publicMetadataCors(response: Response, request: Request): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", \"*\");\n headers.set(\"access-control-allow-methods\", \"GET, OPTIONS\");\n const requestedHeaders = request.method === \"OPTIONS\"\n ? request.headers.get(\"access-control-request-headers\")\n : null;\n if (requestedHeaders !== null) {\n headers.set(\"access-control-allow-headers\", requestedHeaders);\n }\n headers.set(\n \"vary\",\n requestedHeaders === null ? \"Origin\" : \"Origin, Access-Control-Request-Headers\",\n );\n return new Response(response.body, { status: response.status, headers });\n}\n\nfunction publicText(text: string, contentType: string): Response {\n return new Response(text, {\n headers: {\n \"content-type\": contentType,\n \"cache-control\": \"public, max-age=300\",\n \"x-content-type-options\": \"nosniff\",\n },\n });\n}\n\nfunction methodNotAllowed(allow: string): Response {\n return new Response(\"Method not allowed\", { status: 405, headers: { allow } });\n}\n\n\nfunction writeDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`);\n}\n","import {\n OAuthError,\n OAuthErrorCode,\n type AuthInfo,\n type OAuthMetadata,\n type OAuthTokenVerifier,\n} from \"@modelcontextprotocol/server\";\nimport { pkhDid } from \"@tinycloud/node-sdk\";\nimport { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from \"jose\";\n\nimport type { TokenStatusChecker } from \"./token-status.js\";\n\nconst OWNER_DIDS_CLAIM = \"https://tinycloud.xyz/owner_dids\";\n\nexport interface OpenKeyOAuthConfig {\n readonly issuer: string;\n readonly audience: string;\n readonly jwksUri: string;\n readonly requiredScope?: string;\n /**\n * OpenKey token status check run after the signature check on every call.\n * Hosted deployments always set it; a verifier built without one checks the\n * signed claims only.\n */\n readonly tokenStatus?: TokenStatusChecker;\n}\n\nexport function createOpenKeyTokenVerifier(config: OpenKeyOAuthConfig): OAuthTokenVerifier {\n const jwks = createRemoteJWKSet(new URL(config.jwksUri));\n return {\n async verifyAccessToken(token: string): Promise<AuthInfo> {\n try {\n const { payload } = await jwtVerify(token, jwks, {\n issuer: config.issuer,\n audience: config.audience,\n });\n const info = authInfo(token, payload, config);\n if (config.tokenStatus !== undefined) await requireUsableStatus(config.tokenStatus, token);\n return info;\n } catch (error) {\n if (error instanceof errors.JOSEError) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is invalid.\");\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * `inactive` is a 401 invalid_token. `unknown` (OpenKey unreachable, 4xx/5xx,\n * timeout, unreadable answer) is accepted only while `toleratesUnknown` holds;\n * after that it is refused as a 500 server_error, the transport's answer for a\n * fault that is not the token's: a 401 would send clients into re-authorisation\n * that cannot succeed while OpenKey is unavailable.\n */\nasync function requireUsableStatus(checker: TokenStatusChecker, token: string): Promise<void> {\n const status = await checker.tokenStatus(token);\n if (status === \"active\") return;\n if (status === \"inactive\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is no longer active.\");\n }\n if (!checker.toleratesUnknown(token)) {\n throw new OAuthError(OAuthErrorCode.ServerError, \"The OpenKey access token status is unavailable.\");\n }\n}\n\nexport async function loadOAuthMetadata(metadataUrl: URL): Promise<OAuthMetadata> {\n const response = await fetch(metadataUrl, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"OpenKey OAuth discovery failed.\");\n const metadata = await response.json() as OAuthMetadata;\n if (typeof metadata.issuer !== \"string\" || typeof metadata.jwks_uri !== \"string\") {\n throw new Error(\"OpenKey OAuth metadata is incomplete.\");\n }\n return metadata;\n}\n\nfunction authInfo(\n token: string,\n payload: JWTPayload,\n config: OpenKeyOAuthConfig,\n): AuthInfo {\n if (typeof payload.sub !== \"string\" || payload.sub.length === 0) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token does not identify a subject.\");\n }\n if (typeof payload.exp !== \"number\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token has no expiry.\");\n }\n const scopes = typeof payload.scope === \"string\"\n ? payload.scope.split(/\\s+/).filter(Boolean)\n : [];\n if (config.requiredScope !== undefined && !scopes.includes(config.requiredScope)) {\n throw new OAuthError(\n OAuthErrorCode.InsufficientScope,\n \"The OpenKey access token is missing the TinyCloud MCP scope.\",\n );\n }\n const clientId = firstString(payload.azp, payload.client_id) ?? \"unknown\";\n const ownerDids = canonicalOwnerDids(payload[OWNER_DIDS_CLAIM]);\n if (ownerDids === undefined) {\n throw new OAuthError(\n OAuthErrorCode.InvalidToken,\n \"The OpenKey access token has no valid TinyCloud owner identity.\",\n );\n }\n return {\n token,\n clientId,\n scopes,\n expiresAt: payload.exp,\n resource: new URL(config.audience),\n extra: {\n subject: payload.sub,\n ownerDids,\n },\n };\n}\n\n/**\n * OpenKey issues owner DIDs as `did:pkh:eip155:<chain>:<address>`. Only that\n * exact syntax is accepted, canonicalised, and passed on to owner comparison\n * and the approval text. One malformed value refuses the whole claim rather\n * than being skipped.\n */\nconst OWNER_DID = /^did:pkh:eip155:([1-9][0-9]{0,15}):(0x[0-9a-fA-F]{40})$/;\n\nfunction canonicalOwnerDids(claim: unknown): string[] | undefined {\n if (!Array.isArray(claim) || claim.length === 0) return undefined;\n const ownerDids: string[] = [];\n for (const value of claim) {\n const match = typeof value === \"string\" ? OWNER_DID.exec(value) : null;\n if (match === null) return undefined;\n try {\n ownerDids.push(pkhDid(match[2]!, Number(match[1])));\n } catch {\n return undefined;\n }\n }\n return [...new Set(ownerDids)];\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n","import { createHash } from \"node:crypto\";\n\nimport { decodeJwt } from \"jose\";\n\n/** What OpenKey's RFC 7662 token introspection says about one access token. */\nexport type TokenStatus = \"active\" | \"inactive\" | \"unknown\";\n\nexport interface TokenStatusConfig {\n /** OpenKey's resource-server introspection endpoint (`TC_MCP_INTROSPECTION_URL`). */\n readonly endpoint: string;\n /** The resource URL (JWT audience) this checker serves; an active answer must name it. */\n readonly resourceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** How the confidential client authenticates: `client_secret_basic` or `client_secret_post`. */\n readonly authMethod: \"basic\" | \"post\";\n readonly timeoutMs?: number;\n /** Test seams. */\n readonly fetch?: typeof fetch;\n readonly now?: () => number;\n readonly log?: (message: string) => void;\n}\n\nexport interface TokenStatusChecker {\n /** Ask OpenKey whether `token` is still active. Never throws. */\n readonly tokenStatus: (token: string) => Promise<TokenStatus>;\n /**\n * Whether an `unknown` status may still be accepted for this token: only a\n * token that OpenKey itself answered active to this process, and only while\n * the time since that answer is shorter than the token's own lifetime\n * (`exp - iat`, 300 s when the token does not carry both). A token never\n * confirmed active, or one answered inactive, is refused, and nothing is\n * tolerated while OpenKey is refusing the client credentials.\n */\n readonly toleratesUnknown: (token: string) => boolean;\n}\n\n/** What one introspection call concluded; `credentials` and `mismatch` are not answers about the token. */\ntype Outcome = TokenStatus | \"credentials\" | \"mismatch\";\n\nconst ACTIVE_CACHE_MS = 30_000;\nconst DEFAULT_TOKEN_LIFETIME_SECONDS = 300;\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MAX_CACHED_TOKENS = 10_000;\n\nexport function createTokenStatusChecker(config: TokenStatusConfig): TokenStatusChecker {\n const doFetch = config.fetch ?? fetch;\n const clock = config.now ?? Date.now;\n const log = config.log ?? ((message: string) => void process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`));\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n /** token hash -> expiry (ms) of an inactive token; inactive is final. */\n const inactive = new Map<string, number>();\n /** token hash -> end (ms) of the active window. */\n const active = new Map<string, number>();\n const inFlight = new Map<string, Promise<TokenStatus>>();\n /** token hash -> when OpenKey last answered this token active, and the token's expiry (ms). */\n const confirmedActive = new Map<string, { at: number; expiresAt: number }>();\n /** Set while OpenKey refuses the client credentials; cleared by the next answer about a token. */\n let credentialsRefused = false;\n\n async function introspect(token: string): Promise<Outcome> {\n const headers: Record<string, string> = {\n accept: \"application/json\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n };\n const body = new URLSearchParams({ token, token_type_hint: \"access_token\" });\n if (config.authMethod === \"basic\") {\n const encode = (value: string) => encodeURIComponent(value).replace(/%20/g, \"+\");\n const credentials = `${encode(config.clientId)}:${encode(config.clientSecret)}`;\n headers.authorization = `Basic ${Buffer.from(credentials).toString(\"base64\")}`;\n } else {\n body.set(\"client_id\", config.clientId);\n body.set(\"client_secret\", config.clientSecret);\n }\n try {\n const response = await doFetch(config.endpoint, {\n method: \"POST\",\n headers,\n body,\n redirect: \"error\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (response.status === 401) return \"credentials\";\n if (response.status !== 200) return \"unknown\";\n const result: unknown = await response.json();\n if (typeof result !== \"object\" || result === null || !(\"active\" in result)) return \"unknown\";\n if (result.active === false) return \"inactive\";\n if (result.active !== true) return \"unknown\";\n return answerMatchesToken(Object.fromEntries(Object.entries(result)), token, config.resourceUrl)\n ? \"active\"\n : \"mismatch\";\n } catch {\n return \"unknown\";\n }\n }\n\n async function query(key: string, token: string): Promise<TokenStatus> {\n const outcome = await introspect(token);\n if (outcome === \"credentials\") {\n if (!credentialsRefused) {\n log(\"OpenKey token introspection refused the MCP client credentials (401); token checks fail closed until it accepts them.\");\n }\n credentialsRefused = true;\n return \"unknown\";\n }\n if (outcome === \"unknown\") return outcome;\n const now = clock();\n prune(now);\n if (outcome === \"mismatch\") {\n // The answer describes some other token: refused like an inactive one, but it\n // is not an answer about this token and confirms nothing.\n inactive.set(key, tokenExpiryMs(token, now));\n confirmedActive.delete(key);\n return \"inactive\";\n }\n credentialsRefused = false;\n if (outcome === \"inactive\") {\n inactive.set(key, tokenExpiryMs(token, now));\n confirmedActive.delete(key);\n } else {\n active.set(key, now + ACTIVE_CACHE_MS);\n // Delete first so a re-confirmed token moves to the newest slot of the map.\n confirmedActive.delete(key);\n confirmedActive.set(key, { at: now, expiresAt: tokenExpiryMs(token, now) });\n }\n return outcome;\n }\n\n function prune(now: number): void {\n for (const [key, until] of active) if (until <= now) active.delete(key);\n for (const [key, until] of inactive) if (until <= now) inactive.delete(key);\n for (const [key, entry] of confirmedActive) if (entry.expiresAt <= now) confirmedActive.delete(key);\n // An evicted entry costs one more introspection for that token; an evicted\n // confirmation means that token is refused while OpenKey cannot answer.\n for (const cache of [active, inactive, confirmedActive]) {\n while (cache.size >= MAX_CACHED_TOKENS) {\n const oldest = cache.keys().next().value;\n if (oldest === undefined) break;\n cache.delete(oldest);\n }\n }\n }\n\n return {\n async tokenStatus(token) {\n const key = createHash(\"sha256\").update(token).digest(\"hex\");\n const now = clock();\n const inactiveUntil = inactive.get(key);\n if (inactiveUntil !== undefined && inactiveUntil > now) return \"inactive\";\n const activeUntil = active.get(key);\n if (activeUntil !== undefined && activeUntil > now) return \"active\";\n const pending = inFlight.get(key);\n if (pending !== undefined) return pending;\n const asking = query(key, token).finally(() => inFlight.delete(key));\n inFlight.set(key, asking);\n return asking;\n },\n toleratesUnknown(token) {\n if (credentialsRefused) return false;\n const confirmed = confirmedActive.get(createHash(\"sha256\").update(token).digest(\"hex\"));\n if (confirmed === undefined) return false;\n const now = clock();\n return confirmed.expiresAt > now && now - confirmed.at < tokenLifetimeSeconds(token) * 1000;\n },\n };\n}\n\n/**\n * An `active` answer must describe the token that was asked about: `sub` and\n * `client_id` equal the claims of the already verified JWT, and `aud` is a\n * non-empty subset of the JWT's audiences that includes `resourceUrl` (OpenKey\n * answers only with the audiences the resource server may know, while the JWT\n * can carry more, e.g. its userinfo endpoint).\n */\nfunction answerMatchesToken(answer: Record<string, unknown>, token: string, resourceUrl: string): boolean {\n const jwt = claims(token);\n if (typeof jwt.sub === \"string\" && answer.sub !== jwt.sub) return false;\n const jwtClient = [jwt.azp, jwt.client_id].find((value) => typeof value === \"string\" && value.length > 0);\n if (jwtClient !== undefined && answer.client_id !== jwtClient) return false;\n if (jwt.aud === undefined) return true;\n const answered = audienceList(answer.aud);\n const signed = audienceList(jwt.aud);\n return answered.length > 0 && answered.includes(resourceUrl) && answered.every((entry) => signed.includes(entry));\n}\n\n/** An `aud` value (string or array) as a list; a missing or malformed one is empty. */\nfunction audienceList(value: unknown): string[] {\n const list = typeof value === \"string\" ? [value] : value;\n return Array.isArray(list) && list.every((entry) => typeof entry === \"string\") ? list : [];\n}\n\nfunction tokenExpiryMs(token: string, now: number): number {\n const exp = claims(token).exp;\n return typeof exp === \"number\" ? exp * 1000 : now + DEFAULT_TOKEN_LIFETIME_SECONDS * 1000;\n}\n\nfunction tokenLifetimeSeconds(token: string): number {\n const { exp, iat } = claims(token);\n return typeof exp === \"number\" && typeof iat === \"number\" && exp > iat\n ? exp - iat\n : DEFAULT_TOKEN_LIFETIME_SECONDS;\n}\n\nfunction claims(token: string): ReturnType<typeof decodeJwt> {\n try {\n return decodeJwt(token);\n } catch {\n return {};\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n activateValidatedRuntimeDelegation,\n deserializeDelegation,\n InvalidRestoredSessionError,\n RuntimeDelegationRejectedError,\n serializeDelegation,\n TinyCloudNode,\n UnsupportedSessionRestoreError,\n isCapabilitySubset,\n principalDidEquals,\n siweRuntimeDelegation,\n signedCompactUcanExpiry,\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudSession,\n} from \"@tinycloud/node-sdk\";\nimport { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { createOrReusePermissionRequest } from \"@tinycloud/operations/artifacts\";\nimport { withTinyCloudStateRoot } from \"@tinycloud/operations/state\";\nimport { invokeOperation } from \"@tinycloud/operations\";\nimport { nodeRevocationOf, operationRetryDescriptor, type NodeRevocation } from \"@tinycloud/operations/mcp-authority\";\nimport { tcAppsApprovalMessage, tcAppsApprovalReason } from \"@tinycloud/operations/tc-apps\";\nimport { nativeOwnerForConnectorGrant, canonicalOwnerDid, NATIVE_GRANT_MAX_LIFETIME_SECONDS } from \"./native-auth.js\";\n\nimport type { McpOperationInvocation } from \"./tools.js\";\nconst PROFILE = \"agent\";\nconst MAX_CALLBACK_BYTES = 256 * 1024;\nconst NATIVE_GRANT_IMPORT_REJECTION_CODES = new Set([\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n]);\n/**\n * The node host hosted MCP tenants were created with until TC_HOST moved to\n * `https://tee.node.tinycloud.xyz` (js-sdk 48eca361). Profiles keep the host\n * they were created with, so tenants from that era still store it.\n */\nconst LEGACY_DEFAULT_NODE_HOST = \"https://node.tinycloud.xyz\";\nconst BOOTSTRAP_PERMISSIONS: PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"spaces/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"applications/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n];\n\nexport interface RemoteStoreConfig {\n readonly stateDir: string;\n readonly stateSecret: string;\n readonly publicUrl: URL;\n /** Separate public-plugin approvals from the existing root callback. */\n readonly approvalPath?: string;\n readonly nodeHost: string;\n readonly openkeyHost: string;\n readonly approvalTtlSeconds: number;\n readonly delegationExpiry: string;\n /** Shared secret used only by the Exo native client, never logged. */\n readonly nativeServiceCredential?: string;\n}\n\ninterface TenantProfile {\n readonly stateRoot: string;\n readonly sessionDid: string;\n readonly jwk: Record<string, unknown>;\n readonly approvalEpoch: number;\n}\ninterface NativeServiceKey {\n readonly version: 1;\n readonly jwk: Record<string, unknown>;\n}\n\ninterface StoredNativeGrant {\n readonly version: 1;\n readonly ownerDid: string;\n readonly serviceDid: string;\n readonly serializedDelegation: string;\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly permissions: PermissionEntry[];\n readonly expiresAt: string;\n}\n\nexport type NativeGrantLookup =\n | { readonly status: \"ok\"; readonly ownerDid: string; readonly stateRoot: string; readonly expiresAt: string }\n | { readonly status: \"required\" | \"expired\" | \"rejected\" | \"unavailable\" };\n\nexport interface NativeServiceIdentity {\n readonly serviceDid: string;\n}\n\ninterface PendingApproval {\n readonly version: 1;\n readonly nonce: string;\n readonly tenantId: string;\n readonly kind: \"bootstrap\" | \"delegation\";\n readonly requestId?: string;\n readonly permissions: PermissionEntry[];\n readonly ownerDids: string[];\n readonly createdAt: string;\n readonly approvalEpoch: number;\n readonly expiresAt: string;\n}\n\nexport interface ConnectStatus {\n readonly connected: boolean;\n readonly sessionDid: string;\n readonly approvalUrl?: string;\n readonly expiresAt?: string;\n}\n\ntype SessionState = \"valid\" | \"invalid\" | \"unknown\";\n\ninterface CallbackSession {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly jwk: Record<string, unknown>;\n readonly verificationMethod: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/**\n * The approving wallet is not the OpenKey principal whose MCP request created\n * the approval link. The message is static so callers may show it verbatim.\n */\nexport class ApprovalOwnerMismatchError extends Error {\n constructor() {\n super(\"This approval link was requested by a different TinyCloud account, so the delegation was not stored.\");\n this.name = \"ApprovalOwnerMismatchError\";\n }\n}\n\n/** The callback stages `/connect/callback` names when it refuses an approval. */\nexport type ApprovalStage = \"restore_approval\" | \"siwe_runtime_delegation\" | \"auth_import\" | \"activation\";\n\n/**\n * A callback stage refused the approval. `code` and `reason` are\n * server-authored identifiers for diagnostics; the message and cause may quote\n * callback or node data and are never sent or logged.\n */\nexport class ApprovalStageError extends Error {\n readonly stage: ApprovalStage;\n readonly code: string;\n readonly reason: string | undefined;\n\n constructor(stage: ApprovalStage, code: string, reason?: string, cause?: unknown) {\n super(`The approval failed at ${stage} (${code}).`, { cause });\n this.name = \"ApprovalStageError\";\n this.stage = stage;\n this.code = code;\n this.reason = reason;\n }\n}\n\n/** Why a callback was refused before its approval was read. */\nexport type ApprovalRequestDetail =\n | \"state_missing\"\n | \"state_invalid\"\n | \"state_expired\"\n | \"state_not_pending\"\n | \"tenant_missing\"\n | \"body_invalid\";\n\n/**\n * The callback's state, tenant or body was refused before the approval was\n * read. `detail` is for server diagnostics only: callers get one uniform\n * response so they cannot probe whether a state is valid.\n */\nexport class ApprovalRequestError extends Error {\n readonly detail: ApprovalRequestDetail;\n\n constructor(detail: ApprovalRequestDetail, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"ApprovalRequestError\";\n this.detail = detail;\n }\n}\nexport class NativeGrantValidationError extends Error {\n readonly code:\n | \"native_grant_required\"\n | \"native_grant_expired\"\n | \"native_grant_rejected\"\n | \"native_grant_validation_unavailable\"\n | \"native_service_unavailable\";\n\n constructor(\n status: \"required\" | \"expired\" | \"rejected\" | \"unavailable\" |\n \"native_grant_required\" | \"native_grant_expired\" | \"native_grant_rejected\" |\n \"native_grant_validation_unavailable\" | \"native_service_unavailable\",\n ) {\n const code = status.startsWith(\"native_\")\n ? status as NativeGrantValidationError[\"code\"]\n : status === \"required\"\n ? \"native_grant_required\"\n : status === \"expired\"\n ? \"native_grant_expired\"\n : status === \"unavailable\"\n ? \"native_grant_validation_unavailable\"\n : \"native_grant_rejected\";\n super(code);\n this.name = \"NativeGrantValidationError\";\n this.code = code;\n }\n}\n\nexport class RemoteTenantStore {\n readonly #config: RemoteStoreConfig;\n readonly #initializing = new Map<string, Promise<TenantProfile>>();\n readonly #sessionChecks = new Map<string, Promise<SessionState>>();\n readonly #clearing = new Map<string, Promise<void>>();\n readonly #activeSessions = new Map<string, { cids: string; until: number }>();\n readonly #pendingWrites = new Map<string, Promise<PendingApproval>>();\n readonly #renewalRequired = new Set<string>();\n readonly #approvalEpochs = new Map<string, number>();\n readonly #scopedClearing = new Map<string, Promise<void>>();\n readonly #clearedScoped = new Map<string, Set<string>>();\n readonly #approvalProcessing = new Map<string, Promise<void>>();\n #nativeIdentity?: Promise<{ did: string; jwk: Record<string, unknown> }>;\n readonly #nativeGrantQueues = new Map<string, Promise<void>>();\n\n constructor(config: RemoteStoreConfig) {\n this.#config = config;\n }\n\n async nativeServiceIdentity(): Promise<NativeServiceIdentity> {\n const identity = await this.#loadNativeServiceKey();\n return { serviceDid: normalizeDid(identity.did) };\n }\n\n nativeTenantStateRoot(ownerDid: string): string {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) throw new NativeGrantValidationError(\"rejected\");\n const tenant = createHmac(\"sha256\", this.#config.stateSecret)\n .update(`native-tenant:${canonical}`)\n .digest(\"hex\");\n return join(this.#config.stateDir, \"native-tenants\", tenant);\n }\n\n async acceptNativeGrant(serializedDelegation: string): Promise<{\n ownerDid: string;\n serviceDid: string;\n expiresAt: string;\n stateRoot: string;\n }> {\n if (Buffer.byteLength(serializedDelegation) > MAX_CALLBACK_BYTES) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n const identity = await this.#loadNativeServiceKey();\n const activated = await this.#activateNativeDelegation(serializedDelegation, identity);\n const { ownerDid, spaceId, permissions, expiresAt } = activated;\n return this.#withNativeGrantLock(ownerDid, async () => {\n const stateRoot = this.nativeTenantStateRoot(ownerDid);\n let previous: StoredNativeGrant | null = null;\n try {\n const stored = await readJson<unknown>(this.#nativeGrantPath(stateRoot));\n if (isRecord(stored) && stored.version === 1 && stored.ownerDid === ownerDid &&\n typeof stored.serviceDid === \"string\" && samePrincipal(stored.serviceDid, identity.did) &&\n typeof stored.serializedDelegation === \"string\" && typeof stored.delegationCid === \"string\" &&\n typeof stored.spaceId === \"string\" && Array.isArray(stored.permissions) &&\n stored.permissions.every(isPermissionEntry) &&\n nativeOwnerForConnectorGrant(stored.permissions) === ownerDid &&\n typeof stored.expiresAt === \"string\" && Number.isFinite(Date.parse(stored.expiresAt))) {\n previous = stored as unknown as StoredNativeGrant;\n }\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n }\n if (previous !== null) {\n const previousExpiry = Date.parse(previous.expiresAt);\n const nextExpiry = expiresAt.getTime();\n if (previousExpiry > nextExpiry ||\n (previousExpiry === nextExpiry && previous.delegationCid !== activated.cid)) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (previous.delegationCid === activated.cid) {\n return {\n ownerDid,\n serviceDid: normalizeDid(identity.did),\n expiresAt: previous.expiresAt,\n stateRoot,\n };\n }\n }\n const session = {\n delegationHeader: activated.delegation.delegationHeader,\n delegationCid: activated.cid,\n spaceId,\n jwk: identity.jwk,\n verificationMethod: identity.did,\n tinycloudHosts: [this.#config.nodeHost],\n };\n const grant: StoredNativeGrant = {\n version: 1,\n ownerDid,\n serviceDid: normalizeDid(identity.did),\n serializedDelegation: serializeDelegation(activated.delegation),\n delegationCid: activated.cid,\n spaceId,\n permissions,\n expiresAt: expiresAt.toISOString(),\n };\n const sessionPath = this.#sessionPath(stateRoot);\n const previousSession = await readOptionalText(sessionPath);\n try {\n await secureWrite(this.#profilePath(stateRoot), {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: activated.delegation.chainId,\n spaceName: \"applications\",\n did: identity.did,\n createdAt: new Date().toISOString(),\n profile: PROFILE,\n operatorType: \"agent\",\n posture: \"delegate-session\",\n ownerDid,\n sessionDid: identity.did,\n spaceId,\n tinycloudHost: this.#config.nodeHost,\n });\n await secureWrite(this.#keyPath(stateRoot), identity.jwk);\n await secureWrite(sessionPath, session);\n const request = await withTinyCloudStateRoot(stateRoot, () => createOrReusePermissionRequest({\n profile: PROFILE,\n posture: \"delegate-session\",\n operatorType: \"agent\",\n host: this.#config.nodeHost,\n sessionDid: identity.did,\n ownerDid,\n spaceId,\n missing: permissions,\n granted: [],\n replace: true,\n }));\n if (request.status !== \"created\") {\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n const imported = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: request.request.requestId,\n delegationCid: activated.cid,\n delegation: activated.delegation,\n },\n );\n if (imported.status === \"error\") {\n throw new NativeGrantValidationError(\n NATIVE_GRANT_IMPORT_REJECTION_CODES.has(imported.error.code)\n ? \"native_grant_rejected\"\n : \"native_grant_validation_unavailable\",\n );\n }\n if (imported.status !== \"ok\" || !isRecord(imported.output) ||\n imported.output.activated !== true || imported.output.cid !== activated.cid) {\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n await secureWrite(this.#nativeGrantPath(stateRoot), grant);\n } catch (error) {\n try {\n await restoreOptionalText(sessionPath, previousSession);\n } catch {\n await rm(this.#nativeGrantPath(stateRoot), { force: true }).catch(() => undefined);\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n throw error;\n }\n return { ownerDid, serviceDid: normalizeDid(identity.did), expiresAt: grant.expiresAt, stateRoot };\n });\n }\n\n async nativeGrantForOwner(ownerDid: string): Promise<NativeGrantLookup> {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) return { status: \"rejected\" };\n const stateRoot = this.nativeTenantStateRoot(canonical);\n let stored: StoredNativeGrant | null;\n try {\n stored = await readJson<StoredNativeGrant>(this.#nativeGrantPath(stateRoot));\n } catch {\n return { status: \"rejected\" };\n }\n if (stored === null) return { status: \"required\" };\n if (!isRecord(stored) || stored.version !== 1 || stored.ownerDid !== canonical ||\n typeof stored.serviceDid !== \"string\" || typeof stored.serializedDelegation !== \"string\" ||\n typeof stored.delegationCid !== \"string\" || typeof stored.spaceId !== \"string\" ||\n typeof stored.expiresAt !== \"string\" || !Array.isArray(stored.permissions) ||\n !stored.permissions.every(isPermissionEntry) ||\n nativeOwnerForConnectorGrant(stored.permissions) !== canonical) {\n return { status: \"rejected\" };\n }\n const expires = Date.parse(stored.expiresAt);\n if (!Number.isFinite(expires)) return { status: \"rejected\" };\n if (expires <= Date.now()) return { status: \"expired\" };\n try {\n const identity = await this.#loadNativeServiceKey();\n if (!samePrincipal(stored.serviceDid, identity.did)) return { status: \"rejected\" };\n const activated = await this.#activateNativeDelegation(stored.serializedDelegation, identity);\n if (activated.ownerDid !== canonical || activated.cid !== stored.delegationCid ||\n activated.spaceId !== stored.spaceId ||\n JSON.stringify(activated.permissions) !== JSON.stringify(stored.permissions) ||\n activated.expiresAt.toISOString() !== stored.expiresAt) return { status: \"rejected\" };\n return { status: \"ok\", ownerDid: canonical, stateRoot, expiresAt: stored.expiresAt };\n } catch (error) {\n if (error instanceof NativeGrantValidationError) {\n return { status: error.code === \"native_grant_expired\" ? \"expired\" :\n error.code === \"native_grant_validation_unavailable\" ? \"unavailable\" : \"rejected\" };\n }\n return { status: \"unavailable\" };\n }\n }\n\n async assertNativeGrantActive(ownerDid: string): Promise<void> {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) throw new NativeGrantValidationError(\"rejected\");\n const stateRoot = this.nativeTenantStateRoot(canonical);\n let stored: StoredNativeGrant | null;\n try {\n stored = await readJson<StoredNativeGrant>(this.#nativeGrantPath(stateRoot));\n } catch {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (stored === null) throw new NativeGrantValidationError(\"required\");\n if (!isRecord(stored) || stored.version !== 1 || stored.ownerDid !== canonical ||\n typeof stored.expiresAt !== \"string\" || !Number.isFinite(Date.parse(stored.expiresAt))) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (Date.parse(stored.expiresAt) <= Date.now()) throw new NativeGrantValidationError(\"expired\");\n }\n\n tenantStateRoot(subject: string): string {\n return join(this.#config.stateDir, \"tenants\", this.#tenantId(subject));\n }\n\n /** Prepare only this authenticated account's profile before its first operation. */\n async initializeTenant(subject: string): Promise<string> {\n return (await this.#ensureTenant(subject)).stateRoot;\n }\n /** Check stored node authority before an authenticated operation uses it. */\n async validateTenant(subject: string, ownerDids: readonly string[]): Promise<void> {\n await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);\n }\n\n\n async connectStatus(subject: string, ownerDids: readonly string[] = []): Promise<ConnectStatus> {\n const tenant = await this.#ensureTenant(subject);\n const state = await this.#sessionState(tenant, ownerDids, true);\n if (state === \"valid\") return { connected: true, sessionDid: tenant.sessionDid };\n // An unconfirmed session is not connected, but no new approval is issued for it.\n if (state === \"unknown\") return { connected: false, sessionDid: tenant.sessionDid };\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n connected: false,\n sessionDid: tenant.sessionDid,\n approvalUrl: this.#connectUrl(pending),\n expiresAt: pending.expiresAt,\n };\n }\n\n async decorateAuthorityResult(\n subject: string,\n ownerDids: readonly string[],\n result: unknown,\n invocation?: McpOperationInvocation,\n ): Promise<unknown> {\n if (!isRecord(result)) return result;\n if (result.status === \"error\" && isRecord(result.error) &&\n (result.error.code === \"SESSION_NOT_FOUND\" || result.error.code === \"AUTH_REQUIRED\")) {\n const tenant = await this.#ensureTenant(subject);\n const refusal = revocationFromResult(result.error);\n const cleared = refusal === undefined ? undefined : await this.#clearRefusedAuthority(tenant, refusal);\n if (cleared === \"scoped\" && invocation !== undefined) {\n return this.#renewScopedApproval(subject, ownerDids, tenant, result, invocation);\n }\n const valid = await this.#hasValidSession(tenant, ownerDids, true);\n if (valid && result.error.code === \"AUTH_REQUIRED\") {\n if (refusal === undefined) return result;\n return {\n ...result,\n error: { code: \"AUTH_REQUIRED\", message: \"TinyCloud approval is required.\", retryable: false },\n };\n }\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: {\n code: result.error.code === \"SESSION_NOT_FOUND\" &&\n await readJson<unknown>(this.#sessionPath(tenant.stateRoot)) === null\n ? \"SESSION_NOT_FOUND\"\n : \"AUTH_REQUIRED\",\n message: \"A new TinyCloud approval is required.\",\n retryable: false,\n details: { approvalUrl: this.#connectUrl(pending), expiresAt: pending.expiresAt },\n },\n };\n }\n if (result.status !== \"authority_required\") return result;\n const tenant = await this.#ensureTenant(subject);\n if (this.#renewalRequired.has(tenant.stateRoot) ||\n !(await this.#hasValidSession(tenant, ownerDids, true))) {\n if (this.#renewalRequired.has(tenant.stateRoot)) {\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: {\n code: \"AUTH_REQUIRED\",\n message: \"A new TinyCloud approval is required.\",\n retryable: false,\n details: { approvalUrl: this.#connectUrl(pending), expiresAt: pending.expiresAt },\n },\n };\n }\n }\n const request = isRecord(result.request) ? result.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n if (requestId === undefined || requested.length === 0) return result;\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n ...result,\n approval: {\n ...(isRecord(result.approval) ? result.approval : {}),\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: tcAppsApprovalMessage(requested) ??\n \"Open the approval URL, then retry the same MCP tool.\",\n },\n };\n }\n\n async #renewScopedApproval(\n subject: string,\n ownerDids: readonly string[],\n tenant: TenantProfile,\n result: Record<string, unknown>,\n invocation: McpOperationInvocation,\n ): Promise<unknown> {\n const planned = await invokeOperation(\n \"tinycloud.auth.request\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n invocation,\n );\n const output = planned.status === \"ok\" && isRecord(planned.output) ? planned.output : undefined;\n const request = isRecord(output?.request) ? output.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n const missing = Array.isArray(output?.missing) ? output.missing.filter(isPermissionEntry) : [];\n if (requestId === undefined || requested.length === 0 || missing.length === 0) {\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: { code: \"AUTH_REQUIRED\", message: \"A new TinyCloud approval is required.\", retryable: false },\n };\n }\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n status: \"authority_required\",\n operation: result.operation,\n context: result.context,\n missing,\n request,\n approval: {\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: tcAppsApprovalMessage(requested) ??\n \"Open the approval URL, then retry the same MCP tool.\",\n },\n retry: operationRetryDescriptor(invocation, invocation.input),\n };\n }\n\n async #clearRefusedAuthority(\n tenant: TenantProfile,\n refusal: NodeRevocation,\n ): Promise<\"bootstrap\" | \"scoped\" | undefined> {\n const raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot)).catch(() => null);\n const bootstrapCid = raw?.delegationCid;\n const ancestorCid = refusal.reason === \"delegation_ancestor_revoked\" ? refusal.ancestorCid : undefined;\n if (typeof bootstrapCid === \"string\" &&\n (bootstrapCid === refusal.revokedCid || bootstrapCid === ancestorCid)) {\n await this.#clearAuthority(tenant);\n return \"bootstrap\";\n }\n const key = tenant.stateRoot;\n const removed = this.#clearedScoped.get(tenant.stateRoot);\n if (removed?.has(refusal.revokedCid)) return \"scoped\";\n const additional = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n if (this.#clearedScoped.get(key)?.has(refusal.revokedCid)) return \"scoped\";\n if (!Array.isArray(additional)) return undefined;\n const affected = additional.some((entry) => {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" && (cid === refusal.revokedCid || cid === ancestorCid);\n });\n const inProgress = this.#scopedClearing.get(key);\n if (inProgress) {\n await inProgress;\n return this.#clearRefusedAuthority(tenant, refusal);\n }\n if (!affected) return undefined;\n const clearing = (async () => {\n const latest = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n if (!Array.isArray(latest)) return;\n const remaining = latest.filter((entry) => {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid !== \"string\" || (cid !== refusal.revokedCid && cid !== ancestorCid);\n });\n if (remaining.length === latest.length) return;\n this.#activeSessions.delete(tenant.stateRoot);\n const epoch = (this.#approvalEpochs.get(tenant.stateRoot) ?? tenant.approvalEpoch) + 1;\n this.#approvalEpochs.set(tenant.stateRoot, epoch);\n const profilePath = this.#profilePath(tenant.stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n await secureWrite(profilePath, { ...profile, approvalEpoch: epoch });\n if (remaining.length === 0) await rm(this.#additionalPath(tenant.stateRoot), { force: true });\n else await secureWrite(this.#additionalPath(tenant.stateRoot), remaining);\n const cleared = removed ?? new Set<string>();\n cleared.add(refusal.revokedCid);\n this.#clearedScoped.set(tenant.stateRoot, cleared);\n })().finally(() => this.#scopedClearing.delete(key));\n this.#scopedClearing.set(key, clearing);\n await clearing;\n return \"scoped\";\n }\n\n async approvalRedirect(state: string): Promise<string> {\n const pending = await this.#readPending(state, false);\n const tenant = await this.#readTenant(pending.tenantId);\n const callback = new URL(`${this.#config.approvalPath ?? \"/connect\"}/callback`, this.#config.publicUrl);\n callback.searchParams.set(\"state\", state);\n const params = new URLSearchParams({\n did: tenant.sessionDid,\n callback: callback.toString(),\n host: this.#config.nodeHost,\n jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString(\"base64url\"),\n permissions: Buffer.from(JSON.stringify({\n permissions: pending.permissions,\n reason: [\n pending.kind === \"bootstrap\"\n ? \"Connect this TinyCloud account to the hosted MCP delegate.\"\n : tcAppsApprovalReason(pending.permissions) ??\n \"Approve the exact capabilities requested by the TinyCloud MCP operation.\",\n // Owner DIDs come from the verified OpenKey access token of the MCP\n // client that created this link, never from the link itself.\n ...(pending.ownerDids.length === 0\n ? []\n : [`Requested by TinyCloud account ${pending.ownerDids.join(\", \")}; approve only if that is you.`]),\n ].join(\" \"),\n })).toString(\"base64url\"),\n expiry: this.#config.delegationExpiry,\n });\n return `${this.#config.openkeyHost.replace(/\\/+$/, \"\")}/delegate?${params.toString()}`;\n }\n\n async completeApproval(state: string, request: Request): Promise<void> {\n const length = Number(request.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is too large.\");\n }\n const text = await request.text();\n if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is too large.\");\n }\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch (error) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is invalid.\", error);\n }\n if (!isRecord(data)) throw new ApprovalRequestError(\"body_invalid\", \"Callback body is invalid.\");\n\n const pending = await this.#readPending(state, true);\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const prior = this.#approvalProcessing.get(stateRoot);\n const processing = (async () => {\n if (prior) await prior.catch(() => undefined);\n try {\n const tenant = await this.#readTenant(pending.tenantId);\n if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n if (pending.kind === \"bootstrap\") {\n await this.#storeBootstrap(tenant, pending, data);\n } else {\n await this.#storeDelegation(tenant, pending, data);\n }\n await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + \".processing\", { force: true });\n } catch (error) {\n await this.#restorePending(pending).catch(() => undefined);\n throw error;\n }\n })();\n this.#approvalProcessing.set(stateRoot, processing);\n try {\n await processing;\n } finally {\n if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);\n }\n }\n\n async #storeBootstrap(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n const { node, session } = await this.#restoreApproval(tenant, data);\n this.#assertCurrentApproval(pending, session);\n if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {\n throw new ApprovalOwnerMismatchError();\n }\n // The verifier reports one entry per signed action; the SDK subset check\n // judges each requested entry against every matching grant together.\n if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {\n throw new Error(\"The approved delegation does not cover the requested account access.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(tenant.stateRoot));\n await secureWrite(this.#profilePath(tenant.stateRoot), {\n ...profile,\n ownerDid: normalizeDid(node.did),\n spaceId: session.spaceId,\n });\n await secureWrite(this.#sessionPath(tenant.stateRoot), {\n authMethod: \"openkey\",\n ...session,\n });\n this.#renewalRequired.delete(tenant.stateRoot);\n this.#activeSessions.delete(tenant.stateRoot);\n }\n\n async #storeDelegation(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (pending.requestId === undefined) throw new Error(\"Authority request is missing.\");\n // Unlike bootstrap there is no empty-list exemption: a delegation is only\n // imported when its verified signer is the OAuth principal that asked.\n const { node, session } = await this.#restoreApproval(tenant, data);\n this.#assertCurrentApproval(pending, session);\n if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();\n // OpenKey returns a signed-login (CACAO) delegation. Every field is\n // projected from the verified SIWE; `tinycloud.auth.import` verifies it\n // again and checks it stays within the stored request.\n let delegation: PortableDelegation;\n try {\n delegation = siweRuntimeDelegation(node, {\n authorization: session.delegationHeader.Authorization,\n cid: session.delegationCid,\n spaceId: session.spaceId,\n ownerAddress: session.address,\n chainId: session.chainId,\n siwe: session.siwe,\n signature: session.signature,\n host: this.#config.nodeHost,\n });\n } catch (error) {\n throw new ApprovalStageError(\n \"siwe_runtime_delegation\",\n \"DELEGATION_REJECTED\",\n error instanceof RuntimeDelegationRejectedError ? error.reason : undefined,\n error,\n );\n }\n const result = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: pending.requestId,\n delegationCid: delegation.cid,\n delegation,\n },\n );\n if (result.status === \"error\") {\n const reason = result.error.details?.reason;\n // Only a refused node activation carries a rejection reason on DELEGATION_REJECTED.\n throw new ApprovalStageError(\n result.error.code === \"DELEGATION_REJECTED\" && typeof reason === \"string\" ? \"activation\" : \"auth_import\",\n result.error.code,\n typeof reason === \"string\" ? reason : undefined,\n );\n }\n if (result.status !== \"ok\") throw new ApprovalStageError(\"auth_import\", \"AUTHORITY_REQUIRED\");\n }\n\n #assertCurrentApproval(pending: PendingApproval, session: CallbackSession): void {\n const issuedAt = /^Issued At: ([^\\r\\n]+)\\r?$/m.exec(session.siwe)?.[1];\n if (issuedAt === undefined || !Number.isFinite(Date.parse(issuedAt)) ||\n Date.parse(issuedAt) < Date.parse(pending.createdAt)) {\n throw new ApprovalStageError(\"restore_approval\", \"APPROVAL_PREDATES_REQUEST\");\n }\n }\n\n /**\n * Verify the OpenKey callback as a SIWE session for this tenant's key. The\n * callback must carry the full signed proof (SIWE, signature, address and\n * chain), so the WASM verifier always runs: it binds the authorization bytes\n * and CID to the signed SIWE, and `node.did` is the wallet that signed\n * exactly the delegation being stored.\n */\n async #restoreApproval(\n tenant: TenantProfile,\n data: Record<string, unknown>,\n ): Promise<{ node: TinyCloudNode; session: CallbackSession }> {\n let session: CallbackSession;\n try {\n session = sessionFromCallback(data, tenant.jwk);\n } catch (error) {\n throw new ApprovalStageError(\"restore_approval\", \"CALLBACK_INCOMPLETE\", undefined, error);\n }\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession(session);\n } catch (error) {\n throw new ApprovalStageError(\n \"restore_approval\",\n error instanceof InvalidRestoredSessionError || error instanceof UnsupportedSessionRestoreError\n ? error.code\n : \"SESSION_RESTORE_FAILED\",\n undefined,\n error,\n );\n }\n if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {\n throw new ApprovalStageError(\"restore_approval\", \"SESSION_MISMATCH\");\n }\n return { node, session };\n }\n\n async #ensureTenant(subject: string): Promise<TenantProfile> {\n const tenantId = this.#tenantId(subject);\n const current = this.#initializing.get(tenantId);\n if (current !== undefined) return current;\n const initializing = this.#initializeTenant(tenantId).finally(() => {\n this.#initializing.delete(tenantId);\n });\n this.#initializing.set(tenantId, initializing);\n return initializing;\n }\n\n async #hasValidSession(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh = false,\n ): Promise<boolean> {\n return (await this.#sessionState(tenant, ownerDids, fresh)) !== \"invalid\";\n }\n\n async #sessionState(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh = false,\n ): Promise<SessionState> {\n if (this.#renewalRequired.has(tenant.stateRoot)) return \"invalid\";\n const key = JSON.stringify([tenant.stateRoot, ownerDids.map(normalizeDid), fresh]);\n const current = this.#sessionChecks.get(key);\n if (current) return current;\n const checking = this.#checkSession(tenant, ownerDids, fresh).finally(() => {\n this.#sessionChecks.delete(key);\n });\n this.#sessionChecks.set(key, checking);\n return checking;\n }\n\n async #checkSession(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh: boolean,\n ): Promise<SessionState> {\n let raw: Record<string, unknown> | null;\n try {\n raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot));\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (raw === null) return \"invalid\";\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession(raw as unknown as TinyCloudSession);\n } catch {\n const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : undefined;\n const signedExpiry = typeof header === \"string\" ? signedCompactUcanExpiry(header) : undefined;\n const siweExpiry = typeof raw.siwe === \"string\"\n ? /^Expiration Time: ([^\\r\\n]+)\\r?$/m.exec(raw.siwe)?.[1]\n : undefined;\n const expiry = signedExpiry ?? (siweExpiry === undefined ? undefined : new Date(siweExpiry));\n if (expiry !== undefined && expiry.getTime() <= Date.now()) return \"invalid\";\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (!samePrincipal(node.sessionDid, tenant.sessionDid) ||\n !ownerDids.some((did) => samePrincipal(node.did, did))) return \"invalid\";\n const additional = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n const cids = [raw.delegationCid];\n if (additional !== null) {\n if (!Array.isArray(additional)) throw new Error(\"Stored TinyCloud authority is unavailable.\");\n for (const entry of additional) {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n cids.push(cid);\n }\n }\n if (!cids.every((cid): cid is string => typeof cid === \"string\" && cid.length > 0)) {\n throw new Error(\"Stored TinyCloud authority is unavailable.\");\n }\n const fingerprint = cids.join(\"\\n\");\n const cached = this.#activeSessions.get(tenant.stateRoot);\n if (!fresh && cached?.cids === fingerprint && cached.until > Date.now()) return \"valid\";\n // A node refusal is actionable only when it names this stored permission.\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 2_000);\n timer.unref();\n });\n const probe = await Promise.race([\n node.kvForSpace(String(raw.spaceId)).list({ prefix: \"spaces/\" }).catch(() => undefined),\n timeout,\n ]).finally(() => clearTimeout(timer));\n const refusal = probe !== undefined && !probe.ok ? nodeRevocationOf(probe.error) : undefined;\n if (refusal !== undefined &&\n (refusal.revokedCid === raw.delegationCid ||\n (refusal.reason === \"delegation_ancestor_revoked\" && refusal.ancestorCid === raw.delegationCid))) {\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (this.#renewalRequired.has(tenant.stateRoot)) return \"invalid\";\n if (probe?.ok) {\n this.#activeSessions.set(tenant.stateRoot, { cids: fingerprint, until: Date.now() + 30_000 });\n return \"valid\";\n }\n // Timeouts, transport errors and refusals that do not name this permission\n // leave the stored session in place without confirming it.\n return \"unknown\";\n }\n\n async #clearAuthority(tenant: TenantProfile): Promise<void> {\n const current = this.#clearing.get(tenant.stateRoot);\n if (current) return current;\n this.#activeSessions.delete(tenant.stateRoot);\n this.#renewalRequired.add(tenant.stateRoot);\n this.#clearedScoped.delete(tenant.stateRoot);\n this.#approvalEpochs.set(\n tenant.stateRoot,\n (this.#approvalEpochs.get(tenant.stateRoot) ?? tenant.approvalEpoch) + 1,\n );\n const clearing = (async () => {\n const processing = this.#approvalProcessing.get(tenant.stateRoot);\n if (processing) await processing.catch(() => undefined);\n const scoped = this.#scopedClearing.get(tenant.stateRoot);\n if (scoped) await scoped;\n this.#renewalRequired.add(tenant.stateRoot);\n const profilePath = this.#profilePath(tenant.stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n await secureWrite(profilePath, {\n ...profile,\n approvalEpoch: this.#approvalEpochs.get(tenant.stateRoot),\n });\n await rm(this.#additionalPath(tenant.stateRoot), { force: true });\n await rm(join(tenant.stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"auth-requests.json\"), { force: true });\n await rm(this.#pendingDirectory(tenant.stateRoot), { recursive: true, force: true });\n await rm(this.#sessionPath(tenant.stateRoot), { force: true });\n })().finally(() => this.#clearing.delete(tenant.stateRoot));\n this.#clearing.set(tenant.stateRoot, clearing);\n await clearing;\n }\n\n async #initializeTenant(tenantId: string): Promise<TenantProfile> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const keyPath = this.#keyPath(stateRoot);\n await secureDirectory(join(stateRoot, \".tinycloud\", \"profiles\", PROFILE));\n let jwk = await readJson<Record<string, unknown>>(keyPath);\n let sessionDid: string;\n if (jwk === null) {\n const generated = generateSessionKey();\n jwk = generated.jwk;\n sessionDid = generated.did;\n await secureWrite(keyPath, jwk);\n } else {\n sessionDid = didFromJwk(jwk);\n }\n const profilePath = this.#profilePath(stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n if (profile === null) {\n await secureWrite(profilePath, {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: 1,\n spaceName: \"default\",\n did: sessionDid,\n sessionDid,\n createdAt: new Date().toISOString(),\n posture: \"delegate-session\",\n operatorType: \"agent\",\n authMethod: \"openkey\",\n openkeyHost: this.#config.openkeyHost,\n });\n } else if (\n typeof profile.host === \"string\" &&\n profile.host.replace(/\\/+$/, \"\") === LEGACY_DEFAULT_NODE_HOST &&\n this.#config.nodeHost.replace(/\\/+$/, \"\") !== LEGACY_DEFAULT_NODE_HOST\n ) {\n // The runtime already talks to TC_HOST, but `tinycloud.auth.import`\n // checks the stored host, so a tenant left on the retired default\n // refuses every authority approval. Any other stored host is a\n // deliberate pin and keeps its DELEGATION_HOST_MISMATCH.\n await secureWrite(profilePath, { ...profile, host: this.#config.nodeHost });\n process.stderr.write(\n `[tinycloud-mcp-http] tenant node host migrated: from=${LEGACY_DEFAULT_NODE_HOST} to=${new URL(this.#config.nodeHost).origin}\\n`,\n );\n }\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n this.#approvalEpochs.set(stateRoot, approvalEpoch);\n return { stateRoot, sessionDid, jwk, approvalEpoch };\n }\n\n async #readTenant(tenantId: string): Promise<TenantProfile> {\n if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const jwk = await readJson<Record<string, unknown>>(this.#keyPath(stateRoot));\n if (jwk === null) throw new ApprovalRequestError(\"tenant_missing\", \"The TinyCloud delegate no longer exists.\");\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(stateRoot));\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n return { stateRoot, jwk, sessionDid: didFromJwk(jwk), approvalEpoch };\n }\n\n async #createPending(\n subject: string,\n ownerDids: readonly string[],\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const clearing = this.#clearing.get(this.tenantStateRoot(subject));\n if (clearing) await clearing;\n const tenant = await this.#ensureTenant(subject);\n const tenantId = this.#tenantId(subject);\n const normalizedOwners = ownerDids.map(normalizeDid);\n const key = JSON.stringify([tenantId, tenant.approvalEpoch, kind, requestId, permissions, normalizedOwners]);\n const current = this.#pendingWrites.get(key);\n if (current) return current;\n const writing = this.#writePending(tenant, tenantId, kind, permissions, normalizedOwners, requestId)\n .finally(() => this.#pendingWrites.delete(key));\n this.#pendingWrites.set(key, writing);\n return writing;\n }\n\n async #writePending(\n tenant: TenantProfile,\n tenantId: string,\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n ownerDids: string[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const reusable = await reusablePending(\n this.#pendingDirectory(tenant.stateRoot),\n { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },\n );\n if (reusable !== undefined) return reusable;\n const nonce = randomBytes(24).toString(\"base64url\");\n const created = Date.now();\n const pending: PendingApproval = {\n version: 1,\n nonce,\n tenantId,\n approvalEpoch: tenant.approvalEpoch,\n kind,\n ...(requestId === undefined ? {} : { requestId }),\n permissions,\n ownerDids,\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1000).toISOString(),\n };\n await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);\n return pending;\n }\n\n async #readPending(state: string, consume: boolean): Promise<PendingApproval> {\n const [tenantId, nonce, signature] = state.split(\".\");\n if (tenantId === undefined || nonce === undefined || signature === undefined) {\n throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n }\n const expected = this.#signState(tenantId, nonce);\n const supplied = Buffer.from(signature, \"base64url\");\n const expectedBytes = Buffer.from(expected, \"base64url\");\n if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {\n throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n }\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const path = this.#pendingPath(stateRoot, nonce);\n const claimed = `${path}.processing`;\n if (consume) {\n try {\n await rename(path, claimed);\n } catch (error) {\n // No pending file to claim. Other filesystem failures stay unclassified.\n if (!isRecord(error) || error.code !== \"ENOENT\") throw error;\n // The state is signed by this server, so a missing tenant key means the\n // tenant directory itself is gone (for example a reset state volume).\n const tenantExists = await readJson<unknown>(this.#keyPath(stateRoot)).then(\n (jwk) => jwk !== null,\n () => true,\n );\n if (!tenantExists) {\n throw new ApprovalRequestError(\"tenant_missing\", \"The TinyCloud delegate no longer exists.\", error);\n }\n // Already used, being processed, or never issued. This is not proof of\n // replay: retrying an expired link lands here too, because the first\n // attempt deleted its pending file.\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\", error);\n }\n }\n try {\n const pending = await readJson<PendingApproval>(consume ? claimed : path);\n if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(stateRoot));\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n if (new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(consume ? claimed : path, { force: true });\n throw new ApprovalRequestError(\"state_expired\", \"Approval state has expired.\");\n }\n return pending;\n } catch (error) {\n if (consume) await rename(claimed, path).catch(() => undefined);\n throw error;\n }\n }\n\n async #restorePending(pending: PendingApproval): Promise<void> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const path = this.#pendingPath(stateRoot, pending.nonce);\n await rename(`${path}.processing`, path);\n }\n\n #connectUrl(pending: PendingApproval): string {\n const url = new URL(this.#config.approvalPath ?? \"/connect\", this.#config.publicUrl);\n url.searchParams.set(\"state\", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);\n return url.toString();\n }\n\n async #withNativeGrantLock<T>(ownerDid: string, action: () => Promise<T>): Promise<T> {\n const previous = this.#nativeGrantQueues.get(ownerDid) ?? Promise.resolve();\n let releaseNext!: () => void;\n const next = new Promise<void>((resolve) => {\n releaseNext = resolve;\n });\n this.#nativeGrantQueues.set(ownerDid, next);\n await previous;\n try {\n return await action();\n } finally {\n releaseNext();\n if (this.#nativeGrantQueues.get(ownerDid) === next) this.#nativeGrantQueues.delete(ownerDid);\n }\n }\n async #loadNativeServiceKey(): Promise<{ did: string; jwk: Record<string, unknown> }> {\n if (this.#nativeIdentity === undefined) {\n const loading = this.#readOrCreateNativeServiceKey();\n this.#nativeIdentity = loading;\n void loading.catch(() => {\n if (this.#nativeIdentity === loading) this.#nativeIdentity = undefined;\n });\n }\n return this.#nativeIdentity;\n }\n\n async #readOrCreateNativeServiceKey(): Promise<{ did: string; jwk: Record<string, unknown> }> {\n const path = join(this.#config.stateDir, \".tinycloud\", \"native-service-key.json\");\n await secureDirectory(dirname(path));\n let stored = await readJson<NativeServiceKey>(path);\n if (stored === null) {\n const generated = generateSessionKey();\n try {\n await writeFile(path, `${JSON.stringify({ version: 1, jwk: generated.jwk })}\\n`, {\n mode: 0o600,\n flag: \"wx\",\n });\n } catch (error) {\n if (!isRecord(error) || error.code !== \"EEXIST\") throw error;\n }\n await chmod(path, 0o600);\n stored = await readJson<NativeServiceKey>(path);\n }\n if (stored === null || !isRecord(stored) || stored.version !== 1 || !isRecord(stored.jwk)) {\n throw new Error(\"The native MCP service identity is unavailable.\");\n }\n return { did: didFromJwk(stored.jwk), jwk: stored.jwk };\n }\n\n async #activateNativeDelegation(\n serialized: string,\n identity: { did: string; jwk: Record<string, unknown> },\n ): Promise<{\n ownerDid: string;\n spaceId: string;\n permissions: PermissionEntry[];\n cid: string;\n expiresAt: Date;\n delegation: PortableDelegation;\n }> {\n let delegation: PortableDelegation;\n try {\n const parsed: unknown = JSON.parse(serialized);\n if (!isRecord(parsed)) throw new Error(\"invalid delegation\");\n delegation = deserializeDelegation(serialized);\n } catch {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n if (!isRecord(delegation.delegationHeader) ||\n typeof delegation.delegationHeader.Authorization !== \"string\" ||\n delegation.delegationHeader.Authorization.length === 0 ||\n typeof delegation.cid !== \"string\" || delegation.cid.length === 0 ||\n typeof delegation.delegateDID !== \"string\" ||\n !samePrincipal(delegation.delegateDID, normalizeDid(identity.did)) ||\n typeof delegation.spaceId !== \"string\" ||\n typeof delegation.ownerAddress !== \"string\" ||\n !Number.isSafeInteger(delegation.chainId) ||\n typeof delegation.host !== \"string\" || !sameNodeHost(delegation.host, this.#config.nodeHost) ||\n !(delegation.expiry instanceof Date) || !Number.isFinite(delegation.expiry.getTime())) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n const now = Date.now();\n const claimedExpiry = delegation.expiry.getTime();\n if (claimedExpiry <= now) throw new NativeGrantValidationError(\"native_grant_expired\");\n if (claimedExpiry > now + NATIVE_GRANT_MAX_LIFETIME_SECONDS * 1_000) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n\n let ownerDid: string | undefined;\n let spaceId: string | undefined;\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession({\n delegationHeader: delegation.delegationHeader,\n delegationCid: delegation.cid,\n spaceId: delegation.spaceId,\n jwk: identity.jwk,\n verificationMethod: identity.did,\n tinycloudHosts: [this.#config.nodeHost],\n });\n const activated = await activateValidatedRuntimeDelegation(node, delegation, {\n host: this.#config.nodeHost,\n authorize: (permissions) => {\n const derivedOwner = nativeOwnerForConnectorGrant(permissions);\n const signedSpace = permissions[0]?.space;\n if (derivedOwner === undefined || signedSpace === undefined) return false;\n const metadataOwner = canonicalOwnerDid(\n `did:pkh:eip155:${delegation.chainId}:${delegation.ownerAddress}`,\n );\n if (metadataOwner !== derivedOwner ||\n delegation.spaceId.toLowerCase() !== signedSpace.toLowerCase()) return false;\n ownerDid = derivedOwner;\n spaceId = signedSpace;\n return true;\n },\n });\n if (ownerDid === undefined || spaceId === undefined ||\n !samePrincipal(activated.audience, normalizeDid(identity.did)) ||\n activated.expiry.getTime() > now + NATIVE_GRANT_MAX_LIFETIME_SECONDS * 1_000) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n return {\n ownerDid,\n spaceId,\n permissions: [...activated.effectivePermissions],\n cid: activated.cid,\n expiresAt: activated.expiry,\n delegation: activated.delegation,\n };\n } catch (error) {\n if (error instanceof NativeGrantValidationError) throw error;\n if (error instanceof RuntimeDelegationRejectedError) {\n throw new NativeGrantValidationError(\n error.reason === \"expired\"\n ? \"native_grant_expired\"\n : error.reason === \"activation_unavailable\"\n ? \"native_grant_validation_unavailable\"\n : \"native_grant_rejected\",\n );\n }\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n }\n\n #nativeGrantPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"native-grant.json\");\n }\n #tenantId(subject: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret).update(`tenant:${subject}`).digest(\"hex\");\n }\n\n #signState(tenantId: string, nonce: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret)\n .update(`approval:${tenantId}:${nonce}`)\n .digest(\"base64url\");\n }\n\n #profilePath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"profile.json\");\n }\n\n #keyPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"key.json\");\n }\n\n #sessionPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"session.json\");\n }\n\n #additionalPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"additional-delegations.json\");\n }\n\n #pendingPath(stateRoot: string, nonce: string): string {\n return join(this.#pendingDirectory(stateRoot), `${nonce}.json`);\n }\n\n #pendingDirectory(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"pending\");\n }\n}\n\nlet wasmInitialized = false;\n\nfunction generateSessionKey(): { jwk: Record<string, unknown>; did: string } {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = manager.createSessionKey(\"hosted-mcp\");\n const serialized = manager.jwk(keyId);\n if (!serialized) throw new Error(\"Could not generate the hosted delegate key.\");\n return { jwk: JSON.parse(serialized) as Record<string, unknown>, did: manager.getDID(keyId) };\n}\n\nfunction didFromJwk(jwk: Record<string, unknown>): string {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = importKey(manager, JSON.stringify(jwk), \"hosted-mcp\");\n return manager.getDID(keyId);\n}\n\nfunction ensureWasm(): void {\n if (wasmInitialized) return;\n initPanicHook();\n wasmInitialized = true;\n}\n\nfunction revocationFromResult(error: Record<string, unknown>): NodeRevocation | undefined {\n const details = error.details;\n if (!isRecord(details) || typeof details.revokedCid !== \"string\") return undefined;\n if (details.reason === \"delegation_revoked\") {\n return { reason: \"delegation_revoked\", revokedCid: details.revokedCid };\n }\n if (details.reason === \"delegation_ancestor_revoked\" && typeof details.ancestorCid === \"string\") {\n return {\n reason: \"delegation_ancestor_revoked\",\n revokedCid: details.revokedCid,\n ancestorCid: details.ancestorCid,\n };\n }\n return undefined;\n}\n\n/**\n * Parse the OpenKey callback. Every signed-proof field is required: without\n * them `restoreSession` verifies nothing and `node.did` would fall back to the\n * tenant's own key.\n */\nfunction sessionFromCallback(data: Record<string, unknown>, privateJwk: Record<string, unknown>): CallbackSession {\n const delegationHeader = data.delegationHeader;\n if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== \"string\" ||\n typeof data.delegationCid !== \"string\" || typeof data.spaceId !== \"string\" ||\n typeof data.verificationMethod !== \"string\" || typeof data.address !== \"string\" ||\n typeof data.chainId !== \"number\" || typeof data.siwe !== \"string\" ||\n typeof data.signature !== \"string\") {\n throw new Error(\"OpenKey returned an incomplete delegation.\");\n }\n return {\n delegationHeader: { Authorization: delegationHeader.Authorization },\n delegationCid: data.delegationCid,\n spaceId: data.spaceId,\n jwk: privateJwk,\n verificationMethod: data.verificationMethod,\n address: data.address,\n chainId: data.chainId,\n siwe: data.siwe,\n signature: data.signature,\n };\n}\n\nfunction publicJwk(jwk: Record<string, unknown>): Record<string, unknown> {\n const copy = { ...jwk };\n for (const field of [\"d\", \"p\", \"q\", \"dp\", \"dq\", \"qi\", \"oth\", \"k\"]) delete copy[field];\n return copy;\n}\n\nfunction samePrincipal(left: string | undefined, right: string): boolean {\n if (typeof left !== \"string\") return false;\n try {\n return principalDidEquals(left, right);\n } catch {\n return false;\n }\n}\n\nfunction normalizeDid(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\nfunction sameNodeHost(left: string, right: string): boolean {\n try {\n const normalize = (value: string): string => {\n const url = new URL(value);\n if (url.username !== \"\" || url.password !== \"\") return \"\";\n url.hash = \"\";\n url.search = \"\";\n url.pathname = url.pathname.replace(/\\/+$/, \"\");\n return url.toString().replace(/\\/+$/, \"\");\n };\n return normalize(left) !== \"\" && normalize(left) === normalize(right);\n } catch {\n return false;\n }\n}\n\nfunction isPermissionEntry(value: unknown): value is PermissionEntry {\n return isRecord(value) && typeof value.service === \"string\" && typeof value.space === \"string\" &&\n typeof value.path === \"string\" && Array.isArray(value.actions) &&\n value.actions.every((action) => typeof action === \"string\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function secureDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n await chmod(path, 0o700);\n}\n\nasync function secureWrite(path: string, value: unknown): Promise<void> {\n const directory = dirname(path);\n await secureDirectory(directory);\n const temporary = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`;\n await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}\\n`, { mode: 0o600 });\n await rename(temporary, path);\n await chmod(path, 0o600);\n}\n\nfunction jsonReplacer(_key: string, value: unknown): unknown {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nasync function readJson<T>(path: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function readOptionalText(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function restoreOptionalText(path: string, contents: string | null): Promise<void> {\n if (contents === null) {\n await rm(path, { force: true });\n return;\n }\n await secureDirectory(dirname(path));\n await writeFile(path, contents, { mode: 0o600 });\n await chmod(path, 0o600);\n}\n\nasync function reusablePending(\n directory: string,\n expected: Pick<PendingApproval, \"tenantId\" | \"approvalEpoch\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): Promise<PendingApproval | undefined> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return undefined;\n throw error;\n }\n const active: PendingApproval[] = [];\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(directory, name);\n const pending = await readJson<PendingApproval>(path).catch(() => null);\n if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(path, { force: true });\n continue;\n }\n active.push(pending);\n if (samePendingRequest(pending, expected)) return pending;\n }\n if (active.length >= 64) {\n active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));\n await rm(join(directory, `${active[0]!.nonce}.json`), { force: true });\n }\n return undefined;\n}\n\nfunction samePendingRequest(\n pending: PendingApproval,\n expected: Pick<PendingApproval, \"tenantId\" | \"approvalEpoch\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): boolean {\n return pending.version === 1 && pending.tenantId === expected.tenantId &&\n (pending.approvalEpoch ?? 0) === expected.approvalEpoch &&\n pending.kind === expected.kind && pending.requestId === expected.requestId &&\n JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) &&\n JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);\n}\n","import { timingSafeEqual } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/node-sdk\";\n\nexport const NATIVE_SERVICE_CREDENTIAL_HEADER = \"X-TinyCloud-Service-Credential\";\nexport const NATIVE_OWNER_DID_HEADER = \"X-TinyCloud-Owner-DID\";\nexport const NATIVE_GRANT_MAX_LIFETIME_SECONDS = 30 * 24 * 60 * 60;\nexport const NATIVE_GRANT_REQUIRED = \"native_grant_required\";\nexport const NATIVE_GRANT_EXPIRED = \"native_grant_expired\";\nexport const NATIVE_GRANT_REJECTED = \"native_grant_rejected\";\nexport const NATIVE_SERVICE_UNAUTHORIZED = \"native_service_unauthorized\";\nexport const NATIVE_SERVICE_UNAVAILABLE = \"native_service_unavailable\";\nexport const NATIVE_GRANT_VALIDATION_UNAVAILABLE = \"native_grant_validation_unavailable\";\nexport const MAX_NATIVE_GRANT_BODY_BYTES = 256 * 1024;\n\nexport function serviceCredentialMatches(supplied: string | null, configured: string | undefined): boolean {\n if (supplied === null || configured === undefined) return false;\n const suppliedBytes = Buffer.from(supplied, \"utf8\");\n const configuredBytes = Buffer.from(configured, \"utf8\");\n return suppliedBytes.byteLength === configuredBytes.byteLength &&\n timingSafeEqual(suppliedBytes, configuredBytes);\n}\nconst OWNER_APPLICATIONS_SPACE = /^tinycloud:pkh:eip155:([1-9][0-9]*):(0x[0-9a-f]{40}):applications$/i;\nconst SQL_PATH = \"xyz.tinycloud.tinychat/connectors\";\nconst KV_PREFIX = \"xyz.tinycloud.tinychat/connectors/\";\n\nexport function canonicalOwnerDid(value: string): string | undefined {\n const match = /^did:pkh:eip155:([1-9][0-9]*):(0x[0-9a-f]{40})$/i.exec(value);\n if (!match) return undefined;\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) return undefined;\n return `did:pkh:eip155:${chainId}:${match[2]!.toLowerCase()}`;\n}\n\n/** Derive the owner solely from the signed applications-space capabilities. */\nexport function nativeOwnerForConnectorGrant(\n permissions: readonly PermissionEntry[],\n): string | undefined {\n if (permissions.length !== 2) return undefined;\n const sqlEntries = permissions.filter((permission) => permission.service === \"tinycloud.sql\");\n const kvEntries = permissions.filter((permission) => permission.service === \"tinycloud.kv\");\n if (sqlEntries.length !== 1 || kvEntries.length !== 1) return undefined;\n const sql = sqlEntries[0]!;\n const kv = kvEntries[0]!;\n if (typeof sql.space !== \"string\" || typeof kv.space !== \"string\" ||\n sql.path !== SQL_PATH || kv.path !== KV_PREFIX) return undefined;\n if (!actionsEqual(sql.actions, [\"tinycloud.sql/read\"]) ||\n !actionsEqual(kv.actions, [\"tinycloud.kv/get\", \"tinycloud.kv/list\"])) return undefined;\n if (hasCaveats(sql) || hasCaveats(kv)) return undefined;\n\n const sqlSpace = ownerFromApplicationsSpace(sql.space);\n const kvSpace = ownerFromApplicationsSpace(kv.space);\n return sqlSpace !== undefined && sqlSpace === kvSpace ? sqlSpace : undefined;\n}\n\nfunction ownerFromApplicationsSpace(space: string): string | undefined {\n const match = OWNER_APPLICATIONS_SPACE.exec(space);\n if (!match) return undefined;\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) return undefined;\n return `did:pkh:eip155:${chainId}:${match[2]!.toLowerCase()}`;\n}\n\nfunction actionsEqual(actual: readonly string[], expected: readonly string[]): boolean {\n const actualActions = [...actual].sort();\n const expectedActions = [...expected].sort();\n return actualActions.length === expectedActions.length &&\n actualActions.every((value, index) => value === expectedActions[index]);\n}\n\nfunction hasCaveats(permission: PermissionEntry): boolean {\n return Object.hasOwn(permission, \"caveats\") && permission.caveats !== undefined;\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,oCAAoC;;;ACF7C,SAAS,iBAAiB;AAC1B,SAAS,kBAA0C;;;ACDnD,SAAS,qBAAqB;AAC9B,SAAS,YAAY;AAErB,SAAS,sBAA4D;AACrE,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;;;ACmBzB,SAAS,gBACd,QACA,WAA2C,CAAC,GAC5C,UAAgC,CAAC,GAClB;AACf,MAAI,YAAsC,2BAA2B,MAAM,IACvE,iBAAiB,QAAQ,QAAQ,IACjC;AAAA,IACA,QAAQ;AAAA,IACR,WAAW,CAAC;AAAA,IACZ,SAAS,CAAC;AAAA,IACV,OAAO,EAAE,MAAM,iBAAiB;AAAA,EAClC;AACF,MAAI;AACJ,MAAI,QAAQ,YAAY,UAAU;AAChC,iBAAa,KAAK,UAAU,SAAS;AACrC,SACG,QAAQ,aAAa,QACpB,QAAQ,gBAAgB,4BACxB,QAAQ,gBAAgB,2BAC1B,WAAW,SAAS,K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AAAA,CAAI;AAC1D;","names":["join","McpServer","fromJsonSchema","timingSafeEqual","join","invokeOperation","join","invokeOperation","tenant","pending","timingSafeEqual","join","authInfo","McpServer","originFailure","fromJsonSchema"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/server.ts","../src/tools.ts","../src/results.ts","../src/logging.ts","../src/schemas.ts","../package.json","../src/version.ts","../src/http.ts","../src/oauth.ts","../src/token-status.ts","../src/remote-store.ts","../src/native-auth.ts"],"sourcesContent":["import { basename } from \"node:path\";\n\nimport { resolveInvocationProfileName } from \"@tinycloud/operations/profile\";\n\nimport { serveTinyCloudMcp, MCP_VERSION } from \"./server.js\";\n\nexport interface ParsedCliOptions {\n readonly profile?: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n readonly help: boolean;\n readonly version: boolean;\n}\n\nconst HELP = `TinyCloud delegated operations MCP server\n\nUsage: tinycloud-mcp [options]\n\nOptions:\n --profile <name> Pin the TinyCloud profile for this process\n --allow-owner-profile Allow data execution for an explicitly selected owner profile\n --help Show this help\n --version Show the package version\n`;\n\nexport function parseCliOptions(arguments_: readonly string[]): ParsedCliOptions {\n let profile: string | undefined;\n let explicitProfile = false;\n let allowOwnerProfile = false;\n let help = false;\n let version = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === \"--help\" || argument === \"-h\") {\n help = true;\n continue;\n }\n if (argument === \"--version\" || argument === \"-v\") {\n version = true;\n continue;\n }\n if (argument === \"--allow-owner-profile\") {\n allowOwnerProfile = true;\n continue;\n }\n if (argument === \"--profile\") {\n const value = arguments_[index + 1];\n if (value === undefined || value.startsWith(\"-\") || value.trim().length === 0) {\n throw new Error(\"--profile requires a non-empty profile name.\");\n }\n profile = value;\n explicitProfile = true;\n index += 1;\n continue;\n }\n if (argument?.startsWith(\"--profile=\")) {\n const value = argument.slice(\"--profile=\".length);\n if (value.trim().length === 0) throw new Error(\"--profile requires a non-empty profile name.\");\n profile = value;\n explicitProfile = true;\n continue;\n }\n throw new Error(`Unknown option: ${argument}`);\n }\n\n return { profile, explicitProfile, allowOwnerProfile, help, version };\n}\n\nexport async function main(arguments_: readonly string[] = process.argv.slice(2)): Promise<number> {\n let options: ParsedCliOptions;\n try {\n options = parseCliOptions(arguments_);\n } catch (error) {\n process.stderr.write(\"[tinycloud-mcp] Invalid command line.\\n\");\n return 2;\n }\n\n if (options.help) {\n process.stdout.write(HELP);\n return 0;\n }\n if (options.version) {\n process.stdout.write(`${MCP_VERSION}\\n`);\n return 0;\n }\n\n let profile: string;\n try {\n profile = await resolveInvocationProfileName(options.profile);\n } catch {\n process.stderr.write(\"[tinycloud-mcp] Could not select a profile.\\n\");\n return 2;\n }\n\n // The selected profile is now a value captured by the server closure. Every\n // operation receives it explicitly and cannot re-read TC_PROFILE/config.\n serveTinyCloudMcp({\n profile,\n explicitProfile: options.explicitProfile,\n allowOwnerProfile: options.allowOwnerProfile,\n });\n return 0;\n}\n\nfunction isDirectInvocation(): boolean {\n const argv = process.argv[1];\n if (argv === undefined) return false;\n return basename(argv) === \"cli.js\" || basename(argv) === \"cli.cjs\" || basename(argv) === \"tinycloud-mcp\";\n}\n\nif (isDirectInvocation()) {\n void main().then((code) => {\n if (code !== 0) process.exitCode = code;\n }).catch(() => {\n process.stderr.write(\"[tinycloud-mcp] Startup failed.\\n\");\n process.exitCode = 1;\n });\n}\n","import { McpServer } from \"@modelcontextprotocol/server\";\nimport { serveStdio, type StdioServerHandle } from \"@modelcontextprotocol/server/stdio\";\n\nimport { createJsonSchemaValidator, registerTinyCloudTools, type McpStartupSelection } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nexport const MCP_SERVER_NAME = \"tinycloud-mcp\";\nexport { MCP_VERSION } from \"./version.js\";\n/** The stdio server is always the local surface. */\nexport type LocalMcpSelection = Omit<McpStartupSelection, \"surface\">;\n\nexport function createTinyCloudMcpServer(selection: LocalMcpSelection): McpServer {\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n { jsonSchemaValidator: validator },\n );\n registerTinyCloudTools(server, { ...selection, surface: \"local\" }, validator);\n return server;\n}\n\n/** Start the only supported MCP transport: local stdio. */\nexport function serveTinyCloudMcp(selection: LocalMcpSelection): StdioServerHandle {\n return serveStdio(\n () => createTinyCloudMcpServer(selection),\n { onerror: () => writeBoundedDiagnostic(\"MCP transport error\") },\n );\n}\n\nfunction writeBoundedDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp] ${message}\\n`);\n}\n","import { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { fromJsonSchema, type McpServer, type ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport { AjvJsonSchemaValidator } from \"@modelcontextprotocol/server/validators/ajv\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nimport { toMcpToolResult, type McpToolResult } from \"./results.js\";\nimport { logToolCall } from \"./logging.js\";\nimport { toMcpJsonSchema } from \"./schemas.js\";\n\nexport const TOOL_NAMES = [\n \"tinycloud_status\",\n \"tinycloud_auth_status\",\n \"tinycloud_auth_capabilities\",\n \"tinycloud_auth_request\",\n \"tinycloud_auth_import\",\n \"tinycloud_account_spaces_list\",\n \"tinycloud_account_applications_list\",\n \"tinycloud_kv_list\",\n \"tinycloud_kv_get\",\n \"tinycloud_kv_head\",\n \"tinycloud_kv_put\",\n \"tinycloud_kv_delete\",\n \"tinycloud_knowledge_list\",\n \"tinycloud_knowledge_read\",\n \"tinycloud_sql_schema_inspect\",\n \"tinycloud_sql_query\",\n \"tinycloud_sql_execute\",\n \"tinycloud_secrets_get\",\n \"tinycloud_secrets_status\",\n \"tinycloud_apps_context\",\n \"tinycloud_apps_read\",\n \"tinycloud_apps_write\",\n \"tinycloud_apps_query\",\n] as const;\n\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\n/** Private stdio/hosted surfaces and the restricted public plugin. */\nexport type McpSurface = \"local\" | \"hosted\" | \"public\";\n\nexport interface McpStartupSelection {\n /** Which server registers the tools; bindings not on this surface are skipped. */\n readonly surface: McpSurface;\n readonly profile: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n /** Absolute TinyCloud home used to isolate one hosted principal. */\n readonly stateRoot?: string;\n /** Optional allowlist for surfaces whose grant is narrower than hosted OAuth. */\n readonly allowedTools?: readonly ToolName[];\n /** Check node authority only when an operation needs the account. */\n readonly beforeOperation?: () => Promise<void>;\n /** Hosted transports may attach a browser approval URL to canonical results. */\n readonly transformOperationResult?: (result: unknown, invocation: McpOperationInvocation) => Promise<unknown>;\n}\n\nexport interface McpOperationInvocation {\n readonly operationId: string;\n readonly operationVersion: number;\n readonly input: unknown;\n}\n\nexport interface McpInvocationTarget {\n readonly profile: string;\n readonly allowOwnerProfile?: true;\n readonly stateRoot?: string;\n}\n\n/** Project one startup selection into the only owner-sensitive target shape. */\nexport function invocationTargetForMcp(\n selection: Omit<McpStartupSelection, \"surface\">,\n): McpInvocationTarget {\n return {\n profile: selection.profile,\n ...(selection.explicitProfile && selection.allowOwnerProfile\n ? { allowOwnerProfile: true }\n : {}),\n ...(selection.stateRoot === undefined ? {} : { stateRoot: selection.stateRoot }),\n };\n}\n\ninterface CatalogOperation {\n readonly id: string;\n readonly version: number;\n readonly title: string;\n readonly description: string;\n readonly input: Record<string, unknown>;\n readonly result: Record<string, unknown>;\n}\n\ninterface OperationsCatalog {\n readonly stableErrors: readonly string[];\n readonly operations: readonly CatalogOperation[];\n}\n\n// The require anchor is this module, never the consumer entrypoint. In ESM\n// tsup preserves import.meta.url; in CJS it rewrites the same module-relative\n// anchor to the generated __filename, so both formats stay in MCP's package\n// dependency boundary.\nconst packageRequire = createRequire(\n typeof __dirname === \"string\" ? join(__dirname, \"tools.cjs\") : import.meta.url,\n);\nconst generatedCatalog = packageRequire(\n \"@tinycloud/operations/operations.json\",\n) as OperationsCatalog;\nconst stableErrorCodes: Readonly<Record<string, true>> = Object.fromEntries(\n generatedCatalog.stableErrors.map((code) => [code, true as const]),\n);\n\nexport interface ToolBinding {\n readonly name: ToolName;\n readonly operationId: string;\n readonly operationVersion: number;\n readonly readOnlyHint: boolean;\n readonly idempotentHint: boolean;\n readonly destructiveHint: boolean;\n readonly openWorldHint: boolean;\n /** Surfaces that register this tool; omitted means private local and hosted surfaces only. */\n readonly surfaces?: readonly McpSurface[];\n}\n\nconst PRIVATE_SURFACES: readonly McpSurface[] = [\"local\", \"hosted\"];\n\n/** The surfaces a binding is registered on. */\nexport function bindingSurfaces(binding: ToolBinding): readonly McpSurface[] {\n return binding.surfaces ?? PRIVATE_SURFACES;\n}\n\nexport const TOOL_BINDINGS: readonly ToolBinding[] = [\n {\n name: \"tinycloud_status\",\n operationId: \"tinycloud.status.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_status\",\n operationId: \"tinycloud.auth.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_capabilities\",\n operationId: \"tinycloud.auth.capabilities\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_request\",\n operationId: \"tinycloud.auth.request\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_import\",\n operationId: \"tinycloud.auth.import\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n // Hosted delegations must arrive through the owner/request-bound OpenKey callback,\n // not a caller-supplied import artifact.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_account_spaces_list\",\n operationId: \"tinycloud.account.spaces.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_account_applications_list\",\n operationId: \"tinycloud.account.applications.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_list\",\n operationId: \"tinycloud.kv.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_get\",\n operationId: \"tinycloud.kv.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_head\",\n operationId: \"tinycloud.kv.head\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_put\",\n operationId: \"tinycloud.kv.put\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_delete\",\n operationId: \"tinycloud.kv.delete\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_knowledge_list\",\n operationId: \"tinycloud.knowledge.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_knowledge_read\",\n operationId: \"tinycloud.knowledge.read\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_schema_inspect\",\n operationId: \"tinycloud.sql.schema.inspect\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_query\",\n operationId: \"tinycloud.sql.query\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_execute\",\n operationId: \"tinycloud.sql.execute\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_get\",\n operationId: \"tinycloud.secrets.get\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_status\",\n operationId: \"tinycloud.secrets.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n // Hosted has no persistent reauthorization path for a revoked session\n // yet (TC-896), so status is local/stdio only.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_apps_context\",\n operationId: \"tinycloud.apps.context\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_read\",\n operationId: \"tinycloud.apps.read\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_write\",\n operationId: \"tinycloud.apps.write\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n {\n name: \"tinycloud_apps_query\",\n operationId: \"tinycloud.apps.query\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: false,\n surfaces: [\"hosted\", \"public\"],\n },\n] as const;\n\n// Project once per process; never mutate the catalog shared with non-MCP consumers.\nconst definitions = new Map(generatedCatalog.operations.map((operation) => [\n `${operation.id}@${operation.version}`,\n {\n ...operation,\n input: toMcpJsonSchema(operation.input),\n result: toMcpJsonSchema(operation.result),\n },\n]));\n\nexport function createJsonSchemaValidator(): AjvJsonSchemaValidator {\n return new AjvJsonSchemaValidator();\n}\n\nexport function registerTinyCloudTools(\n server: McpServer,\n selection: McpStartupSelection,\n validator: AjvJsonSchemaValidator,\n): void {\n const bindings = TOOL_BINDINGS.filter((binding) =>\n bindingSurfaces(binding).includes(selection.surface) &&\n (selection.allowedTools === undefined || selection.allowedTools.includes(binding.name)));\n for (const binding of bindings) {\n const operation = definitions.get(`${binding.operationId}@${binding.operationVersion}`);\n if (operation === undefined) {\n throw new Error(`Generated operations catalog is missing ${binding.operationId}@${binding.operationVersion}.`);\n }\n\n const inputSchema = fromJsonSchema(\n operation.input as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const outputSchema = fromJsonSchema(\n operation.result as unknown as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const annotations: ToolAnnotations = {\n readOnlyHint: binding.readOnlyHint,\n idempotentHint: binding.idempotentHint,\n destructiveHint: binding.destructiveHint,\n openWorldHint: binding.openWorldHint,\n };\n\n server.registerTool(\n binding.name,\n {\n title: operation.title,\n description: operation.description,\n inputSchema,\n outputSchema,\n annotations,\n },\n async (input: unknown): Promise<McpToolResult> => {\n const startedAt = performance.now();\n const metrics = { replayedGrants: 0 };\n let code = \"INTERNAL_ERROR\";\n try {\n await selection.beforeOperation?.();\n const result = await invokeOperation(\n binding.operationId,\n binding.operationVersion,\n invocationTargetForMcp(selection),\n input,\n metrics,\n );\n const projected = selection.transformOperationResult === undefined\n ? result\n : await selection.transformOperationResult(result, {\n operationId: binding.operationId,\n operationVersion: binding.operationVersion,\n input,\n });\n const response = toMcpToolResult(projected, bindings, {\n surface: selection.surface === \"local\" ? \"local\" : \"hosted\",\n readOnly: binding.readOnlyHint,\n operationId: binding.operationId,\n });\n code = outcomeCode(response.structuredContent);\n return response;\n } finally {\n if (selection.surface !== \"local\") {\n logToolCall(binding.name, code, startedAt, metrics.replayedGrants);\n }\n }\n },\n );\n }\n}\n\nfunction outcomeCode(result: McpToolResult[\"structuredContent\"]): string {\n if (result.status === \"error\") {\n const error = result.error as { code?: unknown } | undefined;\n return typeof error?.code === \"string\" && Object.hasOwn(stableErrorCodes, error.code) ? error.code : \"INTERNAL_ERROR\";\n }\n if (result.status !== \"ok\") return result.status;\n const output = result.output as { outcome?: unknown; ops?: readonly { outcome?: unknown }[] } | undefined;\n if (output?.outcome === \"COPY_PARTIAL\") return \"COPY_PARTIAL\";\n if (Array.isArray(output?.ops) && output.ops.some((op) => op.outcome !== \"ok\")) return \"PARTIAL\";\n return \"ok\";\n}\n\nexport function toolBindingsForTest(): readonly ToolBinding[] {\n return TOOL_BINDINGS;\n}\n","/** MCP preserves the canonical envelope; hosted clients also receive readable JSON. */\nexport interface CanonicalOperationResult {\n readonly status: \"ok\" | \"authority_required\" | \"setup_required\" | \"error\";\n readonly [key: string]: unknown;\n}\n\nexport interface McpToolResult extends CallToolResult {\n readonly content: [{ readonly type: \"text\"; readonly text: string }];\n readonly structuredContent: CanonicalOperationResult;\n}\n\n/** The binding fields needed to name the tool that runs an operation. */\nexport interface RecoveryToolBinding {\n readonly name: string;\n readonly operationId: string;\n}\n\nexport interface McpToolResultOptions {\n readonly surface?: \"hosted\" | \"local\";\n readonly readOnly?: boolean;\n /** Trusted operation identity from the tool binding, not operation output. */\n readonly operationId?: string;\n}\n\nexport function toMcpToolResult(\n result: unknown,\n bindings: readonly RecoveryToolBinding[] = [],\n options: McpToolResultOptions = {},\n): McpToolResult {\n let canonical: CanonicalOperationResult = isCanonicalOperationResult(result)\n ? withRecoveryTool(result, bindings)\n : {\n status: \"error\",\n operation: {},\n context: {},\n error: { code: \"INTERNAL_ERROR\" },\n };\n let serialized: string | undefined;\n if (options.surface === \"hosted\") {\n serialized = JSON.stringify(canonical);\n if (\n (options.readOnly === true ||\n options.operationId === \"tinycloud.apps.context\" ||\n options.operationId === \"tinycloud.apps.query\") &&\n serialized.length > 100_000\n ) {\n const sql = options.operationId?.startsWith(\"tinycloud.sql.\") ||\n options.operationId === \"tinycloud.apps.query\";\n canonical = {\n status: \"error\",\n operation: canonical.operation,\n context: canonical.context,\n error: {\n code: sql ? \"SQL_RESULT_LIMIT_EXCEEDED\" : \"KV_RESPONSE_TOO_LARGE\",\n message: sql\n ? \"The result exceeds 100,000 characters. Select fewer columns or rows, add a WHERE filter or a smaller LIMIT, or aggregate the data.\"\n : \"The result exceeds 100,000 characters. Request fewer keys, narrow the prefix, or use a smaller page size.\",\n retryable: false,\n },\n };\n serialized = JSON.stringify(canonical);\n }\n }\n\n return {\n content: [{\n type: \"text\",\n text: resultSummary(canonical.status) +\n (serialized !== undefined && !(options.operationId === \"tinycloud.secrets.get\" && canonical.status === \"ok\")\n ? `\\n${serialized}` : \"\"),\n }],\n structuredContent: canonical,\n };\n}\n\n/**\n * A redacted `complete_migration` recovery names an operation; MCP clients\n * call tools, so name the bound tool. `tool` comes from the code-owned binding\n * table only, never from operation data, and is added after redaction. An\n * operationId with no binding gets no `tool`.\n */\nfunction withRecoveryTool(\n result: CanonicalOperationResult,\n bindings: readonly RecoveryToolBinding[],\n): CanonicalOperationResult {\n if (result.status !== \"error\") return result;\n // The kernel's redaction already constrained `error.details.recovery` to a\n // safe recovery object; only its discriminant and operationId are read here.\n const error = result.error as\n | { readonly details?: { readonly recovery?: { readonly action?: unknown; readonly operationId?: unknown } } }\n | undefined;\n const recovery = error?.details?.recovery;\n if (recovery?.action !== \"complete_migration\") return result;\n const binding = bindings.find((candidate) => candidate.operationId === recovery.operationId);\n if (binding === undefined) return result;\n return {\n ...result,\n error: { ...error, details: { ...error?.details, recovery: { ...recovery, tool: binding.name } } },\n };\n}\n\n/** The canonical envelope immediately before MCP protocol serialization. */\nexport function canonicalMcpAdapterResult(result: unknown): CanonicalOperationResult {\n return toMcpToolResult(result).structuredContent;\n}\n\nfunction isCanonicalOperationResult(value: unknown): value is CanonicalOperationResult {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const status = (value as { status?: unknown }).status;\n return status === \"ok\" ||\n status === \"authority_required\" ||\n status === \"setup_required\" ||\n status === \"error\";\n}\n\nfunction resultSummary(status: CanonicalOperationResult[\"status\"]): string {\n switch (status) {\n case \"ok\":\n return \"TinyCloud operation completed; use the structured result.\";\n case \"authority_required\":\n return \"TinyCloud authority is required; use the structured request and approval action.\";\n case \"setup_required\":\n return \"TinyCloud setup is required; use the structured setup action.\";\n case \"error\":\n return \"TinyCloud operation failed; use the structured error.\";\n }\n}\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n","/** Only code-owned tool names/codes and numeric counters reach this sink. */\nexport function logToolCall(\n tool: string,\n code: string,\n startedAt: number,\n replayedGrants: number,\n): void {\n process.stderr.write(`${JSON.stringify({\n tool,\n code,\n durationMs: Math.max(0, Math.round(performance.now() - startedAt)),\n replayedGrants,\n })}\\n`);\n}\n","type JsonSchema = boolean | Record<string, unknown>;\n\nconst DRAFT_7 = \"http://json-schema.org/draft-07/schema#\";\nconst DRAFT_2020_12 = \"https://json-schema.org/draft/2020-12/schema\";\nconst schemaMaps = new Set([\"properties\", \"patternProperties\", \"definitions\", \"$defs\"]);\nconst schemaArrays = new Set([\"allOf\", \"anyOf\", \"oneOf\"]);\nconst schemaValues = new Set([\n \"additionalProperties\", \"items\", \"contains\", \"propertyNames\", \"not\", \"if\", \"then\", \"else\",\n]);\n\n/** Project the catalog's shared Draft-07/2020-12 vocabulary without changing its validation rules. */\nexport function toMcpJsonSchema(schema: Record<string, unknown>): Record<string, unknown>;\nexport function toMcpJsonSchema(schema: JsonSchema): JsonSchema;\nexport function toMcpJsonSchema(schema: JsonSchema): JsonSchema {\n if (typeof schema === \"boolean\") return schema;\n // These forms need a semantic migration, not just a dialect declaration. The\n // generated catalog does not use them; fail closed if that contract changes.\n if (Array.isArray(schema.items) || \"additionalItems\" in schema || \"dependencies\" in schema ||\n (\"$ref\" in schema && Object.keys(schema).some((key) => key !== \"$ref\"))) {\n throw new Error(\"The operations schema needs a semantic migration to JSON Schema 2020-12.\");\n }\n\n const projected: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === \"$schema\") {\n if (value !== DRAFT_7) throw new Error(`Unsupported operations schema dialect: ${String(value)}.`);\n projected[key] = DRAFT_2020_12;\n } else if (schemaMaps.has(key)) {\n projected[key] = Object.fromEntries(Object.entries(value as Record<string, JsonSchema>)\n .map(([name, child]) => [name, toMcpJsonSchema(child)]));\n } else if (schemaArrays.has(key)) {\n projected[key] = (value as JsonSchema[]).map(toMcpJsonSchema);\n } else if (schemaValues.has(key)) {\n projected[key] = toMcpJsonSchema(value as JsonSchema);\n } else {\n // Descriptions, defaults, examples and const/enum values are data, not schemas.\n projected[key] = value;\n }\n }\n return projected;\n}\n","{\n \"name\": \"@tinycloud/mcp\",\n \"version\": \"0.8.4-beta.7\",\n \"description\": \"TinyCloud delegated operations MCP server\",\n \"keywords\": [\n \"tinycloud\",\n \"mcp\",\n \"model-context-protocol\",\n \"agents\",\n \"delegation\",\n \"ucan\",\n \"kv\",\n \"sqlite\"\n ],\n \"author\": \"TinyCloud, Inc.\",\n \"license\": \"EGPL\",\n \"type\": \"module\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"tinycloud-mcp\": \"./bin/tinycloud-mcp\",\n \"tinycloud-mcp-http\": \"./bin/tinycloud-mcp-http\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./server\": {\n \"types\": \"./dist/server.d.ts\",\n \"import\": \"./dist/server.js\",\n \"require\": \"./dist/server.cjs\"\n },\n \"./tools\": {\n \"types\": \"./dist/tools.d.ts\",\n \"import\": \"./dist/tools.js\",\n \"require\": \"./dist/tools.cjs\"\n },\n \"./results\": {\n \"types\": \"./dist/results.d.ts\",\n \"import\": \"./dist/results.js\",\n \"require\": \"./dist/results.cjs\"\n },\n \"./http\": {\n \"types\": \"./dist/http.d.ts\",\n \"import\": \"./dist/http.js\",\n \"require\": \"./dist/http.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"bin\",\n \"generated\",\n \"skills\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"test\": \"bun run build && bun scripts/test.ts && bun run check:generated\",\n \"test:stdio\": \"bun run build && bun test src/stdio.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"start:http\": \"node dist/http-cli.js\",\n \"generate\": \"bun scripts/generate.ts\",\n \"check:generated\": \"bun scripts/generate.ts --check\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/node\": \"2.0.0-beta.5\",\n \"@modelcontextprotocol/server\": \"2.0.0-beta.5\",\n \"@tinycloud/node-sdk\": \"3.9.0-beta.8\",\n \"@tinycloud/node-sdk-wasm\": \"1.7.8\",\n \"@tinycloud/operations\": \"0.7.8-beta.7\",\n \"jose\": \"6.2.4\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"2.0.0-beta.5\",\n \"@types/node\": \"^20\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"^5.9.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/TinyCloudLabs/js-sdk\"\n },\n \"homepage\": \"https://docs.tinycloud.xyz/cli/mcp\"\n}\n","import packageMetadata from \"../package.json\";\n\nexport const MCP_VERSION = packageMetadata.version;\n","import { join } from \"node:path\";\n\nimport {\n McpServer,\n createMcpHandler,\n fromJsonSchema,\n getOAuthProtectedResourceMetadataUrl,\n hostHeaderValidationResponse,\n oauthMetadataResponse,\n requireBearerAuth,\n type AuthInfo,\n type OAuthMetadata,\n} from \"@modelcontextprotocol/server\";\nimport { RUNTIME_DELEGATION_REJECTIONS } from \"@tinycloud/node-sdk\";\n\nimport { createOpenKeyTokenVerifier } from \"./oauth.js\";\nimport { createTokenStatusChecker, type TokenStatusChecker, type TokenStatusConfig } from \"./token-status.js\";\nimport { logToolCall } from \"./logging.js\";\nimport {\n ApprovalOwnerMismatchError,\n ApprovalRequestError,\n ApprovalStageError,\n NativeGrantValidationError,\n RemoteTenantStore,\n type RemoteStoreConfig,\n} from \"./remote-store.js\";\nimport {\n MAX_NATIVE_GRANT_BODY_BYTES,\n NATIVE_GRANT_EXPIRED,\n NATIVE_GRANT_MAX_LIFETIME_SECONDS,\n NATIVE_GRANT_REJECTED,\n NATIVE_GRANT_REQUIRED,\n NATIVE_GRANT_VALIDATION_UNAVAILABLE,\n NATIVE_OWNER_DID_HEADER,\n NATIVE_SERVICE_UNAUTHORIZED,\n NATIVE_SERVICE_UNAVAILABLE,\n NATIVE_SERVICE_CREDENTIAL_HEADER,\n serviceCredentialMatches,\n} from \"./native-auth.js\";\nimport { MCP_SERVER_NAME } from \"./server.js\";\nimport { createJsonSchemaValidator, registerTinyCloudTools } from \"./tools.js\";\nimport type { McpOperationInvocation } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nconst REQUIRED_SCOPE = \"tinycloud:mcp\";\nconst LOCAL_CLI_PACKAGE = [\"@tinycloud\", \"cli\"].join(\"/\");\nconst LOCAL_MCP_PACKAGE = [\"@tinycloud\", \"mcp\"].join(\"/\");\n\nexport interface HostedMcpConfig extends RemoteStoreConfig {\n readonly oauthMetadata: OAuthMetadata;\n readonly allowedOrigins?: readonly string[];\n /**\n * OpenKey token introspection client (`TC_MCP_INTROSPECTION_URL` and client\n * credentials). The hosted server always sets this; without it only the\n * signed token claims are checked.\n */\n readonly introspection?: Omit<TokenStatusConfig, \"resourceUrl\">;\n}\n\nexport interface HostedMcpApp {\n readonly fetch: (request: Request) => Promise<Response>;\n readonly close: () => Promise<void>;\n}\n\nexport function createHostedMcpApp(config: HostedMcpConfig): HostedMcpApp {\n if (config.nativeServiceCredential !== undefined &&\n Buffer.byteLength(config.nativeServiceCredential, \"utf8\") < 32) {\n throw new Error(\"TC_MCP_NATIVE_SERVICE_CREDENTIAL must contain at least 32 bytes.\");\n }\n const resourceUrl = canonicalResourceUrl(config.publicUrl);\n const pluginUrl = new URL(\"./chatgpt/mcp\", resourceUrl);\n const statusFor = (resource: URL): TokenStatusChecker | undefined =>\n config.introspection === undefined\n ? undefined\n : createTokenStatusChecker({ ...config.introspection, resourceUrl: resource.toString() });\n const hosted = createHostedSurface(config, resourceUrl, \"hosted\", statusFor(resourceUrl));\n const plugin = createHostedSurface({\n ...config,\n nativeServiceCredential: undefined,\n stateDir: join(config.stateDir, \"chatgpt\"),\n approvalPath: new URL(\"./connect\", pluginUrl).pathname,\n }, pluginUrl, \"public\", statusFor(pluginUrl));\n const pluginPaths: Record<string, true> = {\n [pluginUrl.pathname]: true,\n [new URL(\"./connect\", pluginUrl).pathname]: true,\n [new URL(\"./connect/callback\", pluginUrl).pathname]: true,\n [new URL(getOAuthProtectedResourceMetadataUrl(pluginUrl)).pathname]: true,\n };\n return {\n fetch: (request) => (pluginPaths[new URL(request.url).pathname] === true ? plugin : hosted).fetch(request),\n close: async () => {\n await Promise.all([hosted.close(), plugin.close()]);\n },\n };\n}\n\nfunction createHostedSurface(\n config: HostedMcpConfig,\n resourceUrl: URL,\n surface: \"hosted\" | \"public\",\n tokenStatus: TokenStatusChecker | undefined,\n): HostedMcpApp {\n const connectPath = config.approvalPath ?? \"/connect\";\n const callbackPath = `${connectPath}/callback`;\n const issuer = String(config.oauthMetadata.issuer);\n const jwksUri = String(config.oauthMetadata.jwks_uri);\n const verifier = createOpenKeyTokenVerifier({\n issuer,\n audience: resourceUrl.toString(),\n jwksUri,\n requiredScope: REQUIRED_SCOPE,\n ...(tokenStatus === undefined ? {} : { tokenStatus }),\n });\n const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);\n const authenticate = requireBearerAuth({\n verifier,\n requiredScopes: [REQUIRED_SCOPE],\n resourceMetadataUrl,\n });\n const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });\n const nativeServiceIdentityEnabled = surface === \"hosted\" && config.nativeServiceCredential !== undefined;\n if (nativeServiceIdentityEnabled) void store.nativeServiceIdentity().catch(() => undefined);\n const handler = createMcpHandler(async ({ authInfo }) => {\n const nativeOwner = typeof authInfo?.extra?.nativeOwnerDid === \"string\"\n ? authInfo.extra.nativeOwnerDid\n : undefined;\n const identity = nativeOwner === undefined\n ? oauthIdentity(authInfo)\n : { subject: `native:${nativeOwner}`, ownerDids: [nativeOwner] };\n const { subject, ownerDids } = identity;\n const stateRoot = nativeOwner === undefined\n ? await store.initializeTenant(subject)\n : store.nativeTenantStateRoot(nativeOwner);\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n {\n jsonSchemaValidator: validator,\n instructions: nativeOwner === undefined\n ? surface === \"public\"\n ? \"Use TinyCloud only for the user's requested task. Call tinycloud_connect first. If an operation returns authority_required, present approval.url and wait for the user's approval before retrying. If approval is declined, stop that operation. For personal records, call tinycloud_apps_context first. Never request or store passwords, API keys, authentication codes, government identifiers, payment-card data, or protected health information.\"\n : \"Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged. For personal records such as weight, workouts, goals or todos, call tinycloud_apps_context first.\"\n : \"Use only the user's requested connector-transcript data. The signed TinyCloud grant authorizes read-only SQL and transcript KV reads.\",\n },\n );\n registerTinyCloudTools(server, {\n surface,\n profile: \"agent\",\n explicitProfile: true,\n allowOwnerProfile: false,\n stateRoot,\n ...(nativeOwner === undefined ? {} : {\n allowedTools: [\"tinycloud_sql_query\", \"tinycloud_kv_get\"] as const,\n }),\n beforeOperation: nativeOwner === undefined\n ? () => store.validateTenant(subject, ownerDids)\n : () => store.assertNativeGrantActive(nativeOwner),\n ...(nativeOwner === undefined ? {\n transformOperationResult: (result: unknown, invocation: McpOperationInvocation) =>\n store.decorateAuthorityResult(subject, ownerDids, result, invocation),\n } : {}),\n }, validator);\n if (nativeOwner === undefined) registerConnectTool(server, validator, store, identity, surface);\n return server;\n }, {\n legacy: \"stateless\",\n onerror: () => writeDiagnostic(\"MCP request failed\"),\n });\n\n const metadataOptions = {\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: resourceUrl,\n serviceDocumentationUrl: new URL(\"https://docs.tinycloud.xyz/cli/mcp\"),\n scopesSupported: [REQUIRED_SCOPE],\n resourceName: surface === \"public\" ? \"TinyCloud personal records\" : \"TinyCloud hosted MCP\",\n };\n const allowedHosts = [resourceUrl.hostname];\n\n return {\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname !== \"/healthz\") {\n const hostFailure = hostHeaderValidationResponse(request, allowedHosts);\n if (hostFailure !== undefined) return hostFailure;\n }\n if (url.pathname === \"/.well-known/oauth-protected-resource\" && surface === \"hosted\") {\n const metadataUrl = new URL(getOAuthProtectedResourceMetadataUrl(resourceUrl));\n const metadataRequest = new Request(metadataUrl.toString(), {\n method: request.method,\n headers: request.headers,\n });\n const response = oauthMetadataResponse(metadataRequest, metadataOptions);\n if (response !== undefined) return withBearerMethodsSupported(response);\n }\n const metadata = oauthMetadataResponse(request, metadataOptions);\n if (metadata !== undefined) {\n return surface === \"hosted\" ? withBearerMethodsSupported(metadata) : metadata;\n }\n if (url.pathname === \"/.well-known/ai-catalog.json\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n return publicMetadataCors(Response.json({\n specVersion: \"1.0\",\n host: {\n displayName: \"TinyCloud, Inc.\",\n identifier: \"https://mcp.tinycloud.xyz\",\n documentationUrl: \"https://docs.tinycloud.xyz/cli/mcp\",\n },\n entries: [{\n identifier: \"urn:air:tinycloud.xyz:mcp:tinycloud-mcp\",\n displayName: \"TinyCloud MCP\",\n type: \"application/json\",\n description: \"Hosted Streamable HTTP MCP server for delegated TinyCloud operations.\",\n url: new URL(\"/.well-known/mcp/server-card.json\", resourceUrl).toString(),\n representativeQueries: [\n \"How do I connect to TinyCloud's hosted MCP server?\",\n \"Which endpoint provides TinyCloud's delegated MCP operations?\",\n \"How can I connect to TinyCloud MCP using local stdio?\",\n ],\n }],\n }, {\n headers: {\n \"cache-control\": \"public, max-age=300\",\n \"content-type\": \"application/json; charset=utf-8\",\n },\n }), request);\n }\n\n if (url.pathname === \"/.well-known/poppy.json\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n return publicMetadataCors(Response.json({\n protocol_version: \"0.1\",\n organization: {\n name: \"TinyCloud, Inc.\",\n domain: resourceUrl.hostname,\n },\n web: {},\n }, {\n headers: {\n \"cache-control\": \"public, max-age=300\",\n \"content-type\": \"application/json; charset=utf-8\",\n },\n }), request);\n }\n if (url.pathname === \"/auth.md\" && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n const issuerUrl = new URL(issuer);\n const authorizationServerMetadataUrl = new URL(\n `/.well-known/oauth-authorization-server${issuerUrl.pathname}`,\n issuerUrl.origin,\n );\n const registrationEndpoint = config.oauthMetadata.registration_endpoint;\n const registrationNote = typeof registrationEndpoint === \"string\"\n ? `OpenKey's OAuth \\`registration_endpoint\\` is ${registrationEndpoint}; it registers OAuth clients, not TinyCloud users or agents.`\n : \"The authorization server does not advertise an OAuth client registration endpoint.\";\n const authDoc = [\n \"# TinyCloud MCP auth.md\",\n \"\",\n `Protected resource: ${resourceUrl}.`,\n \"\",\n \"Send an OAuth access token in the `Authorization: Bearer` header.\",\n \"\",\n `Protected Resource Metadata: ${new URL(\"/.well-known/oauth-protected-resource\", resourceUrl)}.`,\n `Authorization server issuer: ${issuer}.`,\n `Authorization server metadata: ${authorizationServerMetadataUrl}.`,\n `Scope: \\`${REQUIRED_SCOPE}\\`.`,\n \"\",\n \"Hosted access uses OpenKey OAuth.\",\n registrationNote,\n \"TinyCloud does not host an Auth.md agent-enrollment or user-registration endpoint for this service.\",\n \"No `agent_auth` registration block is published because no agent-registration endpoint is available.\",\n \"\",\n `Local stdio is a separate option configured with \\`${LOCAL_CLI_PACKAGE}\\` and \\`${LOCAL_MCP_PACKAGE}\\`.`,\n \"\",\n \"Connection steps: https://docs.tinycloud.xyz/cli/mcp\",\n ].join(\"\\n\") + \"\\n\";\n return publicMetadataCors(publicText(authDoc, \"text/markdown; charset=utf-8\"), request);\n }\n if (url.pathname === \"/robots.txt\" && surface === \"hosted\") {\n return request.method === \"GET\"\n ? publicText(`User-agent: *\\nAllow: /\\nSitemap: ${new URL(\"/sitemap.xml\", resourceUrl)}\\nAgentmap: ${new URL(\"/.well-known/ai-catalog.json\", resourceUrl)}\\n`, \"text/plain; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if ((url.pathname === \"/mcp/server-card\" || url.pathname === \"/.well-known/mcp/server-card.json\") && surface === \"hosted\") {\n if (request.method === \"OPTIONS\") {\n return publicMetadataCors(new Response(null, { status: 204 }), request);\n }\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n const identity = nativeServiceIdentityEnabled\n ? await store.nativeServiceIdentity().catch(() => undefined)\n : undefined;\n const card: Record<string, unknown> = {\n $schema: \"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json\",\n name: `xyz.tinycloud/${MCP_SERVER_NAME}`,\n title: \"TinyCloud MCP\",\n version: MCP_VERSION,\n description: \"MCP server for delegated TinyCloud operations.\",\n websiteUrl: \"https://docs.tinycloud.xyz/cli/mcp\",\n repository: { source: \"github\", url: \"https://github.com/TinyCloudLabs/js-sdk\", subfolder: \"packages/mcp\" },\n remotes: [{ type: \"streamable-http\", url: resourceUrl.toString() }],\n };\n if (identity !== undefined) {\n card[\"x-tinycloud-native-auth\"] = {\n serviceDid: identity.serviceDid,\n serviceDidField: \"x-tinycloud-native-auth.serviceDid\",\n grantEndpoint: {\n method: \"POST\",\n path: \"/native/grant\",\n body: { delegation: \"serialized PortableDelegation JSON string\" },\n },\n serviceCredentialHeader: NATIVE_SERVICE_CREDENTIAL_HEADER,\n serviceCredentialEnv: \"TC_MCP_NATIVE_SERVICE_CREDENTIAL\",\n ownerDidHeader: NATIVE_OWNER_DID_HEADER,\n maxGrantLifetimeSeconds: NATIVE_GRANT_MAX_LIFETIME_SECONDS,\n acceptedCapabilities: [\n { service: \"tinycloud.sql\", space: \"applications\", path: \"xyz.tinycloud.tinychat/connectors\", actions: [\"tinycloud.sql/read\"] },\n { service: \"tinycloud.kv\", space: \"applications\", path: \"xyz.tinycloud.tinychat/connectors/\", actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"] },\n ],\n tools: [\"tinycloud_sql_query\", \"tinycloud_kv_get\"],\n errors: {\n required: NATIVE_GRANT_REQUIRED,\n expired: NATIVE_GRANT_EXPIRED,\n rejected: NATIVE_GRANT_REJECTED,\n serviceUnauthorized: NATIVE_SERVICE_UNAUTHORIZED,\n serviceUnavailable: NATIVE_SERVICE_UNAVAILABLE,\n validationUnavailable: NATIVE_GRANT_VALIDATION_UNAVAILABLE,\n },\n };\n }\n return publicMetadataCors(Response.json(card, {\n headers: { \"cache-control\": \"public, max-age=300\" },\n }), request);\n }\n if (url.pathname === \"/llms.txt\" && surface === \"hosted\") {\n return request.method === \"GET\"\n ? publicText(`# TinyCloud MCP\\n\\nHosted Streamable HTTP endpoint: https://mcp.tinycloud.xyz/mcp (OpenKey OAuth).\\n\\nConnection documentation: https://docs.tinycloud.xyz/cli/mcp\\n\\nLocal alternative: install ${LOCAL_CLI_PACKAGE} and ${LOCAL_MCP_PACKAGE}, then set up tinycloud-mcp as a stdio server in your MCP client.\\n`, \"text/plain; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === \"/sitemap.xml\" && surface === \"hosted\") {\n const sitemap = `<?xml version=\"1.0\" encoding=\"UTF-8\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"><url><loc>${new URL(\"/\", resourceUrl)}</loc></url></urlset>`;\n return request.method === \"GET\"\n ? publicText(sitemap, \"application/xml; charset=utf-8\")\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === \"/\" && surface === \"hosted\") {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return methodNotAllowed(\"GET, HEAD\");\n const markdown = request.headers.get(\"accept\")?.includes(\"text/markdown\") ?? false;\n const content = markdown\n ? `# TinyCloud MCP\\n\\nHosted endpoint: <https://mcp.tinycloud.xyz/mcp> (Streamable HTTP, OpenKey OAuth).\\n\\n[Connection documentation](https://docs.tinycloud.xyz/cli/mcp).\\n\\nLocal alternative: install \\`${LOCAL_CLI_PACKAGE}\\` and \\`${LOCAL_MCP_PACKAGE}\\` and connect the \\`tinycloud-mcp\\` stdio server.\\n`\n : `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><link rel=\"ai-catalog\" href=\"/.well-known/ai-catalog.json\"><title>TinyCloud MCP</title></head><main><h1>TinyCloud MCP</h1><p>Hosted MCP endpoint: <code>https://mcp.tinycloud.xyz/mcp</code> (Streamable HTTP, OpenKey OAuth).</p><p><a href=\"https://docs.tinycloud.xyz/cli/mcp\">Connection documentation</a></p><p>Local alternative: install <code>${LOCAL_CLI_PACKAGE}</code> and <code>${LOCAL_MCP_PACKAGE}</code> and connect the <code>tinycloud-mcp</code> stdio server.</p></main></html>`;\n const headers = new Headers({\n \"content-type\": markdown ? \"text/markdown; charset=utf-8\" : \"text/html; charset=utf-8\",\n \"cache-control\": \"public, max-age=300\",\n \"content-security-policy\": \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n \"x-content-type-options\": \"nosniff\",\n vary: \"Accept\",\n });\n headers.set(\n \"link\",\n `<${new URL(\"/mcp/server-card\", resourceUrl)}>; rel=\"describedby\"; type=\"application/json\", <https://docs.tinycloud.xyz/cli/mcp>; rel=\"service-doc\"`,\n );\n return new Response(request.method === \"HEAD\" ? null : content, { headers });\n }\n if (url.pathname === \"/healthz\") {\n return request.method === \"GET\"\n ? json({ ok: true })\n : methodNotAllowed(\"GET\");\n }\n if (url.pathname === connectPath) {\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n try {\n const destination = await store.approvalRedirect(requiredState(url));\n return Response.redirect(destination, 302);\n } catch {\n if (request.headers.get(\"accept\")?.includes(\"text/html\")) {\n return new Response(\n \"<!doctype html><html lang=\\\"en\\\"><meta charset=\\\"utf-8\\\"><meta name=\\\"viewport\\\" content=\\\"width=device-width,initial-scale=1\\\"><title>TinyCloud approval unavailable</title><main><h1>This approval link is unavailable</h1><p>It may have expired or already been used. No new approval was accepted through this link.</p><p>Return to the conversation that requested access. In ChatGPT, select @TinyCloud and ask it to continue your original request. If access is still needed, it can provide a fresh approval link.</p><p>If you declined access, no further approval is required. Never paste passwords, codes or approval links into support messages.</p></main></html>\",\n {\n status: 400,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n vary: \"Accept\",\n },\n },\n );\n }\n return json({ error: \"The approval link is invalid or expired.\" }, 400);\n }\n }\n if (url.pathname === callbackPath) {\n if (request.method === \"OPTIONS\") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n const originFailure = validateCallbackOrigin(request, config.openkeyHost);\n if (originFailure !== undefined) return callbackCors(originFailure, config.openkeyHost);\n try {\n await store.completeApproval(requiredState(url), request);\n return callbackCors(json({ success: true }), config.openkeyHost);\n } catch (error) {\n // Only fixed server-authored text reaches OpenKey; callback input is never echoed.\n if (error instanceof ApprovalOwnerMismatchError) {\n return callbackCors(json({ error: error.message, code: \"approval_owner_mismatch\" }, 403), config.openkeyHost);\n }\n // Stage, code, reason and detail are identifiers, never callback, delegation or node text.\n const stage = error instanceof ApprovalStageError ? error.stage : \"unknown\";\n const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code)\n ? error.code\n : \"UNKNOWN\";\n const reason = !(error instanceof ApprovalStageError) || error.reason === undefined\n ? undefined\n : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? \"unknown\";\n // Only the server log says which state, tenant or body check failed;\n // the response stays uniform so a caller cannot probe a state.\n const detail = error instanceof ApprovalRequestError ? error.detail : \"none\";\n writeDiagnostic(\n `connect callback rejected: stage=${stage} code=${code}${reason === undefined ? \"\" : ` reason=${reason}`} detail=${detail}`,\n );\n return callbackCors(\n json({\n error: stage,\n code,\n ...(reason === undefined ? {} : { reason }),\n message: \"TinyCloud could not accept this delegation.\",\n }, 400),\n config.openkeyHost,\n );\n }\n }\n if (url.pathname === \"/native/grant\" && surface === \"hosted\") {\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n if (request.headers.has(\"origin\")) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (config.nativeServiceCredential === undefined) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n if (!serviceCredentialMatches(\n request.headers.get(NATIVE_SERVICE_CREDENTIAL_HEADER),\n config.nativeServiceCredential,\n )) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (!request.headers.get(\"content-type\")?.toLowerCase().startsWith(\"application/json\")) {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n const bodyText = await readBoundedBodyText(request, MAX_NATIVE_GRANT_BODY_BYTES);\n if (bodyText === undefined) return json({ error: NATIVE_GRANT_REJECTED }, 401);\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body) || !(\"delegation\" in body)) {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n const grantBody = body as { delegation?: unknown };\n if (Object.keys(body).length !== 1 || typeof grantBody.delegation !== \"string\") {\n return json({ error: NATIVE_GRANT_REJECTED }, 401);\n }\n try {\n const accepted = await store.acceptNativeGrant(grantBody.delegation);\n return json({\n ownerDid: accepted.ownerDid,\n serviceDid: accepted.serviceDid,\n expiresAt: accepted.expiresAt,\n }, 201);\n } catch (error) {\n return nativeGrantErrorResponse(error);\n }\n }\n if (url.pathname === resourceUrl.pathname && surface === \"hosted\" &&\n (request.headers.has(NATIVE_SERVICE_CREDENTIAL_HEADER) || request.headers.has(NATIVE_OWNER_DID_HEADER))) {\n if (config.nativeServiceCredential === undefined) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n if (!serviceCredentialMatches(\n request.headers.get(NATIVE_SERVICE_CREDENTIAL_HEADER),\n config.nativeServiceCredential,\n )) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n if (request.headers.has(\"origin\")) return json({ error: NATIVE_SERVICE_UNAUTHORIZED }, 403);\n const ownerHeader = request.headers.get(NATIVE_OWNER_DID_HEADER);\n if (ownerHeader === null || ownerHeader.length === 0) {\n return json({ error: NATIVE_GRANT_REQUIRED }, 401);\n }\n const grant = await store.nativeGrantForOwner(ownerHeader);\n if (grant.status !== \"ok\") {\n const status = grant.status === \"unavailable\" ? 503 : 401;\n const code = grant.status === \"required\"\n ? NATIVE_GRANT_REQUIRED\n : grant.status === \"expired\"\n ? NATIVE_GRANT_EXPIRED\n : grant.status === \"unavailable\"\n ? NATIVE_GRANT_VALIDATION_UNAVAILABLE\n : NATIVE_GRANT_REJECTED;\n return json({ error: code }, status);\n }\n return handler.fetch(request, {\n authInfo: {\n token: \"native-service\",\n clientId: \"tinycloud-native\",\n scopes: [],\n extra: { nativeOwnerDid: grant.ownerDid },\n } as AuthInfo,\n });\n }\n if (url.pathname !== resourceUrl.pathname) return json({ error: \"Not found\" }, 404);\n const originFailure = validateOrigin(request, config.allowedOrigins);\n if (originFailure !== undefined) return originFailure;\n const auth = await authenticate(request);\n if (auth instanceof Response) return auth;\n return handler.fetch(request, { authInfo: auth });\n },\n close: () => handler.close(),\n };\n}\n\nfunction registerConnectTool(\n server: McpServer,\n validator: ReturnType<typeof createJsonSchemaValidator>,\n store: RemoteTenantStore,\n identity: OAuthIdentity,\n surface: \"hosted\" | \"public\",\n): void {\n const inputSchema = fromJsonSchema({ type: \"object\", properties: {}, additionalProperties: false }, validator);\n const outputSchema = fromJsonSchema({\n type: \"object\",\n properties: {\n connected: { type: \"boolean\" },\n ...(surface === \"hosted\" ? { sessionDid: { type: \"string\" } } : {}),\n approvalUrl: { type: \"string\", format: \"uri\" },\n expiresAt: { type: \"string\", format: \"date-time\" },\n },\n required: surface === \"hosted\" ? [\"connected\", \"sessionDid\"] : [\"connected\"],\n additionalProperties: false,\n }, validator);\n server.registerTool(\n \"tinycloud_connect\",\n {\n title: \"Connect TinyCloud\",\n description: \"Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.\",\n inputSchema,\n outputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n },\n async () => {\n const startedAt = performance.now();\n let code = \"INTERNAL_ERROR\";\n let text: string;\n try {\n const status = await store.connectStatus(identity.subject, identity.ownerDids);\n if (status.connected) {\n code = \"ok\";\n text = \"TinyCloud is connected.\";\n } else if (status.approvalUrl === undefined) {\n code = \"unavailable\";\n text = \"TinyCloud is unavailable. Call this tool again shortly.\";\n } else {\n code = \"authority_required\";\n text = `TinyCloud approval is required. Open ${status.approvalUrl}, then call this tool again. This link expires at ${status.expiresAt}.`;\n }\n const visibleStatus = surface === \"hosted\" ? status : {\n connected: status.connected,\n ...(status.approvalUrl === undefined ? {} : { approvalUrl: status.approvalUrl }),\n ...(status.expiresAt === undefined ? {} : { expiresAt: status.expiresAt }),\n };\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: visibleStatus,\n };\n } finally {\n logToolCall(\"tinycloud_connect\", code, startedAt, 0);\n }\n },\n );\n}\n\ninterface OAuthIdentity {\n readonly subject: string;\n readonly ownerDids: string[];\n}\n\nfunction oauthIdentity(authInfo: AuthInfo | undefined): OAuthIdentity {\n const subject = authInfo?.extra?.subject;\n if (typeof subject !== \"string\" || subject.length === 0) {\n throw new Error(\"The authenticated MCP request has no OpenKey subject.\");\n }\n const ownerDids = authInfo?.extra?.ownerDids;\n if (!Array.isArray(ownerDids) || ownerDids.length === 0 ||\n !ownerDids.every((did) => typeof did === \"string\")) {\n throw new Error(\"The authenticated MCP request has no OpenKey owner identity.\");\n }\n return { subject, ownerDids };\n}\n\nfunction canonicalResourceUrl(url: URL): URL {\n const resource = new URL(url);\n resource.hash = \"\";\n resource.search = \"\";\n resource.pathname = resource.pathname.replace(/\\/+$/, \"\") || \"/mcp\";\n if (resource.pathname === \"/\") resource.pathname = \"/mcp\";\n return resource;\n}\n\nfunction requiredState(url: URL): string {\n const state = url.searchParams.get(\"state\");\n if (state === null) throw new ApprovalRequestError(\"state_missing\", \"Missing approval state.\");\n if (state.length > 512) throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n return state;\n}\n\nfunction validateOrigin(request: Request, allowed: readonly string[] | undefined): Response | undefined {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return undefined;\n const allowlist = allowed ?? [];\n return allowlist.includes(origin) ? undefined : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction validateCallbackOrigin(request: Request, openkeyHost: string): Response | undefined {\n const origin = request.headers.get(\"origin\");\n return origin === null || origin === new URL(openkeyHost).origin\n ? undefined\n : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction callbackCors(response: Response, openkeyHost: string): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", new URL(openkeyHost).origin);\n headers.set(\"access-control-allow-methods\", \"POST, OPTIONS\");\n headers.set(\"access-control-allow-headers\", \"content-type\");\n headers.set(\"vary\", \"Origin\");\n return new Response(response.body, { status: response.status, headers });\n}\n\nasync function readBoundedBodyText(request: Request, maxBytes: number): Promise<string | undefined> {\n const contentLength = request.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedLength = Number(contentLength);\n if (Number.isFinite(parsedLength) && parsedLength > maxBytes) return undefined;\n }\n if (request.body === null) return \"\";\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString(\"utf8\");\n}\n\nfunction nativeGrantErrorResponse(error: unknown): Response {\n if (!(error instanceof NativeGrantValidationError)) {\n return json({ error: NATIVE_SERVICE_UNAVAILABLE }, 503);\n }\n const unavailable = error.code === NATIVE_GRANT_VALIDATION_UNAVAILABLE ||\n error.code === NATIVE_SERVICE_UNAVAILABLE;\n return json({ error: error.code }, unavailable ? 503 : 401);\n}\n\nfunction json(value: unknown, status = 200): Response {\n return Response.json(value, { status, headers: { \"cache-control\": \"no-store\" } });\n}\n\n\nasync function withBearerMethodsSupported(response: Response): Promise<Response> {\n if (response.status === 204 || response.body === null) return response;\n const metadata = await response.json() as Record<string, unknown>;\n const headers = new Headers(response.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n return new Response(JSON.stringify({ ...metadata, bearer_methods_supported: [\"header\"] }), {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nfunction publicMetadataCors(response: Response, request: Request): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", \"*\");\n headers.set(\"access-control-allow-methods\", \"GET, OPTIONS\");\n const requestedHeaders = request.method === \"OPTIONS\"\n ? request.headers.get(\"access-control-request-headers\")\n : null;\n if (requestedHeaders !== null) {\n headers.set(\"access-control-allow-headers\", requestedHeaders);\n }\n headers.set(\n \"vary\",\n requestedHeaders === null ? \"Origin\" : \"Origin, Access-Control-Request-Headers\",\n );\n return new Response(response.body, { status: response.status, headers });\n}\n\nfunction publicText(text: string, contentType: string): Response {\n return new Response(text, {\n headers: {\n \"content-type\": contentType,\n \"cache-control\": \"public, max-age=300\",\n \"x-content-type-options\": \"nosniff\",\n },\n });\n}\n\nfunction methodNotAllowed(allow: string): Response {\n return new Response(\"Method not allowed\", { status: 405, headers: { allow } });\n}\n\n\nfunction writeDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`);\n}\n","import {\n OAuthError,\n OAuthErrorCode,\n type AuthInfo,\n type OAuthMetadata,\n type OAuthTokenVerifier,\n} from \"@modelcontextprotocol/server\";\nimport { pkhDid } from \"@tinycloud/node-sdk\";\nimport { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from \"jose\";\n\nimport type { TokenStatusChecker } from \"./token-status.js\";\n\nconst OWNER_DIDS_CLAIM = \"https://tinycloud.xyz/owner_dids\";\n\nexport interface OpenKeyOAuthConfig {\n readonly issuer: string;\n readonly audience: string;\n readonly jwksUri: string;\n readonly requiredScope?: string;\n /**\n * OpenKey token status check run after the signature check on every call.\n * Hosted deployments always set it; a verifier built without one checks the\n * signed claims only.\n */\n readonly tokenStatus?: TokenStatusChecker;\n}\n\nexport function createOpenKeyTokenVerifier(config: OpenKeyOAuthConfig): OAuthTokenVerifier {\n const jwks = createRemoteJWKSet(new URL(config.jwksUri));\n return {\n async verifyAccessToken(token: string): Promise<AuthInfo> {\n try {\n const { payload } = await jwtVerify(token, jwks, {\n issuer: config.issuer,\n audience: config.audience,\n });\n const info = authInfo(token, payload, config);\n if (config.tokenStatus !== undefined) await requireUsableStatus(config.tokenStatus, token);\n return info;\n } catch (error) {\n if (error instanceof errors.JOSEError) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is invalid.\");\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * `inactive` is a 401 invalid_token. `unknown` (OpenKey unreachable, 4xx/5xx,\n * timeout, unreadable answer) is accepted only while `toleratesUnknown` holds;\n * after that it is refused as a 500 server_error, the transport's answer for a\n * fault that is not the token's: a 401 would send clients into re-authorisation\n * that cannot succeed while OpenKey is unavailable.\n */\nasync function requireUsableStatus(checker: TokenStatusChecker, token: string): Promise<void> {\n const status = await checker.tokenStatus(token);\n if (status === \"active\") return;\n if (status === \"inactive\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is no longer active.\");\n }\n if (!checker.toleratesUnknown(token)) {\n throw new OAuthError(OAuthErrorCode.ServerError, \"The OpenKey access token status is unavailable.\");\n }\n}\n\nexport async function loadOAuthMetadata(metadataUrl: URL): Promise<OAuthMetadata> {\n const response = await fetch(metadataUrl, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"OpenKey OAuth discovery failed.\");\n const metadata = await response.json() as OAuthMetadata;\n if (typeof metadata.issuer !== \"string\" || typeof metadata.jwks_uri !== \"string\") {\n throw new Error(\"OpenKey OAuth metadata is incomplete.\");\n }\n return metadata;\n}\n\nfunction authInfo(\n token: string,\n payload: JWTPayload,\n config: OpenKeyOAuthConfig,\n): AuthInfo {\n if (typeof payload.sub !== \"string\" || payload.sub.length === 0) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token does not identify a subject.\");\n }\n if (typeof payload.exp !== \"number\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token has no expiry.\");\n }\n const scopes = typeof payload.scope === \"string\"\n ? payload.scope.split(/\\s+/).filter(Boolean)\n : [];\n if (config.requiredScope !== undefined && !scopes.includes(config.requiredScope)) {\n throw new OAuthError(\n OAuthErrorCode.InsufficientScope,\n \"The OpenKey access token is missing the TinyCloud MCP scope.\",\n );\n }\n const clientId = firstString(payload.azp, payload.client_id) ?? \"unknown\";\n const ownerDids = canonicalOwnerDids(payload[OWNER_DIDS_CLAIM]);\n if (ownerDids === undefined) {\n throw new OAuthError(\n OAuthErrorCode.InvalidToken,\n \"The OpenKey access token has no valid TinyCloud owner identity.\",\n );\n }\n return {\n token,\n clientId,\n scopes,\n expiresAt: payload.exp,\n resource: new URL(config.audience),\n extra: {\n subject: payload.sub,\n ownerDids,\n },\n };\n}\n\n/**\n * OpenKey issues owner DIDs as `did:pkh:eip155:<chain>:<address>`. Only that\n * exact syntax is accepted, canonicalised, and passed on to owner comparison\n * and the approval text. One malformed value refuses the whole claim rather\n * than being skipped.\n */\nconst OWNER_DID = /^did:pkh:eip155:([1-9][0-9]{0,15}):(0x[0-9a-fA-F]{40})$/;\n\nfunction canonicalOwnerDids(claim: unknown): string[] | undefined {\n if (!Array.isArray(claim) || claim.length === 0) return undefined;\n const ownerDids: string[] = [];\n for (const value of claim) {\n const match = typeof value === \"string\" ? OWNER_DID.exec(value) : null;\n if (match === null) return undefined;\n try {\n ownerDids.push(pkhDid(match[2]!, Number(match[1])));\n } catch {\n return undefined;\n }\n }\n return [...new Set(ownerDids)];\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n","import { createHash } from \"node:crypto\";\n\nimport { decodeJwt } from \"jose\";\n\n/** What OpenKey's RFC 7662 token introspection says about one access token. */\nexport type TokenStatus = \"active\" | \"inactive\" | \"unknown\";\n\nexport interface TokenStatusConfig {\n /** OpenKey's resource-server introspection endpoint (`TC_MCP_INTROSPECTION_URL`). */\n readonly endpoint: string;\n /** The resource URL (JWT audience) this checker serves; an active answer must name it. */\n readonly resourceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** How the confidential client authenticates: `client_secret_basic` or `client_secret_post`. */\n readonly authMethod: \"basic\" | \"post\";\n readonly timeoutMs?: number;\n /** Test seams. */\n readonly fetch?: typeof fetch;\n readonly now?: () => number;\n readonly log?: (message: string) => void;\n}\n\nexport interface TokenStatusChecker {\n /** Ask OpenKey whether `token` is still active. Never throws. */\n readonly tokenStatus: (token: string) => Promise<TokenStatus>;\n /**\n * Whether an `unknown` status may still be accepted for this token: only a\n * token that OpenKey itself answered active to this process, and only while\n * the time since that answer is shorter than the token's own lifetime\n * (`exp - iat`, 300 s when the token does not carry both). A token never\n * confirmed active, or one answered inactive, is refused, and nothing is\n * tolerated while OpenKey is refusing the client credentials.\n */\n readonly toleratesUnknown: (token: string) => boolean;\n}\n\n/** What one introspection call concluded; `credentials` and `mismatch` are not answers about the token. */\ntype Outcome = TokenStatus | \"credentials\" | \"mismatch\";\n\nconst ACTIVE_CACHE_MS = 30_000;\nconst DEFAULT_TOKEN_LIFETIME_SECONDS = 300;\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MAX_CACHED_TOKENS = 10_000;\n\nexport function createTokenStatusChecker(config: TokenStatusConfig): TokenStatusChecker {\n const doFetch = config.fetch ?? fetch;\n const clock = config.now ?? Date.now;\n const log = config.log ?? ((message: string) => void process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`));\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n /** token hash -> expiry (ms) of an inactive token; inactive is final. */\n const inactive = new Map<string, number>();\n /** token hash -> end (ms) of the active window. */\n const active = new Map<string, number>();\n const inFlight = new Map<string, Promise<TokenStatus>>();\n /** token hash -> when OpenKey last answered this token active, and the token's expiry (ms). */\n const confirmedActive = new Map<string, { at: number; expiresAt: number }>();\n /** Set while OpenKey refuses the client credentials; cleared by the next answer about a token. */\n let credentialsRefused = false;\n\n async function introspect(token: string): Promise<Outcome> {\n const headers: Record<string, string> = {\n accept: \"application/json\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n };\n const body = new URLSearchParams({ token, token_type_hint: \"access_token\" });\n if (config.authMethod === \"basic\") {\n const encode = (value: string) => encodeURIComponent(value).replace(/%20/g, \"+\");\n const credentials = `${encode(config.clientId)}:${encode(config.clientSecret)}`;\n headers.authorization = `Basic ${Buffer.from(credentials).toString(\"base64\")}`;\n } else {\n body.set(\"client_id\", config.clientId);\n body.set(\"client_secret\", config.clientSecret);\n }\n try {\n const response = await doFetch(config.endpoint, {\n method: \"POST\",\n headers,\n body,\n redirect: \"error\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (response.status === 401) return \"credentials\";\n if (response.status !== 200) return \"unknown\";\n const result: unknown = await response.json();\n if (typeof result !== \"object\" || result === null || !(\"active\" in result)) return \"unknown\";\n if (result.active === false) return \"inactive\";\n if (result.active !== true) return \"unknown\";\n return answerMatchesToken(Object.fromEntries(Object.entries(result)), token, config.resourceUrl)\n ? \"active\"\n : \"mismatch\";\n } catch {\n return \"unknown\";\n }\n }\n\n async function query(key: string, token: string): Promise<TokenStatus> {\n const outcome = await introspect(token);\n if (outcome === \"credentials\") {\n if (!credentialsRefused) {\n log(\"OpenKey token introspection refused the MCP client credentials (401); token checks fail closed until it accepts them.\");\n }\n credentialsRefused = true;\n return \"unknown\";\n }\n if (outcome === \"unknown\") return outcome;\n const now = clock();\n prune(now);\n if (outcome === \"mismatch\") {\n // The answer describes some other token: refused like an inactive one, but it\n // is not an answer about this token and confirms nothing.\n inactive.set(key, tokenExpiryMs(token, now));\n confirmedActive.delete(key);\n return \"inactive\";\n }\n credentialsRefused = false;\n if (outcome === \"inactive\") {\n inactive.set(key, tokenExpiryMs(token, now));\n confirmedActive.delete(key);\n } else {\n active.set(key, now + ACTIVE_CACHE_MS);\n // Delete first so a re-confirmed token moves to the newest slot of the map.\n confirmedActive.delete(key);\n confirmedActive.set(key, { at: now, expiresAt: tokenExpiryMs(token, now) });\n }\n return outcome;\n }\n\n function prune(now: number): void {\n for (const [key, until] of active) if (until <= now) active.delete(key);\n for (const [key, until] of inactive) if (until <= now) inactive.delete(key);\n for (const [key, entry] of confirmedActive) if (entry.expiresAt <= now) confirmedActive.delete(key);\n // An evicted entry costs one more introspection for that token; an evicted\n // confirmation means that token is refused while OpenKey cannot answer.\n for (const cache of [active, inactive, confirmedActive]) {\n while (cache.size >= MAX_CACHED_TOKENS) {\n const oldest = cache.keys().next().value;\n if (oldest === undefined) break;\n cache.delete(oldest);\n }\n }\n }\n\n return {\n async tokenStatus(token) {\n const key = createHash(\"sha256\").update(token).digest(\"hex\");\n const now = clock();\n const inactiveUntil = inactive.get(key);\n if (inactiveUntil !== undefined && inactiveUntil > now) return \"inactive\";\n const activeUntil = active.get(key);\n if (activeUntil !== undefined && activeUntil > now) return \"active\";\n const pending = inFlight.get(key);\n if (pending !== undefined) return pending;\n const asking = query(key, token).finally(() => inFlight.delete(key));\n inFlight.set(key, asking);\n return asking;\n },\n toleratesUnknown(token) {\n if (credentialsRefused) return false;\n const confirmed = confirmedActive.get(createHash(\"sha256\").update(token).digest(\"hex\"));\n if (confirmed === undefined) return false;\n const now = clock();\n return confirmed.expiresAt > now && now - confirmed.at < tokenLifetimeSeconds(token) * 1000;\n },\n };\n}\n\n/**\n * An `active` answer must describe the token that was asked about: `sub` and\n * `client_id` equal the claims of the already verified JWT, and `aud` is a\n * non-empty subset of the JWT's audiences that includes `resourceUrl` (OpenKey\n * answers only with the audiences the resource server may know, while the JWT\n * can carry more, e.g. its userinfo endpoint).\n */\nfunction answerMatchesToken(answer: Record<string, unknown>, token: string, resourceUrl: string): boolean {\n const jwt = claims(token);\n if (typeof jwt.sub === \"string\" && answer.sub !== jwt.sub) return false;\n const jwtClient = [jwt.azp, jwt.client_id].find((value) => typeof value === \"string\" && value.length > 0);\n if (jwtClient !== undefined && answer.client_id !== jwtClient) return false;\n if (jwt.aud === undefined) return true;\n const answered = audienceList(answer.aud);\n const signed = audienceList(jwt.aud);\n return answered.length > 0 && answered.includes(resourceUrl) && answered.every((entry) => signed.includes(entry));\n}\n\n/** An `aud` value (string or array) as a list; a missing or malformed one is empty. */\nfunction audienceList(value: unknown): string[] {\n const list = typeof value === \"string\" ? [value] : value;\n return Array.isArray(list) && list.every((entry) => typeof entry === \"string\") ? list : [];\n}\n\nfunction tokenExpiryMs(token: string, now: number): number {\n const exp = claims(token).exp;\n return typeof exp === \"number\" ? exp * 1000 : now + DEFAULT_TOKEN_LIFETIME_SECONDS * 1000;\n}\n\nfunction tokenLifetimeSeconds(token: string): number {\n const { exp, iat } = claims(token);\n return typeof exp === \"number\" && typeof iat === \"number\" && exp > iat\n ? exp - iat\n : DEFAULT_TOKEN_LIFETIME_SECONDS;\n}\n\nfunction claims(token: string): ReturnType<typeof decodeJwt> {\n try {\n return decodeJwt(token);\n } catch {\n return {};\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n activateValidatedRuntimeDelegation,\n deserializeDelegation,\n InvalidRestoredSessionError,\n RuntimeDelegationRejectedError,\n serializeDelegation,\n TinyCloudNode,\n UnsupportedSessionRestoreError,\n isCapabilitySubset,\n principalDidEquals,\n siweRuntimeDelegation,\n signedCompactUcanExpiry,\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudSession,\n} from \"@tinycloud/node-sdk\";\nimport { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { createOrReusePermissionRequest } from \"@tinycloud/operations/artifacts\";\nimport { withTinyCloudStateRoot } from \"@tinycloud/operations/state\";\nimport { invokeOperation } from \"@tinycloud/operations\";\nimport { nodeRevocationOf, operationRetryDescriptor, type NodeRevocation } from \"@tinycloud/operations/mcp-authority\";\nimport { tcAppsApprovalMessage, tcAppsApprovalReason } from \"@tinycloud/operations/tc-apps\";\nimport { nativeOwnerForConnectorGrant, canonicalOwnerDid, NATIVE_GRANT_MAX_LIFETIME_SECONDS } from \"./native-auth.js\";\n\nimport type { McpOperationInvocation } from \"./tools.js\";\nconst PROFILE = \"agent\";\nconst MAX_CALLBACK_BYTES = 256 * 1024;\nconst NATIVE_GRANT_IMPORT_REJECTION_CODES = new Set([\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n]);\n/**\n * The node host hosted MCP tenants were created with until TC_HOST moved to\n * `https://tee.node.tinycloud.xyz` (js-sdk 48eca361). Profiles keep the host\n * they were created with, so tenants from that era still store it.\n */\nconst LEGACY_DEFAULT_NODE_HOST = \"https://node.tinycloud.xyz\";\nconst BOOTSTRAP_PERMISSIONS: PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"spaces/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"applications/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n];\n\nexport interface RemoteStoreConfig {\n readonly stateDir: string;\n readonly stateSecret: string;\n readonly publicUrl: URL;\n /** Separate public-plugin approvals from the existing root callback. */\n readonly approvalPath?: string;\n readonly nodeHost: string;\n readonly openkeyHost: string;\n readonly approvalTtlSeconds: number;\n readonly delegationExpiry: string;\n /** Shared secret used only by the Exo native client, never logged. */\n readonly nativeServiceCredential?: string;\n}\n\ninterface TenantProfile {\n readonly stateRoot: string;\n readonly sessionDid: string;\n readonly jwk: Record<string, unknown>;\n readonly approvalEpoch: number;\n}\ninterface NativeServiceKey {\n readonly version: 1;\n readonly jwk: Record<string, unknown>;\n}\n\ninterface StoredNativeGrant {\n readonly version: 1;\n readonly ownerDid: string;\n readonly serviceDid: string;\n readonly serializedDelegation: string;\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly permissions: PermissionEntry[];\n readonly expiresAt: string;\n}\n\nexport type NativeGrantLookup =\n | { readonly status: \"ok\"; readonly ownerDid: string; readonly stateRoot: string; readonly expiresAt: string }\n | { readonly status: \"required\" | \"expired\" | \"rejected\" | \"unavailable\" };\n\nexport interface NativeServiceIdentity {\n readonly serviceDid: string;\n}\n\ninterface PendingApproval {\n readonly version: 1;\n readonly nonce: string;\n readonly tenantId: string;\n readonly kind: \"bootstrap\" | \"delegation\";\n readonly requestId?: string;\n readonly permissions: PermissionEntry[];\n readonly ownerDids: string[];\n readonly createdAt: string;\n readonly approvalEpoch: number;\n readonly expiresAt: string;\n}\n\nexport interface ConnectStatus {\n readonly connected: boolean;\n readonly sessionDid: string;\n readonly approvalUrl?: string;\n readonly expiresAt?: string;\n}\n\ntype SessionState = \"valid\" | \"invalid\" | \"unknown\";\n\ninterface CallbackSession {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly jwk: Record<string, unknown>;\n readonly verificationMethod: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/**\n * The approving wallet is not the OpenKey principal whose MCP request created\n * the approval link. The message is static so callers may show it verbatim.\n */\nexport class ApprovalOwnerMismatchError extends Error {\n constructor() {\n super(\"This approval link was requested by a different TinyCloud account, so the delegation was not stored.\");\n this.name = \"ApprovalOwnerMismatchError\";\n }\n}\n\n/** The callback stages `/connect/callback` names when it refuses an approval. */\nexport type ApprovalStage = \"restore_approval\" | \"siwe_runtime_delegation\" | \"auth_import\" | \"activation\";\n\n/**\n * A callback stage refused the approval. `code` and `reason` are\n * server-authored identifiers for diagnostics; the message and cause may quote\n * callback or node data and are never sent or logged.\n */\nexport class ApprovalStageError extends Error {\n readonly stage: ApprovalStage;\n readonly code: string;\n readonly reason: string | undefined;\n\n constructor(stage: ApprovalStage, code: string, reason?: string, cause?: unknown) {\n super(`The approval failed at ${stage} (${code}).`, { cause });\n this.name = \"ApprovalStageError\";\n this.stage = stage;\n this.code = code;\n this.reason = reason;\n }\n}\n\n/** Why a callback was refused before its approval was read. */\nexport type ApprovalRequestDetail =\n | \"state_missing\"\n | \"state_invalid\"\n | \"state_expired\"\n | \"state_not_pending\"\n | \"tenant_missing\"\n | \"body_invalid\";\n\n/**\n * The callback's state, tenant or body was refused before the approval was\n * read. `detail` is for server diagnostics only: callers get one uniform\n * response so they cannot probe whether a state is valid.\n */\nexport class ApprovalRequestError extends Error {\n readonly detail: ApprovalRequestDetail;\n\n constructor(detail: ApprovalRequestDetail, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"ApprovalRequestError\";\n this.detail = detail;\n }\n}\nexport class NativeGrantValidationError extends Error {\n readonly code:\n | \"native_grant_required\"\n | \"native_grant_expired\"\n | \"native_grant_rejected\"\n | \"native_grant_validation_unavailable\"\n | \"native_service_unavailable\";\n\n constructor(\n status: \"required\" | \"expired\" | \"rejected\" | \"unavailable\" |\n \"native_grant_required\" | \"native_grant_expired\" | \"native_grant_rejected\" |\n \"native_grant_validation_unavailable\" | \"native_service_unavailable\",\n ) {\n const code = status.startsWith(\"native_\")\n ? status as NativeGrantValidationError[\"code\"]\n : status === \"required\"\n ? \"native_grant_required\"\n : status === \"expired\"\n ? \"native_grant_expired\"\n : status === \"unavailable\"\n ? \"native_grant_validation_unavailable\"\n : \"native_grant_rejected\";\n super(code);\n this.name = \"NativeGrantValidationError\";\n this.code = code;\n }\n}\n\nexport class RemoteTenantStore {\n readonly #config: RemoteStoreConfig;\n readonly #initializing = new Map<string, Promise<TenantProfile>>();\n readonly #sessionChecks = new Map<string, Promise<SessionState>>();\n readonly #clearing = new Map<string, Promise<void>>();\n readonly #activeSessions = new Map<string, { cids: string; until: number }>();\n readonly #pendingWrites = new Map<string, Promise<PendingApproval>>();\n readonly #renewalRequired = new Set<string>();\n readonly #approvalEpochs = new Map<string, number>();\n readonly #scopedClearing = new Map<string, Promise<void>>();\n readonly #clearedScoped = new Map<string, Set<string>>();\n readonly #approvalProcessing = new Map<string, Promise<void>>();\n #nativeIdentity?: Promise<{ did: string; jwk: Record<string, unknown> }>;\n readonly #nativeGrantQueues = new Map<string, Promise<void>>();\n\n constructor(config: RemoteStoreConfig) {\n this.#config = config;\n }\n\n async nativeServiceIdentity(): Promise<NativeServiceIdentity> {\n const identity = await this.#loadNativeServiceKey();\n return { serviceDid: normalizeDid(identity.did) };\n }\n\n nativeTenantStateRoot(ownerDid: string): string {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) throw new NativeGrantValidationError(\"rejected\");\n const tenant = createHmac(\"sha256\", this.#config.stateSecret)\n .update(`native-tenant:${canonical}`)\n .digest(\"hex\");\n return join(this.#config.stateDir, \"native-tenants\", tenant);\n }\n\n async acceptNativeGrant(serializedDelegation: string): Promise<{\n ownerDid: string;\n serviceDid: string;\n expiresAt: string;\n stateRoot: string;\n }> {\n if (Buffer.byteLength(serializedDelegation) > MAX_CALLBACK_BYTES) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n const identity = await this.#loadNativeServiceKey();\n const activated = await this.#activateNativeDelegation(serializedDelegation, identity);\n const { ownerDid, spaceId, permissions, expiresAt } = activated;\n return this.#withNativeGrantLock(ownerDid, async () => {\n const stateRoot = this.nativeTenantStateRoot(ownerDid);\n let previous: StoredNativeGrant | null = null;\n try {\n const stored = await readJson<unknown>(this.#nativeGrantPath(stateRoot));\n if (isRecord(stored) && stored.version === 1 && stored.ownerDid === ownerDid &&\n typeof stored.serviceDid === \"string\" && samePrincipal(stored.serviceDid, identity.did) &&\n typeof stored.serializedDelegation === \"string\" && typeof stored.delegationCid === \"string\" &&\n typeof stored.spaceId === \"string\" && Array.isArray(stored.permissions) &&\n stored.permissions.every(isPermissionEntry) &&\n nativeOwnerForConnectorGrant(stored.permissions) === ownerDid &&\n typeof stored.expiresAt === \"string\" && Number.isFinite(Date.parse(stored.expiresAt))) {\n previous = stored as unknown as StoredNativeGrant;\n }\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n }\n if (previous !== null) {\n const previousExpiry = Date.parse(previous.expiresAt);\n const nextExpiry = expiresAt.getTime();\n if (previousExpiry > nextExpiry ||\n (previousExpiry === nextExpiry && previous.delegationCid !== activated.cid)) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (previous.delegationCid === activated.cid) {\n return {\n ownerDid,\n serviceDid: normalizeDid(identity.did),\n expiresAt: previous.expiresAt,\n stateRoot,\n };\n }\n }\n const session = {\n delegationHeader: activated.delegation.delegationHeader,\n delegationCid: activated.cid,\n spaceId,\n jwk: identity.jwk,\n verificationMethod: identity.did,\n tinycloudHosts: [this.#config.nodeHost],\n };\n const grant: StoredNativeGrant = {\n version: 1,\n ownerDid,\n serviceDid: normalizeDid(identity.did),\n serializedDelegation: serializeDelegation(activated.delegation),\n delegationCid: activated.cid,\n spaceId,\n permissions,\n expiresAt: expiresAt.toISOString(),\n };\n const sessionPath = this.#sessionPath(stateRoot);\n const previousSession = await readOptionalText(sessionPath);\n try {\n await secureWrite(this.#profilePath(stateRoot), {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: activated.delegation.chainId,\n spaceName: \"applications\",\n did: identity.did,\n createdAt: new Date().toISOString(),\n profile: PROFILE,\n operatorType: \"agent\",\n posture: \"delegate-session\",\n ownerDid,\n sessionDid: identity.did,\n spaceId,\n tinycloudHost: this.#config.nodeHost,\n });\n await secureWrite(this.#keyPath(stateRoot), identity.jwk);\n await secureWrite(sessionPath, session);\n const request = await withTinyCloudStateRoot(stateRoot, () => createOrReusePermissionRequest({\n profile: PROFILE,\n posture: \"delegate-session\",\n operatorType: \"agent\",\n host: this.#config.nodeHost,\n sessionDid: identity.did,\n ownerDid,\n spaceId,\n missing: permissions,\n granted: [],\n replace: true,\n }));\n if (request.status !== \"created\") {\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n const imported = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: request.request.requestId,\n delegationCid: activated.cid,\n delegation: activated.delegation,\n },\n );\n if (imported.status === \"error\") {\n throw new NativeGrantValidationError(\n NATIVE_GRANT_IMPORT_REJECTION_CODES.has(imported.error.code)\n ? \"native_grant_rejected\"\n : \"native_grant_validation_unavailable\",\n );\n }\n if (imported.status !== \"ok\" || !isRecord(imported.output) ||\n imported.output.activated !== true || imported.output.cid !== activated.cid) {\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n await secureWrite(this.#nativeGrantPath(stateRoot), grant);\n } catch (error) {\n try {\n await restoreOptionalText(sessionPath, previousSession);\n } catch {\n await rm(this.#nativeGrantPath(stateRoot), { force: true }).catch(() => undefined);\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n throw error;\n }\n return { ownerDid, serviceDid: normalizeDid(identity.did), expiresAt: grant.expiresAt, stateRoot };\n });\n }\n\n async nativeGrantForOwner(ownerDid: string): Promise<NativeGrantLookup> {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) return { status: \"rejected\" };\n const stateRoot = this.nativeTenantStateRoot(canonical);\n let stored: StoredNativeGrant | null;\n try {\n stored = await readJson<StoredNativeGrant>(this.#nativeGrantPath(stateRoot));\n } catch {\n return { status: \"rejected\" };\n }\n if (stored === null) return { status: \"required\" };\n if (!isRecord(stored) || stored.version !== 1 || stored.ownerDid !== canonical ||\n typeof stored.serviceDid !== \"string\" || typeof stored.serializedDelegation !== \"string\" ||\n typeof stored.delegationCid !== \"string\" || typeof stored.spaceId !== \"string\" ||\n typeof stored.expiresAt !== \"string\" || !Array.isArray(stored.permissions) ||\n !stored.permissions.every(isPermissionEntry) ||\n nativeOwnerForConnectorGrant(stored.permissions) !== canonical) {\n return { status: \"rejected\" };\n }\n const expires = Date.parse(stored.expiresAt);\n if (!Number.isFinite(expires)) return { status: \"rejected\" };\n if (expires <= Date.now()) return { status: \"expired\" };\n try {\n const identity = await this.#loadNativeServiceKey();\n if (!samePrincipal(stored.serviceDid, identity.did)) return { status: \"rejected\" };\n const activated = await this.#activateNativeDelegation(stored.serializedDelegation, identity);\n if (activated.ownerDid !== canonical || activated.cid !== stored.delegationCid ||\n activated.spaceId !== stored.spaceId ||\n JSON.stringify(activated.permissions) !== JSON.stringify(stored.permissions) ||\n activated.expiresAt.toISOString() !== stored.expiresAt) return { status: \"rejected\" };\n return { status: \"ok\", ownerDid: canonical, stateRoot, expiresAt: stored.expiresAt };\n } catch (error) {\n if (error instanceof NativeGrantValidationError) {\n return { status: error.code === \"native_grant_expired\" ? \"expired\" :\n error.code === \"native_grant_validation_unavailable\" ? \"unavailable\" : \"rejected\" };\n }\n return { status: \"unavailable\" };\n }\n }\n\n async assertNativeGrantActive(ownerDid: string): Promise<void> {\n const canonical = canonicalOwnerDid(ownerDid);\n if (canonical === undefined) throw new NativeGrantValidationError(\"rejected\");\n const stateRoot = this.nativeTenantStateRoot(canonical);\n let stored: StoredNativeGrant | null;\n try {\n stored = await readJson<StoredNativeGrant>(this.#nativeGrantPath(stateRoot));\n } catch {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (stored === null) throw new NativeGrantValidationError(\"required\");\n if (!isRecord(stored) || stored.version !== 1 || stored.ownerDid !== canonical ||\n typeof stored.expiresAt !== \"string\" || !Number.isFinite(Date.parse(stored.expiresAt))) {\n throw new NativeGrantValidationError(\"rejected\");\n }\n if (Date.parse(stored.expiresAt) <= Date.now()) throw new NativeGrantValidationError(\"expired\");\n }\n\n tenantStateRoot(subject: string): string {\n return join(this.#config.stateDir, \"tenants\", this.#tenantId(subject));\n }\n\n /** Prepare only this authenticated account's profile before its first operation. */\n async initializeTenant(subject: string): Promise<string> {\n return (await this.#ensureTenant(subject)).stateRoot;\n }\n /** Check stored node authority before an authenticated operation uses it. */\n async validateTenant(subject: string, ownerDids: readonly string[]): Promise<void> {\n await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);\n }\n\n\n async connectStatus(subject: string, ownerDids: readonly string[] = []): Promise<ConnectStatus> {\n const tenant = await this.#ensureTenant(subject);\n const state = await this.#sessionState(tenant, ownerDids, true);\n if (state === \"valid\") return { connected: true, sessionDid: tenant.sessionDid };\n // An unconfirmed session is not connected, but no new approval is issued for it.\n if (state === \"unknown\") return { connected: false, sessionDid: tenant.sessionDid };\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n connected: false,\n sessionDid: tenant.sessionDid,\n approvalUrl: this.#connectUrl(pending),\n expiresAt: pending.expiresAt,\n };\n }\n\n async decorateAuthorityResult(\n subject: string,\n ownerDids: readonly string[],\n result: unknown,\n invocation?: McpOperationInvocation,\n ): Promise<unknown> {\n if (!isRecord(result)) return result;\n if (result.status === \"error\" && isRecord(result.error) &&\n (result.error.code === \"SESSION_NOT_FOUND\" || result.error.code === \"AUTH_REQUIRED\")) {\n const tenant = await this.#ensureTenant(subject);\n const refusal = revocationFromResult(result.error);\n const cleared = refusal === undefined ? undefined : await this.#clearRefusedAuthority(tenant, refusal);\n if (cleared === \"scoped\" && invocation !== undefined) {\n return this.#renewScopedApproval(subject, ownerDids, tenant, result, invocation);\n }\n const valid = await this.#hasValidSession(tenant, ownerDids, true);\n if (valid && result.error.code === \"AUTH_REQUIRED\") {\n if (refusal === undefined) return result;\n return {\n ...result,\n error: { code: \"AUTH_REQUIRED\", message: \"TinyCloud approval is required.\", retryable: false },\n };\n }\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: {\n code: result.error.code === \"SESSION_NOT_FOUND\" &&\n await readJson<unknown>(this.#sessionPath(tenant.stateRoot)) === null\n ? \"SESSION_NOT_FOUND\"\n : \"AUTH_REQUIRED\",\n message: \"A new TinyCloud approval is required.\",\n retryable: false,\n details: { approvalUrl: this.#connectUrl(pending), expiresAt: pending.expiresAt },\n },\n };\n }\n if (result.status !== \"authority_required\") return result;\n const tenant = await this.#ensureTenant(subject);\n if (this.#renewalRequired.has(tenant.stateRoot) ||\n !(await this.#hasValidSession(tenant, ownerDids, true))) {\n if (this.#renewalRequired.has(tenant.stateRoot)) {\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: {\n code: \"AUTH_REQUIRED\",\n message: \"A new TinyCloud approval is required.\",\n retryable: false,\n details: { approvalUrl: this.#connectUrl(pending), expiresAt: pending.expiresAt },\n },\n };\n }\n }\n const request = isRecord(result.request) ? result.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n if (requestId === undefined || requested.length === 0) return result;\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n ...result,\n approval: {\n ...(isRecord(result.approval) ? result.approval : {}),\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: tcAppsApprovalMessage(requested) ??\n \"Open the approval URL, then retry the same MCP tool.\",\n },\n };\n }\n\n async #renewScopedApproval(\n subject: string,\n ownerDids: readonly string[],\n tenant: TenantProfile,\n result: Record<string, unknown>,\n invocation: McpOperationInvocation,\n ): Promise<unknown> {\n const planned = await invokeOperation(\n \"tinycloud.auth.request\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n invocation,\n );\n const output = planned.status === \"ok\" && isRecord(planned.output) ? planned.output : undefined;\n const request = isRecord(output?.request) ? output.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n const missing = Array.isArray(output?.missing) ? output.missing.filter(isPermissionEntry) : [];\n if (requestId === undefined || requested.length === 0 || missing.length === 0) {\n return {\n status: \"error\",\n operation: result.operation,\n context: result.context,\n error: { code: \"AUTH_REQUIRED\", message: \"A new TinyCloud approval is required.\", retryable: false },\n };\n }\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n status: \"authority_required\",\n operation: result.operation,\n context: result.context,\n missing,\n request,\n approval: {\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: tcAppsApprovalMessage(requested) ??\n \"Open the approval URL, then retry the same MCP tool.\",\n },\n retry: operationRetryDescriptor(invocation, invocation.input),\n };\n }\n\n async #clearRefusedAuthority(\n tenant: TenantProfile,\n refusal: NodeRevocation,\n ): Promise<\"bootstrap\" | \"scoped\" | undefined> {\n const raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot)).catch(() => null);\n const bootstrapCid = raw?.delegationCid;\n const ancestorCid = refusal.reason === \"delegation_ancestor_revoked\" ? refusal.ancestorCid : undefined;\n if (typeof bootstrapCid === \"string\" &&\n (bootstrapCid === refusal.revokedCid || bootstrapCid === ancestorCid)) {\n await this.#clearAuthority(tenant);\n return \"bootstrap\";\n }\n const key = tenant.stateRoot;\n const removed = this.#clearedScoped.get(tenant.stateRoot);\n if (removed?.has(refusal.revokedCid)) return \"scoped\";\n const additional = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n if (this.#clearedScoped.get(key)?.has(refusal.revokedCid)) return \"scoped\";\n if (!Array.isArray(additional)) return undefined;\n const affected = additional.some((entry) => {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" && (cid === refusal.revokedCid || cid === ancestorCid);\n });\n const inProgress = this.#scopedClearing.get(key);\n if (inProgress) {\n await inProgress;\n return this.#clearRefusedAuthority(tenant, refusal);\n }\n if (!affected) return undefined;\n const clearing = (async () => {\n const latest = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n if (!Array.isArray(latest)) return;\n const remaining = latest.filter((entry) => {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid !== \"string\" || (cid !== refusal.revokedCid && cid !== ancestorCid);\n });\n if (remaining.length === latest.length) return;\n this.#activeSessions.delete(tenant.stateRoot);\n const epoch = (this.#approvalEpochs.get(tenant.stateRoot) ?? tenant.approvalEpoch) + 1;\n this.#approvalEpochs.set(tenant.stateRoot, epoch);\n const profilePath = this.#profilePath(tenant.stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n await secureWrite(profilePath, { ...profile, approvalEpoch: epoch });\n if (remaining.length === 0) await rm(this.#additionalPath(tenant.stateRoot), { force: true });\n else await secureWrite(this.#additionalPath(tenant.stateRoot), remaining);\n const cleared = removed ?? new Set<string>();\n cleared.add(refusal.revokedCid);\n this.#clearedScoped.set(tenant.stateRoot, cleared);\n })().finally(() => this.#scopedClearing.delete(key));\n this.#scopedClearing.set(key, clearing);\n await clearing;\n return \"scoped\";\n }\n\n async approvalRedirect(state: string): Promise<string> {\n const pending = await this.#readPending(state, false);\n const tenant = await this.#readTenant(pending.tenantId);\n const callback = new URL(`${this.#config.approvalPath ?? \"/connect\"}/callback`, this.#config.publicUrl);\n callback.searchParams.set(\"state\", state);\n const params = new URLSearchParams({\n did: tenant.sessionDid,\n callback: callback.toString(),\n host: this.#config.nodeHost,\n jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString(\"base64url\"),\n permissions: Buffer.from(JSON.stringify({\n permissions: pending.permissions,\n reason: [\n pending.kind === \"bootstrap\"\n ? \"Connect this TinyCloud account to the hosted MCP delegate.\"\n : tcAppsApprovalReason(pending.permissions) ??\n \"Approve the exact capabilities requested by the TinyCloud MCP operation.\",\n // Owner DIDs come from the verified OpenKey access token of the MCP\n // client that created this link, never from the link itself.\n ...(pending.ownerDids.length === 0\n ? []\n : [`Requested by TinyCloud account ${pending.ownerDids.join(\", \")}; approve only if that is you.`]),\n ].join(\" \"),\n })).toString(\"base64url\"),\n expiry: this.#config.delegationExpiry,\n });\n return `${this.#config.openkeyHost.replace(/\\/+$/, \"\")}/delegate?${params.toString()}`;\n }\n\n async completeApproval(state: string, request: Request): Promise<void> {\n const length = Number(request.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is too large.\");\n }\n const text = await request.text();\n if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is too large.\");\n }\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch (error) {\n throw new ApprovalRequestError(\"body_invalid\", \"Callback body is invalid.\", error);\n }\n if (!isRecord(data)) throw new ApprovalRequestError(\"body_invalid\", \"Callback body is invalid.\");\n\n const pending = await this.#readPending(state, true);\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const prior = this.#approvalProcessing.get(stateRoot);\n const processing = (async () => {\n if (prior) await prior.catch(() => undefined);\n try {\n const tenant = await this.#readTenant(pending.tenantId);\n if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n if (pending.kind === \"bootstrap\") {\n await this.#storeBootstrap(tenant, pending, data);\n } else {\n await this.#storeDelegation(tenant, pending, data);\n }\n await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + \".processing\", { force: true });\n } catch (error) {\n await this.#restorePending(pending).catch(() => undefined);\n throw error;\n }\n })();\n this.#approvalProcessing.set(stateRoot, processing);\n try {\n await processing;\n } finally {\n if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);\n }\n }\n\n async #storeBootstrap(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n const { node, session } = await this.#restoreApproval(tenant, data);\n this.#assertCurrentApproval(pending, session);\n if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {\n throw new ApprovalOwnerMismatchError();\n }\n // The verifier reports one entry per signed action; the SDK subset check\n // judges each requested entry against every matching grant together.\n if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {\n throw new Error(\"The approved delegation does not cover the requested account access.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(tenant.stateRoot));\n await secureWrite(this.#profilePath(tenant.stateRoot), {\n ...profile,\n ownerDid: normalizeDid(node.did),\n spaceId: session.spaceId,\n });\n await secureWrite(this.#sessionPath(tenant.stateRoot), {\n authMethod: \"openkey\",\n ...session,\n });\n this.#renewalRequired.delete(tenant.stateRoot);\n this.#activeSessions.delete(tenant.stateRoot);\n }\n\n async #storeDelegation(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (pending.requestId === undefined) throw new Error(\"Authority request is missing.\");\n // Unlike bootstrap there is no empty-list exemption: a delegation is only\n // imported when its verified signer is the OAuth principal that asked.\n const { node, session } = await this.#restoreApproval(tenant, data);\n this.#assertCurrentApproval(pending, session);\n if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();\n // OpenKey returns a signed-login (CACAO) delegation. Every field is\n // projected from the verified SIWE; `tinycloud.auth.import` verifies it\n // again and checks it stays within the stored request.\n let delegation: PortableDelegation;\n try {\n delegation = siweRuntimeDelegation(node, {\n authorization: session.delegationHeader.Authorization,\n cid: session.delegationCid,\n spaceId: session.spaceId,\n ownerAddress: session.address,\n chainId: session.chainId,\n siwe: session.siwe,\n signature: session.signature,\n host: this.#config.nodeHost,\n });\n } catch (error) {\n throw new ApprovalStageError(\n \"siwe_runtime_delegation\",\n \"DELEGATION_REJECTED\",\n error instanceof RuntimeDelegationRejectedError ? error.reason : undefined,\n error,\n );\n }\n const result = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: pending.requestId,\n delegationCid: delegation.cid,\n delegation,\n },\n );\n if (result.status === \"error\") {\n const reason = result.error.details?.reason;\n // Only a refused node activation carries a rejection reason on DELEGATION_REJECTED.\n throw new ApprovalStageError(\n result.error.code === \"DELEGATION_REJECTED\" && typeof reason === \"string\" ? \"activation\" : \"auth_import\",\n result.error.code,\n typeof reason === \"string\" ? reason : undefined,\n );\n }\n if (result.status !== \"ok\") throw new ApprovalStageError(\"auth_import\", \"AUTHORITY_REQUIRED\");\n }\n\n #assertCurrentApproval(pending: PendingApproval, session: CallbackSession): void {\n const issuedAt = /^Issued At: ([^\\r\\n]+)\\r?$/m.exec(session.siwe)?.[1];\n if (issuedAt === undefined || !Number.isFinite(Date.parse(issuedAt)) ||\n Date.parse(issuedAt) < Date.parse(pending.createdAt)) {\n throw new ApprovalStageError(\"restore_approval\", \"APPROVAL_PREDATES_REQUEST\");\n }\n }\n\n /**\n * Verify the OpenKey callback as a SIWE session for this tenant's key. The\n * callback must carry the full signed proof (SIWE, signature, address and\n * chain), so the WASM verifier always runs: it binds the authorization bytes\n * and CID to the signed SIWE, and `node.did` is the wallet that signed\n * exactly the delegation being stored.\n */\n async #restoreApproval(\n tenant: TenantProfile,\n data: Record<string, unknown>,\n ): Promise<{ node: TinyCloudNode; session: CallbackSession }> {\n let session: CallbackSession;\n try {\n session = sessionFromCallback(data, tenant.jwk);\n } catch (error) {\n throw new ApprovalStageError(\"restore_approval\", \"CALLBACK_INCOMPLETE\", undefined, error);\n }\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession(session);\n } catch (error) {\n throw new ApprovalStageError(\n \"restore_approval\",\n error instanceof InvalidRestoredSessionError || error instanceof UnsupportedSessionRestoreError\n ? error.code\n : \"SESSION_RESTORE_FAILED\",\n undefined,\n error,\n );\n }\n if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {\n throw new ApprovalStageError(\"restore_approval\", \"SESSION_MISMATCH\");\n }\n return { node, session };\n }\n\n async #ensureTenant(subject: string): Promise<TenantProfile> {\n const tenantId = this.#tenantId(subject);\n const current = this.#initializing.get(tenantId);\n if (current !== undefined) return current;\n const initializing = this.#initializeTenant(tenantId).finally(() => {\n this.#initializing.delete(tenantId);\n });\n this.#initializing.set(tenantId, initializing);\n return initializing;\n }\n\n async #hasValidSession(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh = false,\n ): Promise<boolean> {\n return (await this.#sessionState(tenant, ownerDids, fresh)) !== \"invalid\";\n }\n\n async #sessionState(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh = false,\n ): Promise<SessionState> {\n if (this.#renewalRequired.has(tenant.stateRoot)) return \"invalid\";\n const key = JSON.stringify([tenant.stateRoot, ownerDids.map(normalizeDid), fresh]);\n const current = this.#sessionChecks.get(key);\n if (current) return current;\n const checking = this.#checkSession(tenant, ownerDids, fresh).finally(() => {\n this.#sessionChecks.delete(key);\n });\n this.#sessionChecks.set(key, checking);\n return checking;\n }\n\n async #checkSession(\n tenant: TenantProfile,\n ownerDids: readonly string[],\n fresh: boolean,\n ): Promise<SessionState> {\n let raw: Record<string, unknown> | null;\n try {\n raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot));\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (raw === null) return \"invalid\";\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession(raw as unknown as TinyCloudSession);\n } catch {\n const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : undefined;\n const signedExpiry = typeof header === \"string\" ? signedCompactUcanExpiry(header) : undefined;\n const siweExpiry = typeof raw.siwe === \"string\"\n ? /^Expiration Time: ([^\\r\\n]+)\\r?$/m.exec(raw.siwe)?.[1]\n : undefined;\n const expiry = signedExpiry ?? (siweExpiry === undefined ? undefined : new Date(siweExpiry));\n if (expiry !== undefined && expiry.getTime() <= Date.now()) return \"invalid\";\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (!samePrincipal(node.sessionDid, tenant.sessionDid) ||\n !ownerDids.some((did) => samePrincipal(node.did, did))) return \"invalid\";\n const additional = await readJson<unknown>(this.#additionalPath(tenant.stateRoot));\n const cids = [raw.delegationCid];\n if (additional !== null) {\n if (!Array.isArray(additional)) throw new Error(\"Stored TinyCloud authority is unavailable.\");\n for (const entry of additional) {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n cids.push(cid);\n }\n }\n if (!cids.every((cid): cid is string => typeof cid === \"string\" && cid.length > 0)) {\n throw new Error(\"Stored TinyCloud authority is unavailable.\");\n }\n const fingerprint = cids.join(\"\\n\");\n const cached = this.#activeSessions.get(tenant.stateRoot);\n if (!fresh && cached?.cids === fingerprint && cached.until > Date.now()) return \"valid\";\n // A node refusal is actionable only when it names this stored permission.\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 2_000);\n timer.unref();\n });\n const probe = await Promise.race([\n node.kvForSpace(String(raw.spaceId)).list({ prefix: \"spaces/\" }).catch(() => undefined),\n timeout,\n ]).finally(() => clearTimeout(timer));\n const refusal = probe !== undefined && !probe.ok ? nodeRevocationOf(probe.error) : undefined;\n if (refusal !== undefined &&\n (refusal.revokedCid === raw.delegationCid ||\n (refusal.reason === \"delegation_ancestor_revoked\" && refusal.ancestorCid === raw.delegationCid))) {\n await this.#clearAuthority(tenant);\n return \"invalid\";\n }\n if (this.#renewalRequired.has(tenant.stateRoot)) return \"invalid\";\n if (probe?.ok) {\n this.#activeSessions.set(tenant.stateRoot, { cids: fingerprint, until: Date.now() + 30_000 });\n return \"valid\";\n }\n // Timeouts, transport errors and refusals that do not name this permission\n // leave the stored session in place without confirming it.\n return \"unknown\";\n }\n\n async #clearAuthority(tenant: TenantProfile): Promise<void> {\n const current = this.#clearing.get(tenant.stateRoot);\n if (current) return current;\n this.#activeSessions.delete(tenant.stateRoot);\n this.#renewalRequired.add(tenant.stateRoot);\n this.#clearedScoped.delete(tenant.stateRoot);\n this.#approvalEpochs.set(\n tenant.stateRoot,\n (this.#approvalEpochs.get(tenant.stateRoot) ?? tenant.approvalEpoch) + 1,\n );\n const clearing = (async () => {\n const processing = this.#approvalProcessing.get(tenant.stateRoot);\n if (processing) await processing.catch(() => undefined);\n const scoped = this.#scopedClearing.get(tenant.stateRoot);\n if (scoped) await scoped;\n this.#renewalRequired.add(tenant.stateRoot);\n const profilePath = this.#profilePath(tenant.stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n await secureWrite(profilePath, {\n ...profile,\n approvalEpoch: this.#approvalEpochs.get(tenant.stateRoot),\n });\n await rm(this.#additionalPath(tenant.stateRoot), { force: true });\n await rm(join(tenant.stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"auth-requests.json\"), { force: true });\n await rm(this.#pendingDirectory(tenant.stateRoot), { recursive: true, force: true });\n await rm(this.#sessionPath(tenant.stateRoot), { force: true });\n })().finally(() => this.#clearing.delete(tenant.stateRoot));\n this.#clearing.set(tenant.stateRoot, clearing);\n await clearing;\n }\n\n async #initializeTenant(tenantId: string): Promise<TenantProfile> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const keyPath = this.#keyPath(stateRoot);\n await secureDirectory(join(stateRoot, \".tinycloud\", \"profiles\", PROFILE));\n let jwk = await readJson<Record<string, unknown>>(keyPath);\n let sessionDid: string;\n if (jwk === null) {\n const generated = generateSessionKey();\n jwk = generated.jwk;\n sessionDid = generated.did;\n await secureWrite(keyPath, jwk);\n } else {\n sessionDid = didFromJwk(jwk);\n }\n const profilePath = this.#profilePath(stateRoot);\n const profile = await readJson<Record<string, unknown>>(profilePath);\n if (profile === null) {\n await secureWrite(profilePath, {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: 1,\n spaceName: \"default\",\n did: sessionDid,\n sessionDid,\n createdAt: new Date().toISOString(),\n posture: \"delegate-session\",\n operatorType: \"agent\",\n authMethod: \"openkey\",\n openkeyHost: this.#config.openkeyHost,\n });\n } else if (\n typeof profile.host === \"string\" &&\n profile.host.replace(/\\/+$/, \"\") === LEGACY_DEFAULT_NODE_HOST &&\n this.#config.nodeHost.replace(/\\/+$/, \"\") !== LEGACY_DEFAULT_NODE_HOST\n ) {\n // The runtime already talks to TC_HOST, but `tinycloud.auth.import`\n // checks the stored host, so a tenant left on the retired default\n // refuses every authority approval. Any other stored host is a\n // deliberate pin and keeps its DELEGATION_HOST_MISMATCH.\n await secureWrite(profilePath, { ...profile, host: this.#config.nodeHost });\n process.stderr.write(\n `[tinycloud-mcp-http] tenant node host migrated: from=${LEGACY_DEFAULT_NODE_HOST} to=${new URL(this.#config.nodeHost).origin}\\n`,\n );\n }\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n this.#approvalEpochs.set(stateRoot, approvalEpoch);\n return { stateRoot, sessionDid, jwk, approvalEpoch };\n }\n\n async #readTenant(tenantId: string): Promise<TenantProfile> {\n if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const jwk = await readJson<Record<string, unknown>>(this.#keyPath(stateRoot));\n if (jwk === null) throw new ApprovalRequestError(\"tenant_missing\", \"The TinyCloud delegate no longer exists.\");\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(stateRoot));\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n return { stateRoot, jwk, sessionDid: didFromJwk(jwk), approvalEpoch };\n }\n\n async #createPending(\n subject: string,\n ownerDids: readonly string[],\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const clearing = this.#clearing.get(this.tenantStateRoot(subject));\n if (clearing) await clearing;\n const tenant = await this.#ensureTenant(subject);\n const tenantId = this.#tenantId(subject);\n const normalizedOwners = ownerDids.map(normalizeDid);\n const key = JSON.stringify([tenantId, tenant.approvalEpoch, kind, requestId, permissions, normalizedOwners]);\n const current = this.#pendingWrites.get(key);\n if (current) return current;\n const writing = this.#writePending(tenant, tenantId, kind, permissions, normalizedOwners, requestId)\n .finally(() => this.#pendingWrites.delete(key));\n this.#pendingWrites.set(key, writing);\n return writing;\n }\n\n async #writePending(\n tenant: TenantProfile,\n tenantId: string,\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n ownerDids: string[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const reusable = await reusablePending(\n this.#pendingDirectory(tenant.stateRoot),\n { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },\n );\n if (reusable !== undefined) return reusable;\n const nonce = randomBytes(24).toString(\"base64url\");\n const created = Date.now();\n const pending: PendingApproval = {\n version: 1,\n nonce,\n tenantId,\n approvalEpoch: tenant.approvalEpoch,\n kind,\n ...(requestId === undefined ? {} : { requestId }),\n permissions,\n ownerDids,\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1000).toISOString(),\n };\n await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);\n return pending;\n }\n\n async #readPending(state: string, consume: boolean): Promise<PendingApproval> {\n const [tenantId, nonce, signature] = state.split(\".\");\n if (tenantId === undefined || nonce === undefined || signature === undefined) {\n throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n }\n const expected = this.#signState(tenantId, nonce);\n const supplied = Buffer.from(signature, \"base64url\");\n const expectedBytes = Buffer.from(expected, \"base64url\");\n if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {\n throw new ApprovalRequestError(\"state_invalid\", \"Approval state is invalid.\");\n }\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const path = this.#pendingPath(stateRoot, nonce);\n const claimed = `${path}.processing`;\n if (consume) {\n try {\n await rename(path, claimed);\n } catch (error) {\n // No pending file to claim. Other filesystem failures stay unclassified.\n if (!isRecord(error) || error.code !== \"ENOENT\") throw error;\n // The state is signed by this server, so a missing tenant key means the\n // tenant directory itself is gone (for example a reset state volume).\n const tenantExists = await readJson<unknown>(this.#keyPath(stateRoot)).then(\n (jwk) => jwk !== null,\n () => true,\n );\n if (!tenantExists) {\n throw new ApprovalRequestError(\"tenant_missing\", \"The TinyCloud delegate no longer exists.\", error);\n }\n // Already used, being processed, or never issued. This is not proof of\n // replay: retrying an expired link lands here too, because the first\n // attempt deleted its pending file.\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\", error);\n }\n }\n try {\n const pending = await readJson<PendingApproval>(consume ? claimed : path);\n if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(stateRoot));\n const approvalEpoch = this.#approvalEpochs.get(stateRoot) ??\n (typeof profile?.approvalEpoch === \"number\" ? profile.approvalEpoch : 0);\n if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {\n throw new ApprovalRequestError(\"state_not_pending\", \"Approval state is invalid or already used.\");\n }\n if (new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(consume ? claimed : path, { force: true });\n throw new ApprovalRequestError(\"state_expired\", \"Approval state has expired.\");\n }\n return pending;\n } catch (error) {\n if (consume) await rename(claimed, path).catch(() => undefined);\n throw error;\n }\n }\n\n async #restorePending(pending: PendingApproval): Promise<void> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const path = this.#pendingPath(stateRoot, pending.nonce);\n await rename(`${path}.processing`, path);\n }\n\n #connectUrl(pending: PendingApproval): string {\n const url = new URL(this.#config.approvalPath ?? \"/connect\", this.#config.publicUrl);\n url.searchParams.set(\"state\", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);\n return url.toString();\n }\n\n async #withNativeGrantLock<T>(ownerDid: string, action: () => Promise<T>): Promise<T> {\n const previous = this.#nativeGrantQueues.get(ownerDid) ?? Promise.resolve();\n let releaseNext!: () => void;\n const next = new Promise<void>((resolve) => {\n releaseNext = resolve;\n });\n this.#nativeGrantQueues.set(ownerDid, next);\n await previous;\n try {\n return await action();\n } finally {\n releaseNext();\n if (this.#nativeGrantQueues.get(ownerDid) === next) this.#nativeGrantQueues.delete(ownerDid);\n }\n }\n async #loadNativeServiceKey(): Promise<{ did: string; jwk: Record<string, unknown> }> {\n if (this.#nativeIdentity === undefined) {\n const loading = this.#readOrCreateNativeServiceKey();\n this.#nativeIdentity = loading;\n void loading.catch(() => {\n if (this.#nativeIdentity === loading) this.#nativeIdentity = undefined;\n });\n }\n return this.#nativeIdentity;\n }\n\n async #readOrCreateNativeServiceKey(): Promise<{ did: string; jwk: Record<string, unknown> }> {\n const path = join(this.#config.stateDir, \".tinycloud\", \"native-service-key.json\");\n await secureDirectory(dirname(path));\n let stored = await readJson<NativeServiceKey>(path);\n if (stored === null) {\n const generated = generateSessionKey();\n try {\n await writeFile(path, `${JSON.stringify({ version: 1, jwk: generated.jwk })}\\n`, {\n mode: 0o600,\n flag: \"wx\",\n });\n } catch (error) {\n if (!isRecord(error) || error.code !== \"EEXIST\") throw error;\n }\n await chmod(path, 0o600);\n stored = await readJson<NativeServiceKey>(path);\n }\n if (stored === null || !isRecord(stored) || stored.version !== 1 || !isRecord(stored.jwk)) {\n throw new Error(\"The native MCP service identity is unavailable.\");\n }\n return { did: didFromJwk(stored.jwk), jwk: stored.jwk };\n }\n\n async #activateNativeDelegation(\n serialized: string,\n identity: { did: string; jwk: Record<string, unknown> },\n ): Promise<{\n ownerDid: string;\n spaceId: string;\n permissions: PermissionEntry[];\n cid: string;\n expiresAt: Date;\n delegation: PortableDelegation;\n }> {\n let delegation: PortableDelegation;\n try {\n const parsed: unknown = JSON.parse(serialized);\n if (!isRecord(parsed)) throw new Error(\"invalid delegation\");\n delegation = deserializeDelegation(serialized);\n } catch {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n if (!isRecord(delegation.delegationHeader) ||\n typeof delegation.delegationHeader.Authorization !== \"string\" ||\n delegation.delegationHeader.Authorization.length === 0 ||\n typeof delegation.cid !== \"string\" || delegation.cid.length === 0 ||\n typeof delegation.delegateDID !== \"string\" ||\n !samePrincipal(delegation.delegateDID, normalizeDid(identity.did)) ||\n typeof delegation.spaceId !== \"string\" ||\n typeof delegation.ownerAddress !== \"string\" ||\n !Number.isSafeInteger(delegation.chainId) ||\n typeof delegation.host !== \"string\" || !sameNodeHost(delegation.host, this.#config.nodeHost) ||\n !(delegation.expiry instanceof Date) || !Number.isFinite(delegation.expiry.getTime())) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n const now = Date.now();\n const claimedExpiry = delegation.expiry.getTime();\n if (claimedExpiry <= now) throw new NativeGrantValidationError(\"native_grant_expired\");\n if (claimedExpiry > now + NATIVE_GRANT_MAX_LIFETIME_SECONDS * 1_000) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n\n let ownerDid: string | undefined;\n let spaceId: string | undefined;\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n try {\n await node.restoreSession({\n delegationHeader: delegation.delegationHeader,\n delegationCid: delegation.cid,\n spaceId: delegation.spaceId,\n jwk: identity.jwk,\n verificationMethod: identity.did,\n tinycloudHosts: [this.#config.nodeHost],\n });\n const activated = await activateValidatedRuntimeDelegation(node, delegation, {\n host: this.#config.nodeHost,\n authorize: (permissions) => {\n const derivedOwner = nativeOwnerForConnectorGrant(permissions);\n const signedSpace = permissions[0]?.space;\n if (derivedOwner === undefined || signedSpace === undefined) return false;\n const metadataOwner = canonicalOwnerDid(\n `did:pkh:eip155:${delegation.chainId}:${delegation.ownerAddress}`,\n );\n if (metadataOwner !== derivedOwner ||\n delegation.spaceId.toLowerCase() !== signedSpace.toLowerCase()) return false;\n ownerDid = derivedOwner;\n spaceId = signedSpace;\n return true;\n },\n });\n if (ownerDid === undefined || spaceId === undefined ||\n !samePrincipal(activated.audience, normalizeDid(identity.did)) ||\n activated.expiry.getTime() > now + NATIVE_GRANT_MAX_LIFETIME_SECONDS * 1_000) {\n throw new NativeGrantValidationError(\"native_grant_rejected\");\n }\n return {\n ownerDid,\n spaceId,\n permissions: [...activated.effectivePermissions],\n cid: activated.cid,\n expiresAt: activated.expiry,\n delegation: activated.delegation,\n };\n } catch (error) {\n if (error instanceof NativeGrantValidationError) throw error;\n if (error instanceof RuntimeDelegationRejectedError) {\n throw new NativeGrantValidationError(\n error.reason === \"expired\"\n ? \"native_grant_expired\"\n : error.reason === \"activation_unavailable\"\n ? \"native_grant_validation_unavailable\"\n : \"native_grant_rejected\",\n );\n }\n throw new NativeGrantValidationError(\"native_grant_validation_unavailable\");\n }\n }\n\n #nativeGrantPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"native-grant.json\");\n }\n #tenantId(subject: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret).update(`tenant:${subject}`).digest(\"hex\");\n }\n\n #signState(tenantId: string, nonce: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret)\n .update(`approval:${tenantId}:${nonce}`)\n .digest(\"base64url\");\n }\n\n #profilePath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"profile.json\");\n }\n\n #keyPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"key.json\");\n }\n\n #sessionPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"session.json\");\n }\n\n #additionalPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"additional-delegations.json\");\n }\n\n #pendingPath(stateRoot: string, nonce: string): string {\n return join(this.#pendingDirectory(stateRoot), `${nonce}.json`);\n }\n\n #pendingDirectory(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"pending\");\n }\n}\n\nlet wasmInitialized = false;\n\nfunction generateSessionKey(): { jwk: Record<string, unknown>; did: string } {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = manager.createSessionKey(\"hosted-mcp\");\n const serialized = manager.jwk(keyId);\n if (!serialized) throw new Error(\"Could not generate the hosted delegate key.\");\n return { jwk: JSON.parse(serialized) as Record<string, unknown>, did: manager.getDID(keyId) };\n}\n\nfunction didFromJwk(jwk: Record<string, unknown>): string {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = importKey(manager, JSON.stringify(jwk), \"hosted-mcp\");\n return manager.getDID(keyId);\n}\n\nfunction ensureWasm(): void {\n if (wasmInitialized) return;\n initPanicHook();\n wasmInitialized = true;\n}\n\nfunction revocationFromResult(error: Record<string, unknown>): NodeRevocation | undefined {\n const details = error.details;\n if (!isRecord(details) || typeof details.revokedCid !== \"string\") return undefined;\n if (details.reason === \"delegation_revoked\") {\n return { reason: \"delegation_revoked\", revokedCid: details.revokedCid };\n }\n if (details.reason === \"delegation_ancestor_revoked\" && typeof details.ancestorCid === \"string\") {\n return {\n reason: \"delegation_ancestor_revoked\",\n revokedCid: details.revokedCid,\n ancestorCid: details.ancestorCid,\n };\n }\n return undefined;\n}\n\n/**\n * Parse the OpenKey callback. Every signed-proof field is required: without\n * them `restoreSession` verifies nothing and `node.did` would fall back to the\n * tenant's own key.\n */\nfunction sessionFromCallback(data: Record<string, unknown>, privateJwk: Record<string, unknown>): CallbackSession {\n const delegationHeader = data.delegationHeader;\n if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== \"string\" ||\n typeof data.delegationCid !== \"string\" || typeof data.spaceId !== \"string\" ||\n typeof data.verificationMethod !== \"string\" || typeof data.address !== \"string\" ||\n typeof data.chainId !== \"number\" || typeof data.siwe !== \"string\" ||\n typeof data.signature !== \"string\") {\n throw new Error(\"OpenKey returned an incomplete delegation.\");\n }\n return {\n delegationHeader: { Authorization: delegationHeader.Authorization },\n delegationCid: data.delegationCid,\n spaceId: data.spaceId,\n jwk: privateJwk,\n verificationMethod: data.verificationMethod,\n address: data.address,\n chainId: data.chainId,\n siwe: data.siwe,\n signature: data.signature,\n };\n}\n\nfunction publicJwk(jwk: Record<string, unknown>): Record<string, unknown> {\n const copy = { ...jwk };\n for (const field of [\"d\", \"p\", \"q\", \"dp\", \"dq\", \"qi\", \"oth\", \"k\"]) delete copy[field];\n return copy;\n}\n\nfunction samePrincipal(left: string | undefined, right: string): boolean {\n if (typeof left !== \"string\") return false;\n try {\n return principalDidEquals(left, right);\n } catch {\n return false;\n }\n}\n\nfunction normalizeDid(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\nfunction sameNodeHost(left: string, right: string): boolean {\n try {\n const normalize = (value: string): string => {\n const url = new URL(value);\n if (url.username !== \"\" || url.password !== \"\") return \"\";\n url.hash = \"\";\n url.search = \"\";\n url.pathname = url.pathname.replace(/\\/+$/, \"\");\n return url.toString().replace(/\\/+$/, \"\");\n };\n return normalize(left) !== \"\" && normalize(left) === normalize(right);\n } catch {\n return false;\n }\n}\n\nfunction isPermissionEntry(value: unknown): value is PermissionEntry {\n return isRecord(value) && typeof value.service === \"string\" && typeof value.space === \"string\" &&\n typeof value.path === \"string\" && Array.isArray(value.actions) &&\n value.actions.every((action) => typeof action === \"string\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function secureDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n await chmod(path, 0o700);\n}\n\nasync function secureWrite(path: string, value: unknown): Promise<void> {\n const directory = dirname(path);\n await secureDirectory(directory);\n const temporary = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`;\n await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}\\n`, { mode: 0o600 });\n await rename(temporary, path);\n await chmod(path, 0o600);\n}\n\nfunction jsonReplacer(_key: string, value: unknown): unknown {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nasync function readJson<T>(path: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function readOptionalText(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function restoreOptionalText(path: string, contents: string | null): Promise<void> {\n if (contents === null) {\n await rm(path, { force: true });\n return;\n }\n await secureDirectory(dirname(path));\n await writeFile(path, contents, { mode: 0o600 });\n await chmod(path, 0o600);\n}\n\nasync function reusablePending(\n directory: string,\n expected: Pick<PendingApproval, \"tenantId\" | \"approvalEpoch\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): Promise<PendingApproval | undefined> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return undefined;\n throw error;\n }\n const active: PendingApproval[] = [];\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(directory, name);\n const pending = await readJson<PendingApproval>(path).catch(() => null);\n if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(path, { force: true });\n continue;\n }\n active.push(pending);\n if (samePendingRequest(pending, expected)) return pending;\n }\n if (active.length >= 64) {\n active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));\n await rm(join(directory, `${active[0]!.nonce}.json`), { force: true });\n }\n return undefined;\n}\n\nfunction samePendingRequest(\n pending: PendingApproval,\n expected: Pick<PendingApproval, \"tenantId\" | \"approvalEpoch\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): boolean {\n return pending.version === 1 && pending.tenantId === expected.tenantId &&\n (pending.approvalEpoch ?? 0) === expected.approvalEpoch &&\n pending.kind === expected.kind && pending.requestId === expected.requestId &&\n JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) &&\n JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);\n}\n","import { timingSafeEqual } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/node-sdk\";\n\nexport const NATIVE_SERVICE_CREDENTIAL_HEADER = \"X-TinyCloud-Service-Credential\";\nexport const NATIVE_OWNER_DID_HEADER = \"X-TinyCloud-Owner-DID\";\nexport const NATIVE_GRANT_MAX_LIFETIME_SECONDS = 30 * 24 * 60 * 60;\nexport const NATIVE_GRANT_REQUIRED = \"native_grant_required\";\nexport const NATIVE_GRANT_EXPIRED = \"native_grant_expired\";\nexport const NATIVE_GRANT_REJECTED = \"native_grant_rejected\";\nexport const NATIVE_SERVICE_UNAUTHORIZED = \"native_service_unauthorized\";\nexport const NATIVE_SERVICE_UNAVAILABLE = \"native_service_unavailable\";\nexport const NATIVE_GRANT_VALIDATION_UNAVAILABLE = \"native_grant_validation_unavailable\";\nexport const MAX_NATIVE_GRANT_BODY_BYTES = 256 * 1024;\n\nexport function serviceCredentialMatches(supplied: string | null, configured: string | undefined): boolean {\n if (supplied === null || configured === undefined) return false;\n const suppliedBytes = Buffer.from(supplied, \"utf8\");\n const configuredBytes = Buffer.from(configured, \"utf8\");\n return suppliedBytes.byteLength === configuredBytes.byteLength &&\n timingSafeEqual(suppliedBytes, configuredBytes);\n}\nconst OWNER_APPLICATIONS_SPACE = /^tinycloud:pkh:eip155:([1-9][0-9]*):(0x[0-9a-f]{40}):applications$/i;\nconst SQL_PATH = \"xyz.tinycloud.tinychat/connectors\";\nconst KV_PREFIX = \"xyz.tinycloud.tinychat/connectors/\";\n\nexport function canonicalOwnerDid(value: string): string | undefined {\n const match = /^did:pkh:eip155:([1-9][0-9]*):(0x[0-9a-f]{40})$/i.exec(value);\n if (!match) return undefined;\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) return undefined;\n return `did:pkh:eip155:${chainId}:${match[2]!.toLowerCase()}`;\n}\n\n/** Derive the owner solely from the signed applications-space capabilities. */\nexport function nativeOwnerForConnectorGrant(\n permissions: readonly PermissionEntry[],\n): string | undefined {\n if (permissions.length !== 2) return undefined;\n const sqlEntries = permissions.filter((permission) => permission.service === \"tinycloud.sql\");\n const kvEntries = permissions.filter((permission) => permission.service === \"tinycloud.kv\");\n if (sqlEntries.length !== 1 || kvEntries.length !== 1) return undefined;\n const sql = sqlEntries[0]!;\n const kv = kvEntries[0]!;\n if (typeof sql.space !== \"string\" || typeof kv.space !== \"string\" ||\n sql.path !== SQL_PATH || kv.path !== KV_PREFIX) return undefined;\n if (!actionsEqual(sql.actions, [\"tinycloud.sql/read\"]) ||\n !actionsEqual(kv.actions, [\"tinycloud.kv/get\", \"tinycloud.kv/list\"])) return undefined;\n if (hasCaveats(sql) || hasCaveats(kv)) return undefined;\n\n const sqlSpace = ownerFromApplicationsSpace(sql.space);\n const kvSpace = ownerFromApplicationsSpace(kv.space);\n return sqlSpace !== undefined && sqlSpace === kvSpace ? sqlSpace : undefined;\n}\n\nfunction ownerFromApplicationsSpace(space: string): string | undefined {\n const match = OWNER_APPLICATIONS_SPACE.exec(space);\n if (!match) return undefined;\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) return undefined;\n return `did:pkh:eip155:${chainId}:${match[2]!.toLowerCase()}`;\n}\n\nfunction actionsEqual(actual: readonly string[], expected: readonly string[]): boolean {\n const actualActions = [...actual].sort();\n const expectedActions = [...expected].sort();\n return actualActions.length === expectedActions.length &&\n actualActions.every((value, index) => value === expectedActions[index]);\n}\n\nfunction hasCaveats(permission: PermissionEntry): boolean {\n return Object.hasOwn(permission, \"caveats\") && permission.caveats !== undefined;\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,oCAAoC;;;ACF7C,SAAS,iBAAiB;AAC1B,SAAS,kBAA0C;;;ACDnD,SAAS,qBAAqB;AAC9B,SAAS,YAAY;AAErB,SAAS,sBAA4D;AACrE,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;;;ACmBzB,SAAS,gBACd,QACA,WAA2C,CAAC,GAC5C,UAAgC,CAAC,GAClB;AACf,MAAI,YAAsC,2BAA2B,MAAM,IACvE,iBAAiB,QAAQ,QAAQ,IACjC;AAAA,IACA,QAAQ;AAAA,IACR,WAAW,CAAC;AAAA,IACZ,SAAS,CAAC;AAAA,IACV,OAAO,EAAE,MAAM,iBAAiB;AAAA,EAClC;AACF,MAAI;AACJ,MAAI,QAAQ,YAAY,UAAU;AAChC,iBAAa,KAAK,UAAU,SAAS;AACrC,SACG,QAAQ,aAAa,QACpB,QAAQ,gBAAgB,4BACxB,QAAQ,gBAAgB,2BAC1B,WAAW,SAAS,KACpB;AACA,YAAM,MAAM,QAAQ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pServer","fromJsonSchema","timingSafeEqual","join","invokeOperation","join","invokeOperation","tenant","pending","timingSafeEqual","join","authInfo","McpServer","originFailure","fromJsonSchema"]}