@tinycloud/operations 0.4.0-beta.9 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/ms/index.js","../src/artifacts.ts","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../src/authority.ts","../src/state.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === \"*\" || grantedAction === requestedAction) return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mCAAAA,UAAAC,SAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,I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;AACH;AAEA,SAAS,0BACP,SACA,UACA,cACA;AACA,SAAO,iBAAiB,SACpB,kBAAkB,SAAS,QAAQ,IACnC,2BAA2B,SAAS,UAAU,YAAY;AAChE;AAEA,SAAS,iBAAiB,KAAmB;AAC3C,SAAO,OAAO,IAAI,QAAQ,EAAE,SAAS,EAAE,CAAC,QAAI,gCAAW,EAAE,QAAQ,MAAM,EAAE,CAAC;AAC5E;","names":["exports","module","ms","import_node_crypto","_a","ownership","resolve"]}
1
+ {"version":3,"sources":["../../../node_modules/ms/index.js","../src/artifacts.ts","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../src/authority.ts","../src/state.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n// Literal strings, not `KV.SYNC`/`KV.RETAIN`: those are derived from the\n// vendored registry at runtime, so an older bootstrap would turn them into\n// `undefined` and silently disable this guard.\nconst EXPLICIT_ONLY_ACTIONS: Readonly<Record<string, true>> = {\n \"tinycloud.kv/sync\": true,\n \"tinycloud.kv/retain\": true,\n};\n\n/**\n * Whether `action` is one no wildcard covers: `*` and `tinycloud.kv/*` do not\n * grant it, so a grant must name it (TC-732). `tinycloud.kv/sync` discloses a\n * prefix's change feed and `tinycloud.kv/retain` is an owner-approved\n * retention attestation; the node refuses both unless granted by name.\n */\nexport function isExplicitOnlyAction(action: string): boolean {\n return Object.prototype.hasOwnProperty.call(EXPLICIT_ONLY_ACTIONS, action);\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) return true;\n if (isExplicitOnlyAction(requestedAction)) return false;\n if (grantedAction === \"*\") return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n /**\n * Lock only a profile that exists (its `profile.json` is present), and\n * never create its directory: a missing or deleted profile is refused with\n * ProfileDeletedError, before and after waiting for the lock. For writers\n * of state that lives inside an existing profile (replicas).\n */\n requireProfile?: boolean;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) throw new ProfileDeletedError(profile);\n if (!options.requireProfile) await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // Holding the turn, no deletion runs: a profile present now stays until release.\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) {\n // A deletion that finished while this waited could not remove the\n // directory if a lock was held then; remove it if empty.\n await rmdir(directory).catch(() => undefined);\n throw new ProfileDeletedError(profile);\n }\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token, options.requireProfile === true)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string, requireProfile: boolean): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n // With requireProfile only an older release's deletion (which takes no turn) gets here.\n if (requireProfile) throw new ProfileDeletedError(profile);\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mCAAAA,UAAAC,SAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,IAAAA,QAAO,UAAU,SAAU,KAAK,SAAS;AACvC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAA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