@tinycloud/node-sdk 3.11.1-beta.0 → 3.12.0-beta.2

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.
Files changed (35) hide show
  1. package/dist/NodeUserAuthorization-B05Wjjpb.d.cts +900 -0
  2. package/dist/NodeUserAuthorization-B05Wjjpb.d.ts +900 -0
  3. package/dist/{TinyCloudNode-AUotFGzy.d.ts → TinyCloudNode-6_IumWu0.d.cts} +32 -875
  4. package/dist/{TinyCloudNode-BmpjkpWR.d.cts → TinyCloudNode-CEFGtSWn.d.ts} +32 -875
  5. package/dist/{authority-BYSEyjDI.d.cts → authority-DODDXxoP.d.cts} +1 -1
  6. package/dist/{authority-dRnJD4iL.d.ts → authority-DXpnuId1.d.ts} +1 -1
  7. package/dist/core.cjs +182 -109
  8. package/dist/core.cjs.map +1 -1
  9. package/dist/core.d.cts +5 -4
  10. package/dist/core.d.ts +5 -4
  11. package/dist/core.js +182 -109
  12. package/dist/core.js.map +1 -1
  13. package/dist/credentials-core.d.cts +1 -1
  14. package/dist/credentials-core.d.ts +1 -1
  15. package/dist/credentials.d.cts +1 -1
  16. package/dist/credentials.d.ts +1 -1
  17. package/dist/{delegation-Ckc3UETl.d.cts → delegation-BQbAuKad.d.cts} +1 -1
  18. package/dist/{delegation-Ckc3UETl.d.ts → delegation-BQbAuKad.d.ts} +1 -1
  19. package/dist/encryption-keys.d.cts +3 -2
  20. package/dist/encryption-keys.d.ts +3 -2
  21. package/dist/index.cjs +182 -109
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +4 -3
  24. package/dist/index.d.ts +4 -3
  25. package/dist/index.js +182 -109
  26. package/dist/index.js.map +1 -1
  27. package/dist/replication/authority.d.cts +4 -3
  28. package/dist/replication/authority.d.ts +4 -3
  29. package/dist/space-hosting.cjs +183 -0
  30. package/dist/space-hosting.cjs.map +1 -0
  31. package/dist/space-hosting.d.cts +84 -0
  32. package/dist/space-hosting.d.ts +84 -0
  33. package/dist/space-hosting.js +157 -0
  34. package/dist/space-hosting.js.map +1 -0
  35. package/package.json +11 -1
@@ -1,7 +1,7 @@
1
1
  import { ReplicationOptions, PermissionEntry, TinyCloudSession, KVReplicaStorage, ServiceContext, IWasmBindings, WasmRecapEntry } from '@tinycloud/sdk-core';
2
2
  import { ReplicaConsentAnchor, AuthorityRefusal, ReplicationAuthority } from '@tinycloud/sdk-services';
3
3
  import { ReplicaLocalEraseOutcome, ReplicaPurgeLocalCopyResult, ReplicaPurgeTrigger, ReplicaPurgeFailedEvent, ReplicaSessionStamp, ReplicaDenyInput } from '@tinycloud/sdk-services/kv/replication';
4
- import { T as TinyCloudNode } from './TinyCloudNode-BmpjkpWR.cjs';
4
+ import { T as TinyCloudNode } from './TinyCloudNode-6_IumWu0.cjs';
5
5
 
6
6
  /** Constructor-time validation; the space-dependent secrets check runs at sign-in and open. */
7
7
  declare function assertValidReplicationConfig(replication: (ReplicationOptions & {
@@ -1,7 +1,7 @@
1
1
  import { ReplicationOptions, PermissionEntry, TinyCloudSession, KVReplicaStorage, ServiceContext, IWasmBindings, WasmRecapEntry } from '@tinycloud/sdk-core';
2
2
  import { ReplicaConsentAnchor, AuthorityRefusal, ReplicationAuthority } from '@tinycloud/sdk-services';
3
3
  import { ReplicaLocalEraseOutcome, ReplicaPurgeLocalCopyResult, ReplicaPurgeTrigger, ReplicaPurgeFailedEvent, ReplicaSessionStamp, ReplicaDenyInput } from '@tinycloud/sdk-services/kv/replication';
4
- import { T as TinyCloudNode } from './TinyCloudNode-AUotFGzy.js';
4
+ import { T as TinyCloudNode } from './TinyCloudNode-CEFGtSWn.js';
5
5
 
6
6
  /** Constructor-time validation; the space-dependent secrets check runs at sign-in and open. */
7
7
  declare function assertValidReplicationConfig(replication: (ReplicationOptions & {
package/dist/core.cjs CHANGED
@@ -568,6 +568,8 @@ var NodeUserAuthorization = class {
568
568
  * delegation lists them: the node answers a repeat with empty lists.
569
569
  */
570
570
  this._lastActivationActivatedSpaceIds = [];
571
+ /** See {@link spaceHosting}. Written only from node answers. */
572
+ this._spaceHosting = "unknown";
571
573
  this.wasm = config.wasmBindings;
572
574
  this.signer = config.signer;
573
575
  this.signStrategy = config.signStrategy ?? defaultSignStrategy;
@@ -727,6 +729,7 @@ var NodeUserAuthorization = class {
727
729
  this.registryVerdict = void 0;
728
730
  this._lastActivationSkippedSpaceIds = [];
729
731
  this._lastActivationActivatedSpaceIds = [];
732
+ this._spaceHosting = "unknown";
730
733
  if (!session) {
731
734
  this._session = void 0;
732
735
  this._tinyCloudSession = void 0;
@@ -867,6 +870,18 @@ var NodeUserAuthorization = class {
867
870
  get lastActivationActivatedSpaceIds() {
868
871
  return [...this._lastActivationActivatedSpaceIds];
869
872
  }
873
+ /**
874
+ * The node's last answer for whether this session's primary space is hosted:
875
+ * recorded from the sign-in activation, or by {@link noteSpaceHosting}.
876
+ * `unknown` until one of them answers, and after a restore.
877
+ */
878
+ get spaceHosting() {
879
+ return this._spaceHosting;
880
+ }
881
+ /** @internal Record the hosting probe's answer for the primary space. */
882
+ noteSpaceHosting(hosting) {
883
+ this._spaceHosting = hosting;
884
+ }
870
885
  /**
871
886
  * Compute the `abilities` map the WASM `prepareSession` call should
872
887
  * see at sign-in time.
@@ -1246,23 +1261,35 @@ var NodeUserAuthorization = class {
1246
1261
  * Create the space on the TinyCloud server (host delegation).
1247
1262
  * This registers the user as the owner of the space.
1248
1263
  */
1249
- async hostSpace(targetSpaceId, purpose, signal) {
1250
- if (!this._tinyCloudSession || !this._address || !this._chainId) {
1264
+ async hostSpace(targetSpaceId, purpose, signal, assertCurrent, siweParameters) {
1265
+ const context = typeof targetSpaceId === "object" ? targetSpaceId : void 0;
1266
+ const address = context?.address ?? this._address;
1267
+ const chainId = context?.chainId ?? this._chainId;
1268
+ if (!address || chainId === void 0 || !this._tinyCloudSession) {
1251
1269
  throw new Error("Must be signed in to host space");
1252
1270
  }
1271
+ const checkCurrent = () => {
1272
+ signal?.throwIfAborted();
1273
+ assertCurrent?.();
1274
+ };
1275
+ checkCurrent();
1253
1276
  await this.ensureTinyCloudHosts();
1254
- const host = this.primaryTinyCloudHost;
1255
- const spaceId = targetSpaceId ?? this._tinyCloudSession.spaceId;
1277
+ checkCurrent();
1278
+ const host = context?.host ?? this.primaryTinyCloudHost;
1279
+ const spaceId = context?.spaceId ?? (typeof targetSpaceId === "string" ? targetSpaceId : this._tinyCloudSession.spaceId);
1256
1280
  const peerId = await (0, import_sdk_core5.fetchPeerId)(host, spaceId, signal);
1257
- const siwe = this.wasm.generateHostSIWEMessage({
1258
- address: this._address,
1259
- chainId: this._chainId,
1260
- domain: this.domain,
1261
- issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
1262
- spaceId,
1263
- peerId
1264
- });
1265
- if (signal?.aborted) throw signal.reason;
1281
+ checkCurrent();
1282
+ const siwe = this.wasm.generateHostSIWEMessage(
1283
+ context && siweParameters ? siweParameters(peerId) : {
1284
+ address,
1285
+ chainId,
1286
+ domain: this.domain,
1287
+ issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
1288
+ spaceId,
1289
+ peerId
1290
+ }
1291
+ );
1292
+ checkCurrent();
1266
1293
  const signing = this.signMessage(siwe, purpose);
1267
1294
  let signature;
1268
1295
  if (!signal) {
@@ -1281,8 +1308,9 @@ var NodeUserAuthorization = class {
1281
1308
  signal.removeEventListener("abort", onAbort);
1282
1309
  }
1283
1310
  }
1284
- if (signal?.aborted) throw signal.reason;
1311
+ checkCurrent();
1285
1312
  const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });
1313
+ checkCurrent();
1286
1314
  return (0, import_sdk_core5.submitHostDelegation)(host, headers, signal);
1287
1315
  }
1288
1316
  /**
@@ -1327,103 +1355,48 @@ var NodeUserAuthorization = class {
1327
1355
  this._tinyCloudSession.delegationHeader
1328
1356
  );
1329
1357
  this.recordActivationSkippedSpaces(result, primarySpaceId);
1330
- const handler = this.spaceCreationHandler ?? (this.autoCreateSpace ? new import_sdk_core5.AutoApproveSpaceCreationHandler() : void 0);
1331
- const creationContext = {
1332
- spaceId: primarySpaceId,
1333
- address: this._address,
1334
- chainId: this._chainId,
1335
- host
1336
- };
1337
- if (result.success) {
1338
- const primarySkipped = result.skipped?.includes(primarySpaceId);
1339
- if (!primarySkipped) {
1340
- return;
1341
- }
1342
- if (!handler) {
1343
- return;
1344
- }
1345
- await this.guardSpaceCreation(handler, creationContext);
1346
- const confirmed = await handler.confirmSpaceCreation(creationContext);
1347
- if (!confirmed) {
1348
- return;
1349
- }
1350
- try {
1351
- const created = await this.hostSpace();
1352
- if (!created.success) {
1353
- const err2 = Object.assign(
1354
- new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),
1355
- { cause: created }
1356
- );
1357
- throw err2;
1358
- }
1359
- } catch (error) {
1360
- handler.onSpaceCreationFailed?.(
1361
- creationContext,
1362
- error instanceof Error ? error : new Error(String(error))
1363
- );
1364
- throw error;
1365
- }
1366
- await new Promise((resolve) => setTimeout(resolve, 100));
1367
- const retryResult = await (0, import_sdk_core5.activateSessionWithHost)(
1368
- host,
1369
- this._tinyCloudSession.delegationHeader
1370
- );
1371
- if (!retryResult.success) {
1372
- const err2 = Object.assign(
1373
- new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),
1374
- { cause: retryResult }
1375
- );
1376
- handler.onSpaceCreationFailed?.(creationContext, err2);
1377
- throw err2;
1378
- }
1379
- handler.onSpaceCreated?.(creationContext);
1380
- return;
1381
- }
1382
- if (result.status === 404) {
1383
- if (!handler) {
1384
- return;
1385
- }
1386
- await this.guardSpaceCreation(handler, creationContext);
1387
- const confirmed = await handler.confirmSpaceCreation(creationContext);
1388
- if (!confirmed) {
1389
- return;
1390
- }
1391
- try {
1392
- const created = await this.hostSpace();
1393
- if (!created.success) {
1394
- const err2 = Object.assign(
1395
- new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),
1396
- { cause: created }
1397
- );
1398
- throw err2;
1399
- }
1400
- } catch (error) {
1401
- handler.onSpaceCreationFailed?.(
1402
- creationContext,
1403
- error instanceof Error ? error : new Error(String(error))
1404
- );
1405
- throw error;
1406
- }
1407
- await new Promise((resolve) => setTimeout(resolve, 100));
1408
- const retryResult = await (0, import_sdk_core5.activateSessionWithHost)(
1409
- host,
1410
- this._tinyCloudSession.delegationHeader
1358
+ if (!result.success && result.status !== 404) {
1359
+ throw Object.assign(
1360
+ new Error(`Failed to activate session: ${describeHostFailure(result)}`),
1361
+ { cause: result }
1411
1362
  );
1412
- if (!retryResult.success) {
1413
- const err2 = Object.assign(
1414
- new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),
1415
- { cause: retryResult }
1416
- );
1417
- handler.onSpaceCreationFailed?.(creationContext, err2);
1418
- throw err2;
1419
- }
1420
- handler.onSpaceCreated?.(creationContext);
1421
- return;
1422
1363
  }
1423
- throw Object.assign(
1424
- new Error(`Failed to activate session: ${describeHostFailure(result)}`),
1425
- { cause: result }
1426
- );
1364
+ await this.ensurePrimarySpaceHosted(this._spaceHosting);
1365
+ }
1366
+ /**
1367
+ * The create step of {@link ensureSpaceExists}: given the node's answer for
1368
+ * the primary space, host it through the space creation handler when it is
1369
+ * `not-hosted`. Any other answer, and a missing handler, change nothing. The
1370
+ * caller supplies the answer (sign-in's activation, or the hosting probe);
1371
+ * an empty activation list is never one.
1372
+ *
1373
+ * @throws Error if the creation handler fails or times out, or hosting fails
1374
+ */
1375
+ async ensurePrimarySpaceHosted(hosting, signal) {
1376
+ const session = this._tinyCloudSession;
1377
+ if (hosting !== "not-hosted") return;
1378
+ if (!session) throw new Error("Must be signed in to host the primary space");
1379
+ const handler = this.spaceCreationHandler ?? (this.autoCreateSpace ? new import_sdk_core5.AutoApproveSpaceCreationHandler() : void 0);
1380
+ if (!handler) return;
1381
+ const { createPrimarySpace } = await import("./space-hosting.cjs");
1382
+ await createPrimarySpace({
1383
+ handler,
1384
+ session,
1385
+ currentSession: () => this._tinyCloudSession,
1386
+ signerAddress: () => this.signer.getAddress(),
1387
+ resolveHost: async () => {
1388
+ await this.ensureTinyCloudHosts();
1389
+ return this.primaryTinyCloudHost;
1390
+ },
1391
+ domain: this.domain,
1392
+ guard: (context) => this.guardSpaceCreation(handler, context),
1393
+ host: (context, assertCurrent, siweParameters) => this.hostSpace(context, void 0, signal, assertCurrent, siweParameters),
1394
+ onHosted: () => {
1395
+ this._spaceHosting = "hosted";
1396
+ },
1397
+ activate: (context) => (0, import_sdk_core5.activateSessionWithHost)(context.host, session.delegationHeader),
1398
+ signal
1399
+ });
1427
1400
  }
1428
1401
  /** {@link assertMayCreateSpace}, reporting a refusal to the creation handler before rethrowing it. */
1429
1402
  async guardSpaceCreation(handler, context) {
@@ -1439,10 +1412,12 @@ var NodeUserAuthorization = class {
1439
1412
  if (result.success) {
1440
1413
  this._lastActivationSkippedSpaceIds = result.skipped ?? [];
1441
1414
  this._lastActivationActivatedSpaceIds = result.activated ?? [];
1415
+ this._spaceHosting = this._lastActivationSkippedSpaceIds.includes(primarySpaceId) ? "not-hosted" : this._lastActivationActivatedSpaceIds.includes(primarySpaceId) ? "hosted" : "unknown";
1442
1416
  return;
1443
1417
  }
1444
1418
  this._lastActivationActivatedSpaceIds = [];
1445
1419
  this._lastActivationSkippedSpaceIds = result.status === 404 ? [primarySpaceId] : [];
1420
+ this._spaceHosting = result.status === 404 ? "not-hosted" : "unknown";
1446
1421
  }
1447
1422
  async createBootstrapSession(options) {
1448
1423
  refuseCaveated(options.capabilityRequest.manifests);
@@ -4074,6 +4049,8 @@ var _TinyCloudNode = class _TinyCloudNode {
4074
4049
  * hosting is confirmed against the session that was active at the time.
4075
4050
  */
4076
4051
  this.confirmedHostedSpaceIds = /* @__PURE__ */ new Set();
4052
+ /** The primary space's hosting answer when no authorization layer holds it (a session-only restore). */
4053
+ this._restoredSpaceHosting = "unknown";
4077
4054
  /**
4078
4055
  * Owned space ids known to be hosted for the current session: the sign-in
4079
4056
  * activation listed them as `activated`, or this session hosted them. Unlike
@@ -4412,6 +4389,96 @@ var _TinyCloudNode = class _TinyCloudNode {
4412
4389
  ));
4413
4390
  }
4414
4391
  }
4392
+ /**
4393
+ * Whether the TinyCloud node hosts the primary space (the default) or a named
4394
+ * or full-id space: `"hosted"`, `"not-hosted"`, or `"unknown"` when the node
4395
+ * cannot say.
4396
+ *
4397
+ * Sends one authorized read the session already holds on that space (a kv
4398
+ * list under a granted prefix, else kv metadata, `tinycloud.space/info`, or
4399
+ * a kv get of a key that does not exist), signed for that space. A session
4400
+ * with no such read sends nothing and answers `unknown`. A 401/403 registers
4401
+ * the session delegation with the node once and asks again once. Network
4402
+ * failures, 5xx and a 5 s timeout answer `unknown`; this never throws.
4403
+ *
4404
+ * `hosted` is remembered for the session and `not-hosted` never is. The
4405
+ * answer for the primary space is also what {@link spaceHosting} reports; a
4406
+ * `unknown` answer leaves the previous one in place.
4407
+ */
4408
+ async checkSpaceHosting(space) {
4409
+ try {
4410
+ return await this.probeSpaceHosting(space);
4411
+ } catch {
4412
+ return "unknown";
4413
+ }
4414
+ }
4415
+ /** Run the existing primary-space creation flow for the restored session. */
4416
+ async ensurePrimarySpaceHosted(hosting) {
4417
+ const graph = this._serviceGraph;
4418
+ const epoch = this.sessionEpoch;
4419
+ graph.assertActive();
4420
+ this.assertSessionEpoch(epoch, "Space hosting");
4421
+ const auth = this.auth;
4422
+ if (!auth || !this.session) return;
4423
+ await auth.ensurePrimarySpaceHosted(hosting, graph.signal);
4424
+ graph.assertActive();
4425
+ this.assertSessionEpoch(epoch, "Space hosting");
4426
+ }
4427
+ /**
4428
+ * The node's last answer for the primary space: recorded at sign-in from the
4429
+ * activation, or by {@link checkSpaceHosting}. `unknown` after a restore until
4430
+ * something asks.
4431
+ */
4432
+ get spaceHosting() {
4433
+ return this.auth ? this.auth.spaceHosting : this._restoredSpaceHosting;
4434
+ }
4435
+ async probeSpaceHosting(space) {
4436
+ const context = this._serviceContext;
4437
+ const session = context?.session;
4438
+ const host = context?.hosts[0];
4439
+ if (!context || !session || !host) {
4440
+ return "unknown";
4441
+ }
4442
+ const spaceId = space === void 0 ? session.spaceId : space.startsWith("tinycloud:") ? space : this.ownedSpaceId(space);
4443
+ const graph = this._serviceGraph;
4444
+ const epoch = this.sessionEpoch;
4445
+ const assertCurrent = () => {
4446
+ graph.assertActive();
4447
+ if (epoch !== this.sessionEpoch || graph !== this._serviceGraph || this._serviceContext !== context) {
4448
+ throw new Error("The session changed during the hosting check.");
4449
+ }
4450
+ };
4451
+ const { askSpaceHosting } = await import("./space-hosting.cjs");
4452
+ assertCurrent();
4453
+ this.pruneExpiredRuntimePermissionGrants();
4454
+ const primary = this.currentTinyCloudSession();
4455
+ const answer = await askSpaceHosting({
4456
+ spaceId,
4457
+ operations: [
4458
+ ...this.runtimePermissionGrants.flatMap((grant) => grant.operations),
4459
+ ...primary ? this.recapOperationsFromSession(primary) : []
4460
+ ],
4461
+ covers: (granted, requested) => this.operationCovers(granted, requested),
4462
+ scope: context,
4463
+ host,
4464
+ fetch: unrecordedFetchOf(context),
4465
+ sign: (entries) => {
4466
+ assertCurrent();
4467
+ return graph.invokeAny({ ...session, spaceId }, entries);
4468
+ },
4469
+ // A session saved but never registered on this node is refused: it registers once.
4470
+ activate: (signal) => {
4471
+ assertCurrent();
4472
+ return (0, import_sdk_core11.activateSessionWithHost)(host, session.delegationHeader, AbortSignal.any([signal, graph.signal]));
4473
+ }
4474
+ });
4475
+ assertCurrent();
4476
+ if (answer !== "unknown" && this.spaceIdsEqual(spaceId, session.spaceId)) {
4477
+ if (this.auth) this.auth.noteSpaceHosting(answer);
4478
+ else this._restoredSpaceHosting = answer;
4479
+ }
4480
+ return answer;
4481
+ }
4415
4482
  get nodeFeatures() {
4416
4483
  return this.auth?.nodeFeatures ?? this._restoredNodeFeatures ?? [];
4417
4484
  }
@@ -4903,6 +4970,7 @@ var _TinyCloudNode = class _TinyCloudNode {
4903
4970
  this._spaceService = void 0;
4904
4971
  this.runtimePermissionGrants = [];
4905
4972
  this._recapOperationsCache = void 0;
4973
+ this._restoredSpaceHosting = "unknown";
4906
4974
  this.confirmedHostedSpaceIds.clear();
4907
4975
  this.hostedOwnedSpaceIds.clear();
4908
4976
  this.cancelOwnedSpaceHosts();
@@ -5096,6 +5164,10 @@ var _TinyCloudNode = class _TinyCloudNode {
5096
5164
  const primarySession = this.currentTinyCloudSession();
5097
5165
  if (primarySession) {
5098
5166
  this.registerPrimarySessionGrant(primarySession);
5167
+ if (this.auth?.spaceHosting === "unknown") {
5168
+ await this.checkSpaceHosting();
5169
+ this.assertSessionEpoch(epoch, "Sign-in");
5170
+ }
5099
5171
  }
5100
5172
  const bootstrapped = await this.bootstrapAccountIfNeeded();
5101
5173
  this.assertSessionEpoch(epoch, "Sign-in");
@@ -6475,6 +6547,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6475
6547
  this.tc = stagedGraph.core;
6476
6548
  this._recapOperationsCache = stagedPrimary.cache;
6477
6549
  this.runtimePermissionGrants = stagedPrimary.grants;
6550
+ this._restoredSpaceHosting = "unknown";
6478
6551
  this.confirmedHostedSpaceIds.clear();
6479
6552
  this.hostedOwnedSpaceIds.clear();
6480
6553
  this.cancelOwnedSpaceHosts();