@tinycloud/sdk-core 3.7.0 → 3.8.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/delegations/index.cjs +65 -6
- package/dist/delegations/index.cjs.map +1 -1
- package/dist/delegations/index.d.cts +4 -2
- package/dist/delegations/index.d.ts +4 -2
- package/dist/delegations/index.js +66 -7
- package/dist/delegations/index.js.map +1 -1
- package/dist/delegations/issued.cjs +697 -0
- package/dist/delegations/issued.cjs.map +1 -0
- package/dist/delegations/issued.d.cts +54 -0
- package/dist/delegations/issued.d.ts +54 -0
- package/dist/delegations/issued.js +674 -0
- package/dist/delegations/issued.js.map +1 -0
- package/dist/index.cjs +118 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -3
- package/dist/index.d.ts +17 -3
- package/dist/index.js +124 -12
- package/dist/index.js.map +1 -1
- package/dist/{recipient-types.schema-BApcOn1t.d.cts → recipient-types.schema-BIJcihno.d.cts} +42 -1741
- package/dist/{recipient-types.schema-BApcOn1t.d.ts → recipient-types.schema-Ebi5aliq.d.ts} +42 -1741
- package/dist/types.schema-BmN-OnCA.d.cts +1763 -0
- package/dist/types.schema-BmN-OnCA.d.ts +1763 -0
- package/package.json +9 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/delegations/types.schema.ts","../../src/delegations/shared.ts","../../src/delegations/issued.ts"],"sourcesContent":["/**\n * Zod schemas for delegation management types.\n *\n * These schemas provide runtime validation for delegation, capability key management,\n * and sharing link functionality. Types are derived from schemas using z.infer<>.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type {\n FetchFunction,\n InvokeAnyFunction,\n InvokeFunction,\n ServiceSession,\n} from \"@tinycloud/sdk-services\";\n\n// =============================================================================\n// Result Type (Generic)\n// =============================================================================\n\n/**\n * Creates a Result schema for a given data type and error type.\n * Result types provide explicit error handling instead of throwing.\n */\nexport function createResultSchema<T extends z.ZodTypeAny, E extends z.ZodTypeAny>(\n dataSchema: T,\n errorSchema: E\n) {\n return z.discriminatedUnion(\"ok\", [\n z.object({ ok: z.literal(true), data: dataSchema }),\n z.object({ ok: z.literal(false), error: errorSchema }),\n ]);\n}\n\n/**\n * Result type pattern for delegation operations.\n */\nexport type Result<T, E = DelegationError> =\n | { ok: true; data: T }\n | { ok: false; error: E };\n\n// =============================================================================\n// JWK Type (JSON Web Key)\n// =============================================================================\n\n/**\n * JSON Web Key representation for cryptographic keys.\n * Follows the JWK specification (RFC 7517).\n */\nexport const JWKSchema = z.object({\n /** Key type (e.g., \"EC\", \"RSA\", \"OKP\") */\n kty: z.string(),\n /** Curve for EC/OKP keys (e.g., \"P-256\", \"Ed25519\") */\n crv: z.string().optional(),\n /** X coordinate for EC keys, public key for OKP */\n x: z.string().optional(),\n /** Y coordinate for EC keys */\n y: z.string().optional(),\n /** Private key value (d parameter) */\n d: z.string().optional(),\n /** Public exponent for RSA keys */\n e: z.string().optional(),\n /** Modulus for RSA keys */\n n: z.string().optional(),\n /** Key ID */\n kid: z.string().optional(),\n /** Algorithm */\n alg: z.string().optional(),\n /** Key use (e.g., \"sig\", \"enc\") */\n use: z.string().optional(),\n /** Key operations (e.g., [\"sign\", \"verify\"]) */\n key_ops: z.array(z.string()).optional(),\n});\n\nexport type JWK = z.infer<typeof JWKSchema>;\n\n// =============================================================================\n// Key Management Types\n// =============================================================================\n\n/**\n * Type of key in the capability registry.\n */\nexport const KeyTypeSchema = z.enum([\"main\", \"session\", \"ingested\"]);\nexport type KeyType = z.infer<typeof KeyTypeSchema>;\n\n/**\n * Information about a cryptographic key used for delegations.\n */\nexport const KeyInfoSchema = z.object({\n /** Unique identifier for this key */\n id: z.string(),\n /** DID associated with this key */\n did: z.string(),\n /** Type of key determining its authority level */\n type: KeyTypeSchema,\n /** Private key in JWK format */\n jwk: JWKSchema.optional(),\n /** Priority for key selection (lower = higher priority) */\n priority: z.number(),\n});\n\nexport type KeyInfo = z.infer<typeof KeyInfoSchema>;\n\n// =============================================================================\n// Error Types\n// =============================================================================\n\n/**\n * Error type for delegation operations.\n */\nexport const DelegationErrorSchema = z.object({\n /** Error code for programmatic handling */\n code: z.string(),\n /** Human-readable error message */\n message: z.string(),\n /** The service that produced the error */\n service: z.literal(\"delegation\"),\n /** Original error if wrapping another error */\n cause: z.instanceof(Error).optional(),\n /** Additional metadata about the error */\n meta: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type DelegationError = z.infer<typeof DelegationErrorSchema>;\n\n/**\n * Error codes for delegation operations.\n */\nexport const DelegationErrorCodes = {\n AUTH_REQUIRED: \"AUTH_REQUIRED\",\n AUTH_UNAUTHORIZED: \"AUTH_UNAUTHORIZED\",\n AUTH_EXPIRED: \"AUTH_EXPIRED\",\n NOT_INITIALIZED: \"NOT_INITIALIZED\",\n NOT_FOUND: \"NOT_FOUND\",\n REVOKED: \"REVOKED\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n TIMEOUT: \"TIMEOUT\",\n ABORTED: \"ABORTED\",\n INVALID_INPUT: \"INVALID_INPUT\",\n PERMISSION_DENIED: \"PERMISSION_DENIED\",\n CREATION_FAILED: \"CREATION_FAILED\",\n REVOCATION_FAILED: \"REVOCATION_FAILED\",\n INVALID_TOKEN: \"INVALID_TOKEN\",\n KV_SERVICE_UNAVAILABLE: \"KV_SERVICE_UNAVAILABLE\",\n DATA_FETCH_FAILED: \"DATA_FETCH_FAILED\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n UNSUPPORTED_OPERATION: \"UNSUPPORTED_OPERATION\",\n /** The node answered 503: the delegation chain is too deep to evaluate right now. Retry later. */\n CHAIN_TOO_DEEP: \"CHAIN_TOO_DEEP\",\n /** The node answered 400 \"invalid delegation query cursor\": malformed, foreign or from another filter. Start the listing again without it. */\n INVALID_CURSOR: \"INVALID_CURSOR\",\n} as const;\n\nexport type DelegationErrorCode =\n (typeof DelegationErrorCodes)[keyof typeof DelegationErrorCodes];\n\n// =============================================================================\n// Delegation Types\n// =============================================================================\n\n/**\n * Represents a delegation from one DID to another.\n */\nexport const DelegationSchema = z.object({\n /** Content identifier (CID) of the delegation */\n cid: z.string(),\n /** DID of the delegate (the party receiving the delegation) */\n delegateDID: z.string(),\n /** Space ID this delegation applies to */\n spaceId: z.string(),\n /** Resource path this delegation grants access to */\n path: z.string(),\n /** Actions this delegation authorizes */\n actions: z.array(z.string()),\n /** Exact ReCap caveats that constrain every action in this scope. */\n caveats: z.array(z.record(z.string(), z.unknown())).optional(),\n /** When this delegation expires (accepts Date or ISO string from JSON) */\n expiry: z.coerce.date(),\n /** Whether this delegation has been revoked */\n isRevoked: z.boolean(),\n /** DID of the delegator (the party granting the delegation) */\n delegatorDID: z.string().optional(),\n /** When this delegation was created (accepts Date or ISO string from JSON) */\n createdAt: z.coerce.date().optional(),\n /** Parent delegation CID if this is a sub-delegation */\n parentCid: z.string().optional(),\n /** Whether sub-delegation is allowed */\n allowSubDelegation: z.boolean().optional(),\n /** Authorization header (UCAN bearer token) */\n authHeader: z.string().optional(),\n});\n\nexport type Delegation = z.infer<typeof DelegationSchema>;\n\n/** Node-confirmed lifecycle state for one delegation. */\nexport const DelegationStatusSchema = z.object({\n cid: z.string().min(1),\n status: z.enum([\"active\", \"revoked\", \"expired\", \"unavailable\", \"not_found\"]),\n exists: z.boolean(),\n active: z.boolean(),\n revoked: z.boolean(),\n expired: z.boolean(),\n}).strict().superRefine((value, context) => {\n const valid = value.status === \"active\"\n ? value.exists && value.active && !value.revoked && !value.expired\n : value.status === \"revoked\"\n ? value.exists && !value.active && value.revoked && !value.expired\n : value.status === \"expired\"\n ? value.exists && !value.active && !value.revoked && value.expired\n : value.status === \"unavailable\"\n ? value.exists && !value.active && !value.revoked && !value.expired\n : !value.exists && !value.active && !value.revoked && !value.expired;\n if (!valid) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"delegation status flags do not match status\",\n });\n }\n});\n\nexport type DelegationStatus = z.infer<typeof DelegationStatusSchema>;\n\nexport const DelegationRevocationReceiptSchema = z.object({\n revoked: z.literal(true),\n cid: z.string().min(1),\n}).strict();\n\nexport type DelegationRevocationReceipt = z.infer<typeof DelegationRevocationReceiptSchema>;\n\nexport const AccountDelegationResourceSchema = z.object({\n resource: z.string().min(1),\n actions: z.array(z.string()),\n caveats: z.array(z.record(z.string(), z.unknown())),\n}).strict();\n\nconst AccountDelegationDateSchema = z\n .string()\n .datetime({ offset: true })\n .transform((value) => new Date(value));\n\nexport const AccountDelegationRecordSchema = z.object({\n cid: z.string().min(1),\n direction: z.enum([\"granted\", \"received\"]),\n delegatorDid: z.string().min(1),\n delegateDid: z.string().min(1),\n resources: z.array(AccountDelegationResourceSchema),\n parents: z.array(z.string()),\n issuedAt: AccountDelegationDateSchema.nullable(),\n notBefore: AccountDelegationDateSchema.nullable(),\n expiresAt: AccountDelegationDateSchema.nullable(),\n status: z.enum([\"active\", \"pending\", \"expired\", \"revoked\", \"ancestor_revoked\"]),\n revokedAt: AccountDelegationDateSchema.nullable().optional(),\n revokedBy: z.string().optional(),\n revokedAncestorCid: z.string().optional(),\n}).strict();\n\nexport const AccountDelegationPageSchema = z.object({\n schemaVersion: z.literal(2),\n items: z.array(AccountDelegationRecordSchema),\n nextCursor: z.string().optional(),\n}).strict();\n\nexport type AccountDelegationResource = z.infer<typeof AccountDelegationResourceSchema>;\nexport type AccountDelegationRecord = z.infer<typeof AccountDelegationRecordSchema>;\nexport type AccountDelegationPage = z.infer<typeof AccountDelegationPageSchema>;\n\nexport const AccountDelegationQueryOptionsSchema = z.object({\n direction: z.enum([\"granted\", \"received\", \"all\", \"issued\"]).optional(),\n status: z.enum([\"active\", \"pending\", \"expired\", \"revoked\", \"ancestor_revoked\"]).optional(),\n space: z.string().trim().min(1).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n cursor: z.string().min(1).optional(),\n}).strict();\n\nexport type AccountDelegationQueryOptions = z.infer<typeof AccountDelegationQueryOptionsSchema>;\n\n/**\n * Entry in the capability registry mapping a capability to available keys.\n */\nexport const CapabilityEntrySchema = z.object({\n /** Resource URI this capability applies to */\n resource: z.string(),\n /** Action this capability authorizes */\n action: z.string(),\n /** Keys that can exercise this capability, ordered by priority */\n keys: z.array(KeyInfoSchema),\n /** The delegation that grants this capability */\n delegation: DelegationSchema,\n /** When this capability expires (accepts Date or ISO string from JSON) */\n expiresAt: z.coerce.date().optional(),\n});\n\nexport type CapabilityEntry = z.infer<typeof CapabilityEntrySchema>;\n\n/**\n * Persistent record of a delegation stored in the system.\n */\nexport const DelegationRecordSchema = z.object({\n /** Content identifier (CID) of the delegation */\n cid: z.string(),\n /** Space ID this delegation applies to */\n spaceId: z.string(),\n /** DID of the delegator (grantor) */\n delegator: z.string(),\n /** DID of the delegatee (recipient) */\n delegatee: z.string(),\n /** Key ID used to sign/exercise this delegation */\n keyId: z.string().optional(),\n /** Resource path pattern this delegation grants access to */\n path: z.string(),\n /** Actions this delegation authorizes */\n actions: z.array(z.string()),\n /** When this delegation expires (accepts Date or ISO string from JSON) */\n expiry: z.coerce.date().optional(),\n /** When this delegation becomes valid (not before) (accepts Date or ISO string) */\n notBefore: z.coerce.date().optional(),\n /** Whether this delegation has been revoked */\n isRevoked: z.boolean(),\n /** When this delegation was created (accepts Date or ISO string from JSON) */\n createdAt: z.coerce.date(),\n /** Parent delegation CID if this is a sub-delegation */\n parentCid: z.string().optional(),\n});\n\nexport type DelegationRecord = z.infer<typeof DelegationRecordSchema>;\n\n/**\n * Parameters for creating a new delegation.\n */\nexport const CreateDelegationParamsSchema = z.object({\n /** DID of the delegate (the party receiving the delegation) */\n delegateDID: z.string(),\n /** Resource path this delegation grants access to */\n path: z.string(),\n /** Actions to authorize */\n actions: z.array(z.string()),\n /** When this delegation expires (accepts Date or ISO string) */\n expiry: z.coerce.date().optional(),\n /** Whether to disable sub-delegation */\n disableSubDelegation: z.boolean().optional(),\n /** Optional statement for the SIWE message */\n statement: z.string().optional(),\n});\n\nexport type CreateDelegationParams = z.infer<typeof CreateDelegationParamsSchema>;\n\n/**\n * A chain of delegations from root to leaf (array format).\n */\nexport const DelegationChainSchema = z.array(DelegationSchema);\nexport type DelegationChain = z.infer<typeof DelegationChainSchema>;\n\n/**\n * Structured delegation chain (v2 spec).\n */\nexport const DelegationChainV2Schema = z.object({\n /** The root delegation from the original authority */\n root: DelegationSchema,\n /** Intermediate delegations in the chain (may be empty) */\n chain: z.array(DelegationSchema),\n /** The final delegation to the current user */\n leaf: DelegationSchema,\n});\n\nexport type DelegationChainV2 = z.infer<typeof DelegationChainV2Schema>;\n\n// =============================================================================\n// Filtering and Query Types\n// =============================================================================\n\n/**\n * Direction of delegation to filter by.\n */\nexport const DelegationDirectionSchema = z.enum([\"granted\", \"received\", \"all\"]);\nexport type DelegationDirection = z.infer<typeof DelegationDirectionSchema>;\n\n/**\n * Filters for listing delegations.\n */\nexport const DelegationFiltersSchema = z.object({\n /** Filter by delegation direction */\n direction: DelegationDirectionSchema.optional(),\n /** Filter by resource path pattern */\n path: z.string().optional(),\n /** Filter by required actions */\n actions: z.array(z.string()).optional(),\n /** Include revoked delegations */\n includeRevoked: z.boolean().optional(),\n /** Filter by delegator DID */\n delegator: z.string().optional(),\n /** Filter by delegatee DID */\n delegatee: z.string().optional(),\n /** Only include delegations valid at this time */\n validAt: z.coerce.date().optional(),\n /** Maximum number of results to return */\n limit: z.number().optional(),\n /** Cursor for pagination */\n cursor: z.string().optional(),\n});\n\nexport type DelegationFilters = z.infer<typeof DelegationFiltersSchema>;\n\n// =============================================================================\n// Space Types\n// =============================================================================\n\n/**\n * Type of space ownership.\n */\nexport const SpaceOwnershipSchema = z.enum([\"owned\", \"delegated\"]);\nexport type SpaceOwnership = z.infer<typeof SpaceOwnershipSchema>;\n\n/**\n * Information about a space the user has access to.\n */\nexport const SpaceInfoSchema = z.object({\n /** Space identifier */\n id: z.string(),\n /** Human-readable name for the space */\n name: z.string().optional(),\n /** DID of the space owner */\n owner: z.string(),\n /** Whether user owns or has delegated access */\n type: SpaceOwnershipSchema,\n /** Permissions the user has in this space */\n permissions: z.array(z.string()).optional(),\n /** When the access expires (for delegated spaces) */\n expiresAt: z.coerce.date().optional(),\n});\n\nexport type SpaceInfo = z.infer<typeof SpaceInfoSchema>;\n\n// =============================================================================\n// Share Link Types\n// =============================================================================\n\n/**\n * Schema for encoding share link data.\n */\nexport const ShareSchemaSchema = z.enum([\"base64\", \"compact\", \"ipfs\"]);\nexport type ShareSchema = z.infer<typeof ShareSchemaSchema>;\n\n/**\n * A shareable link containing delegation credentials.\n */\nexport const ShareLinkSchema = z.object({\n /** Unique token identifying this share link */\n token: z.string(),\n /** Full URL for sharing */\n url: z.string(),\n /** The delegation this link grants access to */\n delegation: DelegationSchema,\n /** Encoding schema used for the link */\n schema: ShareSchemaSchema,\n /** When this share link expires */\n expiresAt: z.coerce.date().optional(),\n /** Human-readable description of what is being shared */\n description: z.string().optional(),\n});\n\nexport type ShareLink = z.infer<typeof ShareLinkSchema>;\n\n/**\n * Data retrieved from a share link.\n */\nexport function createShareLinkDataSchema<T extends z.ZodTypeAny>(dataSchema: T) {\n return z.object({\n /** The retrieved data */\n data: dataSchema,\n /** The delegation that authorized this access */\n delegation: DelegationSchema,\n /** The space the data belongs to */\n spaceId: z.string(),\n /** The resource path that was accessed */\n path: z.string(),\n });\n}\n\nexport const ShareLinkDataSchema = createShareLinkDataSchema(z.unknown());\nexport type ShareLinkData<T = unknown> = {\n data: T;\n delegation: Delegation;\n spaceId: string;\n path: string;\n};\n\n// =============================================================================\n// Ingestion Types\n// =============================================================================\n\n/**\n * Options for ingesting an external delegation.\n */\nexport const IngestOptionsSchema = z.object({\n /** Whether to persist the delegation to storage */\n persist: z.boolean().optional(),\n /** Whether to validate the full delegation chain */\n validateChain: z.boolean().optional(),\n /** Name for the ingested key */\n keyName: z.string().optional(),\n /** Whether to create a session key for this delegation */\n createSessionKey: z.boolean().optional(),\n /** Override the priority for the ingested key */\n priority: z.number().optional(),\n});\n\nexport type IngestOptions = z.infer<typeof IngestOptionsSchema>;\n\n// =============================================================================\n// Parameter Types\n// =============================================================================\n\n/**\n * Parameters for generating a share link.\n */\nexport const GenerateShareParamsSchema = z.object({\n /** Resource path to share */\n path: z.string(),\n /** Actions to authorize */\n actions: z.array(z.string()).optional(),\n /** When the share link expires */\n expiry: z.coerce.date().optional(),\n /** Encoding schema for the link */\n schema: ShareSchemaSchema.optional(),\n /** Human-readable description */\n description: z.string().optional(),\n /** Base URL for the share link */\n baseUrl: z.string().optional(),\n /**\n * Whether the recipient may re-delegate the share. Default `true`.\n * `false` issues a terminal delegation: the node refuses onward `/delegate`.\n * Without a session-key delegation that covers the path, `false` fails with PERMISSION_DENIED.\n * Receive such a share with `receive(link, { autoSubdelegate: false })`; the default auto-subdelegation is refused for it.\n */\n allowSubDelegation: z.boolean().optional(),\n});\n\nexport type GenerateShareParams = z.infer<typeof GenerateShareParamsSchema>;\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n// Note: These types include functions and external types which cannot be fully validated at runtime.\n// We use z.unknown().refine() for runtime type checking while preserving TypeScript types.\n\n/**\n * Signs invocations with the session's own did:key and no proof. The node\n * accepts these for listing the delegations that key issued and for revoking\n * a delegation that key is the delegator of.\n */\nexport interface SessionInvocationSigner {\n /** The session key's bare did:key (no fragment). */\n did(): string;\n /**\n * Signs one short-lived invocation carrying exactly `attenuation` and no\n * proof; returns the `Authorization` header value.\n */\n sign(attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>): Promise<string>;\n}\n\n/**\n * Configuration for DelegationManager.\n * Note: ServiceSession, InvokeFunction, and FetchFunction are external types.\n */\nexport const DelegationManagerConfigSchema = z.object({\n /** TinyCloud host URLs */\n hosts: z.array(z.string()),\n /** Account space used by account-wide delegation history queries */\n accountSpaceId: z.string().min(1).optional(),\n /** Active session for authentication */\n session: z.unknown().refine(\n (val): val is ServiceSession => val !== null && typeof val === \"object\",\n { message: \"Expected a ServiceSession object\" }\n ),\n /** Platform-specific invoke function */\n invoke: z.unknown().refine(\n (val): val is InvokeFunction => typeof val === \"function\",\n { message: \"Expected an invoke function\" }\n ),\n /** Platform-specific invoke function for raw resource URIs */\n invokeAny: z.unknown().refine(\n (val): val is InvokeAnyFunction => val === undefined || typeof val === \"function\",\n { message: \"Expected an invokeAny function or undefined\" }\n ).optional(),\n /** Optional owner-signed authorization for direct CID revocation */\n signOwnerRevocation: z.custom<(cid: string) => Promise<string>>().optional(),\n /** Optional signer for proofless invocations by the session's own did:key (issued-delegation list and revoke) */\n sessionInvocationSigner: z.custom<SessionInvocationSigner>().optional(),\n /** Optional custom fetch implementation */\n fetch: z.unknown().refine(\n (val): val is FetchFunction => val === undefined || typeof val === \"function\",\n { message: \"Expected a fetch function or undefined\" }\n ).optional(),\n});\n\nexport type DelegationManagerConfig = z.infer<typeof DelegationManagerConfigSchema>;\n\n/**\n * Provider interface for cryptographic key operations.\n */\nexport const KeyProviderSchema = z.object({\n /** Generate a new session key, returns key ID */\n createSessionKey: z.unknown().refine(\n (val): val is (name: string) => Promise<string> => typeof val === \"function\",\n { message: \"Expected a function\" }\n ),\n /** Get JWK for a key */\n getJWK: z.unknown().refine(\n (val): val is (keyId: string) => object => typeof val === \"function\",\n { message: \"Expected a function\" }\n ),\n /** Get DID for a key */\n getDID: z.unknown().refine(\n (val): val is (keyId: string) => Promise<string> => typeof val === \"function\",\n { message: \"Expected a function\" }\n ),\n});\n\nexport type KeyProvider = z.infer<typeof KeyProviderSchema>;\n\n// =============================================================================\n// API Response Types\n// =============================================================================\n\n/**\n * Response from the delegation API.\n */\nexport const DelegationApiResponseSchema = z.object({\n /** SIWE message content */\n siwe: z.string(),\n /** Signature of the SIWE message */\n signature: z.string(),\n /** Delegation version */\n version: z.number(),\n /** CID of the created delegation */\n cid: z.string().optional(),\n});\n\nexport type DelegationApiResponse = z.infer<typeof DelegationApiResponseSchema>;\n\n// =============================================================================\n// WASM Delegation Types\n// =============================================================================\n\n/**\n * A single (service, space, path, actions) entry inside a\n * createDelegation WASM result.\n *\n * Mirrors the Rust `DelegatedResource` struct in\n * `tinycloud-sdk-wasm/src/session.rs`. Field names match the manifest\n * {@link PermissionEntry} shape so callers can reconstruct what they sent\n * without having to re-parse the UCAN.\n *\n * `service` is the short form (e.g. `\"kv\"`, `\"sql\"`) as returned by the\n * Rust layer. The SDK layer translates to the long form\n * (`\"tinycloud.kv\"`) when comparing against manifests.\n */\nexport const DelegatedResourceSchema = z.object({\n /** Short-form service name, e.g. \"kv\", \"sql\", \"duckdb\", \"capabilities\", \"hooks\". */\n service: z.string(),\n /** Full space id string, e.g. \"tinycloud:pkh:eip155:1:0x....:default\". */\n space: z.string(),\n /** Resource path; empty string when the resource URI had no path segment. */\n path: z.string(),\n /** Full-URN ability strings, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: z.array(z.string()),\n /** Exact ReCap caveats that constrain every action in this scope. */\n caveats: z.array(z.record(z.string(), z.unknown())).optional(),\n});\n\nexport type DelegatedResource = z.infer<typeof DelegatedResourceSchema>;\n\n/**\n * Input parameters for the createDelegation WASM function.\n *\n * A single call may encode multiple `(service, path, actions)` entries\n * via the `abilities` map — the underlying UCAN will contain one\n * attenuation entry per `(service, path)` pair, all signed by the same\n * session key in one blob.\n *\n * The `abilities` shape is identical to what `prepareSession` accepts\n * (`Record<shortService, Record<path, actionURNs[]>>`), so manifest\n * resolution can feed both sides from one data structure.\n */\nexport const CreateDelegationWasmParamsSchema = z.object({\n /** The session containing delegation credentials */\n session: z.unknown().refine(\n (val): val is ServiceSession => val !== null && typeof val === \"object\",\n { message: \"Expected a ServiceSession object\" }\n ),\n /** DID of the delegate */\n delegateDID: z.string(),\n /** Space ID this delegation applies to */\n spaceId: z.string(),\n /**\n * Multi-resource abilities map: short-service → path → full-URN actions.\n * Matches the shape accepted by `prepareSession`.\n *\n * Example:\n * ```\n * {\n * kv: {\n * \"com.listen.app/\": [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]\n * },\n * sql: {\n * \"com.listen.app/data.sqlite\": [\"tinycloud.sql/read\"]\n * }\n * }\n * ```\n */\n abilities: z.record(z.string(), z.record(z.string(), z.array(z.string()))),\n /** Expiration time in seconds since Unix epoch */\n expirationSecs: z.number(),\n /** Optional not-before time in seconds since Unix epoch */\n notBeforeSecs: z.number().optional(),\n /** Issue a terminal delegation: the node refuses onward delegation. Default `false`. */\n disableSubDelegation: z.boolean().optional(),\n});\n\nexport type CreateDelegationWasmParams = z.infer<typeof CreateDelegationWasmParamsSchema>;\n\n/**\n * Result from the createDelegation WASM function.\n *\n * A single UCAN may cover multiple resources. The `resources` array\n * describes every `(service, space, path, actions)` entry granted, in\n * deterministic (service, path) lexicographic order (the Rust side sorts\n * the HashMap entries before signing).\n */\nexport const CreateDelegationWasmResultSchema = z.object({\n /** Base64url-encoded UCAN delegation */\n delegation: z.string(),\n /** CID of the delegation */\n cid: z.string(),\n /** DID of the delegate */\n delegateDID: z.string(),\n /** Expiration time */\n expiry: z.coerce.date(),\n /**\n * All (service, space, path, actions) entries granted by this delegation.\n * Always non-empty on success.\n */\n resources: z.array(DelegatedResourceSchema),\n});\n\nexport type CreateDelegationWasmResult = z.infer<typeof CreateDelegationWasmResultSchema>;\n\n// =============================================================================\n// Validation Helpers\n// =============================================================================\n\n/**\n * Validates a Delegation object and returns a Result.\n */\nexport function validateDelegation(data: unknown): Result<Delegation, DelegationError> {\n const result = DelegationSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: DelegationErrorCodes.VALIDATION_ERROR,\n message: result.error.message,\n service: \"delegation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validates a CreateDelegationParams object and returns a Result.\n */\nexport function validateCreateDelegationParams(\n data: unknown\n): Result<CreateDelegationParams, DelegationError> {\n const result = CreateDelegationParamsSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: DelegationErrorCodes.VALIDATION_ERROR,\n message: result.error.message,\n service: \"delegation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validates a DelegationFilters object and returns a Result.\n */\nexport function validateDelegationFilters(\n data: unknown\n): Result<DelegationFilters, DelegationError> {\n const result = DelegationFiltersSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: DelegationErrorCodes.VALIDATION_ERROR,\n message: result.error.message,\n service: \"delegation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validates a ShareLink object and returns a Result.\n */\nexport function validateShareLink(data: unknown): Result<ShareLink, DelegationError> {\n const result = ShareLinkSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: DelegationErrorCodes.VALIDATION_ERROR,\n message: result.error.message,\n service: \"delegation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Generic validation function factory.\n */\nexport function createValidator<T>(\n schema: z.ZodType<T>\n): (data: unknown) => Result<T, DelegationError> {\n return (data: unknown): Result<T, DelegationError> => {\n const result = schema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: DelegationErrorCodes.VALIDATION_ERROR,\n message: result.error.message,\n service: \"delegation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n };\n}\n","/**\n * Helpers shared by DelegationManager and the lazily loaded issued-delegation\n * module. Kept free of other imports so neither bundle drags the other in.\n *\n * @packageDocumentation\n */\n\nimport type { DelegationError } from \"./types.schema\";\n\n/**\n * Delegation action constants.\n */\nexport const DelegationAction = {\n REVOKE: \"tinycloud.delegation/revoke\",\n STATUS: \"tinycloud.delegation/status\",\n LIST: \"tinycloud.delegation/list\",\n GET: \"tinycloud.delegation/get\",\n CHECK: \"tinycloud.delegation/check\",\n} as const;\n\n/**\n * Creates a DelegationError with the given parameters.\n */\nexport function createError(\n code: string,\n message: string,\n cause?: Error,\n meta?: Record<string, unknown>\n): DelegationError {\n return {\n code,\n message,\n service: \"delegation\",\n cause,\n meta,\n };\n}\n","/**\n * Issued-delegation listing and proofless revocation.\n *\n * DelegationManager loads this module with a dynamic `import()` the first time\n * `query({ direction: \"issued\" })`, `queryAllIssued` or `revokeIssued` runs, so\n * bundles that never list or revoke issued delegations do not carry it. It\n * must not import DelegationManager as a value.\n *\n * @packageDocumentation\n */\n\nimport type { FetchFunction, FetchResponse } from \"@tinycloud/sdk-services\";\nimport {\n DelegationErrorCodes,\n DelegationRevocationReceiptSchema,\n AccountDelegationPageSchema,\n} from \"./types.schema\";\nimport type {\n Result,\n DelegationError,\n DelegationRevocationReceipt,\n AccountDelegationPage,\n AccountDelegationQueryOptions,\n AccountDelegationRecord,\n SessionInvocationSigner,\n} from \"./types.schema\";\nimport { DelegationAction, createError } from \"./shared\";\n\n/** `GET /info` feature that marks a node able to answer `direction: \"issued\"` queries. */\nconst ISSUED_QUERY_FEATURE = \"delegation-issued-query-v1\";\n\n/** What the issued-delegation functions need from the DelegationManager that owns them. */\nexport interface IssuedContext {\n host: string;\n fetchFn: FetchFunction;\n sessionInvocationSigner?: SessionInvocationSigner;\n /** Set once the node's `/info` lists the issued-query feature; owned by the manager. */\n state: { issuedQuerySupported: boolean };\n}\n\n/** The node's plain-text refusal reason, without control characters and bounded in length. */\nasync function refusalText(response: FetchResponse): Promise<string> {\n const text = await response.text();\n return text.replace(/[\\u0000-\\u001f\\u007f]+/g, \" \").trim().slice(0, 200);\n}\n\n/**\n * Maps a non-2xx answer to an issued-delegation query or proofless revocation.\n * The node refuses with a plain-text 401 or 403, answers 400 for a cursor it will not\n * accept (the same answer for a malformed, foreign or other-filter cursor) and\n * 503 \"Delegation query unavailable\" for a chain it will not evaluate (deeper\n * than 64 levels or 4096 nodes; the whole page fails, no partial items).\n */\nasync function issuedHttpError(\n response: FetchResponse,\n what: string,\n meta: Record<string, unknown>,\n): Promise<DelegationError> {\n const text = await refusalText(response);\n const details = { ...meta, status: response.status };\n if (response.status === 401 || response.status === 403) {\n return createError(\n DelegationErrorCodes.PERMISSION_DENIED,\n text === \"\" ? \"The node refused the request\" : text,\n undefined,\n details,\n );\n }\n if (response.status === 400 && text.includes(\"invalid delegation query cursor\")) {\n return createError(\n DelegationErrorCodes.INVALID_CURSOR,\n \"The node rejected the page cursor; list again from the start\",\n undefined,\n details,\n );\n }\n if (response.status === 503) {\n return createError(\n DelegationErrorCodes.CHAIN_TOO_DEEP,\n \"This delegation chain is too long for the node to check right now; try again later\",\n undefined,\n { ...details, retryable: true },\n );\n }\n return createError(\n DelegationErrorCodes.NETWORK_ERROR,\n `${what}: ${response.status} - ${text}`,\n undefined,\n details,\n );\n}\n\n/**\n * Whether the node advertises `delegation-issued-query-v1` in `GET /info`.\n * A positive answer is remembered; an absent flag is read again next time.\n */\nasync function nodeListsIssued(ctx: IssuedContext): Promise<Result<boolean>> {\n if (ctx.state.issuedQuerySupported) return { ok: true, data: true };\n const response = await ctx.fetchFn(`${ctx.host}/info`);\n if (!response.ok) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.NETWORK_ERROR,\n `Couldn't read the node's info: ${response.status}`,\n undefined,\n { status: response.status },\n ),\n };\n }\n const info = (await response.json()) as { features?: unknown };\n ctx.state.issuedQuerySupported =\n Array.isArray(info.features) && info.features.includes(ISSUED_QUERY_FEATURE);\n return { ok: true, data: ctx.state.issuedQuerySupported };\n}\n\n/**\n * Lists the delegations this session's own key issued: one invocation signed\n * by that key with the single capability `tinycloud.delegation/list` on\n * `<key DID>/delegation` and no proof. Pages are ordered by delegation CID,\n * not by time, and may be short; only a missing `nextCursor` ends the list.\n */\nexport async function queryIssued(\n ctx: IssuedContext,\n options: AccountDelegationQueryOptions,\n): Promise<Result<AccountDelegationPage>> {\n const signer = ctx.sessionInvocationSigner;\n if (!signer) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.NOT_INITIALIZED,\n \"Listing issued delegations needs a session key signer\",\n ),\n };\n }\n try {\n const supported = await nodeListsIssued(ctx);\n if (!supported.ok) return supported;\n if (!supported.data) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.UNSUPPORTED_OPERATION,\n \"This node doesn't support listing issued delegations yet\",\n undefined,\n { feature: ISSUED_QUERY_FEATURE },\n ),\n };\n }\n const authorization = await signer.sign({\n [`${signer.did()}/delegation`]: { [DelegationAction.LIST]: [{}] },\n });\n const response = await ctx.fetchFn(`${ctx.host}/delegation/query`, {\n method: \"POST\",\n headers: { Authorization: authorization, \"content-type\": \"application/json\" },\n body: JSON.stringify(options),\n });\n if (!response.ok) {\n return {\n ok: false,\n error: await issuedHttpError(response, \"Failed to query issued delegations\", {}),\n };\n }\n const parsed = AccountDelegationPageSchema.safeParse(await response.json());\n if (!parsed.success) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.INVALID_TOKEN,\n \"Node returned an invalid delegation query response\",\n ),\n };\n }\n return { ok: true, data: parsed.data };\n } catch (error) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.NETWORK_ERROR,\n `Network error during delegation query: ${String(error)}`,\n error instanceof Error ? error : undefined,\n ),\n };\n }\n}\n\n/**\n * Every delegation this session's key issued, following `nextCursor` until\n * it is absent. `maxItems` stops early once that many are collected;\n * `untilCid` stops after the page that contains that delegation. Items come\n * in CID order (each carries `issuedAt`). `query` is the manager's public\n * `query`, so every page goes through its option validation.\n */\nexport async function queryAllIssued(\n query: (options: AccountDelegationQueryOptions) => Promise<Result<AccountDelegationPage>>,\n options: Pick<AccountDelegationQueryOptions, \"status\" | \"space\"> & {\n pageSize?: number;\n maxItems?: number;\n untilCid?: string;\n },\n): Promise<Result<AccountDelegationRecord[]>> {\n const { pageSize = 100, maxItems, untilCid, ...filters } = options;\n if (maxItems !== undefined && (!Number.isInteger(maxItems) || maxItems < 1)) {\n return {\n ok: false,\n error: createError(DelegationErrorCodes.INVALID_INPUT, \"maxItems must be a positive integer\"),\n };\n }\n const items: AccountDelegationRecord[] = [];\n const seen = new Set<string>();\n let cursor: string | undefined;\n do {\n const limit = Math.min(pageSize, maxItems === undefined ? pageSize : maxItems - items.length);\n const page = await query({\n ...filters,\n direction: \"issued\",\n limit,\n ...(cursor === undefined ? {} : { cursor }),\n });\n if (!page.ok) return page;\n items.push(...page.data.items);\n cursor = page.data.nextCursor;\n if (cursor !== undefined) {\n if (seen.has(cursor)) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.INVALID_TOKEN,\n \"The node returned the same page cursor twice while listing issued delegations\",\n ),\n };\n }\n seen.add(cursor);\n }\n } while (\n cursor !== undefined &&\n (maxItems === undefined || items.length < maxItems) &&\n !(untilCid !== undefined && items.some((item) => item.cid === untilCid))\n );\n return { ok: true, data: maxItems === undefined ? items : items.slice(0, maxItems) };\n}\n\n/**\n * Revokes a delegation this session's key issued, with no proof: a UCAN\n * signed by the session's own did:key carrying `urn:cid:<cid>` and\n * `tinycloud.delegation/revoke`. Revoking a delegation that is already revoked\n * succeeds. A refusal (the key is not the delegator) carries the node's\n * message; 503 means the chain is too deep right now, retry later.\n */\nexport async function revokeIssued(\n ctx: IssuedContext,\n cid: string,\n): Promise<Result<DelegationRevocationReceipt>> {\n if (!cid) {\n return {\n ok: false,\n error: createError(DelegationErrorCodes.INVALID_INPUT, \"cid is required\"),\n };\n }\n const signer = ctx.sessionInvocationSigner;\n if (!signer) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.NOT_INITIALIZED,\n \"Revoking an issued delegation needs a session key signer\",\n ),\n };\n }\n try {\n const authorization = await signer.sign({\n [`urn:cid:${cid}`]: { [DelegationAction.REVOKE]: [{}] },\n });\n const response = await ctx.fetchFn(`${ctx.host}/revoke`, {\n method: \"POST\",\n headers: { Authorization: authorization },\n });\n if (!response.ok) {\n if (response.status === 404) {\n return {\n ok: false,\n error: createError(DelegationErrorCodes.NOT_FOUND, `Delegation not found: ${cid}`),\n };\n }\n return {\n ok: false,\n error: await issuedHttpError(response, \"Failed to revoke delegation\", { cid }),\n };\n }\n const parsed = DelegationRevocationReceiptSchema.safeParse(await response.json());\n if (!parsed.success || parsed.data.cid !== cid) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.REVOCATION_FAILED,\n \"Node returned an invalid delegation revocation receipt\",\n undefined,\n { cid },\n ),\n };\n }\n return { ok: true, data: parsed.data };\n } catch (error) {\n return {\n ok: false,\n error: createError(\n DelegationErrorCodes.NETWORK_ERROR,\n `Network error during delegation revocation: ${String(error)}`,\n error instanceof Error ? error : undefined,\n ),\n };\n }\n}\n"],"mappings":";AASA,SAAS,SAAS;AAyCX,IAAM,YAAY,EAAE,OAAO;AAAA;AAAA,EAEhC,KAAK,EAAE,OAAO;AAAA;AAAA,EAEd,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEzB,GAAG,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEvB,GAAG,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEvB,GAAG,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEvB,GAAG,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEvB,GAAG,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEvB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEzB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEzB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEzB,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AACxC,CAAC;AAWM,IAAM,gBAAgB,EAAE,KAAK,CAAC,QAAQ,WAAW,UAAU,CAAC;AAM5D,IAAM,gBAAgB,EAAE,OAAO;AAAA;AAAA,EAEpC,IAAI,EAAE,OAAO;AAAA;AAAA,EAEb,KAAK,EAAE,OAAO;AAAA;AAAA,EAEd,MAAM;AAAA;AAAA,EAEN,KAAK,UAAU,SAAS;AAAA;AAAA,EAExB,UAAU,EAAE,OAAO;AACrB,CAAC;AAWM,IAAM,wBAAwB,EAAE,OAAO;AAAA;AAAA,EAE5C,MAAM,EAAE,O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689
|
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
6690
|
-
UNSUPPORTED_OPERATION: "UNSUPPORTED_OPERATION"
|
|
6690
|
+
UNSUPPORTED_OPERATION: "UNSUPPORTED_OPERATION",
|
|
6691
|
+
/** The node answered 503: the delegation chain is too deep to evaluate right now. Retry later. */
|
|
6692
|
+
CHAIN_TOO_DEEP: "CHAIN_TOO_DEEP",
|
|
6693
|
+
/** The node answered 400 "invalid delegation query cursor": malformed, foreign or from another filter. Start the listing again without it. */
|
|
6694
|
+
INVALID_CURSOR: "INVALID_CURSOR"
|
|
6691
6695
|
};
|
|
6692
6696
|
var DelegationSchema = import_zod4.z.object({
|
|
6693
6697
|
/** Content identifier (CID) of the delegation */
|
|
@@ -6764,7 +6768,7 @@ var AccountDelegationPageSchema = import_zod4.z.object({
|
|
|
6764
6768
|
nextCursor: import_zod4.z.string().optional()
|
|
6765
6769
|
}).strict();
|
|
6766
6770
|
var AccountDelegationQueryOptionsSchema = import_zod4.z.object({
|
|
6767
|
-
direction: import_zod4.z.enum(["granted", "received", "all"]).optional(),
|
|
6771
|
+
direction: import_zod4.z.enum(["granted", "received", "all", "issued"]).optional(),
|
|
6768
6772
|
status: import_zod4.z.enum(["active", "pending", "expired", "revoked", "ancestor_revoked"]).optional(),
|
|
6769
6773
|
space: import_zod4.z.string().trim().min(1).optional(),
|
|
6770
6774
|
limit: import_zod4.z.number().int().min(1).max(100).optional(),
|
|
@@ -6950,6 +6954,8 @@ var DelegationManagerConfigSchema = import_zod4.z.object({
|
|
|
6950
6954
|
).optional(),
|
|
6951
6955
|
/** Optional owner-signed authorization for direct CID revocation */
|
|
6952
6956
|
signOwnerRevocation: import_zod4.z.custom().optional(),
|
|
6957
|
+
/** Optional signer for proofless invocations by the session's own did:key (issued-delegation list and revoke) */
|
|
6958
|
+
sessionInvocationSigner: import_zod4.z.custom().optional(),
|
|
6953
6959
|
/** Optional custom fetch implementation */
|
|
6954
6960
|
fetch: import_zod4.z.unknown().refine(
|
|
6955
6961
|
(val) => val === void 0 || typeof val === "function",
|
|
@@ -7045,7 +7051,7 @@ var CreateDelegationWasmResultSchema = import_zod4.z.object({
|
|
|
7045
7051
|
resources: import_zod4.z.array(DelegatedResourceSchema)
|
|
7046
7052
|
});
|
|
7047
7053
|
|
|
7048
|
-
// src/delegations/
|
|
7054
|
+
// src/delegations/shared.ts
|
|
7049
7055
|
var DelegationAction = {
|
|
7050
7056
|
REVOKE: "tinycloud.delegation/revoke",
|
|
7051
7057
|
STATUS: "tinycloud.delegation/status",
|
|
@@ -7062,6 +7068,8 @@ function createError(code3, message, cause, meta) {
|
|
|
7062
7068
|
meta
|
|
7063
7069
|
};
|
|
7064
7070
|
}
|
|
7071
|
+
|
|
7072
|
+
// src/delegations/DelegationManager.ts
|
|
7065
7073
|
async function readInvokedJson(response, action) {
|
|
7066
7074
|
const text3 = await response.text();
|
|
7067
7075
|
if (text3.trim() === "") {
|
|
@@ -7084,11 +7092,13 @@ var DelegationManager = class {
|
|
|
7084
7092
|
* @param config - Configuration including hosts, session, and invoke function
|
|
7085
7093
|
*/
|
|
7086
7094
|
constructor(config) {
|
|
7095
|
+
this.issuedState = { issuedQuerySupported: false };
|
|
7087
7096
|
this.hosts = config.hosts;
|
|
7088
7097
|
this.session = config.session;
|
|
7089
7098
|
this.invoke = config.invoke;
|
|
7090
7099
|
this.invokeAny = config.invokeAny;
|
|
7091
7100
|
this.signOwnerRevocation = config.signOwnerRevocation;
|
|
7101
|
+
this.sessionInvocationSigner = config.sessionInvocationSigner;
|
|
7092
7102
|
this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
7093
7103
|
this.accountSpaceId = config.accountSpaceId;
|
|
7094
7104
|
}
|
|
@@ -7311,8 +7321,14 @@ var DelegationManager = class {
|
|
|
7311
7321
|
};
|
|
7312
7322
|
}
|
|
7313
7323
|
}
|
|
7314
|
-
/**
|
|
7315
|
-
|
|
7324
|
+
/**
|
|
7325
|
+
* Query lifecycle-complete delegation history for the authenticated account.
|
|
7326
|
+
*
|
|
7327
|
+
* `scope.spaces` lists the spaces to sign `tinycloud.delegation/list` for, in order. Omitted, the
|
|
7328
|
+
* account space is tried, then the session's own space. A caller that knows which of them the session
|
|
7329
|
+
* holds passes only those; an empty list sends nothing and answers PERMISSION_DENIED.
|
|
7330
|
+
*/
|
|
7331
|
+
async query(options2 = {}, scope = {}) {
|
|
7316
7332
|
const validated = AccountDelegationQueryOptionsSchema.safeParse(options2);
|
|
7317
7333
|
if (!validated.success) {
|
|
7318
7334
|
return {
|
|
@@ -7325,6 +7341,7 @@ var DelegationManager = class {
|
|
|
7325
7341
|
)
|
|
7326
7342
|
};
|
|
7327
7343
|
}
|
|
7344
|
+
if (validated.data.direction === "issued") return this.queryIssued(validated.data);
|
|
7328
7345
|
if (!this.invokeAny) {
|
|
7329
7346
|
return {
|
|
7330
7347
|
ok: false,
|
|
@@ -7346,7 +7363,7 @@ var DelegationManager = class {
|
|
|
7346
7363
|
}
|
|
7347
7364
|
try {
|
|
7348
7365
|
let response;
|
|
7349
|
-
for (const spaceId of
|
|
7366
|
+
for (const spaceId of new Set(scope.spaces ?? [accountSpaceId, this.session.spaceId])) {
|
|
7350
7367
|
const headers = Object.fromEntries(new Headers(this.invokeAny(this.session, [{
|
|
7351
7368
|
spaceId,
|
|
7352
7369
|
service: "delegation",
|
|
@@ -7406,6 +7423,45 @@ var DelegationManager = class {
|
|
|
7406
7423
|
};
|
|
7407
7424
|
}
|
|
7408
7425
|
}
|
|
7426
|
+
/** The state the lazily loaded issued-delegation module reads and updates. */
|
|
7427
|
+
issuedContext() {
|
|
7428
|
+
return {
|
|
7429
|
+
host: this.host,
|
|
7430
|
+
fetchFn: this.fetchFn,
|
|
7431
|
+
sessionInvocationSigner: this.sessionInvocationSigner,
|
|
7432
|
+
state: this.issuedState
|
|
7433
|
+
};
|
|
7434
|
+
}
|
|
7435
|
+
/**
|
|
7436
|
+
* Lists the delegations this session's own key issued (`direction: "issued"`).
|
|
7437
|
+
* The implementation loads on first use.
|
|
7438
|
+
*/
|
|
7439
|
+
async queryIssued(options2) {
|
|
7440
|
+
const issued = await import("@tinycloud/sdk-core/delegations/issued");
|
|
7441
|
+
return issued.queryIssued(this.issuedContext(), options2);
|
|
7442
|
+
}
|
|
7443
|
+
/**
|
|
7444
|
+
* Every delegation this session's key issued, following `nextCursor` until
|
|
7445
|
+
* it is absent. `maxItems` stops early once that many are collected;
|
|
7446
|
+
* `untilCid` stops after the page that contains that delegation. Items come
|
|
7447
|
+
* in CID order (each carries `issuedAt`). The implementation loads on first use.
|
|
7448
|
+
*/
|
|
7449
|
+
async queryAllIssued(options2 = {}) {
|
|
7450
|
+
const issued = await import("@tinycloud/sdk-core/delegations/issued");
|
|
7451
|
+
return issued.queryAllIssued((page) => this.query(page), options2);
|
|
7452
|
+
}
|
|
7453
|
+
/**
|
|
7454
|
+
* Revokes a delegation this session's key issued, with no proof: a UCAN
|
|
7455
|
+
* signed by the session's own did:key carrying `urn:cid:<cid>` and
|
|
7456
|
+
* `tinycloud.delegation/revoke`. Revoking a delegation that is already revoked
|
|
7457
|
+
* succeeds. A refusal (the key is not the delegator) carries the node's
|
|
7458
|
+
* message; 503 means the chain is too deep right now, retry later.
|
|
7459
|
+
* The implementation loads on first use.
|
|
7460
|
+
*/
|
|
7461
|
+
async revokeIssued(cid2) {
|
|
7462
|
+
const issued = await import("@tinycloud/sdk-core/delegations/issued");
|
|
7463
|
+
return issued.revokeIssued(this.issuedContext(), cid2);
|
|
7464
|
+
}
|
|
7409
7465
|
/**
|
|
7410
7466
|
* Gets the full delegation chain for a given delegation.
|
|
7411
7467
|
*
|
|
@@ -7835,6 +7891,14 @@ function expandEncryptionPermissionEntry(entry) {
|
|
|
7835
7891
|
`tinycloud.encryption entries require path to be a networkId URN (got ${JSON.stringify(entry.path)})`
|
|
7836
7892
|
);
|
|
7837
7893
|
}
|
|
7894
|
+
if (entry.path.includes("/")) {
|
|
7895
|
+
throw new ManifestValidationError("named keys go in manifest.keys");
|
|
7896
|
+
}
|
|
7897
|
+
try {
|
|
7898
|
+
(0, import_sdk_services2.parseNetworkId)(entry.path);
|
|
7899
|
+
} catch {
|
|
7900
|
+
throw new ManifestValidationError("tinycloud.encryption entries require a valid networkId URN");
|
|
7901
|
+
}
|
|
7838
7902
|
const normalizedActions = [];
|
|
7839
7903
|
for (const action of entry.actions) {
|
|
7840
7904
|
if (action === "decrypt" || action === "tinycloud.encryption/decrypt") {
|
|
@@ -7959,8 +8023,56 @@ function validateManifest(input) {
|
|
|
7959
8023
|
if (m.secrets !== void 0) {
|
|
7960
8024
|
validateManifestSecrets(m.secrets);
|
|
7961
8025
|
}
|
|
8026
|
+
if (Object.prototype.hasOwnProperty.call(m, "keys_app_id") && (typeof m.keys_app_id !== "string" || !KEY_APP_ID.test(m.keys_app_id))) {
|
|
8027
|
+
throw new ManifestValidationError("manifest.keys_app_id is invalid");
|
|
8028
|
+
}
|
|
8029
|
+
validateManifestKeys(m.keys_app_id ?? m.app_id, m.keys);
|
|
7962
8030
|
return m;
|
|
7963
8031
|
}
|
|
8032
|
+
var KEY_SEGMENT = "[a-z0-9][a-z0-9._-]{0,63}";
|
|
8033
|
+
var KEY_APP_ID = new RegExp(`^${KEY_SEGMENT}$`);
|
|
8034
|
+
var KEY_PATH = new RegExp(`^${KEY_SEGMENT}(?:/${KEY_SEGMENT}){2,7}$`);
|
|
8035
|
+
var KEY_ABILITIES = ["key.create", "decrypt", "key.block", "key.unblock"];
|
|
8036
|
+
function validateManifestKeys(appId, keys) {
|
|
8037
|
+
if (keys === void 0) return;
|
|
8038
|
+
if (!Array.isArray(keys) || keys.length > 32) {
|
|
8039
|
+
throw new ManifestValidationError("manifest.keys must contain at most 32 entries");
|
|
8040
|
+
}
|
|
8041
|
+
if (keys.length === 0) return;
|
|
8042
|
+
if (!KEY_APP_ID.test(appId)) {
|
|
8043
|
+
throw new ManifestValidationError("manifest.keys requires a valid app_id");
|
|
8044
|
+
}
|
|
8045
|
+
const paths = /* @__PURE__ */ new Set();
|
|
8046
|
+
let prefixSeen = false;
|
|
8047
|
+
for (const [index, value] of keys.entries()) {
|
|
8048
|
+
const label = `manifest.keys[${index}]`;
|
|
8049
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
8050
|
+
throw new ManifestValidationError(`${label} must be an object`);
|
|
8051
|
+
}
|
|
8052
|
+
const entry = value;
|
|
8053
|
+
const fields = Object.keys(entry);
|
|
8054
|
+
const hasPath = Object.prototype.hasOwnProperty.call(entry, "path");
|
|
8055
|
+
const hasPrefix = Object.prototype.hasOwnProperty.call(entry, "prefix");
|
|
8056
|
+
if (hasPath === hasPrefix || fields.some((field) => !["path", "prefix", "abilities"].includes(field))) {
|
|
8057
|
+
throw new ManifestValidationError(`${label} must have one path or prefix and abilities`);
|
|
8058
|
+
}
|
|
8059
|
+
if (!Array.isArray(entry.abilities) || entry.abilities.length === 0 || new Set(entry.abilities).size !== entry.abilities.length || entry.abilities.some((ability) => typeof ability !== "string" || !KEY_ABILITIES.includes(ability))) {
|
|
8060
|
+
throw new ManifestValidationError(`${label}.abilities is invalid`);
|
|
8061
|
+
}
|
|
8062
|
+
if (hasPath) {
|
|
8063
|
+
const path = entry.path;
|
|
8064
|
+
if (typeof path !== "string" || path.length > 255 || !KEY_PATH.test(path) || !path.startsWith(`apps/${appId}/`) || paths.has(path)) {
|
|
8065
|
+
throw new ManifestValidationError(`${label}.path is invalid`);
|
|
8066
|
+
}
|
|
8067
|
+
paths.add(path);
|
|
8068
|
+
} else {
|
|
8069
|
+
if (entry.prefix !== `apps/${appId}/` || prefixSeen) {
|
|
8070
|
+
throw new ManifestValidationError(`${label}.prefix is invalid`);
|
|
8071
|
+
}
|
|
8072
|
+
prefixSeen = true;
|
|
8073
|
+
}
|
|
8074
|
+
}
|
|
8075
|
+
}
|
|
7964
8076
|
function resolveManifestKnowledgeRoot(knowledge) {
|
|
7965
8077
|
if (knowledge === void 0) {
|
|
7966
8078
|
return void 0;
|