@tinycloud/mcp 0.11.1-beta.8 → 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-cli.cjs CHANGED
@@ -30,7 +30,6 @@ var import_node = require("@modelcontextprotocol/node");
30
30
  // src/http.ts
31
31
  var import_node_path4 = require("path");
32
32
  var import_server4 = require("@modelcontextprotocol/server");
33
- var import_node_sdk3 = require("@tinycloud/node-sdk");
34
33
 
35
34
  // src/agent-discovery.ts
36
35
  var import_node_crypto = require("crypto");
@@ -381,16 +380,21 @@ function logToolCall(tool, code, startedAt, replayedGrants) {
381
380
 
382
381
  // src/remote-store.ts
383
382
  var import_sdk_core = require("@tinycloud/sdk-core");
384
- var import_node_crypto4 = require("crypto");
383
+ var import_renewal = require("@tinycloud/sdk-core/delegations/renewal");
384
+ var import_renewal_receipt = require("@tinycloud/sdk-core/delegations/renewal-receipt");
385
+ var import_node_crypto5 = require("crypto");
385
386
  var import_promises = require("fs/promises");
386
387
  var import_node_path2 = require("path");
388
+ var import_promises2 = require("timers/promises");
387
389
  var import_node_sdk2 = require("@tinycloud/node-sdk");
388
390
  var import_node_sdk_wasm = require("@tinycloud/node-sdk-wasm");
389
391
  var import_artifacts = require("@tinycloud/operations/artifacts");
390
392
  var import_state = require("@tinycloud/operations/state");
391
393
  var import_operations = require("@tinycloud/operations");
394
+ var import_profile = require("@tinycloud/operations/profile");
392
395
  var import_mcp_authority = require("@tinycloud/operations/mcp-authority");
393
396
  var import_tc_apps = require("@tinycloud/operations/tc-apps");
397
+ var import_links2 = require("@tinycloud/share-envelope/links");
394
398
 
395
399
  // src/native-auth.ts
396
400
  var import_node_crypto3 = require("crypto");
@@ -450,9 +454,133 @@ function hasCaveats(permission) {
450
454
  return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
451
455
  }
452
456
 
457
+ // src/openkey-approval.ts
458
+ var import_node_crypto4 = require("crypto");
459
+ var import_links = require("@tinycloud/share-envelope/links");
460
+ var import_registry_publication = require("@tinycloud/sdk-core/registry-publication");
461
+ var MIN_REQUEST_LIFE_MS = 18e4;
462
+ var MAX_RESULT_REPLY_BYTES = 256 * 1024;
463
+ var boundedFetch = Object.assign(async (input, init) => {
464
+ const response = await fetch(input, init);
465
+ const bytes = await (0, import_registry_publication.boundedResponseBytes)(response, MAX_RESULT_REPLY_BYTES);
466
+ return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
467
+ status: response.status,
468
+ statusText: response.statusText
469
+ });
470
+ }, globalThis.fetch);
471
+ async function createOpenKeyRequest(endpoints, input) {
472
+ const signingKey = ed25519PrivateJwk(input.jwk);
473
+ const signer = (0, import_links.signerFromJwk)(signingKey);
474
+ const relay = (0, import_links.generateRelayKey)();
475
+ const request = {
476
+ issuer: signer.did,
477
+ requestVersion: 1,
478
+ targetDid: signer.did,
479
+ targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
480
+ nodeOrigin: new URL(input.nodeHost).origin,
481
+ permissions: input.permissions.map(requestPermission),
482
+ reason: input.reason,
483
+ grantLifetimeSeconds: input.grantLifetimeSeconds,
484
+ resultEncryptionPublicJwk: relay.publicJwk,
485
+ ...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
486
+ };
487
+ const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
488
+ const created = await (0, import_links.createApprovalRequest)({
489
+ request,
490
+ issuerKey: signer,
491
+ apiOrigin: endpoints.linksApiOrigin,
492
+ openkeyOrigin: endpoints.openkeyOrigin,
493
+ expiresAt
494
+ });
495
+ return {
496
+ requestId: created.id,
497
+ bodyCid: created.bodyCid,
498
+ record: { header: created.record.header, signature: created.record.signature },
499
+ link: created.link,
500
+ request,
501
+ expiresAt: created.expiresAt,
502
+ relayPrivateKey: relay.privateKey,
503
+ ackId: (0, import_node_crypto4.randomUUID)(),
504
+ apiOrigin: endpoints.openkeyApiOrigin
505
+ };
506
+ }
507
+ async function collectOpenKeyResult(state, jwk, timeoutMs) {
508
+ const requester = requesterState(state, jwk);
509
+ if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
510
+ const discovered = await (0, import_links.discoverApprovalResult)(requester, { timeoutMs, fetch: boundedFetch });
511
+ if (discovered.status === "pending") return discovered;
512
+ return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
513
+ }
514
+ const relay = await (0, import_links.fetchApprovalResult)(
515
+ requester,
516
+ { resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
517
+ { timeoutMs, fetch: boundedFetch }
518
+ );
519
+ const opened = await (0, import_links.openRelayResult)(relay, state.requestId, state.relayPrivateKey);
520
+ return {
521
+ status: "ready",
522
+ checked: (0, import_links.checkApprovalResultBinding)(opened, {
523
+ requestId: state.requestId,
524
+ bodyCid: state.bodyCid,
525
+ request: state.request
526
+ })
527
+ };
528
+ }
529
+ async function ackOpenKeyResult(state, jwk, timeoutMs) {
530
+ if (state.resultRef === void 0) return;
531
+ await (0, import_links.ackApprovalResult)(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
532
+ }
533
+ function lifetimeSeconds(value) {
534
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
535
+ const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
536
+ const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
537
+ if (!Number.isSafeInteger(seconds) || seconds < 60) {
538
+ throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
539
+ }
540
+ return seconds;
541
+ }
542
+ function requesterState(state, jwk) {
543
+ return {
544
+ requestId: state.requestId,
545
+ bodyCid: state.bodyCid,
546
+ record: state.record,
547
+ apiOrigin: state.apiOrigin,
548
+ signingKey: ed25519PrivateJwk(jwk)
549
+ };
550
+ }
551
+ function requestPermission(entry) {
552
+ if (entry.space === void 0 || entry.space.length === 0) {
553
+ throw new Error("An approval request needs a space for every permission.");
554
+ }
555
+ return {
556
+ service: entry.service,
557
+ space: entry.space,
558
+ path: entry.path,
559
+ actions: [...entry.actions],
560
+ ...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
561
+ };
562
+ }
563
+ function ed25519PrivateJwk(jwk) {
564
+ const { kty, crv, x, d } = jwk;
565
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
566
+ throw new Error("The tenant key is not an Ed25519 private key.");
567
+ }
568
+ return { kty, crv, x, d };
569
+ }
570
+
453
571
  // src/remote-store.ts
454
572
  var PROFILE = "agent";
455
573
  var MAX_CALLBACK_BYTES = 256 * 1024;
574
+ var PENDING_VERSION = 2;
575
+ var CALL_COLLECTION_TIMEOUT_MS = 3e3;
576
+ var CALL_COLLECTION_BUDGET_MS = 3e3;
577
+ var POLL_COLLECTION_TIMEOUT_MS = 1e4;
578
+ var FAST_POLL_WINDOW_MS = 6e4;
579
+ var SLOW_POLL_INTERVAL_MS = 1e4;
580
+ var MAX_COLLECTION_POLLS = 64;
581
+ var RESULT_COLLECTION_GRACE_MS = 6e5;
582
+ var PROCESSING_STALE_MS = 12e4;
583
+ var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
456
584
  var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
457
585
  "DELEGATION_ARTIFACT_INVALID",
458
586
  "DELEGATION_EXPIRED",
@@ -493,6 +621,12 @@ var ApprovalStageError = class extends Error {
493
621
  this.reason = reason;
494
622
  }
495
623
  };
624
+ var RenewalAdmissionUnavailableError = class extends Error {
625
+ constructor(cause) {
626
+ super("The renewal lease could not be admitted yet.", { cause });
627
+ this.name = "RenewalAdmissionUnavailableError";
628
+ }
629
+ };
496
630
  var ApprovalRequestError = class extends Error {
497
631
  detail;
498
632
  constructor(detail, message, cause) {
@@ -501,6 +635,12 @@ var ApprovalRequestError = class extends Error {
501
635
  this.detail = detail;
502
636
  }
503
637
  };
638
+ var ApprovalLinkUnavailableError = class extends Error {
639
+ constructor(cause) {
640
+ super("The approval link could not be created.", { cause });
641
+ this.name = "ApprovalLinkUnavailableError";
642
+ }
643
+ };
504
644
  var NativeGrantValidationError = class extends Error {
505
645
  code;
506
646
  constructor(status) {
@@ -522,10 +662,25 @@ var RemoteTenantStore = class {
522
662
  #scopedClearing = /* @__PURE__ */ new Map();
523
663
  #clearedScoped = /* @__PURE__ */ new Map();
524
664
  #approvalProcessing = /* @__PURE__ */ new Map();
665
+ #linkCreations = /* @__PURE__ */ new Map();
666
+ #collections = /* @__PURE__ */ new Map();
667
+ #polls = /* @__PURE__ */ new Map();
668
+ #closed = false;
669
+ #endpoints;
670
+ #grantLifetimeSeconds;
525
671
  #nativeIdentity;
526
672
  #nativeGrantQueues = /* @__PURE__ */ new Map();
527
673
  constructor(config) {
528
674
  this.#config = config;
675
+ const openkeyOrigin = new URL(config.openkeyHost).origin;
676
+ this.#endpoints = {
677
+ openkeyOrigin,
678
+ openkeyApiOrigin: new URL(
679
+ config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
680
+ ).origin,
681
+ linksApiOrigin: new URL(config.linksApiOrigin ?? import_links2.DEFAULT_LINKS_API_ORIGIN).origin
682
+ };
683
+ this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
529
684
  }
530
685
  async nativeServiceIdentity() {
531
686
  const identity = await this.#loadNativeServiceKey();
@@ -534,7 +689,7 @@ var RemoteTenantStore = class {
534
689
  nativeTenantStateRoot(ownerDid) {
535
690
  const canonical = canonicalOwnerDid(ownerDid);
536
691
  if (canonical === void 0) throw new NativeGrantValidationError("rejected");
537
- const tenant = (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
692
+ const tenant = (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
538
693
  return (0, import_node_path2.join)(this.#config.stateDir, "native-tenants", tenant);
539
694
  }
540
695
  async acceptNativeGrant(serializedDelegation) {
@@ -711,10 +866,13 @@ var RemoteTenantStore = class {
711
866
  }
712
867
  /** Check stored node authority before an authenticated operation uses it. */
713
868
  async validateTenant(subject, ownerDids) {
714
- await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);
869
+ const tenant = await this.#ensureTenant(subject);
870
+ await this.#collectApprovals(tenant);
871
+ await this.#hasValidSession(tenant, ownerDids);
715
872
  }
716
873
  async connectStatus(subject, ownerDids = []) {
717
874
  const tenant = await this.#ensureTenant(subject);
875
+ await this.#collectApprovals(tenant);
718
876
  const state = await this.#sessionState(tenant, ownerDids, true);
719
877
  if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
720
878
  if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
@@ -874,77 +1032,267 @@ var RemoteTenantStore = class {
874
1032
  await clearing;
875
1033
  return "scoped";
876
1034
  }
877
- async approvalRedirect(state) {
878
- const pending = await this.#readPending(state, false);
1035
+ /**
1036
+ * The OpenKey link behind one of this server's `/connect?state=` links. The
1037
+ * first visit creates the OpenKey approval request, signed by the tenant's
1038
+ * own key; later visits reuse it. Collection starts in the background and on
1039
+ * the tenant's next call.
1040
+ */
1041
+ async approvalLink(state) {
1042
+ const located = await this.#readPending(state);
1043
+ const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
1044
+ const prior = this.#linkCreations.get(path);
1045
+ if (prior) return prior;
1046
+ const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
1047
+ this.#linkCreations.set(path, creating);
1048
+ return creating;
1049
+ }
1050
+ async #createApprovalLink(stateRoot, initial) {
1051
+ const path = this.#pendingPath(stateRoot, initial.nonce);
1052
+ const pending = await readJson(path);
1053
+ if (pending === null || pending.version !== PENDING_VERSION) {
1054
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1055
+ }
1056
+ if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
1057
+ if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
1058
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1059
+ }
1060
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1061
+ return pending.openkey.link;
1062
+ }
1063
+ if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
879
1064
  const tenant = await this.#readTenant(pending.tenantId);
880
- const callback = new URL(`${this.#config.approvalPath ?? "/connect"}/callback`, this.#config.publicUrl);
881
- callback.searchParams.set("state", state);
882
- const params = new URLSearchParams({
883
- did: tenant.sessionDid,
884
- callback: callback.toString(),
885
- host: this.#config.nodeHost,
886
- requesterOrigin: this.#config.publicUrl.origin,
887
- jwk: Buffer.from(JSON.stringify((0, import_node_sdk2.publicJwk)(tenant.jwk))).toString("base64url"),
888
- permissions: Buffer.from(JSON.stringify({
1065
+ let openkey;
1066
+ try {
1067
+ openkey = await createOpenKeyRequest(this.#endpoints, {
1068
+ jwk: tenant.jwk,
1069
+ nodeHost: this.#config.nodeHost,
889
1070
  permissions: pending.permissions,
890
- reason: [
891
- 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.",
892
- // Owner DIDs come from the verified OpenKey access token of the MCP
893
- // client that created this link, never from the link itself. The
894
- // callback refuses a signer outside them, so the approver isn't asked to check.
895
- ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
896
- ].join(" ")
897
- })).toString("base64url"),
898
- expiry: this.#config.delegationExpiry
899
- });
900
- return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
901
- }
902
- async completeApproval(state, request) {
903
- const length = Number(request.headers.get("content-length") ?? "0");
904
- if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
905
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1071
+ reason: approvalReason(pending),
1072
+ grantLifetimeSeconds: this.#grantLifetimeSeconds,
1073
+ ...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
1074
+ expiresAt: new Date(pending.expiresAt)
1075
+ });
1076
+ } catch (error) {
1077
+ throw new ApprovalLinkUnavailableError(error);
906
1078
  }
907
- const text = await request.text();
908
- if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {
909
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1079
+ if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
1080
+ throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
910
1081
  }
911
- let data;
1082
+ const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
1083
+ await secureWrite(path, { ...pending, expiresAt, openkey });
1084
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1085
+ return openkey.link;
1086
+ }
1087
+ /**
1088
+ * Collect every approval result this tenant has open in OpenKey before a
1089
+ * call decides whether it is connected. The call waits at most
1090
+ * `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
1091
+ * finishes in the background, and a failure leaves the pending approval for
1092
+ * the next call or poll.
1093
+ */
1094
+ async #collectApprovals(tenant) {
1095
+ const budget = new AbortController();
1096
+ await Promise.race([
1097
+ this.#collectEach(tenant),
1098
+ (0, import_promises2.setTimeout)(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
1099
+ ]).finally(() => budget.abort());
1100
+ }
1101
+ async #collectEach(tenant) {
1102
+ const directory = this.#pendingDirectory(tenant.stateRoot);
1103
+ let names;
912
1104
  try {
913
- data = JSON.parse(text);
1105
+ names = await (0, import_promises.readdir)(directory);
914
1106
  } catch (error) {
915
- throw new ApprovalRequestError("body_invalid", "Callback body is invalid.", error);
1107
+ if (isRecord(error) && error.code === "ENOENT") return;
1108
+ throw error;
1109
+ }
1110
+ for (const name of names) {
1111
+ if (name.endsWith(".json.processing")) await this.#recoverProcessing((0, import_node_path2.join)(directory, name));
1112
+ }
1113
+ const nonces = (await (0, import_promises.readdir)(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
1114
+ for (const nonce of nonces) {
1115
+ await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
1116
+ }
1117
+ }
1118
+ /**
1119
+ * A claimed result whose processing never finished (the server stopped
1120
+ * mid-way). Once it is stored only the acknowledgement remains; otherwise,
1121
+ * after a grace period, it becomes collectable again.
1122
+ */
1123
+ async #recoverProcessing(claimed) {
1124
+ const pending = await readJson(claimed).catch(() => null);
1125
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
1126
+ await (0, import_promises.rm)(claimed, { force: true });
1127
+ return;
916
1128
  }
917
- if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
918
- const pending = await this.#readPending(state, true);
919
1129
  const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", pending.tenantId);
1130
+ if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
1131
+ if (pending.openkey.storedCid !== void 0) {
1132
+ await this.#acknowledge(stateRoot, pending.openkey);
1133
+ await (0, import_promises.rm)(claimed, { force: true });
1134
+ return;
1135
+ }
1136
+ const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
1137
+ if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
1138
+ const { claimedAt: _claimed, ...fresh } = pending;
1139
+ await secureWrite(claimed.slice(0, -".processing".length), fresh);
1140
+ await (0, import_promises.rm)(claimed, { force: true });
1141
+ }
1142
+ /** One collection attempt for one pending approval, single-flight per approval. */
1143
+ async #collectApproval(stateRoot, nonce, timeoutMs) {
1144
+ const path = this.#pendingPath(stateRoot, nonce);
1145
+ const running = this.#collections.get(path);
1146
+ if (running) return running;
1147
+ const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
1148
+ writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
1149
+ return "retry";
1150
+ }).finally(() => this.#collections.delete(path));
1151
+ this.#collections.set(path, collecting);
1152
+ return collecting;
1153
+ }
1154
+ async #collectStep(stateRoot, nonce, timeoutMs) {
1155
+ const path = this.#pendingPath(stateRoot, nonce);
1156
+ const pending = await readJson(path).catch(() => null);
1157
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
1158
+ const openkey = pending.openkey;
1159
+ if (!this.#currentRequest(openkey)) {
1160
+ writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1161
+ await (0, import_promises.rm)(path, { force: true });
1162
+ return "done";
1163
+ }
1164
+ if (Date.now() >= collectionDeadline(openkey)) {
1165
+ await (0, import_promises.rm)(path, { force: true });
1166
+ return "done";
1167
+ }
1168
+ const tenant = await this.#readTenant(pending.tenantId);
1169
+ if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1170
+ await (0, import_promises.rm)(path, { force: true });
1171
+ return "done";
1172
+ }
1173
+ let collected;
1174
+ try {
1175
+ collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
1176
+ } catch (error) {
1177
+ if (!(0, import_links2.isApprovalClientError)(error)) throw error;
1178
+ return this.#collectionRefused(path, pending, error);
1179
+ }
1180
+ if (collected.status === "pending") return "pending";
1181
+ if (collected.status === "discovered") {
1182
+ await secureWrite(path, {
1183
+ ...pending,
1184
+ openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
1185
+ });
1186
+ return this.#collectStep(stateRoot, nonce, timeoutMs);
1187
+ }
1188
+ const claimed = `${path}.processing`;
1189
+ try {
1190
+ await (0, import_promises.rename)(path, claimed);
1191
+ } catch (error) {
1192
+ if (isRecord(error) && error.code === "ENOENT") return "done";
1193
+ throw error;
1194
+ }
1195
+ await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
920
1196
  const prior = this.#approvalProcessing.get(stateRoot);
921
1197
  const processing = (async () => {
922
1198
  if (prior) await prior.catch(() => void 0);
923
- try {
924
- const tenant = await this.#readTenant(pending.tenantId);
925
- if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
926
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
927
- }
928
- if (pending.kind === "bootstrap") {
929
- await this.#storeBootstrap(tenant, pending, data);
930
- } else {
931
- await this.#storeDelegation(tenant, pending, data);
932
- }
933
- await (0, import_promises.rm)(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
934
- } catch (error) {
935
- await this.#restorePending(pending).catch(() => void 0);
936
- throw error;
1199
+ const current = await this.#readTenant(pending.tenantId);
1200
+ if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
1201
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
937
1202
  }
1203
+ const { checked } = collected;
1204
+ 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);
1205
+ await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
938
1206
  })();
939
1207
  this.#approvalProcessing.set(stateRoot, processing);
940
1208
  try {
941
1209
  await processing;
1210
+ } catch (error) {
1211
+ if (error instanceof RenewalAdmissionUnavailableError) {
1212
+ await secureWrite(path, pending).catch(() => void 0);
1213
+ await (0, import_promises.rm)(claimed, { force: true });
1214
+ writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
1215
+ return "retry";
1216
+ }
1217
+ const { openkey: _spent, ...fresh } = pending;
1218
+ await secureWrite(path, fresh).catch(() => void 0);
1219
+ await (0, import_promises.rm)(claimed, { force: true });
1220
+ writeDiagnostic(approvalRefusalDiagnostic(error));
1221
+ return "done";
942
1222
  } finally {
943
1223
  if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
944
1224
  }
1225
+ await this.#acknowledge(stateRoot, openkey);
1226
+ await (0, import_promises.rm)(claimed, { force: true });
1227
+ return "done";
1228
+ }
1229
+ async #collectionRefused(path, pending, error) {
1230
+ switch (error.code) {
1231
+ case "network":
1232
+ case "unavailable":
1233
+ return "retry";
1234
+ case "request_expired":
1235
+ if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
1236
+ await (0, import_promises.rm)(path, { force: true });
1237
+ return "done";
1238
+ case "acknowledged":
1239
+ await (0, import_promises.rm)(path, { force: true });
1240
+ return "done";
1241
+ default: {
1242
+ const { openkey: _spent, ...fresh } = pending;
1243
+ await secureWrite(path, fresh);
1244
+ writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
1245
+ return "done";
1246
+ }
1247
+ }
1248
+ }
1249
+ async #acknowledge(stateRoot, openkey) {
1250
+ try {
1251
+ const tenant = await this.#readTenant((0, import_node_path2.basename)(stateRoot));
1252
+ await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
1253
+ } catch (error) {
1254
+ writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
1255
+ }
1256
+ }
1257
+ /**
1258
+ * Poll one opened approval until it is collected or its request and result
1259
+ * window end: every 2 s for the first minute, then every 10 s. At most
1260
+ * `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
1261
+ * collects.
1262
+ */
1263
+ #startCollectionPoll(stateRoot, nonce) {
1264
+ const key = this.#pendingPath(stateRoot, nonce);
1265
+ if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
1266
+ const startedAt = Date.now();
1267
+ const schedule = () => {
1268
+ const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? import_links2.APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
1269
+ const timer = setTimeout(() => void tick(), delay);
1270
+ timer.unref();
1271
+ this.#polls.set(key, timer);
1272
+ };
1273
+ const tick = async () => {
1274
+ const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
1275
+ if (this.#closed || outcome === "done" || outcome === "idle") {
1276
+ this.#polls.delete(key);
1277
+ return;
1278
+ }
1279
+ schedule();
1280
+ };
1281
+ schedule();
1282
+ }
1283
+ /** Stop background collection. Pending approvals stay on disk for the next start. */
1284
+ async close() {
1285
+ this.#closed = true;
1286
+ for (const timer of this.#polls.values()) clearTimeout(timer);
1287
+ this.#polls.clear();
1288
+ await Promise.allSettled([...this.#collections.values()]);
945
1289
  }
946
- async #storeBootstrap(tenant, pending, data) {
947
- const { node, session } = await this.#restoreApproval(tenant, data);
1290
+ /** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
1291
+ #currentRequest(openkey) {
1292
+ 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;
1293
+ }
1294
+ async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
1295
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
948
1296
  this.#assertCurrentApproval(pending, session);
949
1297
  if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
950
1298
  throw new ApprovalOwnerMismatchError();
@@ -952,6 +1300,7 @@ var RemoteTenantStore = class {
952
1300
  if (!(0, import_node_sdk2.isCapabilitySubset)(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
953
1301
  throw new Error("The approved delegation does not cover the requested account access.");
954
1302
  }
1303
+ if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
955
1304
  const profile = await readJson(this.#profilePath(tenant.stateRoot));
956
1305
  await secureWrite(this.#profilePath(tenant.stateRoot), {
957
1306
  ...profile,
@@ -960,14 +1309,51 @@ var RemoteTenantStore = class {
960
1309
  });
961
1310
  await secureWrite(this.#sessionPath(tenant.stateRoot), {
962
1311
  authMethod: "openkey",
963
- ...session
1312
+ ...session,
1313
+ ...renewal === void 0 ? {} : { renewal }
964
1314
  });
965
1315
  this.#renewalRequired.delete(tenant.stateRoot);
966
1316
  this.#activeSessions.delete(tenant.stateRoot);
1317
+ return session.delegationCid;
967
1318
  }
968
- async #storeDelegation(tenant, pending, data) {
1319
+ /**
1320
+ * Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
1321
+ * session is stored. Admission replays the exact signed lease, so a retry admits the same one.
1322
+ */
1323
+ async #admitRenewal(tenant, ownerDid, session, renewal) {
1324
+ let signed;
1325
+ try {
1326
+ signed = await (0, import_renewal_receipt.verifyOwnerRenewalLease)(session, ownerDid, renewal);
1327
+ } catch (error) {
1328
+ throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
1329
+ }
1330
+ if (Date.parse(signed.originalExpiresAt) - Date.now() < import_renewal_receipt.RENEWAL_ADMISSION_LEAD_MS) {
1331
+ throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
1332
+ }
1333
+ try {
1334
+ await (0, import_renewal.admitOwnerRenewalLease)({
1335
+ host: new URL(this.#config.nodeHost).origin,
1336
+ originalAuthorization: session.delegationHeader.Authorization,
1337
+ originalCid: session.delegationCid,
1338
+ ownerDid,
1339
+ agentDid: tenant.sessionDid.split("#")[0],
1340
+ spaceId: session.spaceId,
1341
+ nodeIdentity: renewal.receipt.nodeIdentity,
1342
+ leaseAuthorization: renewal.receipt.leaseAuthorization,
1343
+ leaseCid: renewal.receipt.leaseCid,
1344
+ leaseExpiresAt: signed.leaseSignedExpiresAt
1345
+ });
1346
+ } catch (error) {
1347
+ const code = isRecord(error) ? error.code : void 0;
1348
+ if (code === import_renewal.RENEWAL_RENEWER_CHANGED || code === import_renewal.RENEWAL_LEASE_ORIGINAL_EXPIRED) {
1349
+ throw new ApprovalStageError("renewal", code, void 0, error);
1350
+ }
1351
+ throw new RenewalAdmissionUnavailableError(error);
1352
+ }
1353
+ }
1354
+ async #storeDelegation(tenant, pending, data, resultOwner) {
969
1355
  if (pending.requestId === void 0) throw new Error("Authority request is missing.");
970
- const { node, session } = await this.#restoreApproval(tenant, data);
1356
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
971
1357
  this.#assertCurrentApproval(pending, session);
972
1358
  if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
973
1359
  let delegation;
@@ -1011,6 +1397,7 @@ var RemoteTenantStore = class {
1011
1397
  );
1012
1398
  }
1013
1399
  if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
1400
+ return session.delegationCid;
1014
1401
  }
1015
1402
  #assertCurrentApproval(pending, session) {
1016
1403
  const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
@@ -1019,13 +1406,14 @@ var RemoteTenantStore = class {
1019
1406
  }
1020
1407
  }
1021
1408
  /**
1022
- * Verify the OpenKey callback as a SIWE session for this tenant's key. The
1023
- * callback must carry the full signed proof (SIWE, signature, address and
1024
- * chain), so the WASM verifier always runs: it binds the authorization bytes
1025
- * and CID to the signed SIWE, and `node.did` is the wallet that signed
1026
- * exactly the delegation being stored.
1409
+ * Verify OpenKey's delegation as a SIWE session for this tenant's key. It
1410
+ * must carry the full signed proof (SIWE, signature, address and chain), so
1411
+ * the WASM verifier always runs: it binds the authorization bytes and CID to
1412
+ * the signed SIWE, and `node.did` is the wallet that signed exactly the
1413
+ * delegation being stored. That wallet must be the owner OpenKey's result
1414
+ * names.
1027
1415
  */
1028
- async #restoreApproval(tenant, data) {
1416
+ async #restoreApproval(tenant, data, resultOwner) {
1029
1417
  let session;
1030
1418
  try {
1031
1419
  session = sessionFromCallback(data, tenant.jwk);
@@ -1046,6 +1434,9 @@ var RemoteTenantStore = class {
1046
1434
  if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
1047
1435
  throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
1048
1436
  }
1437
+ if (!samePrincipal(node.did, resultOwner)) {
1438
+ throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
1439
+ }
1049
1440
  return { node, session };
1050
1441
  }
1051
1442
  async #ensureTenant(subject) {
@@ -1084,13 +1475,16 @@ var RemoteTenantStore = class {
1084
1475
  if (raw === null) return "invalid";
1085
1476
  const node = new import_node_sdk2.TinyCloudNode({ host: this.#config.nodeHost });
1086
1477
  try {
1087
- await node.restoreSession(raw);
1088
- } catch {
1478
+ await (0, import_profile.restoreStoredSession)(node, raw, raw);
1479
+ } catch (error) {
1089
1480
  const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
1090
1481
  const signedExpiry = typeof header === "string" ? (0, import_node_sdk2.signedCompactUcanExpiry)(header) : void 0;
1091
1482
  const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
1092
1483
  const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
1093
- if (expiry !== void 0 && expiry.getTime() <= Date.now()) return "invalid";
1484
+ if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
1485
+ const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
1486
+ return (0, import_profile.liveStoredLease)(raw) !== void 0 && !ended ? "unknown" : "invalid";
1487
+ }
1094
1488
  await this.#clearAuthority(tenant);
1095
1489
  return "invalid";
1096
1490
  }
@@ -1225,15 +1619,17 @@ var RemoteTenantStore = class {
1225
1619
  return writing;
1226
1620
  }
1227
1621
  async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
1622
+ const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
1228
1623
  const reusable = await reusablePending(
1229
1624
  this.#pendingDirectory(tenant.stateRoot),
1230
- { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
1625
+ { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
1626
+ (openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
1231
1627
  );
1232
1628
  if (reusable !== void 0) return reusable;
1233
- const nonce = (0, import_node_crypto4.randomBytes)(24).toString("base64url");
1629
+ const nonce = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
1234
1630
  const created = Date.now();
1235
1631
  const pending = {
1236
- version: 1,
1632
+ version: PENDING_VERSION,
1237
1633
  nonce,
1238
1634
  tenantId,
1239
1635
  approvalEpoch: tenant.approvalEpoch,
@@ -1247,7 +1643,7 @@ var RemoteTenantStore = class {
1247
1643
  await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
1248
1644
  return pending;
1249
1645
  }
1250
- async #readPending(state, consume) {
1646
+ async #readPending(state) {
1251
1647
  const [tenantId, nonce, signature] = state.split(".");
1252
1648
  if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
1253
1649
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
@@ -1255,51 +1651,35 @@ var RemoteTenantStore = class {
1255
1651
  const expected = this.#signState(tenantId, nonce);
1256
1652
  const supplied = Buffer.from(signature, "base64url");
1257
1653
  const expectedBytes = Buffer.from(expected, "base64url");
1258
- if (supplied.length !== expectedBytes.length || !(0, import_node_crypto4.timingSafeEqual)(supplied, expectedBytes)) {
1654
+ if (supplied.length !== expectedBytes.length || !(0, import_node_crypto5.timingSafeEqual)(supplied, expectedBytes)) {
1259
1655
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
1260
1656
  }
1261
1657
  const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", tenantId);
1262
1658
  const path = this.#pendingPath(stateRoot, nonce);
1263
- const claimed = `${path}.processing`;
1264
- if (consume) {
1265
- try {
1266
- await (0, import_promises.rename)(path, claimed);
1267
- } catch (error) {
1268
- if (!isRecord(error) || error.code !== "ENOENT") throw error;
1269
- const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1270
- (jwk) => jwk !== null,
1271
- () => true
1272
- );
1273
- if (!tenantExists) {
1274
- throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
1275
- }
1276
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
1277
- }
1659
+ const pending = await readJson(path);
1660
+ if (pending === null) {
1661
+ const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1662
+ (jwk) => jwk !== null,
1663
+ () => true
1664
+ );
1665
+ if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
1666
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1278
1667
  }
1279
- try {
1280
- const pending = await readJson(consume ? claimed : path);
1281
- if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1282
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1283
- }
1284
- const profile = await readJson(this.#profilePath(stateRoot));
1285
- const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1286
- if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1287
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1288
- }
1289
- if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1290
- await (0, import_promises.rm)(consume ? claimed : path, { force: true });
1291
- throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1668
+ if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1669
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1670
+ }
1671
+ const profile = await readJson(this.#profilePath(stateRoot));
1672
+ const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1673
+ if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1674
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1675
+ }
1676
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1677
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
1678
+ await (0, import_promises.rm)(path, { force: true });
1292
1679
  }
1293
- return pending;
1294
- } catch (error) {
1295
- if (consume) await (0, import_promises.rename)(claimed, path).catch(() => void 0);
1296
- throw error;
1680
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1297
1681
  }
1298
- }
1299
- async #restorePending(pending) {
1300
- const stateRoot = (0, import_node_path2.join)(this.#config.stateDir, "tenants", pending.tenantId);
1301
- const path = this.#pendingPath(stateRoot, pending.nonce);
1302
- await (0, import_promises.rename)(`${path}.processing`, path);
1682
+ return { stateRoot, pending };
1303
1683
  }
1304
1684
  #connectUrl(pending) {
1305
1685
  const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
@@ -1424,10 +1804,10 @@ var RemoteTenantStore = class {
1424
1804
  return (0, import_node_path2.join)(stateRoot, ".tinycloud", "native-grant.json");
1425
1805
  }
1426
1806
  #tenantId(subject) {
1427
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
1807
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
1428
1808
  }
1429
1809
  #signState(tenantId, nonce) {
1430
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
1810
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
1431
1811
  }
1432
1812
  #profilePath(stateRoot) {
1433
1813
  return (0, import_node_path2.join)(stateRoot, ".tinycloud", "profiles", PROFILE, "profile.json");
@@ -1500,6 +1880,37 @@ function sessionFromCallback(data, privateJwk) {
1500
1880
  signature: data.signature
1501
1881
  };
1502
1882
  }
1883
+ function approvalReason(pending) {
1884
+ return [
1885
+ 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.",
1886
+ // Owner DIDs come from the verified OpenKey access token of the MCP
1887
+ // client that created this link, never from the link itself. Collection
1888
+ // refuses a signer outside them, so the approver isn't asked to check.
1889
+ ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
1890
+ ].join(" ");
1891
+ }
1892
+ function collectionDeadline(openkey) {
1893
+ return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
1894
+ }
1895
+ function collectionErrorCode(error) {
1896
+ if ((0, import_links2.isApprovalClientError)(error)) return error.code.toUpperCase();
1897
+ if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
1898
+ return "UNKNOWN";
1899
+ }
1900
+ function approvalRefusalDiagnostic(error) {
1901
+ if (error instanceof ApprovalOwnerMismatchError) {
1902
+ return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
1903
+ }
1904
+ const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
1905
+ const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
1906
+ const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk2.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
1907
+ const detail = error instanceof ApprovalRequestError ? error.detail : "none";
1908
+ return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
1909
+ }
1910
+ function writeDiagnostic(message) {
1911
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
1912
+ `);
1913
+ }
1503
1914
  function samePrincipal(left, right) {
1504
1915
  if (typeof left !== "string") return false;
1505
1916
  try {
@@ -1540,7 +1951,7 @@ async function secureDirectory(path) {
1540
1951
  async function secureWrite(path, value) {
1541
1952
  const directory = (0, import_node_path2.dirname)(path);
1542
1953
  await secureDirectory(directory);
1543
- const temporary = `${path}.${process.pid}.${(0, import_node_crypto4.randomBytes)(8).toString("hex")}.tmp`;
1954
+ const temporary = `${path}.${process.pid}.${(0, import_node_crypto5.randomBytes)(8).toString("hex")}.tmp`;
1544
1955
  await (0, import_promises.writeFile)(temporary, `${JSON.stringify(value, jsonReplacer, 2)}
1545
1956
  `, { mode: 384 });
1546
1957
  await (0, import_promises.rename)(temporary, path);
@@ -1574,7 +1985,7 @@ async function restoreOptionalText(path, contents) {
1574
1985
  await (0, import_promises.writeFile)(path, contents, { mode: 384 });
1575
1986
  await (0, import_promises.chmod)(path, 384);
1576
1987
  }
1577
- async function reusablePending(directory, expected) {
1988
+ async function reusablePending(directory, expected, currentRequest) {
1578
1989
  let names;
1579
1990
  try {
1580
1991
  names = await (0, import_promises.readdir)(directory);
@@ -1587,12 +1998,18 @@ async function reusablePending(directory, expected) {
1587
1998
  if (!name.endsWith(".json")) continue;
1588
1999
  const path = (0, import_node_path2.join)(directory, name);
1589
2000
  const pending = await readJson(path).catch(() => null);
1590
- if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
2001
+ if (pending === null) {
1591
2002
  await (0, import_promises.rm)(path, { force: true });
1592
2003
  continue;
1593
2004
  }
2005
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2006
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2007
+ await (0, import_promises.rm)(path, { force: true });
2008
+ }
2009
+ continue;
2010
+ }
1594
2011
  active.push(pending);
1595
- if (samePendingRequest(pending, expected)) return pending;
2012
+ if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
1596
2013
  }
1597
2014
  if (active.length >= 64) {
1598
2015
  active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
@@ -1601,7 +2018,7 @@ async function reusablePending(directory, expected) {
1601
2018
  return void 0;
1602
2019
  }
1603
2020
  function samePendingRequest(pending, expected) {
1604
- 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);
2021
+ 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);
1605
2022
  }
1606
2023
 
1607
2024
  // src/server.ts
@@ -2117,7 +2534,7 @@ function outcomeCode(result) {
2117
2534
  // package.json
2118
2535
  var package_default = {
2119
2536
  name: "@tinycloud/mcp",
2120
- version: "0.11.1-beta.8",
2537
+ version: "0.12.0-beta.11",
2121
2538
  description: "TinyCloud delegated operations MCP server",
2122
2539
  keywords: [
2123
2540
  "tinycloud",
@@ -2188,10 +2605,11 @@ var package_default = {
2188
2605
  dependencies: {
2189
2606
  "@modelcontextprotocol/node": "2.0.0-beta.5",
2190
2607
  "@modelcontextprotocol/server": "2.0.0-beta.5",
2191
- "@tinycloud/node-sdk": "3.14.0-beta.10",
2192
- "@tinycloud/sdk-core": "3.14.0-beta.10",
2608
+ "@tinycloud/node-sdk": "3.14.0-beta.13",
2609
+ "@tinycloud/sdk-core": "3.14.0-beta.13",
2193
2610
  "@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
2194
- "@tinycloud/operations": "0.9.2-beta.8",
2611
+ "@tinycloud/operations": "0.9.2-beta.11",
2612
+ "@tinycloud/share-envelope": "1.6.0",
2195
2613
  jose: "6.2.4"
2196
2614
  },
2197
2615
  devDependencies: {
@@ -2243,7 +2661,6 @@ function createHostedMcpApp(config) {
2243
2661
  for (const owned of [
2244
2662
  restrictedUrl,
2245
2663
  connectUrl,
2246
- new URL("./connect/callback", restrictedUrl),
2247
2664
  new URL((0, import_server4.getOAuthProtectedResourceMetadataUrl)(restrictedUrl))
2248
2665
  ]) {
2249
2666
  restrictedByPath.set(owned.pathname, restricted);
@@ -2258,7 +2675,6 @@ function createHostedMcpApp(config) {
2258
2675
  }
2259
2676
  function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
2260
2677
  const connectPath = config.approvalPath ?? "/connect";
2261
- const callbackPath = `${connectPath}/callback`;
2262
2678
  const issuer = String(config.oauthMetadata.issuer);
2263
2679
  const jwksUri = String(config.oauthMetadata.jwks_uri);
2264
2680
  const verifier = createOpenKeyTokenVerifier({
@@ -2309,7 +2725,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
2309
2725
  return server;
2310
2726
  }, {
2311
2727
  legacy: "stateless",
2312
- onerror: () => writeDiagnostic("MCP request failed")
2728
+ onerror: () => writeDiagnostic2("MCP request failed")
2313
2729
  });
2314
2730
  const metadataOptions = {
2315
2731
  oauthMetadata: config.oauthMetadata,
@@ -2537,16 +2953,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2537
2953
  if (url.pathname === connectPath) {
2538
2954
  if (request.method !== "GET") return methodNotAllowed("GET");
2539
2955
  try {
2540
- const destination = await store.approvalRedirect(requiredState(url));
2956
+ const destination = await store.approvalLink(requiredState(url));
2541
2957
  return Response.redirect(destination, 302);
2542
2958
  } catch (error) {
2543
- const reason = error instanceof ApprovalRequestError ? error.detail : "unknown";
2544
- writeDiagnostic(`connect rejected: reason=${reason} path=${connectPath}`);
2959
+ const unavailable = error instanceof ApprovalLinkUnavailableError;
2960
+ const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
2961
+ writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
2545
2962
  if (request.headers.get("accept")?.includes("text/html")) {
2546
2963
  return new Response(
2547
- '<!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>',
2964
+ 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>',
2548
2965
  {
2549
- status: 400,
2966
+ status: unavailable ? 503 : 400,
2550
2967
  headers: {
2551
2968
  "content-type": "text/html; charset=utf-8",
2552
2969
  "cache-control": "no-store",
@@ -2558,37 +2975,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2558
2975
  }
2559
2976
  );
2560
2977
  }
2561
- return json({ error: "The approval link is invalid or expired." }, 400);
2562
- }
2563
- }
2564
- if (url.pathname === callbackPath) {
2565
- if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
2566
- if (request.method !== "POST") return methodNotAllowed("POST");
2567
- const originFailure = validateCallbackOrigin(request, config.openkeyHost);
2568
- if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
2569
- try {
2570
- await store.completeApproval(requiredState(url), request);
2571
- return callbackCors(json({ success: true }), config.openkeyHost);
2572
- } catch (error) {
2573
- if (error instanceof ApprovalOwnerMismatchError) {
2574
- return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
2575
- }
2576
- const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2577
- const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2578
- const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk3.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2579
- const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2580
- writeDiagnostic(
2581
- `connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
2582
- );
2583
- return callbackCors(
2584
- json({
2585
- error: stage,
2586
- code,
2587
- ...reason === void 0 ? {} : { reason },
2588
- message: "TinyCloud could not accept this delegation."
2589
- }, 400),
2590
- config.openkeyHost
2591
- );
2978
+ 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);
2592
2979
  }
2593
2980
  }
2594
2981
  if (url.pathname === "/native/grant" && surface === "hosted") {
@@ -2663,7 +3050,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2663
3050
  const auth = await authenticate(request);
2664
3051
  return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
2665
3052
  },
2666
- close: () => handler.close()
3053
+ close: async () => {
3054
+ await store.close();
3055
+ await handler.close();
3056
+ }
2667
3057
  };
2668
3058
  }
2669
3059
  function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
@@ -2762,18 +3152,6 @@ function mcpCors(response, request) {
2762
3152
  }
2763
3153
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
2764
3154
  }
2765
- function validateCallbackOrigin(request, openkeyHost) {
2766
- const origin = request.headers.get("origin");
2767
- return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
2768
- }
2769
- function callbackCors(response, openkeyHost) {
2770
- const headers = new Headers(response.headers);
2771
- headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
2772
- headers.set("access-control-allow-methods", "POST, OPTIONS");
2773
- headers.set("access-control-allow-headers", "content-type");
2774
- headers.set("vary", "Origin");
2775
- return new Response(response.body, { status: response.status, headers });
2776
- }
2777
3155
  async function readBoundedBodyText(request, maxBytes) {
2778
3156
  const contentLength = request.headers.get("content-length");
2779
3157
  if (contentLength !== null) {
@@ -2848,7 +3226,7 @@ function publicText(text, contentType) {
2848
3226
  function methodNotAllowed(allow) {
2849
3227
  return new Response("Method not allowed", { status: 405, headers: { allow } });
2850
3228
  }
2851
- function writeDiagnostic(message) {
3229
+ function writeDiagnostic2(message) {
2852
3230
  process.stderr.write(`[tinycloud-mcp-http] ${message}
2853
3231
  `);
2854
3232
  }
@@ -2871,6 +3249,8 @@ async function main() {
2871
3249
  stateSecret,
2872
3250
  nodeHost: process.env.TC_HOST ?? "https://node.tinycloud.xyz",
2873
3251
  openkeyHost,
3252
+ ...process.env.TC_OPENKEY_API_HOST === void 0 ? {} : { openkeyApiHost: process.env.TC_OPENKEY_API_HOST },
3253
+ ...process.env.TC_LINKS_API_ORIGIN === void 0 ? {} : { linksApiOrigin: process.env.TC_LINKS_API_ORIGIN },
2874
3254
  approvalTtlSeconds: positiveInteger(process.env.TC_MCP_APPROVAL_TTL_SECONDS, 300),
2875
3255
  delegationExpiry: process.env.TC_MCP_DELEGATION_EXPIRY ?? "1h",
2876
3256
  ...process.env.TC_MCP_NATIVE_SERVICE_CREDENTIAL === void 0 ? {} : { nativeServiceCredential: process.env.TC_MCP_NATIVE_SERVICE_CREDENTIAL },