@tinycloud/mcp 0.11.1-beta.9 → 0.12.0-beta.11

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/http.cjs CHANGED
@@ -25,7 +25,6 @@ __export(http_exports, {
25
25
  module.exports = __toCommonJS(http_exports);
26
26
  var import_node_path4 = require("path");
27
27
  var import_server4 = require("@modelcontextprotocol/server");
28
- var import_node_sdk3 = require("@tinycloud/node-sdk");
29
28
 
30
29
  // src/agent-discovery.ts
31
30
  var import_node_crypto = require("crypto");
@@ -364,16 +363,21 @@ function logToolCall(tool, code, startedAt, replayedGrants) {
364
363
 
365
364
  // src/remote-store.ts
366
365
  var import_sdk_core = require("@tinycloud/sdk-core");
367
- var import_node_crypto4 = require("crypto");
366
+ var import_renewal = require("@tinycloud/sdk-core/delegations/renewal");
367
+ var import_renewal_receipt = require("@tinycloud/sdk-core/delegations/renewal-receipt");
368
+ var import_node_crypto5 = require("crypto");
368
369
  var import_promises = require("fs/promises");
369
370
  var import_node_path2 = require("path");
371
+ var import_promises2 = require("timers/promises");
370
372
  var import_node_sdk2 = require("@tinycloud/node-sdk");
371
373
  var import_node_sdk_wasm = require("@tinycloud/node-sdk-wasm");
372
374
  var import_artifacts = require("@tinycloud/operations/artifacts");
373
375
  var import_state = require("@tinycloud/operations/state");
374
376
  var import_operations = require("@tinycloud/operations");
377
+ var import_profile = require("@tinycloud/operations/profile");
375
378
  var import_mcp_authority = require("@tinycloud/operations/mcp-authority");
376
379
  var import_tc_apps = require("@tinycloud/operations/tc-apps");
380
+ var import_links2 = require("@tinycloud/share-envelope/links");
377
381
 
378
382
  // src/native-auth.ts
379
383
  var import_node_crypto3 = require("crypto");
@@ -433,9 +437,133 @@ function hasCaveats(permission) {
433
437
  return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
434
438
  }
435
439
 
440
+ // src/openkey-approval.ts
441
+ var import_node_crypto4 = require("crypto");
442
+ var import_links = require("@tinycloud/share-envelope/links");
443
+ var import_registry_publication = require("@tinycloud/sdk-core/registry-publication");
444
+ var MIN_REQUEST_LIFE_MS = 18e4;
445
+ var MAX_RESULT_REPLY_BYTES = 256 * 1024;
446
+ var boundedFetch = Object.assign(async (input, init) => {
447
+ const response = await fetch(input, init);
448
+ const bytes = await (0, import_registry_publication.boundedResponseBytes)(response, MAX_RESULT_REPLY_BYTES);
449
+ return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
450
+ status: response.status,
451
+ statusText: response.statusText
452
+ });
453
+ }, globalThis.fetch);
454
+ async function createOpenKeyRequest(endpoints, input) {
455
+ const signingKey = ed25519PrivateJwk(input.jwk);
456
+ const signer = (0, import_links.signerFromJwk)(signingKey);
457
+ const relay = (0, import_links.generateRelayKey)();
458
+ const request = {
459
+ issuer: signer.did,
460
+ requestVersion: 1,
461
+ targetDid: signer.did,
462
+ targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
463
+ nodeOrigin: new URL(input.nodeHost).origin,
464
+ permissions: input.permissions.map(requestPermission),
465
+ reason: input.reason,
466
+ grantLifetimeSeconds: input.grantLifetimeSeconds,
467
+ resultEncryptionPublicJwk: relay.publicJwk,
468
+ ...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
469
+ };
470
+ const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
471
+ const created = await (0, import_links.createApprovalRequest)({
472
+ request,
473
+ issuerKey: signer,
474
+ apiOrigin: endpoints.linksApiOrigin,
475
+ openkeyOrigin: endpoints.openkeyOrigin,
476
+ expiresAt
477
+ });
478
+ return {
479
+ requestId: created.id,
480
+ bodyCid: created.bodyCid,
481
+ record: { header: created.record.header, signature: created.record.signature },
482
+ link: created.link,
483
+ request,
484
+ expiresAt: created.expiresAt,
485
+ relayPrivateKey: relay.privateKey,
486
+ ackId: (0, import_node_crypto4.randomUUID)(),
487
+ apiOrigin: endpoints.openkeyApiOrigin
488
+ };
489
+ }
490
+ async function collectOpenKeyResult(state, jwk, timeoutMs) {
491
+ const requester = requesterState(state, jwk);
492
+ if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
493
+ const discovered = await (0, import_links.discoverApprovalResult)(requester, { timeoutMs, fetch: boundedFetch });
494
+ if (discovered.status === "pending") return discovered;
495
+ return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
496
+ }
497
+ const relay = await (0, import_links.fetchApprovalResult)(
498
+ requester,
499
+ { resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
500
+ { timeoutMs, fetch: boundedFetch }
501
+ );
502
+ const opened = await (0, import_links.openRelayResult)(relay, state.requestId, state.relayPrivateKey);
503
+ return {
504
+ status: "ready",
505
+ checked: (0, import_links.checkApprovalResultBinding)(opened, {
506
+ requestId: state.requestId,
507
+ bodyCid: state.bodyCid,
508
+ request: state.request
509
+ })
510
+ };
511
+ }
512
+ async function ackOpenKeyResult(state, jwk, timeoutMs) {
513
+ if (state.resultRef === void 0) return;
514
+ await (0, import_links.ackApprovalResult)(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
515
+ }
516
+ function lifetimeSeconds(value) {
517
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
518
+ const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
519
+ const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
520
+ if (!Number.isSafeInteger(seconds) || seconds < 60) {
521
+ throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
522
+ }
523
+ return seconds;
524
+ }
525
+ function requesterState(state, jwk) {
526
+ return {
527
+ requestId: state.requestId,
528
+ bodyCid: state.bodyCid,
529
+ record: state.record,
530
+ apiOrigin: state.apiOrigin,
531
+ signingKey: ed25519PrivateJwk(jwk)
532
+ };
533
+ }
534
+ function requestPermission(entry) {
535
+ if (entry.space === void 0 || entry.space.length === 0) {
536
+ throw new Error("An approval request needs a space for every permission.");
537
+ }
538
+ return {
539
+ service: entry.service,
540
+ space: entry.space,
541
+ path: entry.path,
542
+ actions: [...entry.actions],
543
+ ...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
544
+ };
545
+ }
546
+ function ed25519PrivateJwk(jwk) {
547
+ const { kty, crv, x, d } = jwk;
548
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
549
+ throw new Error("The tenant key is not an Ed25519 private key.");
550
+ }
551
+ return { kty, crv, x, d };
552
+ }
553
+
436
554
  // src/remote-store.ts
437
555
  var PROFILE = "agent";
438
556
  var MAX_CALLBACK_BYTES = 256 * 1024;
557
+ var PENDING_VERSION = 2;
558
+ var CALL_COLLECTION_TIMEOUT_MS = 3e3;
559
+ var CALL_COLLECTION_BUDGET_MS = 3e3;
560
+ var POLL_COLLECTION_TIMEOUT_MS = 1e4;
561
+ var FAST_POLL_WINDOW_MS = 6e4;
562
+ var SLOW_POLL_INTERVAL_MS = 1e4;
563
+ var MAX_COLLECTION_POLLS = 64;
564
+ var RESULT_COLLECTION_GRACE_MS = 6e5;
565
+ var PROCESSING_STALE_MS = 12e4;
566
+ var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
439
567
  var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
440
568
  "DELEGATION_ARTIFACT_INVALID",
441
569
  "DELEGATION_EXPIRED",
@@ -476,6 +604,12 @@ var ApprovalStageError = class extends Error {
476
604
  this.reason = reason;
477
605
  }
478
606
  };
607
+ var RenewalAdmissionUnavailableError = class extends Error {
608
+ constructor(cause) {
609
+ super("The renewal lease could not be admitted yet.", { cause });
610
+ this.name = "RenewalAdmissionUnavailableError";
611
+ }
612
+ };
479
613
  var ApprovalRequestError = class extends Error {
480
614
  detail;
481
615
  constructor(detail, message, cause) {
@@ -484,6 +618,12 @@ var ApprovalRequestError = class extends Error {
484
618
  this.detail = detail;
485
619
  }
486
620
  };
621
+ var ApprovalLinkUnavailableError = class extends Error {
622
+ constructor(cause) {
623
+ super("The approval link could not be created.", { cause });
624
+ this.name = "ApprovalLinkUnavailableError";
625
+ }
626
+ };
487
627
  var NativeGrantValidationError = class extends Error {
488
628
  code;
489
629
  constructor(status) {
@@ -505,10 +645,25 @@ var RemoteTenantStore = class {
505
645
  #scopedClearing = /* @__PURE__ */ new Map();
506
646
  #clearedScoped = /* @__PURE__ */ new Map();
507
647
  #approvalProcessing = /* @__PURE__ */ new Map();
648
+ #linkCreations = /* @__PURE__ */ new Map();
649
+ #collections = /* @__PURE__ */ new Map();
650
+ #polls = /* @__PURE__ */ new Map();
651
+ #closed = false;
652
+ #endpoints;
653
+ #grantLifetimeSeconds;
508
654
  #nativeIdentity;
509
655
  #nativeGrantQueues = /* @__PURE__ */ new Map();
510
656
  constructor(config) {
511
657
  this.#config = config;
658
+ const openkeyOrigin = new URL(config.openkeyHost).origin;
659
+ this.#endpoints = {
660
+ openkeyOrigin,
661
+ openkeyApiOrigin: new URL(
662
+ config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
663
+ ).origin,
664
+ linksApiOrigin: new URL(config.linksApiOrigin ?? import_links2.DEFAULT_LINKS_API_ORIGIN).origin
665
+ };
666
+ this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
512
667
  }
513
668
  async nativeServiceIdentity() {
514
669
  const identity = await this.#loadNativeServiceKey();
@@ -517,7 +672,7 @@ var RemoteTenantStore = class {
517
672
  nativeTenantStateRoot(ownerDid) {
518
673
  const canonical = canonicalOwnerDid(ownerDid);
519
674
  if (canonical === void 0) throw new NativeGrantValidationError("rejected");
520
- const tenant = (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
675
+ const tenant = (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
521
676
  return (0, import_node_path2.join)(this.#config.stateDir, "native-tenants", tenant);
522
677
  }
523
678
  async acceptNativeGrant(serializedDelegation) {
@@ -694,10 +849,13 @@ var RemoteTenantStore = class {
694
849
  }
695
850
  /** Check stored node authority before an authenticated operation uses it. */
696
851
  async validateTenant(subject, ownerDids) {
697
- await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);
852
+ const tenant = await this.#ensureTenant(subject);
853
+ await this.#collectApprovals(tenant);
854
+ await this.#hasValidSession(tenant, ownerDids);
698
855
  }
699
856
  async connectStatus(subject, ownerDids = []) {
700
857
  const tenant = await this.#ensureTenant(subject);
858
+ await this.#collectApprovals(tenant);
701
859
  const state = await this.#sessionState(tenant, ownerDids, true);
702
860
  if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
703
861
  if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
@@ -857,77 +1015,267 @@ var RemoteTenantStore = class {
857
1015
  await clearing;
858
1016
  return "scoped";
859
1017
  }
860
- async approvalRedirect(state) {
861
- const pending = await this.#readPending(state, false);
1018
+ /**
1019
+ * The OpenKey link behind one of this server's `/connect?state=` links. The
1020
+ * first visit creates the OpenKey approval request, signed by the tenant's
1021
+ * own key; later visits reuse it. Collection starts in the background and on
1022
+ * the tenant's next call.
1023
+ */
1024
+ async approvalLink(state) {
1025
+ const located = await this.#readPending(state);
1026
+ const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
1027
+ const prior = this.#linkCreations.get(path);
1028
+ if (prior) return prior;
1029
+ const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
1030
+ this.#linkCreations.set(path, creating);
1031
+ return creating;
1032
+ }
1033
+ async #createApprovalLink(stateRoot, initial) {
1034
+ const path = this.#pendingPath(stateRoot, initial.nonce);
1035
+ const pending = await readJson(path);
1036
+ if (pending === null || pending.version !== PENDING_VERSION) {
1037
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1038
+ }
1039
+ if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
1040
+ if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
1041
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1042
+ }
1043
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1044
+ return pending.openkey.link;
1045
+ }
1046
+ if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
862
1047
  const tenant = await this.#readTenant(pending.tenantId);
863
- const callback = new URL(`${this.#config.approvalPath ?? "/connect"}/callback`, this.#config.publicUrl);
864
- callback.searchParams.set("state", state);
865
- const params = new URLSearchParams({
866
- did: tenant.sessionDid,
867
- callback: callback.toString(),
868
- host: this.#config.nodeHost,
869
- requesterOrigin: this.#config.publicUrl.origin,
870
- jwk: Buffer.from(JSON.stringify((0, import_node_sdk2.publicJwk)(tenant.jwk))).toString("base64url"),
871
- permissions: Buffer.from(JSON.stringify({
1048
+ let openkey;
1049
+ try {
1050
+ openkey = await createOpenKeyRequest(this.#endpoints, {
1051
+ jwk: tenant.jwk,
1052
+ nodeHost: this.#config.nodeHost,
872
1053
  permissions: pending.permissions,
873
- reason: [
874
- pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : (0, import_tc_apps.tcAppsApprovalReason)(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
875
- // Owner DIDs come from the verified OpenKey access token of the MCP
876
- // client that created this link, never from the link itself. The
877
- // callback refuses a signer outside them, so the approver isn't asked to check.
878
- ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
879
- ].join(" ")
880
- })).toString("base64url"),
881
- expiry: this.#config.delegationExpiry
882
- });
883
- return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
884
- }
885
- async completeApproval(state, request) {
886
- const length = Number(request.headers.get("content-length") ?? "0");
887
- if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
888
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1054
+ reason: approvalReason(pending),
1055
+ grantLifetimeSeconds: this.#grantLifetimeSeconds,
1056
+ ...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
1057
+ expiresAt: new Date(pending.expiresAt)
1058
+ });
1059
+ } catch (error) {
1060
+ throw new ApprovalLinkUnavailableError(error);
889
1061
  }
890
- const text = await request.text();
891
- if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {
892
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1062
+ if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
1063
+ throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
893
1064
  }
894
- let data;
1065
+ const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
1066
+ await secureWrite(path, { ...pending, expiresAt, openkey });
1067
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1068
+ return openkey.link;
1069
+ }
1070
+ /**
1071
+ * Collect every approval result this tenant has open in OpenKey before a
1072
+ * call decides whether it is connected. The call waits at most
1073
+ * `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
1074
+ * finishes in the background, and a failure leaves the pending approval for
1075
+ * the next call or poll.
1076
+ */
1077
+ async #collectApprovals(tenant) {
1078
+ const budget = new AbortController();
1079
+ await Promise.race([
1080
+ this.#collectEach(tenant),
1081
+ (0, import_promises2.setTimeout)(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
1082
+ ]).finally(() => budget.abort());
1083
+ }
1084
+ async #collectEach(tenant) {
1085
+ const directory = this.#pendingDirectory(tenant.stateRoot);
1086
+ let names;
895
1087
  try {
896
- data = JSON.parse(text);
1088
+ names = await (0, import_promises.readdir)(directory);
897
1089
  } catch (error) {
898
- throw new ApprovalRequestError("body_invalid", "Callback body is invalid.", error);
1090
+ if (isRecord(error) && error.code === "ENOENT") return;
1091
+ throw error;
1092
+ }
1093
+ for (const name of names) {
1094
+ if (name.endsWith(".json.processing")) await this.#recoverProcessing((0, import_node_path2.join)(directory, name));
1095
+ }
1096
+ const nonces = (await (0, import_promises.readdir)(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
1097
+ for (const nonce of nonces) {
1098
+ await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
1099
+ }
1100
+ }
1101
+ /**
1102
+ * A claimed result whose processing never finished (the server stopped
1103
+ * mid-way). Once it is stored only the acknowledgement remains; otherwise,
1104
+ * after a grace period, it becomes collectable again.
1105
+ */
1106
+ async #recoverProcessing(claimed) {
1107
+ const pending = await readJson(claimed).catch(() => null);
1108
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
1109
+ await (0, import_promises.rm)(claimed, { force: true });
1110
+ return;
899
1111
  }
900
- if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
901
- const pending = await this.#readPending(state, true);
902
1112
  const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", pending.tenantId);
1113
+ if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
1114
+ if (pending.openkey.storedCid !== void 0) {
1115
+ await this.#acknowledge(stateRoot, pending.openkey);
1116
+ await (0, import_promises.rm)(claimed, { force: true });
1117
+ return;
1118
+ }
1119
+ const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
1120
+ if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
1121
+ const { claimedAt: _claimed, ...fresh } = pending;
1122
+ await secureWrite(claimed.slice(0, -".processing".length), fresh);
1123
+ await (0, import_promises.rm)(claimed, { force: true });
1124
+ }
1125
+ /** One collection attempt for one pending approval, single-flight per approval. */
1126
+ async #collectApproval(stateRoot, nonce, timeoutMs) {
1127
+ const path = this.#pendingPath(stateRoot, nonce);
1128
+ const running = this.#collections.get(path);
1129
+ if (running) return running;
1130
+ const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
1131
+ writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
1132
+ return "retry";
1133
+ }).finally(() => this.#collections.delete(path));
1134
+ this.#collections.set(path, collecting);
1135
+ return collecting;
1136
+ }
1137
+ async #collectStep(stateRoot, nonce, timeoutMs) {
1138
+ const path = this.#pendingPath(stateRoot, nonce);
1139
+ const pending = await readJson(path).catch(() => null);
1140
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
1141
+ const openkey = pending.openkey;
1142
+ if (!this.#currentRequest(openkey)) {
1143
+ writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1144
+ await (0, import_promises.rm)(path, { force: true });
1145
+ return "done";
1146
+ }
1147
+ if (Date.now() >= collectionDeadline(openkey)) {
1148
+ await (0, import_promises.rm)(path, { force: true });
1149
+ return "done";
1150
+ }
1151
+ const tenant = await this.#readTenant(pending.tenantId);
1152
+ if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1153
+ await (0, import_promises.rm)(path, { force: true });
1154
+ return "done";
1155
+ }
1156
+ let collected;
1157
+ try {
1158
+ collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
1159
+ } catch (error) {
1160
+ if (!(0, import_links2.isApprovalClientError)(error)) throw error;
1161
+ return this.#collectionRefused(path, pending, error);
1162
+ }
1163
+ if (collected.status === "pending") return "pending";
1164
+ if (collected.status === "discovered") {
1165
+ await secureWrite(path, {
1166
+ ...pending,
1167
+ openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
1168
+ });
1169
+ return this.#collectStep(stateRoot, nonce, timeoutMs);
1170
+ }
1171
+ const claimed = `${path}.processing`;
1172
+ try {
1173
+ await (0, import_promises.rename)(path, claimed);
1174
+ } catch (error) {
1175
+ if (isRecord(error) && error.code === "ENOENT") return "done";
1176
+ throw error;
1177
+ }
1178
+ await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
903
1179
  const prior = this.#approvalProcessing.get(stateRoot);
904
1180
  const processing = (async () => {
905
1181
  if (prior) await prior.catch(() => void 0);
906
- try {
907
- const tenant = await this.#readTenant(pending.tenantId);
908
- if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
909
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
910
- }
911
- if (pending.kind === "bootstrap") {
912
- await this.#storeBootstrap(tenant, pending, data);
913
- } else {
914
- await this.#storeDelegation(tenant, pending, data);
915
- }
916
- await (0, import_promises.rm)(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
917
- } catch (error) {
918
- await this.#restorePending(pending).catch(() => void 0);
919
- throw error;
1182
+ const current = await this.#readTenant(pending.tenantId);
1183
+ if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
1184
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
920
1185
  }
1186
+ const { checked } = collected;
1187
+ const storedCid = pending.kind === "bootstrap" ? await this.#storeBootstrap(current, pending, checked.delegation, checked.ownerDid, checked.renewal) : await this.#storeDelegation(current, pending, checked.delegation, checked.ownerDid);
1188
+ await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
921
1189
  })();
922
1190
  this.#approvalProcessing.set(stateRoot, processing);
923
1191
  try {
924
1192
  await processing;
1193
+ } catch (error) {
1194
+ if (error instanceof RenewalAdmissionUnavailableError) {
1195
+ await secureWrite(path, pending).catch(() => void 0);
1196
+ await (0, import_promises.rm)(claimed, { force: true });
1197
+ writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
1198
+ return "retry";
1199
+ }
1200
+ const { openkey: _spent, ...fresh } = pending;
1201
+ await secureWrite(path, fresh).catch(() => void 0);
1202
+ await (0, import_promises.rm)(claimed, { force: true });
1203
+ writeDiagnostic(approvalRefusalDiagnostic(error));
1204
+ return "done";
925
1205
  } finally {
926
1206
  if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
927
1207
  }
1208
+ await this.#acknowledge(stateRoot, openkey);
1209
+ await (0, import_promises.rm)(claimed, { force: true });
1210
+ return "done";
1211
+ }
1212
+ async #collectionRefused(path, pending, error) {
1213
+ switch (error.code) {
1214
+ case "network":
1215
+ case "unavailable":
1216
+ return "retry";
1217
+ case "request_expired":
1218
+ if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
1219
+ await (0, import_promises.rm)(path, { force: true });
1220
+ return "done";
1221
+ case "acknowledged":
1222
+ await (0, import_promises.rm)(path, { force: true });
1223
+ return "done";
1224
+ default: {
1225
+ const { openkey: _spent, ...fresh } = pending;
1226
+ await secureWrite(path, fresh);
1227
+ writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
1228
+ return "done";
1229
+ }
1230
+ }
1231
+ }
1232
+ async #acknowledge(stateRoot, openkey) {
1233
+ try {
1234
+ const tenant = await this.#readTenant((0, import_node_path2.basename)(stateRoot));
1235
+ await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
1236
+ } catch (error) {
1237
+ writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
1238
+ }
1239
+ }
1240
+ /**
1241
+ * Poll one opened approval until it is collected or its request and result
1242
+ * window end: every 2 s for the first minute, then every 10 s. At most
1243
+ * `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
1244
+ * collects.
1245
+ */
1246
+ #startCollectionPoll(stateRoot, nonce) {
1247
+ const key = this.#pendingPath(stateRoot, nonce);
1248
+ if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
1249
+ const startedAt = Date.now();
1250
+ const schedule = () => {
1251
+ const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? import_links2.APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
1252
+ const timer = setTimeout(() => void tick(), delay);
1253
+ timer.unref();
1254
+ this.#polls.set(key, timer);
1255
+ };
1256
+ const tick = async () => {
1257
+ const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
1258
+ if (this.#closed || outcome === "done" || outcome === "idle") {
1259
+ this.#polls.delete(key);
1260
+ return;
1261
+ }
1262
+ schedule();
1263
+ };
1264
+ schedule();
1265
+ }
1266
+ /** Stop background collection. Pending approvals stay on disk for the next start. */
1267
+ async close() {
1268
+ this.#closed = true;
1269
+ for (const timer of this.#polls.values()) clearTimeout(timer);
1270
+ this.#polls.clear();
1271
+ await Promise.allSettled([...this.#collections.values()]);
928
1272
  }
929
- async #storeBootstrap(tenant, pending, data) {
930
- const { node, session } = await this.#restoreApproval(tenant, data);
1273
+ /** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
1274
+ #currentRequest(openkey) {
1275
+ return openkey.apiOrigin === this.#endpoints.openkeyApiOrigin && URL.canParse(openkey.link) && URL.canParse(this.#endpoints.openkeyOrigin) && new URL(openkey.link).origin === new URL(this.#endpoints.openkeyOrigin).origin;
1276
+ }
1277
+ async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
1278
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
931
1279
  this.#assertCurrentApproval(pending, session);
932
1280
  if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
933
1281
  throw new ApprovalOwnerMismatchError();
@@ -935,6 +1283,7 @@ var RemoteTenantStore = class {
935
1283
  if (!(0, import_node_sdk2.isCapabilitySubset)(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
936
1284
  throw new Error("The approved delegation does not cover the requested account access.");
937
1285
  }
1286
+ if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
938
1287
  const profile = await readJson(this.#profilePath(tenant.stateRoot));
939
1288
  await secureWrite(this.#profilePath(tenant.stateRoot), {
940
1289
  ...profile,
@@ -943,14 +1292,51 @@ var RemoteTenantStore = class {
943
1292
  });
944
1293
  await secureWrite(this.#sessionPath(tenant.stateRoot), {
945
1294
  authMethod: "openkey",
946
- ...session
1295
+ ...session,
1296
+ ...renewal === void 0 ? {} : { renewal }
947
1297
  });
948
1298
  this.#renewalRequired.delete(tenant.stateRoot);
949
1299
  this.#activeSessions.delete(tenant.stateRoot);
1300
+ return session.delegationCid;
950
1301
  }
951
- async #storeDelegation(tenant, pending, data) {
1302
+ /**
1303
+ * Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
1304
+ * session is stored. Admission replays the exact signed lease, so a retry admits the same one.
1305
+ */
1306
+ async #admitRenewal(tenant, ownerDid, session, renewal) {
1307
+ let signed;
1308
+ try {
1309
+ signed = await (0, import_renewal_receipt.verifyOwnerRenewalLease)(session, ownerDid, renewal);
1310
+ } catch (error) {
1311
+ throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
1312
+ }
1313
+ if (Date.parse(signed.originalExpiresAt) - Date.now() < import_renewal_receipt.RENEWAL_ADMISSION_LEAD_MS) {
1314
+ throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
1315
+ }
1316
+ try {
1317
+ await (0, import_renewal.admitOwnerRenewalLease)({
1318
+ host: new URL(this.#config.nodeHost).origin,
1319
+ originalAuthorization: session.delegationHeader.Authorization,
1320
+ originalCid: session.delegationCid,
1321
+ ownerDid,
1322
+ agentDid: tenant.sessionDid.split("#")[0],
1323
+ spaceId: session.spaceId,
1324
+ nodeIdentity: renewal.receipt.nodeIdentity,
1325
+ leaseAuthorization: renewal.receipt.leaseAuthorization,
1326
+ leaseCid: renewal.receipt.leaseCid,
1327
+ leaseExpiresAt: signed.leaseSignedExpiresAt
1328
+ });
1329
+ } catch (error) {
1330
+ const code = isRecord(error) ? error.code : void 0;
1331
+ if (code === import_renewal.RENEWAL_RENEWER_CHANGED || code === import_renewal.RENEWAL_LEASE_ORIGINAL_EXPIRED) {
1332
+ throw new ApprovalStageError("renewal", code, void 0, error);
1333
+ }
1334
+ throw new RenewalAdmissionUnavailableError(error);
1335
+ }
1336
+ }
1337
+ async #storeDelegation(tenant, pending, data, resultOwner) {
952
1338
  if (pending.requestId === void 0) throw new Error("Authority request is missing.");
953
- const { node, session } = await this.#restoreApproval(tenant, data);
1339
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
954
1340
  this.#assertCurrentApproval(pending, session);
955
1341
  if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
956
1342
  let delegation;
@@ -994,6 +1380,7 @@ var RemoteTenantStore = class {
994
1380
  );
995
1381
  }
996
1382
  if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
1383
+ return session.delegationCid;
997
1384
  }
998
1385
  #assertCurrentApproval(pending, session) {
999
1386
  const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
@@ -1002,13 +1389,14 @@ var RemoteTenantStore = class {
1002
1389
  }
1003
1390
  }
1004
1391
  /**
1005
- * Verify the OpenKey callback as a SIWE session for this tenant's key. The
1006
- * callback must carry the full signed proof (SIWE, signature, address and
1007
- * chain), so the WASM verifier always runs: it binds the authorization bytes
1008
- * and CID to the signed SIWE, and `node.did` is the wallet that signed
1009
- * exactly the delegation being stored.
1392
+ * Verify OpenKey's delegation as a SIWE session for this tenant's key. It
1393
+ * must carry the full signed proof (SIWE, signature, address and chain), so
1394
+ * the WASM verifier always runs: it binds the authorization bytes and CID to
1395
+ * the signed SIWE, and `node.did` is the wallet that signed exactly the
1396
+ * delegation being stored. That wallet must be the owner OpenKey's result
1397
+ * names.
1010
1398
  */
1011
- async #restoreApproval(tenant, data) {
1399
+ async #restoreApproval(tenant, data, resultOwner) {
1012
1400
  let session;
1013
1401
  try {
1014
1402
  session = sessionFromCallback(data, tenant.jwk);
@@ -1029,6 +1417,9 @@ var RemoteTenantStore = class {
1029
1417
  if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
1030
1418
  throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
1031
1419
  }
1420
+ if (!samePrincipal(node.did, resultOwner)) {
1421
+ throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
1422
+ }
1032
1423
  return { node, session };
1033
1424
  }
1034
1425
  async #ensureTenant(subject) {
@@ -1067,13 +1458,16 @@ var RemoteTenantStore = class {
1067
1458
  if (raw === null) return "invalid";
1068
1459
  const node = new import_node_sdk2.TinyCloudNode({ host: this.#config.nodeHost });
1069
1460
  try {
1070
- await node.restoreSession(raw);
1071
- } catch {
1461
+ await (0, import_profile.restoreStoredSession)(node, raw, raw);
1462
+ } catch (error) {
1072
1463
  const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
1073
1464
  const signedExpiry = typeof header === "string" ? (0, import_node_sdk2.signedCompactUcanExpiry)(header) : void 0;
1074
1465
  const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
1075
1466
  const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
1076
- if (expiry !== void 0 && expiry.getTime() <= Date.now()) return "invalid";
1467
+ if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
1468
+ const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
1469
+ return (0, import_profile.liveStoredLease)(raw) !== void 0 && !ended ? "unknown" : "invalid";
1470
+ }
1077
1471
  await this.#clearAuthority(tenant);
1078
1472
  return "invalid";
1079
1473
  }
@@ -1208,15 +1602,17 @@ var RemoteTenantStore = class {
1208
1602
  return writing;
1209
1603
  }
1210
1604
  async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
1605
+ const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
1211
1606
  const reusable = await reusablePending(
1212
1607
  this.#pendingDirectory(tenant.stateRoot),
1213
- { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
1608
+ { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
1609
+ (openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
1214
1610
  );
1215
1611
  if (reusable !== void 0) return reusable;
1216
- const nonce = (0, import_node_crypto4.randomBytes)(24).toString("base64url");
1612
+ const nonce = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
1217
1613
  const created = Date.now();
1218
1614
  const pending = {
1219
- version: 1,
1615
+ version: PENDING_VERSION,
1220
1616
  nonce,
1221
1617
  tenantId,
1222
1618
  approvalEpoch: tenant.approvalEpoch,
@@ -1230,7 +1626,7 @@ var RemoteTenantStore = class {
1230
1626
  await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
1231
1627
  return pending;
1232
1628
  }
1233
- async #readPending(state, consume) {
1629
+ async #readPending(state) {
1234
1630
  const [tenantId, nonce, signature] = state.split(".");
1235
1631
  if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
1236
1632
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
@@ -1238,51 +1634,35 @@ var RemoteTenantStore = class {
1238
1634
  const expected = this.#signState(tenantId, nonce);
1239
1635
  const supplied = Buffer.from(signature, "base64url");
1240
1636
  const expectedBytes = Buffer.from(expected, "base64url");
1241
- if (supplied.length !== expectedBytes.length || !(0, import_node_crypto4.timingSafeEqual)(supplied, expectedBytes)) {
1637
+ if (supplied.length !== expectedBytes.length || !(0, import_node_crypto5.timingSafeEqual)(supplied, expectedBytes)) {
1242
1638
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
1243
1639
  }
1244
1640
  const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", tenantId);
1245
1641
  const path = this.#pendingPath(stateRoot, nonce);
1246
- const claimed = `${path}.processing`;
1247
- if (consume) {
1248
- try {
1249
- await (0, import_promises.rename)(path, claimed);
1250
- } catch (error) {
1251
- if (!isRecord(error) || error.code !== "ENOENT") throw error;
1252
- const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1253
- (jwk) => jwk !== null,
1254
- () => true
1255
- );
1256
- if (!tenantExists) {
1257
- throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
1258
- }
1259
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
1260
- }
1642
+ const pending = await readJson(path);
1643
+ if (pending === null) {
1644
+ const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1645
+ (jwk) => jwk !== null,
1646
+ () => true
1647
+ );
1648
+ if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
1649
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1261
1650
  }
1262
- try {
1263
- const pending = await readJson(consume ? claimed : path);
1264
- if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1265
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1266
- }
1267
- const profile = await readJson(this.#profilePath(stateRoot));
1268
- const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1269
- if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1270
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1271
- }
1272
- if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1273
- await (0, import_promises.rm)(consume ? claimed : path, { force: true });
1274
- throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1651
+ if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1652
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1653
+ }
1654
+ const profile = await readJson(this.#profilePath(stateRoot));
1655
+ const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1656
+ if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1657
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1658
+ }
1659
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1660
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
1661
+ await (0, import_promises.rm)(path, { force: true });
1275
1662
  }
1276
- return pending;
1277
- } catch (error) {
1278
- if (consume) await (0, import_promises.rename)(claimed, path).catch(() => void 0);
1279
- throw error;
1663
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1280
1664
  }
1281
- }
1282
- async #restorePending(pending) {
1283
- const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", pending.tenantId);
1284
- const path = this.#pendingPath(stateRoot, pending.nonce);
1285
- await (0, import_promises.rename)(`${path}.processing`, path);
1665
+ return { stateRoot, pending };
1286
1666
  }
1287
1667
  #connectUrl(pending) {
1288
1668
  const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
@@ -1407,10 +1787,10 @@ var RemoteTenantStore = class {
1407
1787
  return (0, import_node_path2.join)(stateRoot, ".tinycloud", "native-grant.json");
1408
1788
  }
1409
1789
  #tenantId(subject) {
1410
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
1790
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
1411
1791
  }
1412
1792
  #signState(tenantId, nonce) {
1413
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
1793
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
1414
1794
  }
1415
1795
  #profilePath(stateRoot) {
1416
1796
  return (0, import_node_path2.join)(stateRoot, ".tinycloud", "profiles", PROFILE, "profile.json");
@@ -1483,6 +1863,37 @@ function sessionFromCallback(data, privateJwk) {
1483
1863
  signature: data.signature
1484
1864
  };
1485
1865
  }
1866
+ function approvalReason(pending) {
1867
+ return [
1868
+ pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : (0, import_tc_apps.tcAppsApprovalReason)(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
1869
+ // Owner DIDs come from the verified OpenKey access token of the MCP
1870
+ // client that created this link, never from the link itself. Collection
1871
+ // refuses a signer outside them, so the approver isn't asked to check.
1872
+ ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
1873
+ ].join(" ");
1874
+ }
1875
+ function collectionDeadline(openkey) {
1876
+ return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
1877
+ }
1878
+ function collectionErrorCode(error) {
1879
+ if ((0, import_links2.isApprovalClientError)(error)) return error.code.toUpperCase();
1880
+ if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
1881
+ return "UNKNOWN";
1882
+ }
1883
+ function approvalRefusalDiagnostic(error) {
1884
+ if (error instanceof ApprovalOwnerMismatchError) {
1885
+ return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
1886
+ }
1887
+ const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
1888
+ const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
1889
+ const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk2.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
1890
+ const detail = error instanceof ApprovalRequestError ? error.detail : "none";
1891
+ return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
1892
+ }
1893
+ function writeDiagnostic(message) {
1894
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
1895
+ `);
1896
+ }
1486
1897
  function samePrincipal(left, right) {
1487
1898
  if (typeof left !== "string") return false;
1488
1899
  try {
@@ -1523,7 +1934,7 @@ async function secureDirectory(path) {
1523
1934
  async function secureWrite(path, value) {
1524
1935
  const directory = (0, import_node_path2.dirname)(path);
1525
1936
  await secureDirectory(directory);
1526
- const temporary = `${path}.${process.pid}.${(0, import_node_crypto4.randomBytes)(8).toString("hex")}.tmp`;
1937
+ const temporary = `${path}.${process.pid}.${(0, import_node_crypto5.randomBytes)(8).toString("hex")}.tmp`;
1527
1938
  await (0, import_promises.writeFile)(temporary, `${JSON.stringify(value, jsonReplacer, 2)}
1528
1939
  `, { mode: 384 });
1529
1940
  await (0, import_promises.rename)(temporary, path);
@@ -1557,7 +1968,7 @@ async function restoreOptionalText(path, contents) {
1557
1968
  await (0, import_promises.writeFile)(path, contents, { mode: 384 });
1558
1969
  await (0, import_promises.chmod)(path, 384);
1559
1970
  }
1560
- async function reusablePending(directory, expected) {
1971
+ async function reusablePending(directory, expected, currentRequest) {
1561
1972
  let names;
1562
1973
  try {
1563
1974
  names = await (0, import_promises.readdir)(directory);
@@ -1570,12 +1981,18 @@ async function reusablePending(directory, expected) {
1570
1981
  if (!name.endsWith(".json")) continue;
1571
1982
  const path = (0, import_node_path2.join)(directory, name);
1572
1983
  const pending = await readJson(path).catch(() => null);
1573
- if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
1984
+ if (pending === null) {
1574
1985
  await (0, import_promises.rm)(path, { force: true });
1575
1986
  continue;
1576
1987
  }
1988
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1989
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
1990
+ await (0, import_promises.rm)(path, { force: true });
1991
+ }
1992
+ continue;
1993
+ }
1577
1994
  active.push(pending);
1578
- if (samePendingRequest(pending, expected)) return pending;
1995
+ if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
1579
1996
  }
1580
1997
  if (active.length >= 64) {
1581
1998
  active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
@@ -1584,7 +2001,7 @@ async function reusablePending(directory, expected) {
1584
2001
  return void 0;
1585
2002
  }
1586
2003
  function samePendingRequest(pending, expected) {
1587
- return pending.version === 1 && pending.tenantId === expected.tenantId && (pending.approvalEpoch ?? 0) === expected.approvalEpoch && pending.kind === expected.kind && pending.requestId === expected.requestId && JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) && JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);
2004
+ return pending.version === PENDING_VERSION && pending.tenantId === expected.tenantId && (pending.approvalEpoch ?? 0) === expected.approvalEpoch && pending.kind === expected.kind && pending.requestId === expected.requestId && JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) && JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);
1588
2005
  }
1589
2006
 
1590
2007
  // src/server.ts
@@ -2100,7 +2517,7 @@ function outcomeCode(result) {
2100
2517
  // package.json
2101
2518
  var package_default = {
2102
2519
  name: "@tinycloud/mcp",
2103
- version: "0.11.1-beta.9",
2520
+ version: "0.12.0-beta.11",
2104
2521
  description: "TinyCloud delegated operations MCP server",
2105
2522
  keywords: [
2106
2523
  "tinycloud",
@@ -2171,10 +2588,11 @@ var package_default = {
2171
2588
  dependencies: {
2172
2589
  "@modelcontextprotocol/node": "2.0.0-beta.5",
2173
2590
  "@modelcontextprotocol/server": "2.0.0-beta.5",
2174
- "@tinycloud/node-sdk": "3.14.0-beta.11",
2175
- "@tinycloud/sdk-core": "3.14.0-beta.11",
2591
+ "@tinycloud/node-sdk": "3.14.0-beta.13",
2592
+ "@tinycloud/sdk-core": "3.14.0-beta.13",
2176
2593
  "@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
2177
- "@tinycloud/operations": "0.9.2-beta.9",
2594
+ "@tinycloud/operations": "0.9.2-beta.11",
2595
+ "@tinycloud/share-envelope": "1.6.0",
2178
2596
  jose: "6.2.4"
2179
2597
  },
2180
2598
  devDependencies: {
@@ -2226,7 +2644,6 @@ function createHostedMcpApp(config) {
2226
2644
  for (const owned of [
2227
2645
  restrictedUrl,
2228
2646
  connectUrl,
2229
- new URL("./connect/callback", restrictedUrl),
2230
2647
  new URL((0, import_server4.getOAuthProtectedResourceMetadataUrl)(restrictedUrl))
2231
2648
  ]) {
2232
2649
  restrictedByPath.set(owned.pathname, restricted);
@@ -2241,7 +2658,6 @@ function createHostedMcpApp(config) {
2241
2658
  }
2242
2659
  function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
2243
2660
  const connectPath = config.approvalPath ?? "/connect";
2244
- const callbackPath = `${connectPath}/callback`;
2245
2661
  const issuer = String(config.oauthMetadata.issuer);
2246
2662
  const jwksUri = String(config.oauthMetadata.jwks_uri);
2247
2663
  const verifier = createOpenKeyTokenVerifier({
@@ -2292,7 +2708,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
2292
2708
  return server;
2293
2709
  }, {
2294
2710
  legacy: "stateless",
2295
- onerror: () => writeDiagnostic("MCP request failed")
2711
+ onerror: () => writeDiagnostic2("MCP request failed")
2296
2712
  });
2297
2713
  const metadataOptions = {
2298
2714
  oauthMetadata: config.oauthMetadata,
@@ -2520,16 +2936,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2520
2936
  if (url.pathname === connectPath) {
2521
2937
  if (request.method !== "GET") return methodNotAllowed("GET");
2522
2938
  try {
2523
- const destination = await store.approvalRedirect(requiredState(url));
2939
+ const destination = await store.approvalLink(requiredState(url));
2524
2940
  return Response.redirect(destination, 302);
2525
2941
  } catch (error) {
2526
- const reason = error instanceof ApprovalRequestError ? error.detail : "unknown";
2527
- writeDiagnostic(`connect rejected: reason=${reason} path=${connectPath}`);
2942
+ const unavailable = error instanceof ApprovalLinkUnavailableError;
2943
+ const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
2944
+ writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
2528
2945
  if (request.headers.get("accept")?.includes("text/html")) {
2529
2946
  return new Response(
2530
- '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TinyCloud approval unavailable</title><main><h1>This approval link is unavailable</h1><p>It may have expired or already been used. Go back to the assistant that sent it and ask it to connect TinyCloud again.</p><p>If you declined access, no further approval is required. Never paste passwords, codes or approval links into support messages.</p></main></html>',
2947
+ unavailable ? '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TinyCloud approval unavailable</title><main><h1>The approval page could not be opened</h1><p>TinyCloud could not reach the approval service. Wait a minute, then open this link again.</p><p>Never paste passwords, codes or approval links into support messages.</p></main></html>' : '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TinyCloud approval unavailable</title><main><h1>This approval link is unavailable</h1><p>It may have expired or already been used. Go back to the assistant that sent it and ask it to connect TinyCloud again.</p><p>If you declined access, no further approval is required. Never paste passwords, codes or approval links into support messages.</p></main></html>',
2531
2948
  {
2532
- status: 400,
2949
+ status: unavailable ? 503 : 400,
2533
2950
  headers: {
2534
2951
  "content-type": "text/html; charset=utf-8",
2535
2952
  "cache-control": "no-store",
@@ -2541,37 +2958,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2541
2958
  }
2542
2959
  );
2543
2960
  }
2544
- return json({ error: "The approval link is invalid or expired." }, 400);
2545
- }
2546
- }
2547
- if (url.pathname === callbackPath) {
2548
- if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
2549
- if (request.method !== "POST") return methodNotAllowed("POST");
2550
- const originFailure = validateCallbackOrigin(request, config.openkeyHost);
2551
- if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
2552
- try {
2553
- await store.completeApproval(requiredState(url), request);
2554
- return callbackCors(json({ success: true }), config.openkeyHost);
2555
- } catch (error) {
2556
- if (error instanceof ApprovalOwnerMismatchError) {
2557
- return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
2558
- }
2559
- const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2560
- const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2561
- const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk3.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2562
- const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2563
- writeDiagnostic(
2564
- `connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
2565
- );
2566
- return callbackCors(
2567
- json({
2568
- error: stage,
2569
- code,
2570
- ...reason === void 0 ? {} : { reason },
2571
- message: "TinyCloud could not accept this delegation."
2572
- }, 400),
2573
- config.openkeyHost
2574
- );
2961
+ return unavailable ? json({ error: "The approval service is unavailable. Wait a minute, then open the link again." }, 503) : json({ error: "The approval link is invalid or expired." }, 400);
2575
2962
  }
2576
2963
  }
2577
2964
  if (url.pathname === "/native/grant" && surface === "hosted") {
@@ -2646,7 +3033,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2646
3033
  const auth = await authenticate(request);
2647
3034
  return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
2648
3035
  },
2649
- close: () => handler.close()
3036
+ close: async () => {
3037
+ await store.close();
3038
+ await handler.close();
3039
+ }
2650
3040
  };
2651
3041
  }
2652
3042
  function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
@@ -2745,18 +3135,6 @@ function mcpCors(response, request) {
2745
3135
  }
2746
3136
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
2747
3137
  }
2748
- function validateCallbackOrigin(request, openkeyHost) {
2749
- const origin = request.headers.get("origin");
2750
- return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
2751
- }
2752
- function callbackCors(response, openkeyHost) {
2753
- const headers = new Headers(response.headers);
2754
- headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
2755
- headers.set("access-control-allow-methods", "POST, OPTIONS");
2756
- headers.set("access-control-allow-headers", "content-type");
2757
- headers.set("vary", "Origin");
2758
- return new Response(response.body, { status: response.status, headers });
2759
- }
2760
3138
  async function readBoundedBodyText(request, maxBytes) {
2761
3139
  const contentLength = request.headers.get("content-length");
2762
3140
  if (contentLength !== null) {
@@ -2831,7 +3209,7 @@ function publicText(text, contentType) {
2831
3209
  function methodNotAllowed(allow) {
2832
3210
  return new Response("Method not allowed", { status: 405, headers: { allow } });
2833
3211
  }
2834
- function writeDiagnostic(message) {
3212
+ function writeDiagnostic2(message) {
2835
3213
  process.stderr.write(`[tinycloud-mcp-http] ${message}
2836
3214
  `);
2837
3215
  }