@tinycloud/sdk-core 2.4.0-beta.9 → 2.5.0-beta.1

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.cjs CHANGED
@@ -30,10 +30,21 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ACCOUNT_INDEX_SCHEMA: () => import_bootstrap2.ACCOUNT_INDEX_SCHEMA,
33
34
  ACCOUNT_REGISTRY_PATH: () => ACCOUNT_REGISTRY_PATH,
34
35
  ACCOUNT_REGISTRY_SPACE: () => ACCOUNT_REGISTRY_SPACE,
35
36
  AccountService: () => AccountService,
36
37
  AutoApproveSpaceCreationHandler: () => AutoApproveSpaceCreationHandler,
38
+ BOOTSTRAP_ALLOWLIST: () => import_bootstrap2.BOOTSTRAP_ALLOWLIST,
39
+ BOOTSTRAP_DEFAULT_SPACE: () => import_bootstrap2.BOOTSTRAP_DEFAULT_SPACE,
40
+ BOOTSTRAP_ENCRYPTION_NETWORK_NAME: () => import_bootstrap2.BOOTSTRAP_ENCRYPTION_NETWORK_NAME,
41
+ BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE: () => import_bootstrap2.BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE,
42
+ BOOTSTRAP_MANIFEST: () => import_bootstrap2.BOOTSTRAP_MANIFEST,
43
+ BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS: () => import_bootstrap2.BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS,
44
+ BOOTSTRAP_PUBLIC_SPACE: () => import_bootstrap2.BOOTSTRAP_PUBLIC_SPACE,
45
+ BOOTSTRAP_SESSION_REQUESTS: () => import_bootstrap2.BOOTSTRAP_SESSION_REQUESTS,
46
+ BOOTSTRAP_SPACE_MANIFESTS: () => import_bootstrap2.BOOTSTRAP_SPACE_MANIFESTS,
47
+ BOOTSTRAP_SPACE_NAMES: () => import_bootstrap2.BOOTSTRAP_SPACE_NAMES,
37
48
  CapabilityKeyRegistry: () => CapabilityKeyRegistry,
38
49
  CapabilityKeyRegistryErrorCodes: () => CapabilityKeyRegistryErrorCodes,
39
50
  ClientSessionSchema: () => ClientSessionSchema,
@@ -45,6 +56,7 @@ __export(index_exports, {
45
56
  DEFAULT_ENCRYPTION_ALG: () => import_sdk_services7.DEFAULT_ENCRYPTION_ALG,
46
57
  DEFAULT_EXPIRY: () => DEFAULT_EXPIRY,
47
58
  DEFAULT_KEY_VERSION: () => import_sdk_services7.DEFAULT_KEY_VERSION,
59
+ DEFAULT_KNOWLEDGE_ROOT: () => DEFAULT_KNOWLEDGE_ROOT,
48
60
  DEFAULT_MANIFEST_SPACE: () => DEFAULT_MANIFEST_SPACE,
49
61
  DEFAULT_MANIFEST_VERSION: () => DEFAULT_MANIFEST_VERSION,
50
62
  DEFAULT_SIGNED_READ_URL_EXPIRY_MS: () => DEFAULT_SIGNED_READ_URL_EXPIRY_MS,
@@ -77,7 +89,9 @@ __export(index_exports, {
77
89
  PermissionNotInManifestError: () => PermissionNotInManifestError,
78
90
  PrefixedKVService: () => import_sdk_services7.PrefixedKVService,
79
91
  ProtocolMismatchError: () => ProtocolMismatchError,
92
+ SECRETS_SPACE: () => SECRETS_SPACE,
80
93
  SECRET_NAME_RE: () => import_sdk_services7.SECRET_NAME_RE,
94
+ SECRET_RECORDS_SCHEMA: () => import_bootstrap2.SECRET_RECORDS_SCHEMA,
81
95
  SERVICE_LONG_TO_SHORT: () => SERVICE_LONG_TO_SHORT,
82
96
  SERVICE_SHORT_TO_LONG: () => SERVICE_SHORT_TO_LONG,
83
97
  SQLAction: () => import_sdk_services7.SQLAction,
@@ -92,7 +106,13 @@ __export(index_exports, {
92
106
  Space: () => Space,
93
107
  SpaceErrorCodes: () => SpaceErrorCodes,
94
108
  SpaceService: () => SpaceService,
109
+ TINYCLOUD_ACCOUNT_SPACE_MANIFEST: () => import_bootstrap2.TINYCLOUD_ACCOUNT_SPACE_MANIFEST,
110
+ TINYCLOUD_APPLICATIONS_SPACE_MANIFEST: () => import_bootstrap2.TINYCLOUD_APPLICATIONS_SPACE_MANIFEST,
111
+ TINYCLOUD_DEFAULT_SPACE_MANIFEST: () => import_bootstrap2.TINYCLOUD_DEFAULT_SPACE_MANIFEST,
112
+ TINYCLOUD_PUBLIC_SPACE_MANIFEST: () => import_bootstrap2.TINYCLOUD_PUBLIC_SPACE_MANIFEST,
113
+ TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST: () => import_bootstrap2.TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,
95
114
  TinyCloud: () => TinyCloud,
115
+ TinyCloudDebugLogger: () => import_sdk_services7.TinyCloudDebugLogger,
96
116
  UnsupportedFeatureError: () => UnsupportedFeatureError,
97
117
  VAULT_PERMISSION_SERVICE: () => VAULT_PERMISSION_SERVICE,
98
118
  VaultHeaders: () => import_sdk_services7.VaultHeaders,
@@ -101,6 +121,9 @@ __export(index_exports, {
101
121
  activateSessionWithHost: () => activateSessionWithHost,
102
122
  addressStorageKey: () => addressStorageKey,
103
123
  applyPrefix: () => applyPrefix,
124
+ bootstrapEncryptionNetworkId: () => import_bootstrap2.bootstrapEncryptionNetworkId,
125
+ bootstrapSpaceId: () => import_bootstrap2.bootstrapSpaceId,
126
+ bootstrapSteps: () => import_bootstrap2.bootstrapSteps,
104
127
  buildCanonicalDecryptRequest: () => import_sdk_services7.buildCanonicalDecryptRequest,
105
128
  buildDecryptAttenuation: () => import_sdk_services7.buildDecryptAttenuation,
106
129
  buildDecryptFacts: () => import_sdk_services7.buildDecryptFacts,
@@ -118,8 +141,11 @@ __export(index_exports, {
118
141
  canonicalizeSecretScope: () => import_sdk_services7.canonicalizeSecretScope,
119
142
  checkDecryptInvocationInput: () => import_sdk_services7.checkDecryptInvocationInput,
120
143
  checkNodeInfo: () => checkNodeInfo,
144
+ clearTinyCloudDebugLogs: () => import_sdk_services7.clearTinyCloudDebugLogs,
145
+ composeBootstrapSpaceManifest: () => import_bootstrap2.composeBootstrapSpaceManifest,
121
146
  composeManifestRequest: () => composeManifestRequest,
122
147
  createCapabilityKeyRegistry: () => createCapabilityKeyRegistry,
148
+ createOpenKeyCallbackSigningStrategy: () => createOpenKeyCallbackSigningStrategy,
123
149
  createSharingService: () => createSharingService,
124
150
  createSpaceService: () => createSpaceService,
125
151
  createVaultCrypto: () => import_sdk_services7.createVaultCrypto,
@@ -130,7 +156,9 @@ __export(index_exports, {
130
156
  deriveSignedReceiverKey: () => import_sdk_services7.deriveSignedReceiverKey,
131
157
  didCacheKey: () => didCacheKey,
132
158
  didEquals: () => didEquals,
159
+ disableTinyCloudDebug: () => import_sdk_services7.disableTinyCloudDebug,
133
160
  discoverNetwork: () => import_sdk_services7.discoverNetwork,
161
+ enableTinyCloudDebug: () => import_sdk_services7.enableTinyCloudDebug,
134
162
  encryptToNetwork: () => import_sdk_services7.encryptToNetwork,
135
163
  encryptionBase64Decode: () => import_sdk_services7.base64Decode,
136
164
  encryptionBase64Encode: () => import_sdk_services7.base64Encode,
@@ -145,9 +173,11 @@ __export(index_exports, {
145
173
  fetchLocationRecord: () => fetchLocationRecord,
146
174
  fetchPeerId: () => fetchPeerId,
147
175
  generateRandomReceiverKey: () => import_sdk_services7.generateRandomReceiverKey,
176
+ getTinyCloudDebugLogs: () => import_sdk_services7.getTinyCloudDebugLogs,
148
177
  hexDecode: () => import_sdk_services7.hexDecode,
149
178
  hexEncode: () => import_sdk_services7.hexEncode,
150
179
  httpUrlToMultiaddr: () => httpUrlToMultiaddr,
180
+ installTinyCloudDebugGlobals: () => import_sdk_services7.installTinyCloudDebugGlobals,
151
181
  isCapabilitySubset: () => isCapabilitySubset,
152
182
  isEvmAddress: () => isEvmAddress,
153
183
  isNetworkId: () => import_sdk_services7.isNetworkId,
@@ -172,6 +202,7 @@ __export(index_exports, {
172
202
  principalDidEquals: () => principalDidEquals,
173
203
  resolveCloudLocation: () => resolveCloudLocation,
174
204
  resolveManifest: () => resolveManifest,
205
+ resolveManifestKnowledgeRoot: () => resolveManifestKnowledgeRoot,
175
206
  resolveSecretListPrefix: () => import_sdk_services7.resolveSecretListPrefix,
176
207
  resolveSecretPath: () => import_sdk_services7.resolveSecretPath,
177
208
  resolveTinyCloudHosts: () => resolveTinyCloudHosts,
@@ -180,6 +211,7 @@ __export(index_exports, {
180
211
  serviceError: () => import_sdk_services7.serviceError,
181
212
  signLocationRecord: () => signLocationRecord,
182
213
  submitHostDelegation: () => submitHostDelegation,
214
+ tinyCloudDebugLogger: () => import_sdk_services7.tinyCloudDebugLogger,
183
215
  validateClientSession: () => validateClientSession,
184
216
  validateEnvelope: () => import_sdk_services7.validateEnvelope,
185
217
  validateLocationRecord: () => validateLocationRecord,
@@ -379,7 +411,15 @@ var PersistedSessionDataSchema = import_zod2.z.object({
379
411
  /** Schema version for migrations */
380
412
  version: import_zod2.z.string(),
381
413
  /** Optional ENS data */
382
- ens: EnsDataSchema2.optional()
414
+ ens: EnsDataSchema2.optional(),
415
+ /**
416
+ * TinyCloud hosts this session was created against. Persisted so a
417
+ * restored session resolves to the same node without re-running the
418
+ * registry/fallback resolution (or the wallet sign-in flow). Optional
419
+ * for backward compatibility with sessions persisted before this field
420
+ * existed — those restore and lazily re-resolve their hosts.
421
+ */
422
+ tinycloudHosts: import_zod2.z.array(import_zod2.z.string()).optional()
383
423
  });
384
424
  var TinyCloudSessionSchema = import_zod2.z.object({
385
425
  /** User's Ethereum address */
@@ -430,6 +470,15 @@ var import_sdk_services3 = require("@tinycloud/sdk-services");
430
470
  var import_sdk_services2 = require("@tinycloud/sdk-services");
431
471
 
432
472
  // src/spaces/Space.ts
473
+ function unavailableSecretsService() {
474
+ return new Proxy({}, {
475
+ get: () => {
476
+ throw new Error(
477
+ "Secrets service factory not configured. Provide createSecrets in SpaceConfig."
478
+ );
479
+ }
480
+ });
481
+ }
433
482
  var Space = class {
434
483
  /**
435
484
  * Create a new Space instance.
@@ -441,6 +490,7 @@ var Space = class {
441
490
  this._name = config.name;
442
491
  this._kv = config.createKV(config.id);
443
492
  this._vault = config.createVault(config.id);
493
+ this._secrets = config.createSecrets?.(config.id) ?? unavailableSecretsService();
444
494
  this._delegations = config.createDelegations(config.id);
445
495
  this._sharing = config.createSharing(config.id);
446
496
  this._getInfo = config.getInfo;
@@ -469,6 +519,12 @@ var Space = class {
469
519
  get vault() {
470
520
  return this._vault;
471
521
  }
522
+ /**
523
+ * Secrets operations scoped to this space.
524
+ */
525
+ get secrets() {
526
+ return this._secrets;
527
+ }
472
528
  /**
473
529
  * Delegation operations scoped to this space.
474
530
  */
@@ -854,6 +910,8 @@ var SpaceConfigSchema = import_zod4.z.object({
854
910
  createKV: import_zod4.z.function(),
855
911
  /** Factory function to create a space-scoped Data Vault service */
856
912
  createVault: import_zod4.z.function(),
913
+ /** Optional factory function to create a space-scoped secrets service */
914
+ createSecrets: import_zod4.z.function().optional(),
857
915
  /** Factory function to create space-scoped delegations */
858
916
  createDelegations: import_zod4.z.function(),
859
917
  /** Factory function to create space-scoped sharing */
@@ -876,6 +934,8 @@ var SpaceServiceConfigSchema = import_zod4.z.object({
876
934
  createKVService: import_zod4.z.function().optional(),
877
935
  /** Factory function to create a space-scoped Data Vault service */
878
936
  createVaultService: import_zod4.z.function().optional(),
937
+ /** Factory function to create a space-scoped secrets service */
938
+ createSecretsService: import_zod4.z.function().optional(),
879
939
  /** User's PKH DID (derived from address or provided explicitly) */
880
940
  userDid: import_zod4.z.string().optional(),
881
941
  /** Optional SharingService for v2 sharing links (client-side) */
@@ -1148,6 +1208,7 @@ var SpaceService = class {
1148
1208
  this.capabilityRegistry = config.capabilityRegistry;
1149
1209
  this.createKVServiceFn = config.createKVService;
1150
1210
  this.createVaultServiceFn = config.createVaultService;
1211
+ this.createSecretsServiceFn = config.createSecretsService;
1151
1212
  this._userDid = config.userDid;
1152
1213
  this.sharingService = config.sharingService;
1153
1214
  this.createDelegationFn = config.createDelegation;
@@ -1164,6 +1225,7 @@ var SpaceService = class {
1164
1225
  if (config.capabilityRegistry) this.capabilityRegistry = config.capabilityRegistry;
1165
1226
  if (config.createKVService) this.createKVServiceFn = config.createKVService;
1166
1227
  if (config.createVaultService) this.createVaultServiceFn = config.createVaultService;
1228
+ if (config.createSecretsService) this.createSecretsServiceFn = config.createSecretsService;
1167
1229
  if (config.userDid !== void 0) this._userDid = config.userDid;
1168
1230
  if (config.sharingService) this.sharingService = config.sharingService;
1169
1231
  if (config.createDelegation) this.createDelegationFn = config.createDelegation;
@@ -1457,6 +1519,7 @@ var SpaceService = class {
1457
1519
  name,
1458
1520
  createKV: this.createSpaceScopedKV.bind(this),
1459
1521
  createVault: this.createSpaceScopedVault.bind(this),
1522
+ createSecrets: this.createSpaceScopedSecrets.bind(this),
1460
1523
  createDelegations: this.createSpaceScopedDelegations.bind(this),
1461
1524
  createSharing: this.createSpaceScopedSharing.bind(this),
1462
1525
  getInfo: this.getSpaceInfo.bind(this)
@@ -1601,6 +1664,21 @@ var SpaceService = class {
1601
1664
  }
1602
1665
  });
1603
1666
  }
1667
+ /**
1668
+ * Create a space-scoped secrets service.
1669
+ */
1670
+ createSpaceScopedSecrets(spaceId) {
1671
+ if (this.createSecretsServiceFn) {
1672
+ return this.createSecretsServiceFn(spaceId);
1673
+ }
1674
+ return new Proxy({}, {
1675
+ get: () => {
1676
+ throw new Error(
1677
+ "Secrets service factory not configured. Provide createSecretsService in SpaceServiceConfig."
1678
+ );
1679
+ }
1680
+ });
1681
+ }
1604
1682
  /**
1605
1683
  * Create space-scoped delegation operations.
1606
1684
  */
@@ -2349,6 +2427,7 @@ var import_sdk_services5 = require("@tinycloud/sdk-services");
2349
2427
  // src/manifest.ts
2350
2428
  var import_ms = __toESM(require("ms"), 1);
2351
2429
  var import_sdk_services4 = require("@tinycloud/sdk-services");
2430
+ var DEFAULT_KNOWLEDGE_ROOT = "knowledge/index.md";
2352
2431
  var ManifestValidationError = class extends Error {
2353
2432
  constructor(message) {
2354
2433
  super(`Manifest validation failed: ${message}`);
@@ -2403,7 +2482,7 @@ var DEFAULT_ADMIN_ENTRIES = [
2403
2482
  service: "tinycloud.sql",
2404
2483
  space: DEFAULT_MANIFEST_SPACE,
2405
2484
  path: "/",
2406
- actions: ["read", "write", "ddl"]
2485
+ actions: ["read", "write", "schema"]
2407
2486
  }
2408
2487
  ];
2409
2488
  var DEFAULT_ALL_ENTRIES = [
@@ -2417,7 +2496,7 @@ var DEFAULT_ALL_ENTRIES = [
2417
2496
  service: "tinycloud.sql",
2418
2497
  space: DEFAULT_MANIFEST_SPACE,
2419
2498
  path: "/",
2420
- actions: ["read", "write", "ddl"]
2499
+ actions: ["read", "write", "schema"]
2421
2500
  },
2422
2501
  {
2423
2502
  service: "tinycloud.duckdb",
@@ -2575,6 +2654,9 @@ function validateManifest(input) {
2575
2654
  if (m.expiry !== void 0) {
2576
2655
  parseExpiry(m.expiry);
2577
2656
  }
2657
+ if (m.knowledge !== void 0) {
2658
+ resolveManifestKnowledgeRoot(m.knowledge);
2659
+ }
2578
2660
  if (m.permissions !== void 0) {
2579
2661
  if (!Array.isArray(m.permissions)) {
2580
2662
  throw new ManifestValidationError(
@@ -2590,6 +2672,25 @@ function validateManifest(input) {
2590
2672
  }
2591
2673
  return m;
2592
2674
  }
2675
+ function resolveManifestKnowledgeRoot(knowledge) {
2676
+ if (knowledge === void 0) {
2677
+ return void 0;
2678
+ }
2679
+ if (knowledge === true) {
2680
+ return DEFAULT_KNOWLEDGE_ROOT;
2681
+ }
2682
+ if (typeof knowledge !== "string" || knowledge.length === 0) {
2683
+ throw new ManifestValidationError(
2684
+ "manifest.knowledge must be true or a knowledge/*.md root path"
2685
+ );
2686
+ }
2687
+ if (!/^knowledge\/.+\.md$/.test(knowledge)) {
2688
+ throw new ManifestValidationError(
2689
+ "manifest.knowledge must be true or a knowledge/*.md root path"
2690
+ );
2691
+ }
2692
+ return knowledge;
2693
+ }
2593
2694
  function validateManifestSecrets(secrets) {
2594
2695
  if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
2595
2696
  throw new ManifestValidationError("manifest.secrets must be an object");
@@ -2989,7 +3090,7 @@ function accountRegistryIndexPermission() {
2989
3090
  service: "tinycloud.sql",
2990
3091
  space: ACCOUNT_REGISTRY_SPACE,
2991
3092
  path: "account",
2992
- actions: ["tinycloud.sql/read", "tinycloud.sql/write", "tinycloud.sql/ddl"]
3093
+ actions: ["tinycloud.sql/read", "tinycloud.sql/write", "tinycloud.sql/schema"]
2993
3094
  };
2994
3095
  }
2995
3096
  function composeManifestRequest(inputs, options = {}) {
@@ -3094,8 +3195,10 @@ function manifestAbilitiesUnion(resolved) {
3094
3195
  }
3095
3196
 
3096
3197
  // src/account/AccountService.ts
3198
+ var import_bootstrap = require("@tinycloud/bootstrap");
3097
3199
  var SERVICE_NAME2 = "account";
3098
3200
  var ACCOUNT_INDEX_DB = "account";
3201
+ var ACCOUNT_INDEX_NAMESPACE = "tinycloud.account.index";
3099
3202
  var ACCOUNT_SPACES_PATH = "spaces/";
3100
3203
  var AccountService = class {
3101
3204
  constructor(config) {
@@ -3290,6 +3393,13 @@ var AccountService = class {
3290
3393
  }
3291
3394
  };
3292
3395
  this.index = {
3396
+ ensure: async () => {
3397
+ const dbResult = this.accountDb();
3398
+ if (!dbResult.ok) return dbResult;
3399
+ const schema = await this.ensureAccountIndex(dbResult.data);
3400
+ if (!schema.ok) return schema;
3401
+ return (0, import_sdk_services5.ok)({ database: ACCOUNT_INDEX_DB });
3402
+ },
3293
3403
  rebuild: async () => {
3294
3404
  const dbResult = this.accountDb();
3295
3405
  if (!dbResult.ok) return dbResult;
@@ -3300,8 +3410,9 @@ var AccountService = class {
3300
3410
  const delegations = await this.delegations.list();
3301
3411
  if (!delegations.ok) return delegations;
3302
3412
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
3413
+ const schema = await this.ensureAccountIndex(dbResult.data);
3414
+ if (!schema.ok) return schema;
3303
3415
  const statements = [
3304
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3305
3416
  { sql: "DELETE FROM applications" },
3306
3417
  { sql: "DELETE FROM application_state" },
3307
3418
  { sql: "DELETE FROM spaces" },
@@ -3498,7 +3609,7 @@ var AccountService = class {
3498
3609
  async indexHasApplicationHash(appId, manifestHash) {
3499
3610
  const dbResult = this.accountDb();
3500
3611
  if (!dbResult.ok) return false;
3501
- const schema = await dbResult.data.batch(ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })));
3612
+ const schema = await this.ensureAccountIndex(dbResult.data);
3502
3613
  if (!schema.ok) return false;
3503
3614
  const queried = await dbResult.data.query(
3504
3615
  "SELECT 1 FROM application_state WHERE app_id = ? AND manifest_hash = ? LIMIT 1",
@@ -3512,10 +3623,11 @@ var AccountService = class {
3512
3623
  async upsertApplicationIndex(app) {
3513
3624
  const dbResult = this.accountDb();
3514
3625
  if (!dbResult.ok) return (0, import_sdk_services5.ok)(void 0);
3626
+ const schema = await this.ensureAccountIndex(dbResult.data);
3627
+ if (!schema.ok) return schema;
3515
3628
  const updatedAt = app.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
3516
3629
  const manifestHash = app.manifestHash ?? hashJson(app.manifests);
3517
3630
  const written = await dbResult.data.batch([
3518
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3519
3631
  {
3520
3632
  sql: "INSERT OR REPLACE INTO applications (app_id, name, description, updated_at, manifest_json) VALUES (?, ?, ?, ?, ?)",
3521
3633
  params: [
@@ -3540,8 +3652,9 @@ var AccountService = class {
3540
3652
  async deleteApplicationIndex(appId) {
3541
3653
  const dbResult = this.accountDb();
3542
3654
  if (!dbResult.ok) return (0, import_sdk_services5.ok)(void 0);
3655
+ const schema = await this.ensureAccountIndex(dbResult.data);
3656
+ if (!schema.ok) return schema;
3543
3657
  const deleted = await dbResult.data.batch([
3544
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3545
3658
  { sql: "DELETE FROM applications WHERE app_id = ?", params: [appId] },
3546
3659
  { sql: "DELETE FROM application_state WHERE app_id = ?", params: [appId] }
3547
3660
  ]);
@@ -3554,9 +3667,10 @@ var AccountService = class {
3554
3667
  async upsertSpaceIndex(space) {
3555
3668
  const dbResult = this.accountDb();
3556
3669
  if (!dbResult.ok) return (0, import_sdk_services5.ok)(void 0);
3670
+ const schema = await this.ensureAccountIndex(dbResult.data);
3671
+ if (!schema.ok) return schema;
3557
3672
  const updatedAt = space.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
3558
3673
  const written = await dbResult.data.batch([
3559
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3560
3674
  {
3561
3675
  sql: "INSERT OR REPLACE INTO spaces (space_id, name, owner_did, type, permissions_json, status, registered_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
3562
3676
  params: [
@@ -3581,8 +3695,9 @@ var AccountService = class {
3581
3695
  async deleteSpaceIndex(spaceId) {
3582
3696
  const dbResult = this.accountDb();
3583
3697
  if (!dbResult.ok) return (0, import_sdk_services5.ok)(void 0);
3698
+ const schema = await this.ensureAccountIndex(dbResult.data);
3699
+ if (!schema.ok) return schema;
3584
3700
  const deleted = await dbResult.data.batch([
3585
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3586
3701
  { sql: "DELETE FROM spaces WHERE space_id = ?", params: [spaceId] }
3587
3702
  ]);
3588
3703
  if (!deleted.ok) return accountErr(deleted.error);
@@ -3604,8 +3719,9 @@ var AccountService = class {
3604
3719
  const dbResult = this.accountDb();
3605
3720
  if (!dbResult.ok) return;
3606
3721
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
3722
+ const schema = await this.ensureAccountIndex(dbResult.data);
3723
+ if (!schema.ok) return;
3607
3724
  await dbResult.data.batch([
3608
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3609
3725
  { sql: "DELETE FROM applications" },
3610
3726
  { sql: "DELETE FROM application_state" },
3611
3727
  ...applications.map((app) => ({
@@ -3634,8 +3750,9 @@ var AccountService = class {
3634
3750
  const dbResult = this.accountDb();
3635
3751
  if (!dbResult.ok) return;
3636
3752
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
3753
+ const schema = await this.ensureAccountIndex(dbResult.data);
3754
+ if (!schema.ok) return;
3637
3755
  await dbResult.data.batch([
3638
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3639
3756
  { sql: "DELETE FROM spaces" },
3640
3757
  ...spaces.map((space) => ({
3641
3758
  sql: "INSERT OR REPLACE INTO spaces (space_id, name, owner_did, type, permissions_json, status, registered_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
@@ -3663,8 +3780,9 @@ var AccountService = class {
3663
3780
  const dbResult = this.accountDb();
3664
3781
  if (!dbResult.ok) return;
3665
3782
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
3783
+ const schema = await this.ensureAccountIndex(dbResult.data);
3784
+ if (!schema.ok) return;
3666
3785
  await dbResult.data.batch([
3667
- ...ACCOUNT_INDEX_SCHEMA.map((sql) => ({ sql })),
3668
3786
  { sql: "DELETE FROM delegations" },
3669
3787
  ...delegations.map((delegation) => ({
3670
3788
  sql: "INSERT OR REPLACE INTO delegations (cid, direction, space_id, space_name, counterparty_did, delegate_did, delegator_did, path, actions_json, expiry, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
@@ -3691,57 +3809,20 @@ var AccountService = class {
3691
3809
  ]);
3692
3810
  });
3693
3811
  }
3812
+ async ensureAccountIndex(db) {
3813
+ const migrated = await db.migrations.apply({
3814
+ namespace: ACCOUNT_INDEX_NAMESPACE,
3815
+ migrations: [
3816
+ {
3817
+ id: "001_initial",
3818
+ sql: [...import_bootstrap.ACCOUNT_INDEX_SCHEMA]
3819
+ }
3820
+ ]
3821
+ });
3822
+ if (!migrated.ok) return accountErr(migrated.error);
3823
+ return (0, import_sdk_services5.ok)(void 0);
3824
+ }
3694
3825
  };
3695
- var ACCOUNT_INDEX_SCHEMA = [
3696
- `CREATE TABLE IF NOT EXISTS applications (
3697
- app_id TEXT PRIMARY KEY,
3698
- name TEXT,
3699
- description TEXT,
3700
- updated_at TEXT,
3701
- manifest_json TEXT NOT NULL
3702
- )`,
3703
- `CREATE TABLE IF NOT EXISTS application_state (
3704
- app_id TEXT PRIMARY KEY,
3705
- manifest_hash TEXT NOT NULL,
3706
- indexed_at TEXT NOT NULL
3707
- )`,
3708
- `CREATE TABLE IF NOT EXISTS spaces (
3709
- space_id TEXT PRIMARY KEY,
3710
- name TEXT NOT NULL,
3711
- owner_did TEXT NOT NULL,
3712
- type TEXT NOT NULL,
3713
- permissions_json TEXT NOT NULL,
3714
- status TEXT NOT NULL,
3715
- registered_at TEXT,
3716
- updated_at TEXT NOT NULL,
3717
- expires_at TEXT
3718
- )`,
3719
- `CREATE TABLE IF NOT EXISTS delegations (
3720
- cid TEXT PRIMARY KEY,
3721
- direction TEXT NOT NULL,
3722
- space_id TEXT NOT NULL,
3723
- space_name TEXT,
3724
- counterparty_did TEXT NOT NULL,
3725
- delegate_did TEXT NOT NULL,
3726
- delegator_did TEXT,
3727
- path TEXT NOT NULL,
3728
- actions_json TEXT NOT NULL,
3729
- expiry TEXT NOT NULL,
3730
- status TEXT NOT NULL,
3731
- created_at TEXT,
3732
- updated_at TEXT NOT NULL
3733
- )`,
3734
- `CREATE TABLE IF NOT EXISTS sync_state (
3735
- source TEXT PRIMARY KEY,
3736
- synced_at TEXT NOT NULL,
3737
- count INTEGER NOT NULL
3738
- )`,
3739
- "CREATE INDEX IF NOT EXISTS idx_delegations_direction ON delegations(direction)",
3740
- "CREATE INDEX IF NOT EXISTS idx_delegations_space ON delegations(space_id)",
3741
- "CREATE INDEX IF NOT EXISTS idx_delegations_counterparty ON delegations(counterparty_did)",
3742
- "CREATE INDEX IF NOT EXISTS idx_spaces_owner ON spaces(owner_did)",
3743
- "CREATE INDEX IF NOT EXISTS idx_spaces_type ON spaces(type)"
3744
- ];
3745
3826
  function applicationKey(appId) {
3746
3827
  return `${ACCOUNT_REGISTRY_PATH}${appId}`;
3747
3828
  }
@@ -5651,6 +5732,76 @@ function createCapabilityKeyRegistry() {
5651
5732
  }
5652
5733
 
5653
5734
  // src/authorization/strategies.ts
5735
+ async function resolveOpenKeyToken(token) {
5736
+ return typeof token === "function" ? token() : token;
5737
+ }
5738
+ async function resolveOpenKeyHeaders(headers) {
5739
+ return typeof headers === "function" ? headers() : headers ?? {};
5740
+ }
5741
+ function openKeyApprovalReason(body) {
5742
+ if (body.reason) return body.reason;
5743
+ if (body.error) return body.error;
5744
+ if (body.approvalUrl) {
5745
+ return `OpenKey explicit approval required: ${body.approvalUrl}`;
5746
+ }
5747
+ return "OpenKey explicit approval required";
5748
+ }
5749
+ function createOpenKeyCallbackSigningStrategy(options) {
5750
+ return {
5751
+ type: "callback",
5752
+ openKeyAutoSign: true,
5753
+ handler: async (request) => {
5754
+ const fetchImpl = options.fetch ?? globalThis.fetch;
5755
+ if (!fetchImpl) {
5756
+ throw new Error("OpenKey signing strategy requires a fetch implementation");
5757
+ }
5758
+ const token = await resolveOpenKeyToken(options.token);
5759
+ const extraHeaders = await resolveOpenKeyHeaders(options.headers);
5760
+ const body = {
5761
+ ...request,
5762
+ ...options.keyId ? { keyId: options.keyId } : {}
5763
+ };
5764
+ const response = await fetchImpl(options.endpoint, {
5765
+ method: "POST",
5766
+ credentials: options.credentials,
5767
+ headers: {
5768
+ "content-type": "application/json",
5769
+ ...token ? { authorization: `Bearer ${token}` } : {},
5770
+ ...extraHeaders
5771
+ },
5772
+ body: JSON.stringify(body)
5773
+ });
5774
+ let parsed;
5775
+ try {
5776
+ parsed = await response.json();
5777
+ } catch {
5778
+ parsed = void 0;
5779
+ }
5780
+ if (!response.ok) {
5781
+ return {
5782
+ approved: false,
5783
+ reason: parsed?.reason ?? parsed?.error ?? `OpenKey signing failed with HTTP ${response.status}`
5784
+ };
5785
+ }
5786
+ if (parsed?.needsApproval || parsed?.approved === false) {
5787
+ return {
5788
+ approved: false,
5789
+ reason: openKeyApprovalReason(parsed)
5790
+ };
5791
+ }
5792
+ if (typeof parsed?.signature === "string" && parsed.signature.length > 0) {
5793
+ return {
5794
+ approved: true,
5795
+ signature: parsed.signature
5796
+ };
5797
+ }
5798
+ return {
5799
+ approved: false,
5800
+ reason: "OpenKey signing response did not include a signature"
5801
+ };
5802
+ }
5803
+ };
5804
+ }
5654
5805
  var defaultSignStrategy = { type: "auto-sign" };
5655
5806
 
5656
5807
  // src/authorization/spaceCreation.ts
@@ -5726,6 +5877,9 @@ async function checkNodeInfo(host, sdkProtocol, fetchFn = globalThis.fetch.bind(
5726
5877
  };
5727
5878
  }
5728
5879
 
5880
+ // src/index.ts
5881
+ var import_bootstrap2 = require("@tinycloud/bootstrap");
5882
+
5729
5883
  // src/location.ts
5730
5884
  var import_multiaddr = require("@multiformats/multiaddr");
5731
5885
  var import_multiaddr_to_uri = require("@multiformats/multiaddr-to-uri");
@@ -6236,10 +6390,21 @@ function parseRecapCapabilities(parseWasm, siwe) {
6236
6390
  }
6237
6391
  // Annotate the CommonJS export names for ESM import in node:
6238
6392
  0 && (module.exports = {
6393
+ ACCOUNT_INDEX_SCHEMA,
6239
6394
  ACCOUNT_REGISTRY_PATH,
6240
6395
  ACCOUNT_REGISTRY_SPACE,
6241
6396
  AccountService,
6242
6397
  AutoApproveSpaceCreationHandler,
6398
+ BOOTSTRAP_ALLOWLIST,
6399
+ BOOTSTRAP_DEFAULT_SPACE,
6400
+ BOOTSTRAP_ENCRYPTION_NETWORK_NAME,
6401
+ BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE,
6402
+ BOOTSTRAP_MANIFEST,
6403
+ BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS,
6404
+ BOOTSTRAP_PUBLIC_SPACE,
6405
+ BOOTSTRAP_SESSION_REQUESTS,
6406
+ BOOTSTRAP_SPACE_MANIFESTS,
6407
+ BOOTSTRAP_SPACE_NAMES,
6243
6408
  CapabilityKeyRegistry,
6244
6409
  CapabilityKeyRegistryErrorCodes,
6245
6410
  ClientSessionSchema,
@@ -6251,6 +6416,7 @@ function parseRecapCapabilities(parseWasm, siwe) {
6251
6416
  DEFAULT_ENCRYPTION_ALG,
6252
6417
  DEFAULT_EXPIRY,
6253
6418
  DEFAULT_KEY_VERSION,
6419
+ DEFAULT_KNOWLEDGE_ROOT,
6254
6420
  DEFAULT_MANIFEST_SPACE,
6255
6421
  DEFAULT_MANIFEST_VERSION,
6256
6422
  DEFAULT_SIGNED_READ_URL_EXPIRY_MS,
@@ -6283,7 +6449,9 @@ function parseRecapCapabilities(parseWasm, siwe) {
6283
6449
  PermissionNotInManifestError,
6284
6450
  PrefixedKVService,
6285
6451
  ProtocolMismatchError,
6452
+ SECRETS_SPACE,
6286
6453
  SECRET_NAME_RE,
6454
+ SECRET_RECORDS_SCHEMA,
6287
6455
  SERVICE_LONG_TO_SHORT,
6288
6456
  SERVICE_SHORT_TO_LONG,
6289
6457
  SQLAction,
@@ -6298,7 +6466,13 @@ function parseRecapCapabilities(parseWasm, siwe) {
6298
6466
  Space,
6299
6467
  SpaceErrorCodes,
6300
6468
  SpaceService,
6469
+ TINYCLOUD_ACCOUNT_SPACE_MANIFEST,
6470
+ TINYCLOUD_APPLICATIONS_SPACE_MANIFEST,
6471
+ TINYCLOUD_DEFAULT_SPACE_MANIFEST,
6472
+ TINYCLOUD_PUBLIC_SPACE_MANIFEST,
6473
+ TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,
6301
6474
  TinyCloud,
6475
+ TinyCloudDebugLogger,
6302
6476
  UnsupportedFeatureError,
6303
6477
  VAULT_PERMISSION_SERVICE,
6304
6478
  VaultHeaders,
@@ -6307,6 +6481,9 @@ function parseRecapCapabilities(parseWasm, siwe) {
6307
6481
  activateSessionWithHost,
6308
6482
  addressStorageKey,
6309
6483
  applyPrefix,
6484
+ bootstrapEncryptionNetworkId,
6485
+ bootstrapSpaceId,
6486
+ bootstrapSteps,
6310
6487
  buildCanonicalDecryptRequest,
6311
6488
  buildDecryptAttenuation,
6312
6489
  buildDecryptFacts,
@@ -6324,8 +6501,11 @@ function parseRecapCapabilities(parseWasm, siwe) {
6324
6501
  canonicalizeSecretScope,
6325
6502
  checkDecryptInvocationInput,
6326
6503
  checkNodeInfo,
6504
+ clearTinyCloudDebugLogs,
6505
+ composeBootstrapSpaceManifest,
6327
6506
  composeManifestRequest,
6328
6507
  createCapabilityKeyRegistry,
6508
+ createOpenKeyCallbackSigningStrategy,
6329
6509
  createSharingService,
6330
6510
  createSpaceService,
6331
6511
  createVaultCrypto,
@@ -6336,7 +6516,9 @@ function parseRecapCapabilities(parseWasm, siwe) {
6336
6516
  deriveSignedReceiverKey,
6337
6517
  didCacheKey,
6338
6518
  didEquals,
6519
+ disableTinyCloudDebug,
6339
6520
  discoverNetwork,
6521
+ enableTinyCloudDebug,
6340
6522
  encryptToNetwork,
6341
6523
  encryptionBase64Decode,
6342
6524
  encryptionBase64Encode,
@@ -6351,9 +6533,11 @@ function parseRecapCapabilities(parseWasm, siwe) {
6351
6533
  fetchLocationRecord,
6352
6534
  fetchPeerId,
6353
6535
  generateRandomReceiverKey,
6536
+ getTinyCloudDebugLogs,
6354
6537
  hexDecode,
6355
6538
  hexEncode,
6356
6539
  httpUrlToMultiaddr,
6540
+ installTinyCloudDebugGlobals,
6357
6541
  isCapabilitySubset,
6358
6542
  isEvmAddress,
6359
6543
  isNetworkId,
@@ -6378,6 +6562,7 @@ function parseRecapCapabilities(parseWasm, siwe) {
6378
6562
  principalDidEquals,
6379
6563
  resolveCloudLocation,
6380
6564
  resolveManifest,
6565
+ resolveManifestKnowledgeRoot,
6381
6566
  resolveSecretListPrefix,
6382
6567
  resolveSecretPath,
6383
6568
  resolveTinyCloudHosts,
@@ -6386,6 +6571,7 @@ function parseRecapCapabilities(parseWasm, siwe) {
6386
6571
  serviceError,
6387
6572
  signLocationRecord,
6388
6573
  submitHostDelegation,
6574
+ tinyCloudDebugLogger,
6389
6575
  validateClientSession,
6390
6576
  validateEnvelope,
6391
6577
  validateLocationRecord,