@tinycloud/sdk-core 2.4.0-beta.2 → 2.4.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -970,6 +970,7 @@ var SpaceService = class {
970
970
  this._userDid = config.userDid;
971
971
  this.sharingService = config.sharingService;
972
972
  this.createDelegationFn = config.createDelegation;
973
+ this.onSpaceRegisteredFn = config.onSpaceRegistered;
973
974
  }
974
975
  /**
975
976
  * Update the service configuration.
@@ -985,6 +986,7 @@ var SpaceService = class {
985
986
  if (config.userDid !== void 0) this._userDid = config.userDid;
986
987
  if (config.sharingService) this.sharingService = config.sharingService;
987
988
  if (config.createDelegation) this.createDelegationFn = config.createDelegation;
989
+ if (config.onSpaceRegistered) this.onSpaceRegisteredFn = config.onSpaceRegistered;
988
990
  this.spaceCache.clear();
989
991
  this.infoCache.clear();
990
992
  }
@@ -1035,6 +1037,9 @@ var SpaceService = class {
1035
1037
  spaces.push(...delegatedSpaces);
1036
1038
  }
1037
1039
  const uniqueSpaces = this.deduplicateSpaces(spaces);
1040
+ for (const space of uniqueSpaces) {
1041
+ this.notifySpaceRegistered(space);
1042
+ }
1038
1043
  return ok(uniqueSpaces);
1039
1044
  } catch (error) {
1040
1045
  return err(
@@ -1232,6 +1237,7 @@ var SpaceService = class {
1232
1237
  permissions: ["*"]
1233
1238
  };
1234
1239
  this.infoCache.set(spaceInfo.id, { info: spaceInfo, cachedAt: Date.now() });
1240
+ this.notifySpaceRegistered(spaceInfo);
1235
1241
  return ok(spaceInfo);
1236
1242
  } catch (error) {
1237
1243
  return err(
@@ -1244,6 +1250,11 @@ var SpaceService = class {
1244
1250
  );
1245
1251
  }
1246
1252
  }
1253
+ notifySpaceRegistered(space) {
1254
+ if (!this.onSpaceRegisteredFn) return;
1255
+ void Promise.resolve(this.onSpaceRegisteredFn(space)).catch(() => {
1256
+ });
1257
+ }
1247
1258
  // ===========================================================================
1248
1259
  // Get Space
1249
1260
  // ===========================================================================
@@ -2151,1474 +2162,2156 @@ var TinyCloud = class _TinyCloud {
2151
2162
  }
2152
2163
  };
2153
2164
 
2154
- // src/index.ts
2165
+ // src/account/AccountService.ts
2155
2166
  import {
2156
- ServiceContext as ServiceContext2,
2157
- KVService as KVService2,
2158
- PrefixedKVService,
2159
- ok as ok4,
2160
- err as err4,
2161
- serviceError as serviceError4,
2162
- ErrorCodes as ErrorCodes2,
2163
- defaultRetryPolicy as defaultRetryPolicy2,
2164
- SQLService as SQLService2,
2165
- DatabaseHandle,
2166
- SQLAction,
2167
- DuckDbService as DuckDbService2,
2168
- DuckDbDatabaseHandle,
2169
- DuckDbAction,
2170
- HooksService as HooksService2,
2171
- DataVaultService,
2172
- VaultHeaders,
2173
- VaultPublicSpaceKVActions,
2174
- createVaultCrypto,
2175
- SecretsService,
2176
- SECRET_NAME_RE as SECRET_NAME_RE2,
2177
- canonicalizeSecretScope,
2178
- resolveSecretListPrefix,
2179
- resolveSecretPath as resolveSecretPath2,
2180
- EncryptionService,
2181
- parseNetworkId as parseNetworkId2,
2182
- buildNetworkId as buildNetworkId2,
2183
- isNetworkId,
2184
- networkDiscoveryKey,
2185
- NetworkIdError,
2186
- ENCRYPTION_NETWORK_URN_PREFIX,
2187
- NETWORK_NAME_PATTERN,
2188
- canonicalizeEncryptionJson,
2189
- canonicalHashHex,
2190
- hexEncode,
2191
- hexDecode,
2192
- base64Encode,
2193
- base64Decode,
2194
- utf8Encode,
2195
- utf8Decode,
2196
- encryptToNetwork,
2197
- decryptEnvelopeWithKey,
2198
- validateEnvelope,
2199
- generateRandomReceiverKey,
2200
- deriveSignedReceiverKey,
2201
- buildCanonicalDecryptRequest,
2202
- buildDecryptFacts,
2203
- buildDecryptAttenuation,
2204
- buildDecryptInvocation,
2205
- checkDecryptInvocationInput,
2206
- verifyDecryptResponse,
2207
- canonicalSignedResponse,
2208
- openWrappedKey,
2209
- discoverNetwork,
2210
- ensureNetworkUsableForDecrypt,
2211
- DEFAULT_ENCRYPTION_ALG,
2212
- ENVELOPE_VERSION,
2213
- DEFAULT_KEY_VERSION,
2214
- DECRYPT_FACT_TYPE,
2215
- DECRYPT_RESULT_TYPE,
2216
- DECRYPT_ACTION,
2217
- ENCRYPTION_SERVICE,
2218
- ENCRYPTION_SERVICE_SHORT,
2219
- encryptionError
2167
+ err as err3,
2168
+ ok as ok3,
2169
+ serviceError as serviceError3
2220
2170
  } from "@tinycloud/sdk-services";
2221
2171
 
2222
- // src/space.ts
2223
- async function fetchPeerId(host, spaceId) {
2224
- const res = await fetch(
2225
- `${host}/peer/generate/${encodeURIComponent(spaceId)}`
2226
- );
2227
- if (!res.ok) {
2228
- const error = await res.text().catch(() => res.statusText);
2229
- throw new Error(`Failed to get peer ID: ${res.status} - ${error}`);
2172
+ // src/manifest.ts
2173
+ import ms from "ms";
2174
+ import { resolveSecretPath, SECRET_NAME_RE } from "@tinycloud/sdk-services";
2175
+ var ManifestValidationError = class extends Error {
2176
+ constructor(message) {
2177
+ super(`Manifest validation failed: ${message}`);
2178
+ this.name = "ManifestValidationError";
2230
2179
  }
2231
- return res.text();
2180
+ };
2181
+ var DEFAULT_EXPIRY = "30d";
2182
+ var DEFAULT_DEFAULTS = true;
2183
+ var DEFAULT_MANIFEST_VERSION = 1;
2184
+ var DEFAULT_MANIFEST_SPACE = "applications";
2185
+ var ACCOUNT_REGISTRY_SPACE = "account";
2186
+ var ACCOUNT_REGISTRY_PATH = "applications/";
2187
+ var SECRETS_SPACE = "secrets";
2188
+ var VAULT_PERMISSION_SERVICE = "tinycloud.vault";
2189
+ var SERVICE_SHORT_TO_LONG = Object.freeze({
2190
+ kv: "tinycloud.kv",
2191
+ sql: "tinycloud.sql",
2192
+ duckdb: "tinycloud.duckdb",
2193
+ capabilities: "tinycloud.capabilities",
2194
+ hooks: "tinycloud.hooks",
2195
+ encryption: "tinycloud.encryption"
2196
+ });
2197
+ var ENCRYPTION_PERMISSION_SERVICE = "tinycloud.encryption";
2198
+ var ENCRYPTION_MANIFEST_SPACE = "encryption";
2199
+ var SERVICE_LONG_TO_SHORT = Object.freeze(
2200
+ Object.fromEntries(
2201
+ Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s])
2202
+ )
2203
+ );
2204
+ var DEFAULT_STANDARD_ENTRIES = [
2205
+ {
2206
+ service: "tinycloud.kv",
2207
+ space: DEFAULT_MANIFEST_SPACE,
2208
+ path: "/",
2209
+ actions: ["get", "put", "del", "list", "metadata"]
2210
+ },
2211
+ {
2212
+ service: "tinycloud.sql",
2213
+ space: DEFAULT_MANIFEST_SPACE,
2214
+ path: "/",
2215
+ actions: ["read", "write"]
2216
+ }
2217
+ ];
2218
+ var DEFAULT_ADMIN_ENTRIES = [
2219
+ {
2220
+ service: "tinycloud.kv",
2221
+ space: DEFAULT_MANIFEST_SPACE,
2222
+ path: "/",
2223
+ actions: ["get", "put", "del", "list", "metadata"]
2224
+ },
2225
+ {
2226
+ service: "tinycloud.sql",
2227
+ space: DEFAULT_MANIFEST_SPACE,
2228
+ path: "/",
2229
+ actions: ["read", "write", "ddl"]
2230
+ }
2231
+ ];
2232
+ var DEFAULT_ALL_ENTRIES = [
2233
+ {
2234
+ service: "tinycloud.kv",
2235
+ space: DEFAULT_MANIFEST_SPACE,
2236
+ path: "/",
2237
+ actions: ["get", "put", "del", "list", "metadata"]
2238
+ },
2239
+ {
2240
+ service: "tinycloud.sql",
2241
+ space: DEFAULT_MANIFEST_SPACE,
2242
+ path: "/",
2243
+ actions: ["read", "write", "ddl"]
2244
+ },
2245
+ {
2246
+ service: "tinycloud.duckdb",
2247
+ space: DEFAULT_MANIFEST_SPACE,
2248
+ path: "/",
2249
+ actions: ["read", "write"]
2250
+ }
2251
+ ];
2252
+ function parseExpiry(duration) {
2253
+ if (typeof duration !== "string" || duration.length === 0) {
2254
+ throw new ManifestValidationError(
2255
+ `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`
2256
+ );
2257
+ }
2258
+ const parsed = ms(duration);
2259
+ if (typeof parsed !== "number" || !Number.isFinite(parsed) || parsed <= 0) {
2260
+ throw new ManifestValidationError(
2261
+ `invalid expiry duration: ${JSON.stringify(duration)}`
2262
+ );
2263
+ }
2264
+ return parsed;
2232
2265
  }
2233
- async function submitHostDelegation(host, headers) {
2234
- const res = await fetch(`${host}/delegate`, {
2235
- method: "POST",
2236
- headers
2266
+ function expandActionShortNames(service, actions) {
2267
+ return actions.map((a) => {
2268
+ if (a.includes("/")) {
2269
+ return a;
2270
+ }
2271
+ return `${service}/${a}`;
2237
2272
  });
2238
- return {
2239
- success: res.ok,
2240
- status: res.status,
2241
- error: res.ok ? void 0 : await res.text().catch(() => res.statusText)
2242
- };
2243
2273
  }
2244
- async function activateSessionWithHost(host, delegationHeader) {
2245
- const res = await fetch(`${host}/delegate`, {
2246
- method: "POST",
2247
- headers: delegationHeader
2248
- });
2249
- if (res.ok) {
2250
- try {
2251
- const body = await res.json();
2252
- return {
2253
- success: true,
2254
- status: res.status,
2255
- activated: body.activated ?? [],
2256
- skipped: body.skipped ?? []
2257
- };
2258
- } catch {
2259
- return {
2260
- success: true,
2261
- status: res.status,
2262
- activated: [],
2263
- skipped: []
2264
- };
2265
- }
2274
+ function expandPermissionEntry(entry) {
2275
+ if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {
2276
+ return expandEncryptionPermissionEntry(entry);
2266
2277
  }
2267
- return {
2268
- success: false,
2269
- status: res.status,
2270
- error: await res.text().catch(() => res.statusText)
2271
- };
2272
- }
2273
-
2274
- // src/delegations/DelegationManager.ts
2275
- var DelegationAction = {
2276
- CREATE: "tinycloud.delegation/create",
2277
- REVOKE: "tinycloud.delegation/revoke",
2278
- LIST: "tinycloud.delegation/list",
2279
- GET: "tinycloud.delegation/get",
2280
- CHECK: "tinycloud.delegation/check"
2281
- };
2282
- function createError(code, message, cause, meta) {
2283
- return {
2284
- code,
2285
- message,
2286
- service: "delegation",
2287
- cause,
2288
- meta
2289
- };
2278
+ if (entry.service !== VAULT_PERMISSION_SERVICE) {
2279
+ return [
2280
+ {
2281
+ ...entry,
2282
+ actions: expandActionShortNames(entry.service, entry.actions)
2283
+ }
2284
+ ];
2285
+ }
2286
+ return expandVaultPermissionEntry(entry);
2290
2287
  }
2291
- var DelegationManager = class {
2292
- /**
2293
- * Creates a new DelegationManager instance.
2294
- *
2295
- * @param config - Configuration including hosts, session, and invoke function
2296
- */
2297
- constructor(config) {
2298
- this.hosts = config.hosts;
2299
- this.session = config.session;
2300
- this.invoke = config.invoke;
2301
- this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
2288
+ function expandEncryptionPermissionEntry(entry) {
2289
+ if (typeof entry.path !== "string" || !entry.path.startsWith("urn:tinycloud:encryption:")) {
2290
+ throw new ManifestValidationError(
2291
+ `tinycloud.encryption entries require path to be a networkId URN (got ${JSON.stringify(entry.path)})`
2292
+ );
2302
2293
  }
2303
- /**
2304
- * Updates the session (e.g., after re-authentication).
2305
- *
2306
- * @param session - New session to use for operations
2307
- */
2308
- updateSession(session) {
2309
- this.session = session;
2310
- }
2311
- /**
2312
- * Gets the primary host URL.
2313
- */
2314
- get host() {
2315
- return this.hosts[0];
2316
- }
2317
- /**
2318
- * Executes an invoke operation against the delegation API.
2319
- */
2320
- async invokeOperation(path, action, body) {
2321
- const headers = this.invoke(this.session, "delegation", path, action);
2322
- return this.fetchFn(`${this.host}/invoke`, {
2323
- method: "POST",
2324
- headers,
2325
- body
2326
- });
2327
- }
2328
- /**
2329
- * Creates a new delegation.
2330
- *
2331
- * Delegates specific permissions to another DID for a given path.
2332
- * The delegatee can then use these permissions to access resources
2333
- * within the specified scope.
2334
- *
2335
- * @param params - Parameters for the delegation
2336
- * @returns Result containing the created Delegation or an error
2337
- *
2338
- * @example
2339
- * ```typescript
2340
- * const result = await manager.create({
2341
- * delegateDID: bob.did,
2342
- * path: "documents/shared/",
2343
- * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
2344
- * expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
2345
- * });
2346
- * ```
2347
- */
2348
- async create(params) {
2349
- if (!params.delegateDID) {
2350
- return {
2351
- ok: false,
2352
- error: createError(
2353
- DelegationErrorCodes.INVALID_INPUT,
2354
- "delegateDID is required"
2355
- )
2356
- };
2294
+ const normalizedActions = [];
2295
+ for (const action of entry.actions) {
2296
+ if (action === "decrypt" || action === "tinycloud.encryption/decrypt") {
2297
+ normalizedActions.push("tinycloud.encryption/decrypt");
2298
+ continue;
2357
2299
  }
2358
- if (!params.path) {
2359
- return {
2360
- ok: false,
2361
- error: createError(
2362
- DelegationErrorCodes.INVALID_INPUT,
2363
- "path is required"
2364
- )
2365
- };
2300
+ if (action === "network.create" || action === "tinycloud.encryption/network.create") {
2301
+ normalizedActions.push("tinycloud.encryption/network.create");
2302
+ continue;
2366
2303
  }
2367
- if (!params.actions || params.actions.length === 0) {
2368
- return {
2369
- ok: false,
2370
- error: createError(
2371
- DelegationErrorCodes.INVALID_INPUT,
2372
- "at least one action is required"
2373
- )
2374
- };
2304
+ if (action === "network.revoke" || action === "tinycloud.encryption/network.revoke") {
2305
+ normalizedActions.push("tinycloud.encryption/network.revoke");
2306
+ continue;
2375
2307
  }
2376
- try {
2377
- const body = JSON.stringify({
2378
- delegateDID: params.delegateDID,
2379
- path: params.path,
2380
- actions: params.actions,
2381
- expiry: params.expiry?.toISOString(),
2382
- disableSubDelegation: params.disableSubDelegation ?? false,
2383
- statement: params.statement
2384
- });
2385
- const response = await this.invokeOperation(
2386
- params.path,
2387
- DelegationAction.CREATE,
2388
- body
2308
+ if (action.includes("/")) {
2309
+ throw new ManifestValidationError(
2310
+ `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`
2389
2311
  );
2390
- if (!response.ok) {
2391
- const errorText = await response.text();
2392
- return {
2393
- ok: false,
2394
- error: createError(
2395
- DelegationErrorCodes.CREATION_FAILED,
2396
- `Failed to create delegation: ${response.status} - ${errorText}`,
2397
- void 0,
2398
- { status: response.status, path: params.path }
2399
- )
2400
- };
2401
- }
2402
- const apiResponse = await response.json();
2403
- const delegation = {
2404
- cid: apiResponse.cid ?? "",
2405
- delegateDID: params.delegateDID,
2406
- spaceId: this.session.spaceId,
2407
- path: params.path,
2408
- actions: params.actions,
2409
- expiry: params.expiry ?? new Date(Date.now() + EXPIRY.SHARE_MS),
2410
- isRevoked: false,
2411
- allowSubDelegation: !(params.disableSubDelegation ?? false),
2412
- createdAt: /* @__PURE__ */ new Date()
2413
- };
2414
- return { ok: true, data: delegation };
2415
- } catch (error) {
2416
- if (error instanceof Error && error.name === "AbortError") {
2417
- return {
2418
- ok: false,
2419
- error: createError(
2420
- DelegationErrorCodes.ABORTED,
2421
- "Request aborted",
2422
- error
2423
- )
2424
- };
2425
- }
2426
- return {
2427
- ok: false,
2428
- error: createError(
2429
- DelegationErrorCodes.NETWORK_ERROR,
2430
- `Network error during delegation creation: ${String(error)}`,
2431
- error instanceof Error ? error : void 0
2432
- )
2433
- };
2434
2312
  }
2313
+ throw new ManifestValidationError(
2314
+ `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`
2315
+ );
2435
2316
  }
2436
- /**
2437
- * Revokes an existing delegation.
2438
- *
2439
- * Once revoked, the delegation can no longer be used to access resources.
2440
- * This also invalidates any sub-delegations derived from this delegation.
2441
- *
2442
- * @param cid - The CID of the delegation to revoke
2443
- * @returns Result indicating success or an error
2444
- *
2445
- * @example
2446
- * ```typescript
2447
- * const result = await manager.revoke("bafy...");
2448
- * if (result.ok) {
2449
- * console.log("Delegation revoked successfully");
2450
- * }
2451
- * ```
2452
- */
2453
- async revoke(cid) {
2454
- if (!cid) {
2455
- return {
2456
- ok: false,
2457
- error: createError(
2458
- DelegationErrorCodes.INVALID_INPUT,
2459
- "cid is required"
2460
- )
2461
- };
2317
+ const dedupedActions = [];
2318
+ const seen = /* @__PURE__ */ new Set();
2319
+ for (const a of normalizedActions) {
2320
+ if (!seen.has(a)) {
2321
+ dedupedActions.push(a);
2322
+ seen.add(a);
2462
2323
  }
2463
- try {
2464
- const body = JSON.stringify({ cid });
2465
- const response = await this.invokeOperation(
2466
- cid,
2467
- DelegationAction.REVOKE,
2468
- body
2469
- );
2470
- if (!response.ok) {
2471
- const errorText = await response.text();
2472
- if (response.status === 404) {
2473
- return {
2474
- ok: false,
2475
- error: createError(
2476
- DelegationErrorCodes.NOT_FOUND,
2477
- `Delegation not found: ${cid}`
2478
- )
2479
- };
2480
- }
2481
- return {
2482
- ok: false,
2483
- error: createError(
2484
- DelegationErrorCodes.REVOCATION_FAILED,
2485
- `Failed to revoke delegation: ${response.status} - ${errorText}`,
2486
- void 0,
2487
- { status: response.status, cid }
2488
- )
2489
- };
2490
- }
2491
- return { ok: true, data: void 0 };
2492
- } catch (error) {
2493
- if (error instanceof Error && error.name === "AbortError") {
2494
- return {
2495
- ok: false,
2496
- error: createError(
2497
- DelegationErrorCodes.ABORTED,
2498
- "Request aborted",
2499
- error
2500
- )
2501
- };
2502
- }
2503
- return {
2504
- ok: false,
2505
- error: createError(
2506
- DelegationErrorCodes.NETWORK_ERROR,
2507
- `Network error during delegation revocation: ${String(error)}`,
2508
- error instanceof Error ? error : void 0
2509
- )
2510
- };
2324
+ }
2325
+ return [
2326
+ {
2327
+ service: ENCRYPTION_PERMISSION_SERVICE,
2328
+ space: ENCRYPTION_MANIFEST_SPACE,
2329
+ path: entry.path,
2330
+ actions: dedupedActions,
2331
+ skipPrefix: true,
2332
+ ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {},
2333
+ ...entry.description !== void 0 ? { description: entry.description } : {}
2511
2334
  }
2335
+ ];
2336
+ }
2337
+ function expandPermissionEntries(entries) {
2338
+ return entries.flatMap(expandPermissionEntry);
2339
+ }
2340
+ function applyPrefix(prefix, path, skipPrefix) {
2341
+ if (skipPrefix) {
2342
+ return path;
2512
2343
  }
2513
- /**
2514
- * Lists all delegations for the current session's space.
2515
- *
2516
- * Returns both delegations created by the current user (as delegator)
2517
- * and delegations granted to the current user (as delegatee).
2518
- *
2519
- * @returns Result containing an array of Delegations or an error
2520
- *
2521
- * @example
2522
- * ```typescript
2523
- * const result = await manager.list();
2524
- * if (result.ok) {
2525
- * for (const delegation of result.data) {
2526
- * console.log(`${delegation.cid}: ${delegation.path} -> ${delegation.delegateDID}`);
2527
- * }
2528
- * }
2529
- * ```
2530
- */
2531
- async list() {
2532
- try {
2533
- const response = await this.invokeOperation("", DelegationAction.LIST);
2534
- if (!response.ok) {
2535
- const errorText = await response.text();
2536
- return {
2537
- ok: false,
2538
- error: createError(
2539
- DelegationErrorCodes.NETWORK_ERROR,
2540
- `Failed to list delegations: ${response.status} - ${errorText}`,
2541
- void 0,
2542
- { status: response.status }
2543
- )
2544
- };
2545
- }
2546
- const data = await response.json();
2547
- const delegations = data.map((item) => ({
2548
- cid: item.cid,
2549
- delegateDID: item.delegateDID,
2550
- delegatorDID: item.delegatorDID,
2551
- spaceId: item.spaceId,
2552
- path: item.path,
2553
- actions: item.actions,
2554
- expiry: new Date(item.expiry),
2555
- isRevoked: item.isRevoked,
2556
- createdAt: item.createdAt ? new Date(item.createdAt) : void 0,
2557
- parentCid: item.parentCid,
2558
- allowSubDelegation: item.allowSubDelegation
2559
- }));
2560
- return { ok: true, data: delegations };
2561
- } catch (error) {
2562
- if (error instanceof Error && error.name === "AbortError") {
2563
- return {
2564
- ok: false,
2565
- error: createError(
2566
- DelegationErrorCodes.ABORTED,
2567
- "Request aborted",
2568
- error
2569
- )
2570
- };
2571
- }
2572
- return {
2573
- ok: false,
2574
- error: createError(
2575
- DelegationErrorCodes.NETWORK_ERROR,
2576
- `Network error during delegation list: ${String(error)}`,
2577
- error instanceof Error ? error : void 0
2578
- )
2579
- };
2344
+ if (prefix === "") {
2345
+ return path;
2346
+ }
2347
+ if (path.startsWith("/")) {
2348
+ return `${prefix}${path}`;
2349
+ }
2350
+ return `${prefix}/${path}`;
2351
+ }
2352
+ async function loadManifest(url) {
2353
+ const fetchFn = globalThis.fetch;
2354
+ if (typeof fetchFn !== "function") {
2355
+ throw new ManifestValidationError(
2356
+ "loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch"
2357
+ );
2358
+ }
2359
+ const res = await fetchFn(url);
2360
+ if (!res.ok) {
2361
+ throw new ManifestValidationError(
2362
+ `failed to fetch manifest from ${url}: HTTP ${res.status}`
2363
+ );
2364
+ }
2365
+ const json = await res.json();
2366
+ return validateManifest(json);
2367
+ }
2368
+ function validateManifest(input) {
2369
+ if (input === null || typeof input !== "object") {
2370
+ throw new ManifestValidationError("manifest must be an object");
2371
+ }
2372
+ const m = input;
2373
+ if (m.manifest_version !== void 0 && m.manifest_version !== DEFAULT_MANIFEST_VERSION) {
2374
+ throw new ManifestValidationError(
2375
+ `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`
2376
+ );
2377
+ }
2378
+ if (typeof m.app_id !== "string" || m.app_id.length === 0) {
2379
+ throw new ManifestValidationError(
2380
+ "manifest.app_id is required and must be a non-empty string"
2381
+ );
2382
+ }
2383
+ if (typeof m.name !== "string" || m.name.length === 0) {
2384
+ throw new ManifestValidationError(
2385
+ "manifest.name is required and must be a non-empty string"
2386
+ );
2387
+ }
2388
+ if (m.did !== void 0 && (typeof m.did !== "string" || m.did.length === 0)) {
2389
+ throw new ManifestValidationError(
2390
+ "manifest.did must be a non-empty DID string"
2391
+ );
2392
+ }
2393
+ if (m.space !== void 0 && (typeof m.space !== "string" || m.space.length === 0)) {
2394
+ throw new ManifestValidationError(
2395
+ "manifest.space must be a non-empty string"
2396
+ );
2397
+ }
2398
+ if (m.expiry !== void 0) {
2399
+ parseExpiry(m.expiry);
2400
+ }
2401
+ if (m.permissions !== void 0) {
2402
+ if (!Array.isArray(m.permissions)) {
2403
+ throw new ManifestValidationError(
2404
+ "manifest.permissions must be an array"
2405
+ );
2580
2406
  }
2407
+ m.permissions.forEach(
2408
+ (p, i) => validatePermissionEntry(p, `permissions[${i}]`)
2409
+ );
2581
2410
  }
2582
- /**
2583
- * Gets the full delegation chain for a given delegation.
2584
- *
2585
- * Returns the chain of delegations from the root (original delegator)
2586
- * to the specified delegation, including all intermediate sub-delegations.
2587
- *
2588
- * @param cid - The CID of the delegation to get the chain for
2589
- * @returns Result containing the DelegationChain or an error
2590
- *
2591
- * @example
2592
- * ```typescript
2593
- * const result = await manager.getChain("bafy...");
2594
- * if (result.ok) {
2595
- * console.log("Chain length:", result.data.length);
2596
- * for (const delegation of result.data) {
2597
- * console.log(`- ${delegation.delegatorDID} -> ${delegation.delegateDID}`);
2598
- * }
2599
- * }
2600
- * ```
2601
- */
2602
- async getChain(cid) {
2603
- if (!cid) {
2604
- return {
2605
- ok: false,
2606
- error: createError(
2607
- DelegationErrorCodes.INVALID_INPUT,
2608
- "cid is required"
2609
- )
2610
- };
2411
+ if (m.secrets !== void 0) {
2412
+ validateManifestSecrets(m.secrets);
2413
+ }
2414
+ return m;
2415
+ }
2416
+ function validateManifestSecrets(secrets) {
2417
+ if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
2418
+ throw new ManifestValidationError("manifest.secrets must be an object");
2419
+ }
2420
+ for (const [name, spec] of Object.entries(secrets)) {
2421
+ if (!SECRET_NAME_RE.test(name)) {
2422
+ throw new ManifestValidationError(
2423
+ `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`
2424
+ );
2611
2425
  }
2612
2426
  try {
2613
- const body = JSON.stringify({ cid, includeChain: true });
2614
- const response = await this.invokeOperation(
2615
- cid,
2616
- DelegationAction.GET,
2617
- body
2427
+ resolveSecretPath(
2428
+ secretNameFromSpec(name, spec),
2429
+ { scope: secretScopeFromSpec(spec) }
2618
2430
  );
2619
- if (!response.ok) {
2620
- const errorText = await response.text();
2621
- if (response.status === 404) {
2622
- return {
2623
- ok: false,
2624
- error: createError(
2625
- DelegationErrorCodes.NOT_FOUND,
2626
- `Delegation not found: ${cid}`
2627
- )
2628
- };
2629
- }
2630
- return {
2631
- ok: false,
2632
- error: createError(
2633
- DelegationErrorCodes.NETWORK_ERROR,
2634
- `Failed to get delegation chain: ${response.status} - ${errorText}`,
2635
- void 0,
2636
- { status: response.status, cid }
2637
- )
2638
- };
2639
- }
2640
- const data = await response.json();
2641
- const chain = data.chain.map((item) => ({
2642
- cid: item.cid,
2643
- delegateDID: item.delegateDID,
2644
- delegatorDID: item.delegatorDID,
2645
- spaceId: item.spaceId,
2646
- path: item.path,
2647
- actions: item.actions,
2648
- expiry: new Date(item.expiry),
2649
- isRevoked: item.isRevoked,
2650
- createdAt: item.createdAt ? new Date(item.createdAt) : void 0,
2651
- parentCid: item.parentCid,
2652
- allowSubDelegation: item.allowSubDelegation
2653
- }));
2654
- return { ok: true, data: chain };
2655
2431
  } catch (error) {
2656
- if (error instanceof Error && error.name === "AbortError") {
2657
- return {
2658
- ok: false,
2659
- error: createError(
2660
- DelegationErrorCodes.ABORTED,
2661
- "Request aborted",
2662
- error
2663
- )
2664
- };
2432
+ throw new ManifestValidationError(
2433
+ `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`
2434
+ );
2435
+ }
2436
+ const actions = secretActionsFromSpec(name, spec);
2437
+ if (actions.length === 0) {
2438
+ throw new ManifestValidationError(
2439
+ `manifest.secrets.${name} actions must be non-empty`
2440
+ );
2441
+ }
2442
+ for (const action of actions) {
2443
+ if (typeof action !== "string" || action.length === 0) {
2444
+ throw new ManifestValidationError(
2445
+ `manifest.secrets.${name} actions must be non-empty strings`
2446
+ );
2665
2447
  }
2666
- return {
2667
- ok: false,
2668
- error: createError(
2669
- DelegationErrorCodes.NETWORK_ERROR,
2670
- `Network error during chain retrieval: ${String(error)}`,
2671
- error instanceof Error ? error : void 0
2672
- )
2673
- };
2448
+ }
2449
+ if (spec !== null && typeof spec === "object" && !Array.isArray(spec) && spec.expiry !== void 0) {
2450
+ parseExpiry(spec.expiry);
2674
2451
  }
2675
2452
  }
2676
- /**
2677
- * Checks if the current session has permission for a given path and action.
2678
- *
2679
- * This can be used to verify permissions before attempting an operation,
2680
- * or to implement custom access control logic.
2681
- *
2682
- * @param path - The resource path to check
2683
- * @param action - The action to check (e.g., "tinycloud.kv/get")
2684
- * @returns Result containing a boolean indicating permission or an error
2685
- *
2686
- * @example
2687
- * ```typescript
2688
- * const result = await manager.checkPermission("documents/private/", "tinycloud.kv/put");
2689
- * if (result.ok && result.data) {
2690
- * console.log("Permission granted");
2691
- * } else {
2692
- * console.log("Permission denied");
2693
- * }
2694
- * ```
2695
- */
2696
- async checkPermission(path, action) {
2697
- if (!path) {
2698
- return {
2699
- ok: false,
2700
- error: createError(
2701
- DelegationErrorCodes.INVALID_INPUT,
2702
- "path is required"
2703
- )
2704
- };
2705
- }
2706
- if (!action) {
2707
- return {
2708
- ok: false,
2709
- error: createError(
2710
- DelegationErrorCodes.INVALID_INPUT,
2711
- "action is required"
2712
- )
2713
- };
2714
- }
2715
- try {
2716
- const body = JSON.stringify({ path, action });
2717
- const response = await this.invokeOperation(
2718
- path,
2719
- DelegationAction.CHECK,
2720
- body
2721
- );
2722
- if (!response.ok) {
2723
- if (response.status === 403) {
2724
- return { ok: true, data: false };
2725
- }
2726
- const errorText = await response.text();
2727
- return {
2728
- ok: false,
2729
- error: createError(
2730
- DelegationErrorCodes.NETWORK_ERROR,
2731
- `Failed to check permission: ${response.status} - ${errorText}`,
2732
- void 0,
2733
- { status: response.status, path, action }
2734
- )
2735
- };
2736
- }
2737
- const data = await response.json();
2738
- return { ok: true, data: data.allowed };
2739
- } catch (error) {
2740
- if (error instanceof Error && error.name === "AbortError") {
2741
- return {
2742
- ok: false,
2743
- error: createError(
2744
- DelegationErrorCodes.ABORTED,
2745
- "Request aborted",
2746
- error
2747
- )
2748
- };
2749
- }
2750
- return {
2751
- ok: false,
2752
- error: createError(
2753
- DelegationErrorCodes.NETWORK_ERROR,
2754
- `Network error during permission check: ${String(error)}`,
2755
- error instanceof Error ? error : void 0
2756
- )
2757
- };
2758
- }
2759
- }
2760
- };
2761
-
2762
- // src/delegations/SharingService.schema.ts
2763
- import { z as z5 } from "zod";
2764
- var EncodedShareDataSchema = z5.object({
2765
- /** Private key in JWK format (must include d parameter) */
2766
- key: JWKSchema.refine(
2767
- (jwk) => typeof jwk.d === "string" && jwk.d.length > 0,
2768
- { message: "JWK must include private key (d parameter)" }
2769
- ),
2770
- /** DID of the key */
2771
- keyDid: z5.string().min(1, "keyDid is required"),
2772
- /** The delegation granting access */
2773
- delegation: DelegationSchema,
2774
- /** Resource path this link grants access to */
2775
- path: z5.string().min(1, "path is required"),
2776
- /** TinyCloud host URL */
2777
- host: z5.string().url("host must be a valid URL"),
2778
- /** Space ID */
2779
- spaceId: z5.string().min(1, "spaceId is required"),
2780
- /** Schema version (must be 1) */
2781
- version: z5.literal(1)
2782
- });
2783
- var ReceiveOptionsSchema = z5.object({
2784
- /**
2785
- * Whether to automatically create a sub-delegation to the current session key.
2786
- * Default: true
2787
- */
2788
- autoSubdelegate: z5.boolean().optional(),
2789
- /**
2790
- * Whether to use the current session key for operations (requires autoSubdelegate).
2791
- * Default: true
2792
- */
2793
- useSessionKey: z5.boolean().optional(),
2794
- /**
2795
- * Ingestion options passed to CapabilityKeyRegistry.
2796
- */
2797
- ingestOptions: IngestOptionsSchema.optional()
2798
- });
2799
- var SharingServiceConfigSchema = z5.object({
2800
- /** TinyCloud host URLs */
2801
- hosts: z5.array(z5.string().url()).min(1, "At least one host URL is required"),
2802
- /**
2803
- * Active session for authentication.
2804
- * Required for generate(), optional for receive().
2805
- */
2806
- session: z5.unknown().refine(
2807
- (val) => val === void 0 || val !== null && typeof val === "object",
2808
- { message: "Expected a ServiceSession object or undefined" }
2809
- ).optional(),
2810
- /** Platform-specific invoke function */
2811
- invoke: z5.unknown().refine((val) => typeof val === "function", {
2812
- message: "Expected an invoke function"
2813
- }),
2814
- /** Optional custom fetch implementation */
2815
- fetch: z5.unknown().refine(
2816
- (val) => val === void 0 || typeof val === "function",
2817
- { message: "Expected a fetch function or undefined" }
2818
- ).optional(),
2819
- /** Key provider for cryptographic operations */
2820
- keyProvider: KeyProviderSchema,
2821
- /** Capability key registry for key/delegation management */
2822
- registry: z5.unknown().refine(
2823
- (val) => val !== null && typeof val === "object",
2824
- { message: "Expected an ICapabilityKeyRegistry object" }
2825
- ),
2826
- /**
2827
- * Delegation manager for creating delegations.
2828
- * Required for generate(), optional for receive().
2829
- */
2830
- delegationManager: z5.unknown().refine(
2831
- (val) => val === void 0 || val !== null && typeof val === "object",
2832
- { message: "Expected a DelegationManager object or undefined" }
2833
- ).optional(),
2834
- /** Factory for creating KV service instances */
2835
- createKVService: z5.unknown().refine(
2836
- (val) => typeof val === "function",
2837
- { message: "Expected a createKVService factory function" }
2838
- ),
2839
- /** Base URL for sharing links (e.g., "https://share.myapp.com") */
2840
- baseUrl: z5.string().optional(),
2841
- /**
2842
- * Custom delegation creation function.
2843
- */
2844
- createDelegation: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
2845
- message: "Expected a createDelegation function or undefined"
2846
- }).optional(),
2847
- /**
2848
- * WASM function for client-side delegation creation.
2849
- */
2850
- createDelegationWasm: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
2851
- message: "Expected a createDelegationWasm function or undefined"
2852
- }).optional(),
2853
- /**
2854
- * Path prefix for KV operations.
2855
- */
2856
- pathPrefix: z5.string().optional(),
2857
- /**
2858
- * Session expiry time.
2859
- */
2860
- sessionExpiry: z5.date().optional(),
2861
- /**
2862
- * Callback to create a DIRECT delegation from wallet to share key.
2863
- * This is the preferred method for long-lived share links because it
2864
- * bypasses the session delegation chain entirely.
2865
- */
2866
- onRootDelegationNeeded: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
2867
- message: "Expected an onRootDelegationNeeded function or undefined"
2868
- }).optional()
2869
- });
2870
- function validateEncodedShareData(data) {
2871
- const result = EncodedShareDataSchema.safeParse(data);
2872
- if (!result.success) {
2873
- return {
2874
- ok: false,
2875
- error: {
2876
- code: DelegationErrorCodes.VALIDATION_ERROR,
2877
- message: `Invalid share data: ${result.error.message}`,
2878
- service: "delegation",
2879
- meta: { issues: result.error.issues }
2880
- }
2881
- };
2882
- }
2883
- return { ok: true, data: result.data };
2884
2453
  }
2885
-
2886
- // src/manifest.ts
2887
- import ms from "ms";
2888
- import { resolveSecretPath, SECRET_NAME_RE } from "@tinycloud/sdk-services";
2889
- var ManifestValidationError = class extends Error {
2890
- constructor(message) {
2891
- super(`Manifest validation failed: ${message}`);
2892
- this.name = "ManifestValidationError";
2893
- }
2894
- };
2895
- var DEFAULT_EXPIRY = "30d";
2896
- var DEFAULT_DEFAULTS = true;
2897
- var DEFAULT_MANIFEST_VERSION = 1;
2898
- var DEFAULT_MANIFEST_SPACE = "applications";
2899
- var ACCOUNT_REGISTRY_SPACE = "account";
2900
- var ACCOUNT_REGISTRY_PATH = "applications/";
2901
- var SECRETS_SPACE = "secrets";
2902
- var VAULT_PERMISSION_SERVICE = "tinycloud.vault";
2903
- var SERVICE_SHORT_TO_LONG = Object.freeze({
2904
- kv: "tinycloud.kv",
2905
- sql: "tinycloud.sql",
2906
- duckdb: "tinycloud.duckdb",
2907
- capabilities: "tinycloud.capabilities",
2908
- hooks: "tinycloud.hooks",
2909
- encryption: "tinycloud.encryption"
2910
- });
2911
- var ENCRYPTION_PERMISSION_SERVICE = "tinycloud.encryption";
2912
- var ENCRYPTION_MANIFEST_SPACE = "encryption";
2913
- var SERVICE_LONG_TO_SHORT = Object.freeze(
2914
- Object.fromEntries(
2915
- Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s])
2916
- )
2917
- );
2918
- var DEFAULT_STANDARD_ENTRIES = [
2919
- {
2920
- service: "tinycloud.kv",
2921
- space: DEFAULT_MANIFEST_SPACE,
2922
- path: "/",
2923
- actions: ["get", "put", "del", "list", "metadata"]
2924
- },
2925
- {
2926
- service: "tinycloud.sql",
2927
- space: DEFAULT_MANIFEST_SPACE,
2928
- path: "/",
2929
- actions: ["read", "write"]
2930
- }
2931
- ];
2932
- var DEFAULT_ADMIN_ENTRIES = [
2933
- {
2934
- service: "tinycloud.kv",
2935
- space: DEFAULT_MANIFEST_SPACE,
2936
- path: "/",
2937
- actions: ["get", "put", "del", "list", "metadata"]
2938
- },
2939
- {
2940
- service: "tinycloud.sql",
2941
- space: DEFAULT_MANIFEST_SPACE,
2942
- path: "/",
2943
- actions: ["read", "write", "ddl"]
2454
+ function validatePermissionEntry(p, path) {
2455
+ if (p === null || typeof p !== "object") {
2456
+ throw new ManifestValidationError(`${path} must be an object`);
2944
2457
  }
2945
- ];
2946
- var DEFAULT_ALL_ENTRIES = [
2947
- {
2948
- service: "tinycloud.kv",
2949
- space: DEFAULT_MANIFEST_SPACE,
2950
- path: "/",
2951
- actions: ["get", "put", "del", "list", "metadata"]
2952
- },
2953
- {
2954
- service: "tinycloud.sql",
2955
- space: DEFAULT_MANIFEST_SPACE,
2956
- path: "/",
2957
- actions: ["read", "write", "ddl"]
2958
- },
2959
- {
2960
- service: "tinycloud.duckdb",
2961
- space: DEFAULT_MANIFEST_SPACE,
2962
- path: "/",
2963
- actions: ["read", "write"]
2458
+ const entry = p;
2459
+ if (typeof entry.service !== "string" || entry.service.length === 0) {
2460
+ throw new ManifestValidationError(`${path}.service is required`);
2964
2461
  }
2965
- ];
2966
- function parseExpiry(duration) {
2967
- if (typeof duration !== "string" || duration.length === 0) {
2462
+ if (entry.space !== void 0 && (typeof entry.space !== "string" || entry.space.length === 0)) {
2968
2463
  throw new ManifestValidationError(
2969
- `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`
2464
+ `${path}.space must be a non-empty string`
2970
2465
  );
2971
2466
  }
2972
- const parsed = ms(duration);
2973
- if (typeof parsed !== "number" || !Number.isFinite(parsed) || parsed <= 0) {
2467
+ if (typeof entry.path !== "string") {
2974
2468
  throw new ManifestValidationError(
2975
- `invalid expiry duration: ${JSON.stringify(duration)}`
2469
+ `${path}.path is required (use "" or "/" for root)`
2976
2470
  );
2977
2471
  }
2978
- return parsed;
2979
- }
2980
- function expandActionShortNames(service, actions) {
2981
- return actions.map((a) => {
2982
- if (a.includes("/")) {
2983
- return a;
2984
- }
2985
- return `${service}/${a}`;
2986
- });
2987
- }
2988
- function expandPermissionEntry(entry) {
2989
- if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {
2990
- return expandEncryptionPermissionEntry(entry);
2991
- }
2992
- if (entry.service !== VAULT_PERMISSION_SERVICE) {
2993
- return [
2994
- {
2995
- ...entry,
2996
- actions: expandActionShortNames(entry.service, entry.actions)
2997
- }
2998
- ];
2999
- }
3000
- return expandVaultPermissionEntry(entry);
3001
- }
3002
- function expandEncryptionPermissionEntry(entry) {
3003
- if (typeof entry.path !== "string" || !entry.path.startsWith("urn:tinycloud:encryption:")) {
2472
+ if (!Array.isArray(entry.actions) || entry.actions.length === 0) {
3004
2473
  throw new ManifestValidationError(
3005
- `tinycloud.encryption entries require path to be a networkId URN (got ${JSON.stringify(entry.path)})`
2474
+ `${path}.actions must be a non-empty array`
3006
2475
  );
3007
2476
  }
3008
- const normalizedActions = [];
3009
2477
  for (const action of entry.actions) {
3010
- if (action === "decrypt" || action === "tinycloud.encryption/decrypt") {
3011
- normalizedActions.push("tinycloud.encryption/decrypt");
3012
- continue;
3013
- }
3014
- if (action === "network.create" || action === "tinycloud.encryption/network.create") {
3015
- normalizedActions.push("tinycloud.encryption/network.create");
3016
- continue;
3017
- }
3018
- if (action === "network.revoke" || action === "tinycloud.encryption/network.revoke") {
3019
- normalizedActions.push("tinycloud.encryption/network.revoke");
3020
- continue;
3021
- }
3022
- if (action.includes("/")) {
2478
+ if (typeof action !== "string" || action.length === 0) {
3023
2479
  throw new ManifestValidationError(
3024
- `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`
2480
+ `${path}.actions must contain non-empty strings`
3025
2481
  );
3026
2482
  }
3027
- throw new ManifestValidationError(
3028
- `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`
3029
- );
3030
- }
3031
- const dedupedActions = [];
3032
- const seen = /* @__PURE__ */ new Set();
3033
- for (const a of normalizedActions) {
3034
- if (!seen.has(a)) {
3035
- dedupedActions.push(a);
3036
- seen.add(a);
2483
+ if (entry.service === VAULT_PERMISSION_SERVICE) {
2484
+ vaultActionExpansion(action);
3037
2485
  }
3038
2486
  }
3039
- return [
3040
- {
3041
- service: ENCRYPTION_PERMISSION_SERVICE,
3042
- space: ENCRYPTION_MANIFEST_SPACE,
3043
- path: entry.path,
3044
- actions: dedupedActions,
3045
- skipPrefix: true,
3046
- ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {},
3047
- ...entry.description !== void 0 ? { description: entry.description } : {}
3048
- }
3049
- ];
3050
- }
3051
- function expandPermissionEntries(entries) {
3052
- return entries.flatMap(expandPermissionEntry);
3053
- }
3054
- function applyPrefix(prefix, path, skipPrefix) {
3055
- if (skipPrefix) {
3056
- return path;
2487
+ if (entry.expiry !== void 0) {
2488
+ parseExpiry(entry.expiry);
3057
2489
  }
3058
- if (prefix === "") {
3059
- return path;
2490
+ }
2491
+ function normalizeDefaults(value) {
2492
+ if (value === void 0) {
2493
+ return DEFAULT_DEFAULTS;
3060
2494
  }
3061
- if (path.startsWith("/")) {
3062
- return `${prefix}${path}`;
2495
+ if (typeof value === "boolean") {
2496
+ return value;
3063
2497
  }
3064
- return `${prefix}/${path}`;
3065
- }
3066
- async function loadManifest(url) {
3067
- const fetchFn = globalThis.fetch;
3068
- if (typeof fetchFn !== "function") {
3069
- throw new ManifestValidationError(
3070
- "loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch"
3071
- );
2498
+ if (typeof value !== "string") {
2499
+ return true;
3072
2500
  }
3073
- const res = await fetchFn(url);
3074
- if (!res.ok) {
3075
- throw new ManifestValidationError(
3076
- `failed to fetch manifest from ${url}: HTTP ${res.status}`
3077
- );
2501
+ const normalized = value.trim().toLowerCase();
2502
+ if (normalized === "admin" || normalized === "all") {
2503
+ return normalized;
3078
2504
  }
3079
- const json = await res.json();
3080
- return validateManifest(json);
2505
+ return true;
3081
2506
  }
3082
- function validateManifest(input) {
3083
- if (input === null || typeof input !== "object") {
3084
- throw new ManifestValidationError("manifest must be an object");
2507
+ function defaultEntriesForTier(tier) {
2508
+ if (tier === false) {
2509
+ return [];
3085
2510
  }
3086
- const m = input;
3087
- if (m.manifest_version !== void 0 && m.manifest_version !== DEFAULT_MANIFEST_VERSION) {
2511
+ const source = tier === "admin" ? DEFAULT_ADMIN_ENTRIES : tier === "all" ? DEFAULT_ALL_ENTRIES : DEFAULT_STANDARD_ENTRIES;
2512
+ return source.map((e) => ({
2513
+ service: e.service,
2514
+ space: e.space,
2515
+ path: e.path,
2516
+ actions: [...e.actions],
2517
+ ...e.skipPrefix !== void 0 ? { skipPrefix: e.skipPrefix } : {}
2518
+ }));
2519
+ }
2520
+ function resolveManifest(input) {
2521
+ const manifest = validateManifest(input);
2522
+ const prefix = manifest.prefix !== void 0 ? manifest.prefix : manifest.app_id;
2523
+ const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;
2524
+ const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);
2525
+ const includePublicSpace = manifest.includePublicSpace ?? true;
2526
+ const tier = normalizeDefaults(manifest.defaults);
2527
+ const defaultEntries = defaultEntriesForTier(tier);
2528
+ const explicitEntries = manifest.permissions ?? [];
2529
+ const secretEntries = secretEntriesForManifest(manifest.secrets);
2530
+ const allEntries = [
2531
+ ...defaultEntries,
2532
+ ...explicitEntries,
2533
+ ...secretEntries
2534
+ ];
2535
+ const resources = withCapabilitiesReadForSpaces(
2536
+ allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space))
2537
+ );
2538
+ const additionalDelegates = manifest.did === void 0 ? [] : [
2539
+ {
2540
+ did: manifest.did,
2541
+ name: manifest.name,
2542
+ expiryMs,
2543
+ permissions: resources.map(cloneResourceCapability)
2544
+ }
2545
+ ];
2546
+ return {
2547
+ app_id: manifest.app_id,
2548
+ ...manifest.did !== void 0 ? { did: manifest.did } : {},
2549
+ space,
2550
+ resources,
2551
+ expiryMs,
2552
+ includePublicSpace,
2553
+ additionalDelegates
2554
+ };
2555
+ }
2556
+ function normalizeSecretActions(actions) {
2557
+ const out = [];
2558
+ const seen = /* @__PURE__ */ new Set();
2559
+ const add = (action) => {
2560
+ if (!seen.has(action)) {
2561
+ out.push(action);
2562
+ seen.add(action);
2563
+ }
2564
+ };
2565
+ for (const action of actions) {
2566
+ if (action === "read") {
2567
+ add("get");
2568
+ continue;
2569
+ }
2570
+ if (action === "write") {
2571
+ add("put");
2572
+ continue;
2573
+ }
2574
+ if (action === "delete") {
2575
+ add("del");
2576
+ continue;
2577
+ }
2578
+ if (action === "get" || action === "put" || action === "del" || action === "list" || action === "metadata") {
2579
+ add(action);
2580
+ continue;
2581
+ }
2582
+ if (action === "tinycloud.kv/get" || action === "tinycloud.kv/put" || action === "tinycloud.kv/del" || action === "tinycloud.kv/list" || action === "tinycloud.kv/metadata") {
2583
+ add(action);
2584
+ continue;
2585
+ }
3088
2586
  throw new ManifestValidationError(
3089
- `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`
2587
+ `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`
3090
2588
  );
3091
2589
  }
3092
- if (typeof m.app_id !== "string" || m.app_id.length === 0) {
3093
- throw new ManifestValidationError(
3094
- "manifest.app_id is required and must be a non-empty string"
3095
- );
2590
+ return out;
2591
+ }
2592
+ function secretNameFromSpec(fallbackName, spec) {
2593
+ if (spec !== null && typeof spec === "object" && !Array.isArray(spec)) {
2594
+ return spec.name ?? fallbackName;
3096
2595
  }
3097
- if (typeof m.name !== "string" || m.name.length === 0) {
3098
- throw new ManifestValidationError(
3099
- "manifest.name is required and must be a non-empty string"
3100
- );
2596
+ return fallbackName;
2597
+ }
2598
+ function secretScopeFromSpec(spec) {
2599
+ if (spec !== null && typeof spec === "object" && !Array.isArray(spec)) {
2600
+ return spec.scope;
3101
2601
  }
3102
- if (m.did !== void 0 && (typeof m.did !== "string" || m.did.length === 0)) {
3103
- throw new ManifestValidationError(
3104
- "manifest.did must be a non-empty DID string"
3105
- );
2602
+ return void 0;
2603
+ }
2604
+ function secretActionsFromSpec(name, spec) {
2605
+ if (spec === true) {
2606
+ return ["read"];
3106
2607
  }
3107
- if (m.space !== void 0 && (typeof m.space !== "string" || m.space.length === 0)) {
2608
+ if (typeof spec === "string") {
2609
+ return [spec];
2610
+ }
2611
+ if (Array.isArray(spec)) {
2612
+ return spec;
2613
+ }
2614
+ if (spec === null || typeof spec !== "object") {
3108
2615
  throw new ManifestValidationError(
3109
- "manifest.space must be a non-empty string"
2616
+ `manifest.secrets.${name} must be true, a string action, an actions array, or an object`
3110
2617
  );
3111
2618
  }
3112
- if (m.expiry !== void 0) {
3113
- parseExpiry(m.expiry);
2619
+ if (spec.actions === void 0) {
2620
+ return ["read"];
3114
2621
  }
3115
- if (m.permissions !== void 0) {
3116
- if (!Array.isArray(m.permissions)) {
3117
- throw new ManifestValidationError(
3118
- "manifest.permissions must be an array"
3119
- );
3120
- }
3121
- m.permissions.forEach(
3122
- (p, i) => validatePermissionEntry(p, `permissions[${i}]`)
3123
- );
2622
+ if (typeof spec.actions === "string") {
2623
+ return [spec.actions];
3124
2624
  }
3125
- if (m.secrets !== void 0) {
3126
- validateManifestSecrets(m.secrets);
2625
+ if (Array.isArray(spec.actions)) {
2626
+ return spec.actions;
3127
2627
  }
3128
- return m;
2628
+ throw new ManifestValidationError(
2629
+ `manifest.secrets.${name}.actions must be a string or array`
2630
+ );
3129
2631
  }
3130
- function validateManifestSecrets(secrets) {
3131
- if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
3132
- throw new ManifestValidationError("manifest.secrets must be an object");
2632
+ function secretEntriesForManifest(secrets) {
2633
+ if (secrets === void 0) {
2634
+ return [];
3133
2635
  }
2636
+ const entries = [];
3134
2637
  for (const [name, spec] of Object.entries(secrets)) {
3135
- if (!SECRET_NAME_RE.test(name)) {
3136
- throw new ManifestValidationError(
3137
- `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`
3138
- );
3139
- }
3140
- try {
3141
- resolveSecretPath(
3142
- secretNameFromSpec(name, spec),
3143
- { scope: secretScopeFromSpec(spec) }
3144
- );
3145
- } catch (error) {
3146
- throw new ManifestValidationError(
3147
- `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`
3148
- );
3149
- }
3150
2638
  const actions = secretActionsFromSpec(name, spec);
3151
- if (actions.length === 0) {
3152
- throw new ManifestValidationError(
3153
- `manifest.secrets.${name} actions must be non-empty`
3154
- );
3155
- }
3156
- for (const action of actions) {
3157
- if (typeof action !== "string" || action.length === 0) {
3158
- throw new ManifestValidationError(
3159
- `manifest.secrets.${name} actions must be non-empty strings`
3160
- );
2639
+ const secretPath = resolveSecretPath(
2640
+ secretNameFromSpec(name, spec),
2641
+ { scope: secretScopeFromSpec(spec) }
2642
+ );
2643
+ const extra = spec !== true && typeof spec === "object" && !Array.isArray(spec) ? spec : {};
2644
+ entries.push({
2645
+ service: VAULT_PERMISSION_SERVICE,
2646
+ space: SECRETS_SPACE,
2647
+ path: secretPath.vaultKey,
2648
+ actions: normalizeSecretActions(actions),
2649
+ skipPrefix: true,
2650
+ ...extra.expiry !== void 0 ? { expiry: extra.expiry } : {},
2651
+ ...extra.description !== void 0 ? { description: extra.description } : {}
2652
+ });
2653
+ }
2654
+ return entries;
2655
+ }
2656
+ function resolveEntry(entry, prefix, _inheritedExpiryMs, inheritedSpace) {
2657
+ const skipPrefixForEntry = entry.skipPrefix === true || entry.service === ENCRYPTION_PERMISSION_SERVICE;
2658
+ const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);
2659
+ const entryExpiryMs = entry.expiry !== void 0 ? parseExpiry(entry.expiry) : void 0;
2660
+ return expandPermissionEntry({
2661
+ ...entry,
2662
+ space: entry.space ?? inheritedSpace,
2663
+ path: resolvedPath,
2664
+ skipPrefix: true
2665
+ }).map((expanded) => ({
2666
+ service: expanded.service,
2667
+ space: expanded.space ?? inheritedSpace,
2668
+ path: expanded.path,
2669
+ actions: expanded.actions,
2670
+ // Only populate `expiryMs` when the entry had its own expiry override.
2671
+ // When absent, callers use the parent (delegation or manifest) expiry
2672
+ // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.
2673
+ ...entryExpiryMs !== void 0 ? { expiryMs: entryExpiryMs } : {},
2674
+ ...entry.description !== void 0 ? { description: entry.description } : {}
2675
+ }));
2676
+ }
2677
+ function expandVaultPermissionEntry(entry) {
2678
+ const byBase = /* @__PURE__ */ new Map();
2679
+ for (const action of entry.actions) {
2680
+ const expansion = vaultActionExpansion(action);
2681
+ for (const base of expansion.bases) {
2682
+ const actions = byBase.get(base) ?? [];
2683
+ if (!actions.includes(expansion.action)) {
2684
+ actions.push(expansion.action);
3161
2685
  }
3162
- }
3163
- if (spec !== null && typeof spec === "object" && !Array.isArray(spec) && spec.expiry !== void 0) {
3164
- parseExpiry(spec.expiry);
2686
+ byBase.set(base, actions);
3165
2687
  }
3166
2688
  }
2689
+ return [...byBase.entries()].map(([base, actions]) => ({
2690
+ ...entry,
2691
+ service: "tinycloud.kv",
2692
+ path: vaultKVPath(base, entry.path),
2693
+ actions,
2694
+ skipPrefix: true
2695
+ }));
3167
2696
  }
3168
- function validatePermissionEntry(p, path) {
3169
- if (p === null || typeof p !== "object") {
3170
- throw new ManifestValidationError(`${path} must be an object`);
3171
- }
3172
- const entry = p;
3173
- if (typeof entry.service !== "string" || entry.service.length === 0) {
3174
- throw new ManifestValidationError(`${path}.service is required`);
2697
+ function vaultActionExpansion(action) {
2698
+ const normalized = normalizeVaultAction(action);
2699
+ if (normalized === "read" || normalized === "get") {
2700
+ return { bases: ["vault"], action: "tinycloud.kv/get" };
3175
2701
  }
3176
- if (entry.space !== void 0 && (typeof entry.space !== "string" || entry.space.length === 0)) {
3177
- throw new ManifestValidationError(
3178
- `${path}.space must be a non-empty string`
3179
- );
2702
+ if (normalized === "write" || normalized === "put") {
2703
+ return { bases: ["vault"], action: "tinycloud.kv/put" };
3180
2704
  }
3181
- if (typeof entry.path !== "string") {
3182
- throw new ManifestValidationError(
3183
- `${path}.path is required (use "" or "/" for root)`
3184
- );
2705
+ if (normalized === "delete" || normalized === "del") {
2706
+ return { bases: ["vault"], action: "tinycloud.kv/del" };
3185
2707
  }
3186
- if (!Array.isArray(entry.actions) || entry.actions.length === 0) {
3187
- throw new ManifestValidationError(
3188
- `${path}.actions must be a non-empty array`
3189
- );
2708
+ if (normalized === "list") {
2709
+ return { bases: ["vault"], action: "tinycloud.kv/list" };
3190
2710
  }
3191
- for (const action of entry.actions) {
3192
- if (typeof action !== "string" || action.length === 0) {
3193
- throw new ManifestValidationError(
3194
- `${path}.actions must contain non-empty strings`
3195
- );
3196
- }
3197
- if (entry.service === VAULT_PERMISSION_SERVICE) {
3198
- vaultActionExpansion(action);
3199
- }
2711
+ if (normalized === "head") {
2712
+ return { bases: ["vault"], action: "tinycloud.kv/get" };
3200
2713
  }
3201
- if (entry.expiry !== void 0) {
3202
- parseExpiry(entry.expiry);
2714
+ if (normalized === "metadata") {
2715
+ return { bases: ["vault"], action: "tinycloud.kv/metadata" };
3203
2716
  }
2717
+ throw new ManifestValidationError(
2718
+ `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`
2719
+ );
3204
2720
  }
3205
- function normalizeDefaults(value) {
3206
- if (value === void 0) {
3207
- return DEFAULT_DEFAULTS;
2721
+ function normalizeVaultAction(action) {
2722
+ if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {
2723
+ return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);
3208
2724
  }
3209
- if (typeof value === "boolean") {
3210
- return value;
2725
+ if (action.startsWith("tinycloud.kv/")) {
2726
+ return action.slice("tinycloud.kv/".length);
3211
2727
  }
3212
- if (typeof value !== "string") {
3213
- return true;
2728
+ if (action.includes("/")) {
2729
+ throw new ManifestValidationError(
2730
+ `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`
2731
+ );
3214
2732
  }
3215
- const normalized = value.trim().toLowerCase();
3216
- if (normalized === "admin" || normalized === "all") {
3217
- return normalized;
2733
+ return action;
2734
+ }
2735
+ function vaultKVPath(base, path) {
2736
+ const normalized = path.startsWith("/") ? path.slice(1) : path;
2737
+ return `${base}/${normalized}`;
2738
+ }
2739
+ function cloneResourceCapability(entry) {
2740
+ return {
2741
+ service: entry.service,
2742
+ space: entry.space,
2743
+ path: entry.path,
2744
+ actions: [...entry.actions],
2745
+ ...entry.expiryMs !== void 0 ? { expiryMs: entry.expiryMs } : {},
2746
+ ...entry.description !== void 0 ? { description: entry.description } : {}
2747
+ };
2748
+ }
2749
+ function clonePermissionEntry(entry) {
2750
+ return {
2751
+ service: entry.service,
2752
+ ...entry.space !== void 0 ? { space: entry.space } : {},
2753
+ path: entry.path,
2754
+ actions: [...entry.actions],
2755
+ ...entry.skipPrefix !== void 0 ? { skipPrefix: entry.skipPrefix } : {},
2756
+ ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {},
2757
+ ...entry.description !== void 0 ? { description: entry.description } : {}
2758
+ };
2759
+ }
2760
+ function dedupeResources(resources) {
2761
+ const byKey = /* @__PURE__ */ new Map();
2762
+ for (const resource of resources) {
2763
+ const key = `${resource.service}\0${resource.space}\0${resource.path}\0${resource.expiryMs ?? ""}`;
2764
+ const existing = byKey.get(key);
2765
+ if (existing === void 0) {
2766
+ byKey.set(key, cloneResourceCapability(resource));
2767
+ continue;
2768
+ }
2769
+ const seen = new Set(existing.actions);
2770
+ for (const action of resource.actions) {
2771
+ if (!seen.has(action)) {
2772
+ existing.actions.push(action);
2773
+ seen.add(action);
2774
+ }
2775
+ }
2776
+ if (existing.description === void 0 && resource.description !== void 0) {
2777
+ existing.description = resource.description;
2778
+ }
3218
2779
  }
3219
- return true;
2780
+ return [...byKey.values()];
3220
2781
  }
3221
- function defaultEntriesForTier(tier) {
3222
- if (tier === false) {
2782
+ function capabilitiesReadPermission(space) {
2783
+ return {
2784
+ service: "tinycloud.capabilities",
2785
+ space,
2786
+ path: "",
2787
+ actions: ["tinycloud.capabilities/read"]
2788
+ };
2789
+ }
2790
+ function withCapabilitiesReadForSpaces(resources) {
2791
+ if (resources.length === 0) {
3223
2792
  return [];
3224
2793
  }
3225
- const source = tier === "admin" ? DEFAULT_ADMIN_ENTRIES : tier === "all" ? DEFAULT_ALL_ENTRIES : DEFAULT_STANDARD_ENTRIES;
3226
- return source.map((e) => ({
3227
- service: e.service,
3228
- space: e.space,
3229
- path: e.path,
3230
- actions: [...e.actions],
3231
- ...e.skipPrefix !== void 0 ? { skipPrefix: e.skipPrefix } : {}
2794
+ const spaces = new Set(
2795
+ resources.filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE).map((resource) => resource.space)
2796
+ );
2797
+ return dedupeResources([
2798
+ ...resources,
2799
+ ...[...spaces].map(capabilitiesReadPermission)
2800
+ ]);
2801
+ }
2802
+ function accountRegistryPermissions() {
2803
+ return [ACCOUNT_REGISTRY_PATH, "spaces/"].map((path) => ({
2804
+ service: "tinycloud.kv",
2805
+ space: ACCOUNT_REGISTRY_SPACE,
2806
+ path,
2807
+ actions: ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/list"]
3232
2808
  }));
3233
2809
  }
3234
- function resolveManifest(input) {
3235
- const manifest = validateManifest(input);
3236
- const prefix = manifest.prefix !== void 0 ? manifest.prefix : manifest.app_id;
3237
- const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;
3238
- const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);
3239
- const includePublicSpace = manifest.includePublicSpace ?? true;
3240
- const tier = normalizeDefaults(manifest.defaults);
3241
- const defaultEntries = defaultEntriesForTier(tier);
3242
- const explicitEntries = manifest.permissions ?? [];
3243
- const secretEntries = secretEntriesForManifest(manifest.secrets);
3244
- const allEntries = [
3245
- ...defaultEntries,
3246
- ...explicitEntries,
3247
- ...secretEntries
3248
- ];
3249
- const resources = withCapabilitiesReadForSpaces(
3250
- allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space))
3251
- );
3252
- const additionalDelegates = manifest.did === void 0 ? [] : [
3253
- {
3254
- did: manifest.did,
3255
- name: manifest.name,
3256
- expiryMs,
3257
- permissions: resources.map(cloneResourceCapability)
3258
- }
3259
- ];
2810
+ function accountRegistryIndexPermission() {
3260
2811
  return {
3261
- app_id: manifest.app_id,
3262
- ...manifest.did !== void 0 ? { did: manifest.did } : {},
3263
- space,
3264
- resources,
3265
- expiryMs,
3266
- includePublicSpace,
3267
- additionalDelegates
2812
+ service: "tinycloud.sql",
2813
+ space: ACCOUNT_REGISTRY_SPACE,
2814
+ path: "account",
2815
+ actions: ["tinycloud.sql/read", "tinycloud.sql/write"]
3268
2816
  };
3269
2817
  }
3270
- function normalizeSecretActions(actions) {
3271
- const out = [];
3272
- const seen = /* @__PURE__ */ new Set();
3273
- const add = (action) => {
3274
- if (!seen.has(action)) {
3275
- out.push(action);
3276
- seen.add(action);
2818
+ function composeManifestRequest(inputs, options = {}) {
2819
+ if (!Array.isArray(inputs) || inputs.length === 0) {
2820
+ throw new ManifestValidationError(
2821
+ "composeManifestRequest requires at least one manifest"
2822
+ );
2823
+ }
2824
+ const includeAccountRegistryPermissions = options.includeAccountRegistryPermissions ?? true;
2825
+ const manifests = inputs.map(validateManifest);
2826
+ const resolved = manifests.map(resolveManifest);
2827
+ const resources = resolved.flatMap((entry) => entry.resources);
2828
+ const delegationTargets = resolved.flatMap(
2829
+ (entry) => entry.additionalDelegates.map((delegate) => ({
2830
+ ...delegate,
2831
+ permissions: dedupeResources(delegate.permissions)
2832
+ }))
2833
+ );
2834
+ if (includeAccountRegistryPermissions) {
2835
+ resources.push(...accountRegistryPermissions());
2836
+ resources.push(accountRegistryIndexPermission());
2837
+ }
2838
+ const resourcesWithImplicitCapabilities = withCapabilitiesReadForSpaces(resources);
2839
+ const manifestsByAppId = /* @__PURE__ */ new Map();
2840
+ for (const manifest of manifests) {
2841
+ const current = manifestsByAppId.get(manifest.app_id);
2842
+ if (current === void 0) {
2843
+ manifestsByAppId.set(manifest.app_id, [manifest]);
2844
+ } else {
2845
+ current.push(manifest);
3277
2846
  }
2847
+ }
2848
+ const registryRecords = includeAccountRegistryPermissions ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({
2849
+ key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,
2850
+ app_id,
2851
+ manifests: appManifests.map((manifest) => ({
2852
+ ...manifest,
2853
+ permissions: manifest.permissions?.map(clonePermissionEntry)
2854
+ }))
2855
+ })) : [];
2856
+ return {
2857
+ manifests,
2858
+ resources: resourcesWithImplicitCapabilities,
2859
+ delegationTargets,
2860
+ registryRecords,
2861
+ expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),
2862
+ includePublicSpace: resolved.some((entry) => entry.includePublicSpace)
3278
2863
  };
3279
- for (const action of actions) {
3280
- if (action === "read") {
3281
- add("get");
3282
- continue;
3283
- }
3284
- if (action === "write") {
3285
- add("put");
3286
- continue;
3287
- }
3288
- if (action === "delete") {
3289
- add("del");
3290
- continue;
2864
+ }
2865
+ function resourceCapabilitiesToAbilitiesMap(resources) {
2866
+ const out = {};
2867
+ for (const r of resources) {
2868
+ const shortService = SERVICE_LONG_TO_SHORT[r.service];
2869
+ if (shortService === void 0) {
2870
+ throw new ManifestValidationError(
2871
+ `unknown service '${r.service}' \u2014 no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(", ")}`
2872
+ );
3291
2873
  }
3292
- if (action === "get" || action === "put" || action === "del" || action === "list" || action === "metadata") {
3293
- add(action);
3294
- continue;
2874
+ if (out[shortService] === void 0) {
2875
+ out[shortService] = {};
3295
2876
  }
3296
- if (action === "tinycloud.kv/get" || action === "tinycloud.kv/put" || action === "tinycloud.kv/del" || action === "tinycloud.kv/list" || action === "tinycloud.kv/metadata") {
3297
- add(action);
3298
- continue;
2877
+ const pathsMap = out[shortService];
2878
+ const existing = pathsMap[r.path];
2879
+ if (existing === void 0) {
2880
+ pathsMap[r.path] = [...r.actions];
2881
+ } else {
2882
+ const seen = new Set(existing);
2883
+ for (const action of r.actions) {
2884
+ if (!seen.has(action)) {
2885
+ existing.push(action);
2886
+ seen.add(action);
2887
+ }
2888
+ }
3299
2889
  }
3300
- throw new ManifestValidationError(
3301
- `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`
3302
- );
3303
2890
  }
3304
2891
  return out;
3305
2892
  }
3306
- function secretNameFromSpec(fallbackName, spec) {
3307
- if (spec !== null && typeof spec === "object" && !Array.isArray(spec)) {
3308
- return spec.name ?? fallbackName;
2893
+ function resourceCapabilitiesToSpaceAbilitiesMap(resources) {
2894
+ const grouped = /* @__PURE__ */ new Map();
2895
+ for (const resource of resources) {
2896
+ const entries = grouped.get(resource.space);
2897
+ if (entries === void 0) {
2898
+ grouped.set(resource.space, [resource]);
2899
+ } else {
2900
+ entries.push(resource);
2901
+ }
3309
2902
  }
3310
- return fallbackName;
2903
+ const out = {};
2904
+ for (const [space, entries] of grouped.entries()) {
2905
+ out[space] = resourceCapabilitiesToAbilitiesMap(entries);
2906
+ }
2907
+ return out;
3311
2908
  }
3312
- function secretScopeFromSpec(spec) {
3313
- if (spec !== null && typeof spec === "object" && !Array.isArray(spec)) {
3314
- return spec.scope;
2909
+ function manifestAbilitiesUnion(resolved) {
2910
+ const all = [...resolved.resources];
2911
+ for (const delegate of resolved.additionalDelegates) {
2912
+ for (const perm of delegate.permissions) {
2913
+ all.push(perm);
2914
+ }
3315
2915
  }
3316
- return void 0;
2916
+ return resourceCapabilitiesToAbilitiesMap(all);
3317
2917
  }
3318
- function secretActionsFromSpec(name, spec) {
3319
- if (spec === true) {
3320
- return ["read"];
2918
+
2919
+ // src/account/AccountService.ts
2920
+ var SERVICE_NAME2 = "account";
2921
+ var ACCOUNT_INDEX_DB = "account";
2922
+ var ACCOUNT_SPACES_PATH = "spaces/";
2923
+ var AccountService = class {
2924
+ constructor(config) {
2925
+ this.config = config;
2926
+ this.applications = {
2927
+ list: async () => {
2928
+ const kvResult = this.accountKV();
2929
+ if (!kvResult.ok) return kvResult;
2930
+ const listed = await kvResult.data.list({ prefix: ACCOUNT_REGISTRY_PATH });
2931
+ if (!listed.ok) return accountErr(listed.error);
2932
+ const applications = [];
2933
+ for (const key of listed.data.keys) {
2934
+ const loaded = await kvResult.data.get(key);
2935
+ if (!loaded.ok) return accountErr(loaded.error);
2936
+ applications.push(applicationFromRecord(key, loaded.data.data));
2937
+ }
2938
+ applications.sort((a, b) => a.appId.localeCompare(b.appId));
2939
+ return ok3(applications);
2940
+ },
2941
+ get: async (appId) => {
2942
+ const kvResult = this.accountKV();
2943
+ if (!kvResult.ok) return kvResult;
2944
+ const key = applicationKey(appId);
2945
+ const loaded = await kvResult.data.get(key);
2946
+ if (!loaded.ok) return accountErr(loaded.error);
2947
+ return ok3(applicationFromRecord(key, loaded.data.data));
2948
+ },
2949
+ register: async (manifest) => {
2950
+ const manifests = Array.isArray(manifest) ? manifest : [manifest];
2951
+ const request = composeManifestRequest(manifests);
2952
+ if (request.registryRecords.length === 0) {
2953
+ return err3(
2954
+ serviceError3(
2955
+ "INVALID_MANIFEST",
2956
+ "Manifest did not produce an account application registry record",
2957
+ SERVICE_NAME2
2958
+ )
2959
+ );
2960
+ }
2961
+ await this.config.ensureAccountSpaceHosted?.();
2962
+ const kvResult = this.accountKV();
2963
+ if (!kvResult.ok) return kvResult;
2964
+ let registered;
2965
+ for (const record of request.registryRecords) {
2966
+ const manifestHash = hashJson(record.manifests);
2967
+ if (await this.indexHasApplicationHash(record.app_id, manifestHash)) {
2968
+ registered = {
2969
+ appId: record.app_id,
2970
+ manifests: record.manifests,
2971
+ manifestHash,
2972
+ name: record.manifests[0]?.name,
2973
+ description: record.manifests[0]?.description
2974
+ };
2975
+ continue;
2976
+ }
2977
+ const stored = {
2978
+ app_id: record.app_id,
2979
+ manifests: record.manifests,
2980
+ manifest_hash: manifestHash,
2981
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
2982
+ };
2983
+ const written = await kvResult.data.put(record.key, stored);
2984
+ if (!written.ok) return accountErr(written.error);
2985
+ registered = applicationFromRecord(record.key, stored);
2986
+ const indexed = await this.upsertApplicationIndex(registered);
2987
+ if (!indexed.ok) return indexed;
2988
+ }
2989
+ return ok3(registered);
2990
+ },
2991
+ remove: async (appId) => {
2992
+ const kvResult = this.accountKV();
2993
+ if (!kvResult.ok) return kvResult;
2994
+ const removed = await kvResult.data.delete(applicationKey(appId));
2995
+ if (!removed.ok) return accountErr(removed.error);
2996
+ const indexed = await this.deleteApplicationIndex(appId);
2997
+ if (!indexed.ok) return indexed;
2998
+ return ok3(void 0);
2999
+ }
3000
+ };
3001
+ this.spaces = {
3002
+ list: async () => {
3003
+ const kvResult = this.accountKV();
3004
+ if (!kvResult.ok) return kvResult;
3005
+ const listed = await kvResult.data.list({ prefix: ACCOUNT_SPACES_PATH });
3006
+ if (!listed.ok) return accountErr(listed.error);
3007
+ const spaces = [];
3008
+ for (const key of listed.data.keys) {
3009
+ const loaded = await kvResult.data.get(key);
3010
+ if (!loaded.ok) return accountErr(loaded.error);
3011
+ spaces.push(spaceFromRecord(key, loaded.data.data));
3012
+ }
3013
+ spaces.sort((a, b) => a.name.localeCompare(b.name) || a.spaceId.localeCompare(b.spaceId));
3014
+ return ok3(spaces);
3015
+ },
3016
+ get: async (spaceId) => {
3017
+ const kvResult = this.accountKV();
3018
+ if (!kvResult.ok) return kvResult;
3019
+ const loaded = await kvResult.data.get(spaceKey(spaceId));
3020
+ if (!loaded.ok) return accountErr(loaded.error);
3021
+ return ok3(spaceFromRecord(spaceKey(spaceId), loaded.data.data));
3022
+ },
3023
+ register: async (space) => {
3024
+ await this.config.ensureAccountSpaceHosted?.();
3025
+ const kvResult = this.accountKV();
3026
+ if (!kvResult.ok) return kvResult;
3027
+ const stored = spaceRecordFromInput(space);
3028
+ const written = await kvResult.data.put(spaceKey(stored.space_id), stored);
3029
+ if (!written.ok) return accountErr(written.error);
3030
+ const registered = spaceFromRecord(spaceKey(stored.space_id), stored);
3031
+ const indexed = await this.upsertSpaceIndex(registered);
3032
+ if (!indexed.ok) return indexed;
3033
+ return ok3(registered);
3034
+ },
3035
+ syncAccessible: async () => {
3036
+ const listed = await this.config.getSpaces().list();
3037
+ if (!listed.ok) return accountErr(listed.error);
3038
+ const registered = [];
3039
+ for (const space of listed.data) {
3040
+ const result = await this.spaces.register(space);
3041
+ if (!result.ok) return result;
3042
+ registered.push(result.data);
3043
+ }
3044
+ return ok3(registered);
3045
+ },
3046
+ remove: async (spaceId) => {
3047
+ const kvResult = this.accountKV();
3048
+ if (!kvResult.ok) return kvResult;
3049
+ const removed = await kvResult.data.delete(spaceKey(spaceId));
3050
+ if (!removed.ok) return accountErr(removed.error);
3051
+ const indexed = await this.deleteSpaceIndex(spaceId);
3052
+ if (!indexed.ok) return indexed;
3053
+ return ok3(void 0);
3054
+ }
3055
+ };
3056
+ this.delegations = {
3057
+ list: async (options = {}) => {
3058
+ const spaces = await this.config.getSpaces().list();
3059
+ if (!spaces.ok) return accountErr(spaces.error);
3060
+ const targetSpaces = options.space ? spaces.data.filter((space) => space.id === options.space || space.name === options.space) : spaces.data;
3061
+ const delegations = [];
3062
+ for (const space of targetSpaces) {
3063
+ const scoped = this.config.getSpaces().get(space.id).delegations;
3064
+ if (options.direction !== "received") {
3065
+ const granted = await scoped.list();
3066
+ if (!granted.ok) return accountErr(granted.error);
3067
+ delegations.push(...granted.data.map((d) => mapDelegation(d, space, "granted")));
3068
+ }
3069
+ if (options.direction !== "granted") {
3070
+ const received = await scoped.listReceived();
3071
+ if (!received.ok) return accountErr(received.error);
3072
+ delegations.push(...received.data.map((d) => mapDelegation(d, space, "received")));
3073
+ }
3074
+ }
3075
+ delegations.sort((a, b) => a.spaceId.localeCompare(b.spaceId) || a.cid.localeCompare(b.cid));
3076
+ return ok3(delegations);
3077
+ },
3078
+ revoke: async (options) => {
3079
+ const space = await this.resolveSpace(options.space);
3080
+ if (!space.ok) return space;
3081
+ const revoked = await this.config.getSpaces().get(space.data.id).delegations.revoke(options.cid);
3082
+ if (!revoked.ok) return accountErr(revoked.error);
3083
+ return ok3(void 0);
3084
+ }
3085
+ };
3086
+ this.index = {
3087
+ rebuild: async () => {
3088
+ const dbResult = this.accountDb();
3089
+ if (!dbResult.ok) return dbResult;
3090
+ const applications = await this.applications.list();
3091
+ if (!applications.ok) return applications;
3092
+ const spaces = await this.spaces.list();
3093
+ if (!spaces.ok) return spaces;
3094
+ const delegations = await this.delegations.list();
3095
+ if (!delegations.ok) return delegations;
3096
+ const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
3097
+ const statements = [
3098
+ ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3099
+ { sql: "DELETE FROM applications" },
3100
+ { sql: "DELETE FROM application_state" },
3101
+ { sql: "DELETE FROM spaces" },
3102
+ { sql: "DELETE FROM delegations" },
3103
+ { sql: "DELETE FROM sync_state" },
3104
+ ...applications.data.map((app) => ({
3105
+ sql: "INSERT INTO applications (app_id, name, description, updated_at, manifest_json) VALUES (?, ?, ?, ?, ?)",
3106
+ params: [
3107
+ app.appId,
3108
+ app.name ?? null,
3109
+ app.description ?? null,
3110
+ app.updatedAt ?? syncedAt,
3111
+ JSON.stringify(app.manifests)
3112
+ ]
3113
+ })),
3114
+ ...applications.data.map((app) => ({
3115
+ sql: "INSERT OR REPLACE INTO application_state (app_id, manifest_hash, indexed_at) VALUES (?, ?, ?)",
3116
+ params: [app.appId, app.manifestHash ?? hashJson(app.manifests), syncedAt]
3117
+ })),
3118
+ ...spaces.data.map((space) => ({
3119
+ sql: "INSERT OR REPLACE INTO spaces (space_id, name, owner_did, type, permissions_json, status, registered_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
3120
+ params: [
3121
+ space.spaceId,
3122
+ space.name,
3123
+ space.ownerDid,
3124
+ space.type,
3125
+ JSON.stringify(space.permissions),
3126
+ space.status,
3127
+ space.registeredAt ?? syncedAt,
3128
+ space.updatedAt ?? syncedAt,
3129
+ space.expiresAt?.toISOString() ?? null
3130
+ ]
3131
+ })),
3132
+ ...delegations.data.map((delegation) => ({
3133
+ sql: "INSERT INTO delegations (cid, direction, space_id, space_name, counterparty_did, delegate_did, delegator_did, path, actions_json, expiry, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3134
+ params: [
3135
+ delegation.cid,
3136
+ delegation.direction,
3137
+ delegation.spaceId,
3138
+ delegation.spaceName ?? null,
3139
+ delegation.counterpartyDid,
3140
+ delegation.delegateDid,
3141
+ delegation.delegatorDid ?? null,
3142
+ delegation.path,
3143
+ JSON.stringify(delegation.actions),
3144
+ delegation.expiry.toISOString(),
3145
+ delegation.status,
3146
+ delegation.createdAt?.toISOString() ?? null,
3147
+ syncedAt
3148
+ ]
3149
+ })),
3150
+ {
3151
+ sql: "INSERT INTO sync_state (source, synced_at, count) VALUES (?, ?, ?)",
3152
+ params: ["applications", syncedAt, applications.data.length]
3153
+ },
3154
+ {
3155
+ sql: "INSERT INTO sync_state (source, synced_at, count) VALUES (?, ?, ?)",
3156
+ params: ["spaces", syncedAt, spaces.data.length]
3157
+ },
3158
+ {
3159
+ sql: "INSERT INTO sync_state (source, synced_at, count) VALUES (?, ?, ?)",
3160
+ params: ["delegations", syncedAt, delegations.data.length]
3161
+ }
3162
+ ];
3163
+ const rebuilt = await dbResult.data.batch(statements);
3164
+ if (!rebuilt.ok) return accountErr(rebuilt.error);
3165
+ return ok3({
3166
+ database: ACCOUNT_INDEX_DB,
3167
+ applications: applications.data.length,
3168
+ spaces: spaces.data.length,
3169
+ delegations: delegations.data.length,
3170
+ syncedAt
3171
+ });
3172
+ },
3173
+ applications: {
3174
+ list: async () => {
3175
+ const dbResult = this.accountDb();
3176
+ if (!dbResult.ok) return dbResult;
3177
+ const queried = await dbResult.data.query(
3178
+ "SELECT applications.app_id, name, description, updated_at, manifest_json, application_state.manifest_hash FROM applications LEFT JOIN application_state ON applications.app_id = application_state.app_id ORDER BY applications.app_id"
3179
+ );
3180
+ if (!queried.ok) return accountErr(queried.error);
3181
+ return ok3(queried.data.rows.map(indexedApplicationFromRow));
3182
+ }
3183
+ },
3184
+ spaces: {
3185
+ list: async () => {
3186
+ const dbResult = this.accountDb();
3187
+ if (!dbResult.ok) return dbResult;
3188
+ const queried = await dbResult.data.query(
3189
+ "SELECT space_id, name, owner_did, type, permissions_json, status, registered_at, updated_at, expires_at FROM spaces ORDER BY name, space_id"
3190
+ );
3191
+ if (!queried.ok) return accountErr(queried.error);
3192
+ return ok3(queried.data.rows.map(indexedSpaceFromRow));
3193
+ }
3194
+ },
3195
+ delegations: {
3196
+ list: async (options = {}) => {
3197
+ const dbResult = this.accountDb();
3198
+ if (!dbResult.ok) return dbResult;
3199
+ const where = [];
3200
+ const params = [];
3201
+ if (options.direction && options.direction !== "all") {
3202
+ where.push("direction = ?");
3203
+ params.push(options.direction);
3204
+ }
3205
+ if (options.space) {
3206
+ where.push("(space_id = ? OR space_name = ?)");
3207
+ params.push(options.space, options.space);
3208
+ }
3209
+ const queried = await dbResult.data.query(
3210
+ `SELECT cid, direction, space_id, space_name, counterparty_did, delegate_did, delegator_did, path, actions_json, expiry, status, created_at FROM delegations${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY space_id, cid`,
3211
+ params
3212
+ );
3213
+ if (!queried.ok) return accountErr(queried.error);
3214
+ return ok3(queried.data.rows.map(indexedDelegationFromRow));
3215
+ }
3216
+ },
3217
+ query: async (sql, params) => {
3218
+ const dbResult = this.accountDb();
3219
+ if (!dbResult.ok) return dbResult;
3220
+ const queried = await dbResult.data.query(sql, params);
3221
+ if (!queried.ok) return accountErr(queried.error);
3222
+ return ok3(queried.data);
3223
+ },
3224
+ status: async () => {
3225
+ const dbResult = this.accountDb();
3226
+ if (!dbResult.ok) return dbResult;
3227
+ const queried = await dbResult.data.query(
3228
+ "SELECT source, synced_at, count FROM sync_state ORDER BY source"
3229
+ );
3230
+ if (!queried.ok) return accountErr(queried.error);
3231
+ return ok3({
3232
+ database: ACCOUNT_INDEX_DB,
3233
+ sources: queried.data.rows.map(([source, syncedAt, count]) => ({
3234
+ source,
3235
+ syncedAt,
3236
+ count
3237
+ }))
3238
+ });
3239
+ }
3240
+ };
3241
+ }
3242
+ async status() {
3243
+ const apps = await this.applications.list();
3244
+ if (!apps.ok) return apps;
3245
+ const delegations = await this.delegations.list();
3246
+ if (!delegations.ok) return delegations;
3247
+ const spaces = await this.spaces.list();
3248
+ if (!spaces.ok) return spaces;
3249
+ return ok3({
3250
+ did: this.config.getDid(),
3251
+ host: this.config.getHost(),
3252
+ primarySpaceId: this.config.getPrimarySpaceId(),
3253
+ accountSpaceId: this.config.getAccountSpaceId(),
3254
+ applications: apps.data.length,
3255
+ spaces: spaces.data.length,
3256
+ grantedDelegations: delegations.data.filter((d) => d.direction === "granted").length,
3257
+ receivedDelegations: delegations.data.filter((d) => d.direction === "received").length
3258
+ });
3321
3259
  }
3322
- if (typeof spec === "string") {
3323
- return [spec];
3260
+ accountKV() {
3261
+ const accountSpaceId = this.config.getAccountSpaceId();
3262
+ if (!accountSpaceId) {
3263
+ return err3(
3264
+ serviceError3(
3265
+ "ACCOUNT_SPACE_UNAVAILABLE",
3266
+ "Account space is unavailable. Sign in with a wallet-backed profile first.",
3267
+ SERVICE_NAME2
3268
+ )
3269
+ );
3270
+ }
3271
+ return ok3(this.config.getSpaces().get(accountSpaceId).kv);
3324
3272
  }
3325
- if (Array.isArray(spec)) {
3326
- return spec;
3273
+ accountDb() {
3274
+ const db = this.config.getAccountDb?.();
3275
+ if (!db) {
3276
+ return err3(
3277
+ serviceError3(
3278
+ "ACCOUNT_INDEX_UNAVAILABLE",
3279
+ "Account index database is unavailable. Sign in with a wallet-backed profile first.",
3280
+ SERVICE_NAME2
3281
+ )
3282
+ );
3283
+ }
3284
+ return ok3(db);
3327
3285
  }
3328
- if (spec === null || typeof spec !== "object") {
3329
- throw new ManifestValidationError(
3330
- `manifest.secrets.${name} must be true, a string action, an actions array, or an object`
3286
+ async indexHasApplicationHash(appId, manifestHash) {
3287
+ const dbResult = this.accountDb();
3288
+ if (!dbResult.ok) return false;
3289
+ const schema = await dbResult.data.batch(ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })));
3290
+ if (!schema.ok) return false;
3291
+ const queried = await dbResult.data.query(
3292
+ "SELECT 1 FROM application_state WHERE app_id = ? AND manifest_hash = ? LIMIT 1",
3293
+ [appId, manifestHash]
3331
3294
  );
3295
+ return queried.ok && queried.data.rows.length > 0;
3296
+ }
3297
+ async upsertApplicationIndex(app) {
3298
+ const dbResult = this.accountDb();
3299
+ if (!dbResult.ok) return ok3(void 0);
3300
+ const updatedAt = app.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
3301
+ const manifestHash = app.manifestHash ?? hashJson(app.manifests);
3302
+ const written = await dbResult.data.batch([
3303
+ ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3304
+ {
3305
+ sql: "INSERT OR REPLACE INTO applications (app_id, name, description, updated_at, manifest_json) VALUES (?, ?, ?, ?, ?)",
3306
+ params: [
3307
+ app.appId,
3308
+ app.name ?? null,
3309
+ app.description ?? null,
3310
+ updatedAt,
3311
+ JSON.stringify(app.manifests)
3312
+ ]
3313
+ },
3314
+ {
3315
+ sql: "INSERT OR REPLACE INTO application_state (app_id, manifest_hash, indexed_at) VALUES (?, ?, ?)",
3316
+ params: [app.appId, manifestHash, updatedAt]
3317
+ }
3318
+ ]);
3319
+ if (!written.ok) return accountErr(written.error);
3320
+ return ok3(void 0);
3332
3321
  }
3333
- if (spec.actions === void 0) {
3334
- return ["read"];
3335
- }
3336
- if (typeof spec.actions === "string") {
3337
- return [spec.actions];
3322
+ async deleteApplicationIndex(appId) {
3323
+ const dbResult = this.accountDb();
3324
+ if (!dbResult.ok) return ok3(void 0);
3325
+ const deleted = await dbResult.data.batch([
3326
+ ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3327
+ { sql: "DELETE FROM applications WHERE app_id = ?", params: [appId] },
3328
+ { sql: "DELETE FROM application_state WHERE app_id = ?", params: [appId] }
3329
+ ]);
3330
+ if (!deleted.ok) return accountErr(deleted.error);
3331
+ return ok3(void 0);
3338
3332
  }
3339
- if (Array.isArray(spec.actions)) {
3340
- return spec.actions;
3333
+ async upsertSpaceIndex(space) {
3334
+ const dbResult = this.accountDb();
3335
+ if (!dbResult.ok) return ok3(void 0);
3336
+ const updatedAt = space.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
3337
+ const written = await dbResult.data.batch([
3338
+ ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3339
+ {
3340
+ sql: "INSERT OR REPLACE INTO spaces (space_id, name, owner_did, type, permissions_json, status, registered_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
3341
+ params: [
3342
+ space.spaceId,
3343
+ space.name,
3344
+ space.ownerDid,
3345
+ space.type,
3346
+ JSON.stringify(space.permissions),
3347
+ space.status,
3348
+ space.registeredAt ?? updatedAt,
3349
+ updatedAt,
3350
+ space.expiresAt?.toISOString() ?? null
3351
+ ]
3352
+ }
3353
+ ]);
3354
+ if (!written.ok) return accountErr(written.error);
3355
+ return ok3(void 0);
3341
3356
  }
3342
- throw new ManifestValidationError(
3343
- `manifest.secrets.${name}.actions must be a string or array`
3344
- );
3345
- }
3346
- function secretEntriesForManifest(secrets) {
3347
- if (secrets === void 0) {
3348
- return [];
3357
+ async deleteSpaceIndex(spaceId) {
3358
+ const dbResult = this.accountDb();
3359
+ if (!dbResult.ok) return ok3(void 0);
3360
+ const deleted = await dbResult.data.batch([
3361
+ ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3362
+ { sql: "DELETE FROM spaces WHERE space_id = ?", params: [spaceId] }
3363
+ ]);
3364
+ if (!deleted.ok) return accountErr(deleted.error);
3365
+ return ok3(void 0);
3349
3366
  }
3350
- const entries = [];
3351
- for (const [name, spec] of Object.entries(secrets)) {
3352
- const actions = secretActionsFromSpec(name, spec);
3353
- const secretPath = resolveSecretPath(
3354
- secretNameFromSpec(name, spec),
3355
- { scope: secretScopeFromSpec(spec) }
3356
- );
3357
- const extra = spec !== true && typeof spec === "object" && !Array.isArray(spec) ? spec : {};
3358
- entries.push({
3359
- service: VAULT_PERMISSION_SERVICE,
3360
- space: SECRETS_SPACE,
3361
- path: secretPath.vaultKey,
3362
- actions: normalizeSecretActions(actions),
3363
- skipPrefix: true,
3364
- ...extra.expiry !== void 0 ? { expiry: extra.expiry } : {},
3365
- ...extra.description !== void 0 ? { description: extra.description } : {}
3366
- });
3367
+ async resolveSpace(space) {
3368
+ const listed = await this.config.getSpaces().list();
3369
+ if (!listed.ok) return accountErr(listed.error);
3370
+ const found = listed.data.find((candidate) => candidate.id === space || candidate.name === space);
3371
+ if (!found) {
3372
+ return err3(
3373
+ serviceError3("SPACE_NOT_FOUND", `No account space found for ${JSON.stringify(space)}`, SERVICE_NAME2)
3374
+ );
3375
+ }
3376
+ return ok3(found);
3367
3377
  }
3368
- return entries;
3378
+ };
3379
+ var ACCOUNT_INDEX_SCHEMA = [
3380
+ `CREATE TABLE IF NOT EXISTS applications (
3381
+ app_id TEXT PRIMARY KEY,
3382
+ name TEXT,
3383
+ description TEXT,
3384
+ updated_at TEXT,
3385
+ manifest_json TEXT NOT NULL
3386
+ )`,
3387
+ `CREATE TABLE IF NOT EXISTS application_state (
3388
+ app_id TEXT PRIMARY KEY,
3389
+ manifest_hash TEXT NOT NULL,
3390
+ indexed_at TEXT NOT NULL
3391
+ )`,
3392
+ `CREATE TABLE IF NOT EXISTS spaces (
3393
+ space_id TEXT PRIMARY KEY,
3394
+ name TEXT NOT NULL,
3395
+ owner_did TEXT NOT NULL,
3396
+ type TEXT NOT NULL,
3397
+ permissions_json TEXT NOT NULL,
3398
+ status TEXT NOT NULL,
3399
+ registered_at TEXT,
3400
+ updated_at TEXT NOT NULL,
3401
+ expires_at TEXT
3402
+ )`,
3403
+ `CREATE TABLE IF NOT EXISTS delegations (
3404
+ cid TEXT PRIMARY KEY,
3405
+ direction TEXT NOT NULL,
3406
+ space_id TEXT NOT NULL,
3407
+ space_name TEXT,
3408
+ counterparty_did TEXT NOT NULL,
3409
+ delegate_did TEXT NOT NULL,
3410
+ delegator_did TEXT,
3411
+ path TEXT NOT NULL,
3412
+ actions_json TEXT NOT NULL,
3413
+ expiry TEXT NOT NULL,
3414
+ status TEXT NOT NULL,
3415
+ created_at TEXT,
3416
+ updated_at TEXT NOT NULL
3417
+ )`,
3418
+ `CREATE TABLE IF NOT EXISTS sync_state (
3419
+ source TEXT PRIMARY KEY,
3420
+ synced_at TEXT NOT NULL,
3421
+ count INTEGER NOT NULL
3422
+ )`,
3423
+ "CREATE INDEX IF NOT EXISTS idx_delegations_direction ON delegations(direction)",
3424
+ "CREATE INDEX IF NOT EXISTS idx_delegations_space ON delegations(space_id)",
3425
+ "CREATE INDEX IF NOT EXISTS idx_delegations_counterparty ON delegations(counterparty_did)",
3426
+ "CREATE INDEX IF NOT EXISTS idx_spaces_owner ON spaces(owner_did)",
3427
+ "CREATE INDEX IF NOT EXISTS idx_spaces_type ON spaces(type)"
3428
+ ];
3429
+ function applicationKey(appId) {
3430
+ return `${ACCOUNT_REGISTRY_PATH}${appId}`;
3369
3431
  }
3370
- function resolveEntry(entry, prefix, _inheritedExpiryMs, inheritedSpace) {
3371
- const skipPrefixForEntry = entry.skipPrefix === true || entry.service === ENCRYPTION_PERMISSION_SERVICE;
3372
- const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);
3373
- const entryExpiryMs = entry.expiry !== void 0 ? parseExpiry(entry.expiry) : void 0;
3374
- return expandPermissionEntry({
3375
- ...entry,
3376
- space: entry.space ?? inheritedSpace,
3377
- path: resolvedPath,
3378
- skipPrefix: true
3379
- }).map((expanded) => ({
3380
- service: expanded.service,
3381
- space: expanded.space ?? inheritedSpace,
3382
- path: expanded.path,
3383
- actions: expanded.actions,
3384
- // Only populate `expiryMs` when the entry had its own expiry override.
3385
- // When absent, callers use the parent (delegation or manifest) expiry
3386
- // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.
3387
- ...entryExpiryMs !== void 0 ? { expiryMs: entryExpiryMs } : {},
3388
- ...entry.description !== void 0 ? { description: entry.description } : {}
3389
- }));
3432
+ function appIdFromKey(key) {
3433
+ return key.startsWith(ACCOUNT_REGISTRY_PATH) ? key.slice(ACCOUNT_REGISTRY_PATH.length) : key;
3390
3434
  }
3391
- function expandVaultPermissionEntry(entry) {
3392
- const byBase = /* @__PURE__ */ new Map();
3393
- for (const action of entry.actions) {
3394
- const expansion = vaultActionExpansion(action);
3395
- for (const base of expansion.bases) {
3396
- const actions = byBase.get(base) ?? [];
3397
- if (!actions.includes(expansion.action)) {
3398
- actions.push(expansion.action);
3399
- }
3400
- byBase.set(base, actions);
3401
- }
3402
- }
3403
- return [...byBase.entries()].map(([base, actions]) => ({
3404
- ...entry,
3405
- service: "tinycloud.kv",
3406
- path: vaultKVPath(base, entry.path),
3407
- actions,
3408
- skipPrefix: true
3409
- }));
3435
+ function applicationFromRecord(key, record) {
3436
+ const manifests = Array.isArray(record.manifests) ? record.manifests : [];
3437
+ const first = manifests[0];
3438
+ return {
3439
+ appId: record.app_id ?? record.appId ?? first?.app_id ?? appIdFromKey(key),
3440
+ manifests,
3441
+ updatedAt: record.updated_at ?? record.updatedAt,
3442
+ name: first?.name,
3443
+ description: first?.description,
3444
+ manifestHash: record.manifest_hash ?? record.manifestHash ?? hashJson(manifests)
3445
+ };
3410
3446
  }
3411
- function vaultActionExpansion(action) {
3412
- const normalized = normalizeVaultAction(action);
3413
- if (normalized === "read" || normalized === "get") {
3414
- return { bases: ["vault"], action: "tinycloud.kv/get" };
3415
- }
3416
- if (normalized === "write" || normalized === "put") {
3417
- return { bases: ["vault"], action: "tinycloud.kv/put" };
3418
- }
3419
- if (normalized === "delete" || normalized === "del") {
3420
- return { bases: ["vault"], action: "tinycloud.kv/del" };
3421
- }
3422
- if (normalized === "list") {
3423
- return { bases: ["vault"], action: "tinycloud.kv/list" };
3424
- }
3425
- if (normalized === "head") {
3426
- return { bases: ["vault"], action: "tinycloud.kv/get" };
3447
+ function indexedApplicationFromRow(row) {
3448
+ const [appId, name, description, updatedAt, manifestJson, manifestHash] = row;
3449
+ return {
3450
+ appId,
3451
+ name: name ?? void 0,
3452
+ description: description ?? void 0,
3453
+ updatedAt: updatedAt ?? void 0,
3454
+ manifests: JSON.parse(manifestJson),
3455
+ manifestHash: manifestHash ?? void 0
3456
+ };
3457
+ }
3458
+ function spaceKey(spaceId) {
3459
+ return `${ACCOUNT_SPACES_PATH}${spaceId}`;
3460
+ }
3461
+ function spaceIdFromKey(key) {
3462
+ return key.startsWith(ACCOUNT_SPACES_PATH) ? key.slice(ACCOUNT_SPACES_PATH.length) : key;
3463
+ }
3464
+ function spaceRecordFromInput(space) {
3465
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3466
+ const accountSpace = "spaceId" in space ? space : {
3467
+ spaceId: space.id,
3468
+ name: space.name ?? space.id.split(":").pop() ?? space.id,
3469
+ ownerDid: space.owner ?? "",
3470
+ type: space.type ?? "discovered",
3471
+ permissions: space.permissions ?? [],
3472
+ status: "active",
3473
+ expiresAt: space.expiresAt
3474
+ };
3475
+ return {
3476
+ space_id: accountSpace.spaceId,
3477
+ name: accountSpace.name,
3478
+ owner_did: accountSpace.ownerDid,
3479
+ type: accountSpace.type,
3480
+ permissions: accountSpace.permissions,
3481
+ status: accountSpace.status,
3482
+ registered_at: accountSpace.registeredAt ?? now,
3483
+ updated_at: now,
3484
+ expires_at: accountSpace.expiresAt instanceof Date ? accountSpace.expiresAt.toISOString() : accountSpace.expiresAt
3485
+ };
3486
+ }
3487
+ function spaceFromRecord(key, record) {
3488
+ const expiresAt = record.expires_at ?? record.expiresAt;
3489
+ return {
3490
+ spaceId: record.space_id ?? record.spaceId ?? spaceIdFromKey(key),
3491
+ name: record.name ?? spaceIdFromKey(key).split(":").pop() ?? spaceIdFromKey(key),
3492
+ ownerDid: record.owner_did ?? record.ownerDid ?? record.owner ?? "",
3493
+ type: record.type ?? "discovered",
3494
+ permissions: Array.isArray(record.permissions) ? record.permissions : [],
3495
+ status: record.status ?? "active",
3496
+ registeredAt: record.registered_at ?? record.registeredAt,
3497
+ updatedAt: record.updated_at ?? record.updatedAt,
3498
+ expiresAt: expiresAt ? new Date(expiresAt) : void 0
3499
+ };
3500
+ }
3501
+ function indexedSpaceFromRow(row) {
3502
+ const [spaceId, name, ownerDid, type, permissionsJson, status, registeredAt, updatedAt, expiresAt] = row;
3503
+ return {
3504
+ spaceId,
3505
+ name,
3506
+ ownerDid,
3507
+ type,
3508
+ permissions: JSON.parse(permissionsJson),
3509
+ status,
3510
+ registeredAt: registeredAt ?? void 0,
3511
+ updatedAt,
3512
+ expiresAt: expiresAt ? new Date(expiresAt) : void 0
3513
+ };
3514
+ }
3515
+ function hashJson(value) {
3516
+ const input = stableJson(value);
3517
+ let hash = 0xcbf29ce484222325n;
3518
+ const prime = 0x100000001b3n;
3519
+ for (let index = 0; index < input.length; index += 1) {
3520
+ hash ^= BigInt(input.charCodeAt(index));
3521
+ hash = BigInt.asUintN(64, hash * prime);
3522
+ }
3523
+ return hash.toString(16).padStart(16, "0");
3524
+ }
3525
+ function stableJson(value) {
3526
+ if (value === null || typeof value !== "object") {
3527
+ return JSON.stringify(value);
3427
3528
  }
3428
- if (normalized === "metadata") {
3429
- return { bases: ["vault"], action: "tinycloud.kv/metadata" };
3529
+ if (Array.isArray(value)) {
3530
+ return `[${value.map(stableJson).join(",")}]`;
3430
3531
  }
3431
- throw new ManifestValidationError(
3432
- `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`
3433
- );
3532
+ const object = value;
3533
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableJson(object[key])}`).join(",")}}`;
3434
3534
  }
3435
- function normalizeVaultAction(action) {
3436
- if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {
3437
- return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);
3438
- }
3439
- if (action.startsWith("tinycloud.kv/")) {
3440
- return action.slice("tinycloud.kv/".length);
3535
+ function indexedDelegationFromRow(row) {
3536
+ const [
3537
+ cid,
3538
+ direction,
3539
+ spaceId,
3540
+ spaceName,
3541
+ counterpartyDid,
3542
+ delegateDid,
3543
+ delegatorDid,
3544
+ path,
3545
+ actionsJson,
3546
+ expiry,
3547
+ status,
3548
+ createdAt
3549
+ ] = row;
3550
+ return {
3551
+ cid,
3552
+ direction,
3553
+ spaceId,
3554
+ spaceName: spaceName ?? void 0,
3555
+ counterpartyDid,
3556
+ delegateDid,
3557
+ delegatorDid: delegatorDid ?? void 0,
3558
+ path,
3559
+ actions: JSON.parse(actionsJson),
3560
+ expiry: new Date(expiry),
3561
+ status,
3562
+ createdAt: createdAt ? new Date(createdAt) : void 0
3563
+ };
3564
+ }
3565
+ function mapDelegation(delegation, space, direction) {
3566
+ return {
3567
+ cid: delegation.cid,
3568
+ direction,
3569
+ spaceId: delegation.spaceId || space.id,
3570
+ spaceName: space.name,
3571
+ counterpartyDid: direction === "granted" ? delegation.delegateDID : delegation.delegatorDID ?? delegation.delegateDID,
3572
+ delegateDid: delegation.delegateDID,
3573
+ delegatorDid: delegation.delegatorDID,
3574
+ path: delegation.path,
3575
+ actions: delegation.actions,
3576
+ expiry: delegation.expiry,
3577
+ status: delegation.isRevoked ? "revoked" : delegation.expiry.getTime() <= Date.now() ? "expired" : "active",
3578
+ createdAt: delegation.createdAt
3579
+ };
3580
+ }
3581
+ function accountErr(error) {
3582
+ return err3(serviceError3(error.code, error.message, SERVICE_NAME2, { cause: error.cause, meta: error.meta }));
3583
+ }
3584
+
3585
+ // src/index.ts
3586
+ import {
3587
+ ServiceContext as ServiceContext2,
3588
+ KVService as KVService2,
3589
+ PrefixedKVService,
3590
+ ok as ok5,
3591
+ err as err5,
3592
+ serviceError as serviceError5,
3593
+ ErrorCodes as ErrorCodes2,
3594
+ defaultRetryPolicy as defaultRetryPolicy2,
3595
+ SQLService as SQLService2,
3596
+ DatabaseHandle,
3597
+ SQLAction,
3598
+ DuckDbService as DuckDbService2,
3599
+ DuckDbDatabaseHandle,
3600
+ DuckDbAction,
3601
+ HooksService as HooksService2,
3602
+ DataVaultService,
3603
+ VaultHeaders,
3604
+ VaultPublicSpaceKVActions,
3605
+ createVaultCrypto,
3606
+ SecretsService,
3607
+ SECRET_NAME_RE as SECRET_NAME_RE2,
3608
+ canonicalizeSecretScope,
3609
+ resolveSecretListPrefix,
3610
+ resolveSecretPath as resolveSecretPath2,
3611
+ EncryptionService,
3612
+ parseNetworkId as parseNetworkId2,
3613
+ buildNetworkId as buildNetworkId2,
3614
+ isNetworkId,
3615
+ networkDiscoveryKey,
3616
+ NetworkIdError,
3617
+ ENCRYPTION_NETWORK_URN_PREFIX,
3618
+ NETWORK_NAME_PATTERN,
3619
+ canonicalizeEncryptionJson,
3620
+ canonicalHashHex,
3621
+ hexEncode,
3622
+ hexDecode,
3623
+ base64Encode,
3624
+ base64Decode,
3625
+ utf8Encode,
3626
+ utf8Decode,
3627
+ encryptToNetwork,
3628
+ decryptEnvelopeWithKey,
3629
+ validateEnvelope,
3630
+ generateRandomReceiverKey,
3631
+ deriveSignedReceiverKey,
3632
+ buildCanonicalDecryptRequest,
3633
+ buildDecryptFacts,
3634
+ buildDecryptAttenuation,
3635
+ buildDecryptInvocation,
3636
+ checkDecryptInvocationInput,
3637
+ verifyDecryptResponse,
3638
+ canonicalSignedResponse,
3639
+ openWrappedKey,
3640
+ discoverNetwork,
3641
+ ensureNetworkUsableForDecrypt,
3642
+ DEFAULT_ENCRYPTION_ALG,
3643
+ ENVELOPE_VERSION,
3644
+ DEFAULT_KEY_VERSION,
3645
+ DECRYPT_FACT_TYPE,
3646
+ DECRYPT_RESULT_TYPE,
3647
+ DECRYPT_ACTION,
3648
+ ENCRYPTION_SERVICE,
3649
+ ENCRYPTION_SERVICE_SHORT,
3650
+ encryptionError
3651
+ } from "@tinycloud/sdk-services";
3652
+
3653
+ // src/space.ts
3654
+ async function fetchPeerId(host, spaceId) {
3655
+ const res = await fetch(
3656
+ `${host}/peer/generate/${encodeURIComponent(spaceId)}`
3657
+ );
3658
+ if (!res.ok) {
3659
+ const error = await res.text().catch(() => res.statusText);
3660
+ throw new Error(`Failed to get peer ID: ${res.status} - ${error}`);
3441
3661
  }
3442
- if (action.includes("/")) {
3443
- throw new ManifestValidationError(
3444
- `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`
3445
- );
3662
+ return res.text();
3663
+ }
3664
+ async function submitHostDelegation(host, headers) {
3665
+ const res = await fetch(`${host}/delegate`, {
3666
+ method: "POST",
3667
+ headers
3668
+ });
3669
+ return {
3670
+ success: res.ok,
3671
+ status: res.status,
3672
+ error: res.ok ? void 0 : await res.text().catch(() => res.statusText)
3673
+ };
3674
+ }
3675
+ async function activateSessionWithHost(host, delegationHeader) {
3676
+ const res = await fetch(`${host}/delegate`, {
3677
+ method: "POST",
3678
+ headers: delegationHeader
3679
+ });
3680
+ if (res.ok) {
3681
+ try {
3682
+ const body = await res.json();
3683
+ return {
3684
+ success: true,
3685
+ status: res.status,
3686
+ activated: body.activated ?? [],
3687
+ skipped: body.skipped ?? []
3688
+ };
3689
+ } catch {
3690
+ return {
3691
+ success: true,
3692
+ status: res.status,
3693
+ activated: [],
3694
+ skipped: []
3695
+ };
3696
+ }
3446
3697
  }
3447
- return action;
3448
- }
3449
- function vaultKVPath(base, path) {
3450
- const normalized = path.startsWith("/") ? path.slice(1) : path;
3451
- return `${base}/${normalized}`;
3452
- }
3453
- function cloneResourceCapability(entry) {
3454
3698
  return {
3455
- service: entry.service,
3456
- space: entry.space,
3457
- path: entry.path,
3458
- actions: [...entry.actions],
3459
- ...entry.expiryMs !== void 0 ? { expiryMs: entry.expiryMs } : {},
3460
- ...entry.description !== void 0 ? { description: entry.description } : {}
3699
+ success: false,
3700
+ status: res.status,
3701
+ error: await res.text().catch(() => res.statusText)
3461
3702
  };
3462
3703
  }
3463
- function clonePermissionEntry(entry) {
3704
+
3705
+ // src/delegations/DelegationManager.ts
3706
+ var DelegationAction = {
3707
+ CREATE: "tinycloud.delegation/create",
3708
+ REVOKE: "tinycloud.delegation/revoke",
3709
+ LIST: "tinycloud.delegation/list",
3710
+ GET: "tinycloud.delegation/get",
3711
+ CHECK: "tinycloud.delegation/check"
3712
+ };
3713
+ function createError(code, message, cause, meta) {
3464
3714
  return {
3465
- service: entry.service,
3466
- ...entry.space !== void 0 ? { space: entry.space } : {},
3467
- path: entry.path,
3468
- actions: [...entry.actions],
3469
- ...entry.skipPrefix !== void 0 ? { skipPrefix: entry.skipPrefix } : {},
3470
- ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {},
3471
- ...entry.description !== void 0 ? { description: entry.description } : {}
3715
+ code,
3716
+ message,
3717
+ service: "delegation",
3718
+ cause,
3719
+ meta
3472
3720
  };
3473
3721
  }
3474
- function dedupeResources(resources) {
3475
- const byKey = /* @__PURE__ */ new Map();
3476
- for (const resource of resources) {
3477
- const key = `${resource.service}\0${resource.space}\0${resource.path}\0${resource.expiryMs ?? ""}`;
3478
- const existing = byKey.get(key);
3479
- if (existing === void 0) {
3480
- byKey.set(key, cloneResourceCapability(resource));
3481
- continue;
3722
+ var DelegationManager = class {
3723
+ /**
3724
+ * Creates a new DelegationManager instance.
3725
+ *
3726
+ * @param config - Configuration including hosts, session, and invoke function
3727
+ */
3728
+ constructor(config) {
3729
+ this.hosts = config.hosts;
3730
+ this.session = config.session;
3731
+ this.invoke = config.invoke;
3732
+ this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
3733
+ }
3734
+ /**
3735
+ * Updates the session (e.g., after re-authentication).
3736
+ *
3737
+ * @param session - New session to use for operations
3738
+ */
3739
+ updateSession(session) {
3740
+ this.session = session;
3741
+ }
3742
+ /**
3743
+ * Gets the primary host URL.
3744
+ */
3745
+ get host() {
3746
+ return this.hosts[0];
3747
+ }
3748
+ /**
3749
+ * Executes an invoke operation against the delegation API.
3750
+ */
3751
+ async invokeOperation(path, action, body) {
3752
+ const headers = this.invoke(this.session, "delegation", path, action);
3753
+ return this.fetchFn(`${this.host}/invoke`, {
3754
+ method: "POST",
3755
+ headers,
3756
+ body
3757
+ });
3758
+ }
3759
+ /**
3760
+ * Creates a new delegation.
3761
+ *
3762
+ * Delegates specific permissions to another DID for a given path.
3763
+ * The delegatee can then use these permissions to access resources
3764
+ * within the specified scope.
3765
+ *
3766
+ * @param params - Parameters for the delegation
3767
+ * @returns Result containing the created Delegation or an error
3768
+ *
3769
+ * @example
3770
+ * ```typescript
3771
+ * const result = await manager.create({
3772
+ * delegateDID: bob.did,
3773
+ * path: "documents/shared/",
3774
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
3775
+ * expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
3776
+ * });
3777
+ * ```
3778
+ */
3779
+ async create(params) {
3780
+ if (!params.delegateDID) {
3781
+ return {
3782
+ ok: false,
3783
+ error: createError(
3784
+ DelegationErrorCodes.INVALID_INPUT,
3785
+ "delegateDID is required"
3786
+ )
3787
+ };
3482
3788
  }
3483
- const seen = new Set(existing.actions);
3484
- for (const action of resource.actions) {
3485
- if (!seen.has(action)) {
3486
- existing.actions.push(action);
3487
- seen.add(action);
3789
+ if (!params.path) {
3790
+ return {
3791
+ ok: false,
3792
+ error: createError(
3793
+ DelegationErrorCodes.INVALID_INPUT,
3794
+ "path is required"
3795
+ )
3796
+ };
3797
+ }
3798
+ if (!params.actions || params.actions.length === 0) {
3799
+ return {
3800
+ ok: false,
3801
+ error: createError(
3802
+ DelegationErrorCodes.INVALID_INPUT,
3803
+ "at least one action is required"
3804
+ )
3805
+ };
3806
+ }
3807
+ try {
3808
+ const body = JSON.stringify({
3809
+ delegateDID: params.delegateDID,
3810
+ path: params.path,
3811
+ actions: params.actions,
3812
+ expiry: params.expiry?.toISOString(),
3813
+ disableSubDelegation: params.disableSubDelegation ?? false,
3814
+ statement: params.statement
3815
+ });
3816
+ const response = await this.invokeOperation(
3817
+ params.path,
3818
+ DelegationAction.CREATE,
3819
+ body
3820
+ );
3821
+ if (!response.ok) {
3822
+ const errorText = await response.text();
3823
+ return {
3824
+ ok: false,
3825
+ error: createError(
3826
+ DelegationErrorCodes.CREATION_FAILED,
3827
+ `Failed to create delegation: ${response.status} - ${errorText}`,
3828
+ void 0,
3829
+ { status: response.status, path: params.path }
3830
+ )
3831
+ };
3832
+ }
3833
+ const apiResponse = await response.json();
3834
+ const delegation = {
3835
+ cid: apiResponse.cid ?? "",
3836
+ delegateDID: params.delegateDID,
3837
+ spaceId: this.session.spaceId,
3838
+ path: params.path,
3839
+ actions: params.actions,
3840
+ expiry: params.expiry ?? new Date(Date.now() + EXPIRY.SHARE_MS),
3841
+ isRevoked: false,
3842
+ allowSubDelegation: !(params.disableSubDelegation ?? false),
3843
+ createdAt: /* @__PURE__ */ new Date()
3844
+ };
3845
+ return { ok: true, data: delegation };
3846
+ } catch (error) {
3847
+ if (error instanceof Error && error.name === "AbortError") {
3848
+ return {
3849
+ ok: false,
3850
+ error: createError(
3851
+ DelegationErrorCodes.ABORTED,
3852
+ "Request aborted",
3853
+ error
3854
+ )
3855
+ };
3856
+ }
3857
+ return {
3858
+ ok: false,
3859
+ error: createError(
3860
+ DelegationErrorCodes.NETWORK_ERROR,
3861
+ `Network error during delegation creation: ${String(error)}`,
3862
+ error instanceof Error ? error : void 0
3863
+ )
3864
+ };
3865
+ }
3866
+ }
3867
+ /**
3868
+ * Revokes an existing delegation.
3869
+ *
3870
+ * Once revoked, the delegation can no longer be used to access resources.
3871
+ * This also invalidates any sub-delegations derived from this delegation.
3872
+ *
3873
+ * @param cid - The CID of the delegation to revoke
3874
+ * @returns Result indicating success or an error
3875
+ *
3876
+ * @example
3877
+ * ```typescript
3878
+ * const result = await manager.revoke("bafy...");
3879
+ * if (result.ok) {
3880
+ * console.log("Delegation revoked successfully");
3881
+ * }
3882
+ * ```
3883
+ */
3884
+ async revoke(cid) {
3885
+ if (!cid) {
3886
+ return {
3887
+ ok: false,
3888
+ error: createError(
3889
+ DelegationErrorCodes.INVALID_INPUT,
3890
+ "cid is required"
3891
+ )
3892
+ };
3893
+ }
3894
+ try {
3895
+ const body = JSON.stringify({ cid });
3896
+ const response = await this.invokeOperation(
3897
+ cid,
3898
+ DelegationAction.REVOKE,
3899
+ body
3900
+ );
3901
+ if (!response.ok) {
3902
+ const errorText = await response.text();
3903
+ if (response.status === 404) {
3904
+ return {
3905
+ ok: false,
3906
+ error: createError(
3907
+ DelegationErrorCodes.NOT_FOUND,
3908
+ `Delegation not found: ${cid}`
3909
+ )
3910
+ };
3911
+ }
3912
+ return {
3913
+ ok: false,
3914
+ error: createError(
3915
+ DelegationErrorCodes.REVOCATION_FAILED,
3916
+ `Failed to revoke delegation: ${response.status} - ${errorText}`,
3917
+ void 0,
3918
+ { status: response.status, cid }
3919
+ )
3920
+ };
3488
3921
  }
3922
+ return { ok: true, data: void 0 };
3923
+ } catch (error) {
3924
+ if (error instanceof Error && error.name === "AbortError") {
3925
+ return {
3926
+ ok: false,
3927
+ error: createError(
3928
+ DelegationErrorCodes.ABORTED,
3929
+ "Request aborted",
3930
+ error
3931
+ )
3932
+ };
3933
+ }
3934
+ return {
3935
+ ok: false,
3936
+ error: createError(
3937
+ DelegationErrorCodes.NETWORK_ERROR,
3938
+ `Network error during delegation revocation: ${String(error)}`,
3939
+ error instanceof Error ? error : void 0
3940
+ )
3941
+ };
3489
3942
  }
3490
- if (existing.description === void 0 && resource.description !== void 0) {
3491
- existing.description = resource.description;
3492
- }
3493
- }
3494
- return [...byKey.values()];
3495
- }
3496
- function capabilitiesReadPermission(space) {
3497
- return {
3498
- service: "tinycloud.capabilities",
3499
- space,
3500
- path: "",
3501
- actions: ["tinycloud.capabilities/read"]
3502
- };
3503
- }
3504
- function withCapabilitiesReadForSpaces(resources) {
3505
- if (resources.length === 0) {
3506
- return [];
3507
- }
3508
- const spaces = new Set(
3509
- resources.filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE).map((resource) => resource.space)
3510
- );
3511
- return dedupeResources([
3512
- ...resources,
3513
- ...[...spaces].map(capabilitiesReadPermission)
3514
- ]);
3515
- }
3516
- function accountRegistryPermission() {
3517
- return {
3518
- service: "tinycloud.kv",
3519
- space: ACCOUNT_REGISTRY_SPACE,
3520
- path: ACCOUNT_REGISTRY_PATH,
3521
- actions: ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/list"]
3522
- };
3523
- }
3524
- function composeManifestRequest(inputs, options = {}) {
3525
- if (!Array.isArray(inputs) || inputs.length === 0) {
3526
- throw new ManifestValidationError(
3527
- "composeManifestRequest requires at least one manifest"
3528
- );
3529
- }
3530
- const includeAccountRegistryPermissions = options.includeAccountRegistryPermissions ?? true;
3531
- const manifests = inputs.map(validateManifest);
3532
- const resolved = manifests.map(resolveManifest);
3533
- const resources = resolved.flatMap((entry) => entry.resources);
3534
- const delegationTargets = resolved.flatMap(
3535
- (entry) => entry.additionalDelegates.map((delegate) => ({
3536
- ...delegate,
3537
- permissions: dedupeResources(delegate.permissions)
3538
- }))
3539
- );
3540
- if (includeAccountRegistryPermissions) {
3541
- resources.push(accountRegistryPermission());
3542
3943
  }
3543
- const resourcesWithImplicitCapabilities = withCapabilitiesReadForSpaces(resources);
3544
- const manifestsByAppId = /* @__PURE__ */ new Map();
3545
- for (const manifest of manifests) {
3546
- const current = manifestsByAppId.get(manifest.app_id);
3547
- if (current === void 0) {
3548
- manifestsByAppId.set(manifest.app_id, [manifest]);
3549
- } else {
3550
- current.push(manifest);
3944
+ /**
3945
+ * Lists all delegations for the current session's space.
3946
+ *
3947
+ * Returns both delegations created by the current user (as delegator)
3948
+ * and delegations granted to the current user (as delegatee).
3949
+ *
3950
+ * @returns Result containing an array of Delegations or an error
3951
+ *
3952
+ * @example
3953
+ * ```typescript
3954
+ * const result = await manager.list();
3955
+ * if (result.ok) {
3956
+ * for (const delegation of result.data) {
3957
+ * console.log(`${delegation.cid}: ${delegation.path} -> ${delegation.delegateDID}`);
3958
+ * }
3959
+ * }
3960
+ * ```
3961
+ */
3962
+ async list() {
3963
+ try {
3964
+ const response = await this.invokeOperation("", DelegationAction.LIST);
3965
+ if (!response.ok) {
3966
+ const errorText = await response.text();
3967
+ return {
3968
+ ok: false,
3969
+ error: createError(
3970
+ DelegationErrorCodes.NETWORK_ERROR,
3971
+ `Failed to list delegations: ${response.status} - ${errorText}`,
3972
+ void 0,
3973
+ { status: response.status }
3974
+ )
3975
+ };
3976
+ }
3977
+ const data = await response.json();
3978
+ const delegations = data.map((item) => ({
3979
+ cid: item.cid,
3980
+ delegateDID: item.delegateDID,
3981
+ delegatorDID: item.delegatorDID,
3982
+ spaceId: item.spaceId,
3983
+ path: item.path,
3984
+ actions: item.actions,
3985
+ expiry: new Date(item.expiry),
3986
+ isRevoked: item.isRevoked,
3987
+ createdAt: item.createdAt ? new Date(item.createdAt) : void 0,
3988
+ parentCid: item.parentCid,
3989
+ allowSubDelegation: item.allowSubDelegation
3990
+ }));
3991
+ return { ok: true, data: delegations };
3992
+ } catch (error) {
3993
+ if (error instanceof Error && error.name === "AbortError") {
3994
+ return {
3995
+ ok: false,
3996
+ error: createError(
3997
+ DelegationErrorCodes.ABORTED,
3998
+ "Request aborted",
3999
+ error
4000
+ )
4001
+ };
4002
+ }
4003
+ return {
4004
+ ok: false,
4005
+ error: createError(
4006
+ DelegationErrorCodes.NETWORK_ERROR,
4007
+ `Network error during delegation list: ${String(error)}`,
4008
+ error instanceof Error ? error : void 0
4009
+ )
4010
+ };
3551
4011
  }
3552
4012
  }
3553
- const registryRecords = includeAccountRegistryPermissions ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({
3554
- key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,
3555
- app_id,
3556
- manifests: appManifests.map((manifest) => ({
3557
- ...manifest,
3558
- permissions: manifest.permissions?.map(clonePermissionEntry)
3559
- }))
3560
- })) : [];
3561
- return {
3562
- manifests,
3563
- resources: resourcesWithImplicitCapabilities,
3564
- delegationTargets,
3565
- registryRecords,
3566
- expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),
3567
- includePublicSpace: resolved.some((entry) => entry.includePublicSpace)
3568
- };
3569
- }
3570
- function resourceCapabilitiesToAbilitiesMap(resources) {
3571
- const out = {};
3572
- for (const r of resources) {
3573
- const shortService = SERVICE_LONG_TO_SHORT[r.service];
3574
- if (shortService === void 0) {
3575
- throw new ManifestValidationError(
3576
- `unknown service '${r.service}' \u2014 no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(", ")}`
4013
+ /**
4014
+ * Gets the full delegation chain for a given delegation.
4015
+ *
4016
+ * Returns the chain of delegations from the root (original delegator)
4017
+ * to the specified delegation, including all intermediate sub-delegations.
4018
+ *
4019
+ * @param cid - The CID of the delegation to get the chain for
4020
+ * @returns Result containing the DelegationChain or an error
4021
+ *
4022
+ * @example
4023
+ * ```typescript
4024
+ * const result = await manager.getChain("bafy...");
4025
+ * if (result.ok) {
4026
+ * console.log("Chain length:", result.data.length);
4027
+ * for (const delegation of result.data) {
4028
+ * console.log(`- ${delegation.delegatorDID} -> ${delegation.delegateDID}`);
4029
+ * }
4030
+ * }
4031
+ * ```
4032
+ */
4033
+ async getChain(cid) {
4034
+ if (!cid) {
4035
+ return {
4036
+ ok: false,
4037
+ error: createError(
4038
+ DelegationErrorCodes.INVALID_INPUT,
4039
+ "cid is required"
4040
+ )
4041
+ };
4042
+ }
4043
+ try {
4044
+ const body = JSON.stringify({ cid, includeChain: true });
4045
+ const response = await this.invokeOperation(
4046
+ cid,
4047
+ DelegationAction.GET,
4048
+ body
3577
4049
  );
4050
+ if (!response.ok) {
4051
+ const errorText = await response.text();
4052
+ if (response.status === 404) {
4053
+ return {
4054
+ ok: false,
4055
+ error: createError(
4056
+ DelegationErrorCodes.NOT_FOUND,
4057
+ `Delegation not found: ${cid}`
4058
+ )
4059
+ };
4060
+ }
4061
+ return {
4062
+ ok: false,
4063
+ error: createError(
4064
+ DelegationErrorCodes.NETWORK_ERROR,
4065
+ `Failed to get delegation chain: ${response.status} - ${errorText}`,
4066
+ void 0,
4067
+ { status: response.status, cid }
4068
+ )
4069
+ };
4070
+ }
4071
+ const data = await response.json();
4072
+ const chain = data.chain.map((item) => ({
4073
+ cid: item.cid,
4074
+ delegateDID: item.delegateDID,
4075
+ delegatorDID: item.delegatorDID,
4076
+ spaceId: item.spaceId,
4077
+ path: item.path,
4078
+ actions: item.actions,
4079
+ expiry: new Date(item.expiry),
4080
+ isRevoked: item.isRevoked,
4081
+ createdAt: item.createdAt ? new Date(item.createdAt) : void 0,
4082
+ parentCid: item.parentCid,
4083
+ allowSubDelegation: item.allowSubDelegation
4084
+ }));
4085
+ return { ok: true, data: chain };
4086
+ } catch (error) {
4087
+ if (error instanceof Error && error.name === "AbortError") {
4088
+ return {
4089
+ ok: false,
4090
+ error: createError(
4091
+ DelegationErrorCodes.ABORTED,
4092
+ "Request aborted",
4093
+ error
4094
+ )
4095
+ };
4096
+ }
4097
+ return {
4098
+ ok: false,
4099
+ error: createError(
4100
+ DelegationErrorCodes.NETWORK_ERROR,
4101
+ `Network error during chain retrieval: ${String(error)}`,
4102
+ error instanceof Error ? error : void 0
4103
+ )
4104
+ };
3578
4105
  }
3579
- if (out[shortService] === void 0) {
3580
- out[shortService] = {};
4106
+ }
4107
+ /**
4108
+ * Checks if the current session has permission for a given path and action.
4109
+ *
4110
+ * This can be used to verify permissions before attempting an operation,
4111
+ * or to implement custom access control logic.
4112
+ *
4113
+ * @param path - The resource path to check
4114
+ * @param action - The action to check (e.g., "tinycloud.kv/get")
4115
+ * @returns Result containing a boolean indicating permission or an error
4116
+ *
4117
+ * @example
4118
+ * ```typescript
4119
+ * const result = await manager.checkPermission("documents/private/", "tinycloud.kv/put");
4120
+ * if (result.ok && result.data) {
4121
+ * console.log("Permission granted");
4122
+ * } else {
4123
+ * console.log("Permission denied");
4124
+ * }
4125
+ * ```
4126
+ */
4127
+ async checkPermission(path, action) {
4128
+ if (!path) {
4129
+ return {
4130
+ ok: false,
4131
+ error: createError(
4132
+ DelegationErrorCodes.INVALID_INPUT,
4133
+ "path is required"
4134
+ )
4135
+ };
3581
4136
  }
3582
- const pathsMap = out[shortService];
3583
- const existing = pathsMap[r.path];
3584
- if (existing === void 0) {
3585
- pathsMap[r.path] = [...r.actions];
3586
- } else {
3587
- const seen = new Set(existing);
3588
- for (const action of r.actions) {
3589
- if (!seen.has(action)) {
3590
- existing.push(action);
3591
- seen.add(action);
4137
+ if (!action) {
4138
+ return {
4139
+ ok: false,
4140
+ error: createError(
4141
+ DelegationErrorCodes.INVALID_INPUT,
4142
+ "action is required"
4143
+ )
4144
+ };
4145
+ }
4146
+ try {
4147
+ const body = JSON.stringify({ path, action });
4148
+ const response = await this.invokeOperation(
4149
+ path,
4150
+ DelegationAction.CHECK,
4151
+ body
4152
+ );
4153
+ if (!response.ok) {
4154
+ if (response.status === 403) {
4155
+ return { ok: true, data: false };
3592
4156
  }
4157
+ const errorText = await response.text();
4158
+ return {
4159
+ ok: false,
4160
+ error: createError(
4161
+ DelegationErrorCodes.NETWORK_ERROR,
4162
+ `Failed to check permission: ${response.status} - ${errorText}`,
4163
+ void 0,
4164
+ { status: response.status, path, action }
4165
+ )
4166
+ };
3593
4167
  }
4168
+ const data = await response.json();
4169
+ return { ok: true, data: data.allowed };
4170
+ } catch (error) {
4171
+ if (error instanceof Error && error.name === "AbortError") {
4172
+ return {
4173
+ ok: false,
4174
+ error: createError(
4175
+ DelegationErrorCodes.ABORTED,
4176
+ "Request aborted",
4177
+ error
4178
+ )
4179
+ };
4180
+ }
4181
+ return {
4182
+ ok: false,
4183
+ error: createError(
4184
+ DelegationErrorCodes.NETWORK_ERROR,
4185
+ `Network error during permission check: ${String(error)}`,
4186
+ error instanceof Error ? error : void 0
4187
+ )
4188
+ };
3594
4189
  }
3595
4190
  }
3596
- return out;
3597
- }
3598
- function resourceCapabilitiesToSpaceAbilitiesMap(resources) {
3599
- const grouped = /* @__PURE__ */ new Map();
3600
- for (const resource of resources) {
3601
- const entries = grouped.get(resource.space);
3602
- if (entries === void 0) {
3603
- grouped.set(resource.space, [resource]);
3604
- } else {
3605
- entries.push(resource);
3606
- }
3607
- }
3608
- const out = {};
3609
- for (const [space, entries] of grouped.entries()) {
3610
- out[space] = resourceCapabilitiesToAbilitiesMap(entries);
3611
- }
3612
- return out;
3613
- }
3614
- function manifestAbilitiesUnion(resolved) {
3615
- const all = [...resolved.resources];
3616
- for (const delegate of resolved.additionalDelegates) {
3617
- for (const perm of delegate.permissions) {
3618
- all.push(perm);
3619
- }
4191
+ };
4192
+
4193
+ // src/delegations/SharingService.schema.ts
4194
+ import { z as z5 } from "zod";
4195
+ var EncodedShareDataSchema = z5.object({
4196
+ /** Private key in JWK format (must include d parameter) */
4197
+ key: JWKSchema.refine(
4198
+ (jwk) => typeof jwk.d === "string" && jwk.d.length > 0,
4199
+ { message: "JWK must include private key (d parameter)" }
4200
+ ),
4201
+ /** DID of the key */
4202
+ keyDid: z5.string().min(1, "keyDid is required"),
4203
+ /** The delegation granting access */
4204
+ delegation: DelegationSchema,
4205
+ /** Resource path this link grants access to */
4206
+ path: z5.string().min(1, "path is required"),
4207
+ /** TinyCloud host URL */
4208
+ host: z5.string().url("host must be a valid URL"),
4209
+ /** Space ID */
4210
+ spaceId: z5.string().min(1, "spaceId is required"),
4211
+ /** Schema version (must be 1) */
4212
+ version: z5.literal(1)
4213
+ });
4214
+ var ReceiveOptionsSchema = z5.object({
4215
+ /**
4216
+ * Whether to automatically create a sub-delegation to the current session key.
4217
+ * Default: true
4218
+ */
4219
+ autoSubdelegate: z5.boolean().optional(),
4220
+ /**
4221
+ * Whether to use the current session key for operations (requires autoSubdelegate).
4222
+ * Default: true
4223
+ */
4224
+ useSessionKey: z5.boolean().optional(),
4225
+ /**
4226
+ * Ingestion options passed to CapabilityKeyRegistry.
4227
+ */
4228
+ ingestOptions: IngestOptionsSchema.optional()
4229
+ });
4230
+ var SharingServiceConfigSchema = z5.object({
4231
+ /** TinyCloud host URLs */
4232
+ hosts: z5.array(z5.string().url()).min(1, "At least one host URL is required"),
4233
+ /**
4234
+ * Active session for authentication.
4235
+ * Required for generate(), optional for receive().
4236
+ */
4237
+ session: z5.unknown().refine(
4238
+ (val) => val === void 0 || val !== null && typeof val === "object",
4239
+ { message: "Expected a ServiceSession object or undefined" }
4240
+ ).optional(),
4241
+ /** Platform-specific invoke function */
4242
+ invoke: z5.unknown().refine((val) => typeof val === "function", {
4243
+ message: "Expected an invoke function"
4244
+ }),
4245
+ /** Optional custom fetch implementation */
4246
+ fetch: z5.unknown().refine(
4247
+ (val) => val === void 0 || typeof val === "function",
4248
+ { message: "Expected a fetch function or undefined" }
4249
+ ).optional(),
4250
+ /** Key provider for cryptographic operations */
4251
+ keyProvider: KeyProviderSchema,
4252
+ /** Capability key registry for key/delegation management */
4253
+ registry: z5.unknown().refine(
4254
+ (val) => val !== null && typeof val === "object",
4255
+ { message: "Expected an ICapabilityKeyRegistry object" }
4256
+ ),
4257
+ /**
4258
+ * Delegation manager for creating delegations.
4259
+ * Required for generate(), optional for receive().
4260
+ */
4261
+ delegationManager: z5.unknown().refine(
4262
+ (val) => val === void 0 || val !== null && typeof val === "object",
4263
+ { message: "Expected a DelegationManager object or undefined" }
4264
+ ).optional(),
4265
+ /** Factory for creating KV service instances */
4266
+ createKVService: z5.unknown().refine(
4267
+ (val) => typeof val === "function",
4268
+ { message: "Expected a createKVService factory function" }
4269
+ ),
4270
+ /** Base URL for sharing links (e.g., "https://share.myapp.com") */
4271
+ baseUrl: z5.string().optional(),
4272
+ /**
4273
+ * Custom delegation creation function.
4274
+ */
4275
+ createDelegation: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
4276
+ message: "Expected a createDelegation function or undefined"
4277
+ }).optional(),
4278
+ /**
4279
+ * WASM function for client-side delegation creation.
4280
+ */
4281
+ createDelegationWasm: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
4282
+ message: "Expected a createDelegationWasm function or undefined"
4283
+ }).optional(),
4284
+ /**
4285
+ * Path prefix for KV operations.
4286
+ */
4287
+ pathPrefix: z5.string().optional(),
4288
+ /**
4289
+ * Session expiry time.
4290
+ */
4291
+ sessionExpiry: z5.date().optional(),
4292
+ /**
4293
+ * Callback to create a DIRECT delegation from wallet to share key.
4294
+ * This is the preferred method for long-lived share links because it
4295
+ * bypasses the session delegation chain entirely.
4296
+ */
4297
+ onRootDelegationNeeded: z5.unknown().refine((val) => val === void 0 || typeof val === "function", {
4298
+ message: "Expected an onRootDelegationNeeded function or undefined"
4299
+ }).optional()
4300
+ });
4301
+ function validateEncodedShareData(data) {
4302
+ const result = EncodedShareDataSchema.safeParse(data);
4303
+ if (!result.success) {
4304
+ return {
4305
+ ok: false,
4306
+ error: {
4307
+ code: DelegationErrorCodes.VALIDATION_ERROR,
4308
+ message: `Invalid share data: ${result.error.message}`,
4309
+ service: "delegation",
4310
+ meta: { issues: result.error.issues }
4311
+ }
4312
+ };
3620
4313
  }
3621
- return resourceCapabilitiesToAbilitiesMap(all);
4314
+ return { ok: true, data: result.data };
3622
4315
  }
3623
4316
 
3624
4317
  // src/delegations/SharingService.ts
@@ -3799,13 +4492,13 @@ var SharingService = class {
3799
4492
  )
3800
4493
  };
3801
4494
  }
3802
- } catch (err5) {
4495
+ } catch (err6) {
3803
4496
  return {
3804
4497
  ok: false,
3805
4498
  error: createError2(
3806
4499
  DelegationErrorCodes.CREATION_FAILED,
3807
- `Failed to generate session key for share: ${err5 instanceof Error ? err5.message : String(err5)}`,
3808
- err5 instanceof Error ? err5 : void 0
4500
+ `Failed to generate session key for share: ${err6 instanceof Error ? err6.message : String(err6)}`,
4501
+ err6 instanceof Error ? err6 : void 0
3809
4502
  )
3810
4503
  };
3811
4504
  }
@@ -3851,7 +4544,7 @@ var SharingService = class {
3851
4544
  }
3852
4545
  delegation = parsed;
3853
4546
  }
3854
- } catch (err5) {
4547
+ } catch (err6) {
3855
4548
  const fallbackResult = await this.handleSessionExtensionFallback(requestedExpiry);
3856
4549
  expiry = fallbackResult.expiry;
3857
4550
  const delegationResult = await this.createSessionDelegation(plainDID, fullPath, actions, expiry);
@@ -4049,13 +4742,13 @@ var SharingService = class {
4049
4742
  allowSubDelegation: true,
4050
4743
  createdAt: /* @__PURE__ */ new Date()
4051
4744
  };
4052
- } catch (err5) {
4745
+ } catch (err6) {
4053
4746
  return {
4054
4747
  ok: false,
4055
4748
  error: createError2(
4056
4749
  DelegationErrorCodes.CREATION_FAILED,
4057
- `Failed to create delegation via WASM: ${err5 instanceof Error ? err5.message : String(err5)}`,
4058
- err5 instanceof Error ? err5 : void 0
4750
+ `Failed to create delegation via WASM: ${err6 instanceof Error ? err6.message : String(err6)}`,
4751
+ err6 instanceof Error ? err6 : void 0
4059
4752
  )
4060
4753
  };
4061
4754
  }
@@ -4136,8 +4829,8 @@ var SharingService = class {
4136
4829
  let activeKey = keyInfo;
4137
4830
  if (autoSubdelegate && useSessionKey && this.session) {
4138
4831
  try {
4139
- } catch (err5) {
4140
- console.warn("Auto-subdelegation failed, using ingested key directly:", err5);
4832
+ } catch (err6) {
4833
+ console.warn("Auto-subdelegation failed, using ingested key directly:", err6);
4141
4834
  }
4142
4835
  }
4143
4836
  const authHeader = shareData.delegation.authHeader ?? `Bearer ${shareData.delegation.cid}`;
@@ -4235,26 +4928,26 @@ var SharingService = class {
4235
4928
  let jsonString;
4236
4929
  try {
4237
4930
  jsonString = base64UrlDecode(base64Data);
4238
- } catch (err5) {
4931
+ } catch (err6) {
4239
4932
  return {
4240
4933
  ok: false,
4241
4934
  error: createError2(
4242
4935
  DelegationErrorCodes.INVALID_TOKEN,
4243
- `Failed to decode base64 data: ${err5 instanceof Error ? err5.message : String(err5)}`,
4244
- err5 instanceof Error ? err5 : void 0
4936
+ `Failed to decode base64 data: ${err6 instanceof Error ? err6.message : String(err6)}`,
4937
+ err6 instanceof Error ? err6 : void 0
4245
4938
  )
4246
4939
  };
4247
4940
  }
4248
4941
  let parsed;
4249
4942
  try {
4250
4943
  parsed = JSON.parse(jsonString);
4251
- } catch (err5) {
4944
+ } catch (err6) {
4252
4945
  return {
4253
4946
  ok: false,
4254
4947
  error: createError2(
4255
4948
  DelegationErrorCodes.INVALID_TOKEN,
4256
- `Failed to parse share data JSON: ${err5 instanceof Error ? err5.message : String(err5)}`,
4257
- err5 instanceof Error ? err5 : void 0
4949
+ `Failed to parse share data JSON: ${err6 instanceof Error ? err6.message : String(err6)}`,
4950
+ err6 instanceof Error ? err6 : void 0
4258
4951
  )
4259
4952
  };
4260
4953
  }
@@ -4281,8 +4974,8 @@ function createSharingService(config) {
4281
4974
  }
4282
4975
 
4283
4976
  // src/authorization/CapabilityKeyRegistry.ts
4284
- import { ok as ok3, err as err3, serviceError as serviceError3 } from "@tinycloud/sdk-services";
4285
- var SERVICE_NAME2 = "capability-key-registry";
4977
+ import { ok as ok4, err as err4, serviceError as serviceError4 } from "@tinycloud/sdk-services";
4978
+ var SERVICE_NAME3 = "capability-key-registry";
4286
4979
  var CapabilityKeyRegistryErrorCodes = {
4287
4980
  /** Key not found in registry */
4288
4981
  KEY_NOT_FOUND: "KEY_NOT_FOUND",
@@ -4499,11 +5192,11 @@ var CapabilityKeyRegistry = class {
4499
5192
  revokeDelegation(cid) {
4500
5193
  const stored = this.store.byCid.get(cid);
4501
5194
  if (!stored) {
4502
- return err3(
4503
- serviceError3(
5195
+ return err4(
5196
+ serviceError4(
4504
5197
  CapabilityKeyRegistryErrorCodes.KEY_NOT_FOUND,
4505
5198
  `Delegation not found: ${cid}`,
4506
- SERVICE_NAME2
5199
+ SERVICE_NAME3
4507
5200
  )
4508
5201
  );
4509
5202
  }
@@ -4522,7 +5215,7 @@ var CapabilityKeyRegistry = class {
4522
5215
  }
4523
5216
  }
4524
5217
  }
4525
- return ok3(void 0);
5218
+ return ok4(void 0);
4526
5219
  }
4527
5220
  // ===========================================================================
4528
5221
  // Search
@@ -4751,8 +5444,8 @@ async function checkNodeInfo(host, sdkProtocol, fetchFn = globalThis.fetch.bind(
4751
5444
  response = await fetchFn(`${host}/info`, {
4752
5445
  signal: AbortSignal.timeout(5e3)
4753
5446
  });
4754
- } catch (err5) {
4755
- throw new VersionCheckError(host, err5);
5447
+ } catch (err6) {
5448
+ throw new VersionCheckError(host, err6);
4756
5449
  }
4757
5450
  if (!response.ok) {
4758
5451
  throw new VersionCheckError(host);
@@ -5284,6 +5977,7 @@ function parseRecapCapabilities(parseWasm, siwe) {
5284
5977
  export {
5285
5978
  ACCOUNT_REGISTRY_PATH,
5286
5979
  ACCOUNT_REGISTRY_SPACE,
5980
+ AccountService,
5287
5981
  AutoApproveSpaceCreationHandler,
5288
5982
  CapabilityKeyRegistry,
5289
5983
  CapabilityKeyRegistryErrorCodes,
@@ -5389,7 +6083,7 @@ export {
5389
6083
  utf8Decode as encryptionUtf8Decode,
5390
6084
  utf8Encode as encryptionUtf8Encode,
5391
6085
  ensureNetworkUsableForDecrypt,
5392
- err4 as err,
6086
+ err5 as err,
5393
6087
  expandActionShortNames,
5394
6088
  expandPermissionEntries,
5395
6089
  expandPermissionEntry,
@@ -5410,7 +6104,7 @@ export {
5410
6104
  multiaddrToHttpUrl,
5411
6105
  networkDiscoveryKey,
5412
6106
  normalizeDefaults,
5413
- ok4 as ok,
6107
+ ok5 as ok,
5414
6108
  openWrappedKey,
5415
6109
  parseCanonicalNetworkId,
5416
6110
  parseExpiry,
@@ -5428,7 +6122,7 @@ export {
5428
6122
  resolveTinyCloudHosts,
5429
6123
  resourceCapabilitiesToAbilitiesMap,
5430
6124
  resourceCapabilitiesToSpaceAbilitiesMap,
5431
- serviceError4 as serviceError,
6125
+ serviceError5 as serviceError,
5432
6126
  signLocationRecord,
5433
6127
  submitHostDelegation,
5434
6128
  validateClientSession,