@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-cli.js CHANGED
@@ -14,7 +14,6 @@ import {
14
14
  oauthMetadataResponse,
15
15
  requireBearerAuth
16
16
  } from "@modelcontextprotocol/server";
17
- import { RUNTIME_DELEGATION_REJECTIONS } from "@tinycloud/node-sdk";
18
17
 
19
18
  // src/agent-discovery.ts
20
19
  import { createHash } from "crypto";
@@ -367,9 +366,12 @@ function logToolCall(tool, code, startedAt, replayedGrants) {
367
366
 
368
367
  // src/remote-store.ts
369
368
  import { sameTinyCloudNode } from "@tinycloud/sdk-core";
369
+ import { admitOwnerRenewalLease, RENEWAL_LEASE_ORIGINAL_EXPIRED, RENEWAL_RENEWER_CHANGED } from "@tinycloud/sdk-core/delegations/renewal";
370
+ import { RENEWAL_ADMISSION_LEAD_MS, verifyOwnerRenewalLease } from "@tinycloud/sdk-core/delegations/renewal-receipt";
370
371
  import { createHmac, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
371
372
  import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
372
- import { dirname as dirname2, join as join2 } from "path";
373
+ import { basename, dirname as dirname2, join as join2 } from "path";
374
+ import { setTimeout as sleep } from "timers/promises";
373
375
  import {
374
376
  activateValidatedRuntimeDelegation,
375
377
  deserializeDelegation,
@@ -380,7 +382,7 @@ import {
380
382
  UnsupportedSessionRestoreError,
381
383
  isCapabilitySubset,
382
384
  principalDidEquals,
383
- publicJwk,
385
+ RUNTIME_DELEGATION_REJECTIONS,
384
386
  siweRuntimeDelegation,
385
387
  signedCompactUcanExpiry
386
388
  } from "@tinycloud/node-sdk";
@@ -388,8 +390,14 @@ import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk
388
390
  import { createOrReusePermissionRequest } from "@tinycloud/operations/artifacts";
389
391
  import { withTinyCloudStateRoot } from "@tinycloud/operations/state";
390
392
  import { invokeOperation } from "@tinycloud/operations";
393
+ import { liveStoredLease, restoreStoredSession } from "@tinycloud/operations/profile";
391
394
  import { nodeRevocationOf, operationRetryDescriptor } from "@tinycloud/operations/mcp-authority";
392
395
  import { tcAppsApprovalMessage, tcAppsApprovalReason } from "@tinycloud/operations/tc-apps";
396
+ import {
397
+ APPROVAL_POLL_INTERVAL_MS,
398
+ DEFAULT_LINKS_API_ORIGIN,
399
+ isApprovalClientError
400
+ } from "@tinycloud/share-envelope/links";
393
401
 
394
402
  // src/native-auth.ts
395
403
  import { timingSafeEqual } from "crypto";
@@ -449,9 +457,142 @@ function hasCaveats(permission) {
449
457
  return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
450
458
  }
451
459
 
460
+ // src/openkey-approval.ts
461
+ import { randomUUID } from "crypto";
462
+ import {
463
+ ackApprovalResult,
464
+ checkApprovalResultBinding,
465
+ createApprovalRequest,
466
+ discoverApprovalResult,
467
+ fetchApprovalResult,
468
+ generateRelayKey,
469
+ openRelayResult,
470
+ signerFromJwk
471
+ } from "@tinycloud/share-envelope/links";
472
+ import { boundedResponseBytes } from "@tinycloud/sdk-core/registry-publication";
473
+ var MIN_REQUEST_LIFE_MS = 18e4;
474
+ var MAX_RESULT_REPLY_BYTES = 256 * 1024;
475
+ var boundedFetch = Object.assign(async (input, init) => {
476
+ const response = await fetch(input, init);
477
+ const bytes = await boundedResponseBytes(response, MAX_RESULT_REPLY_BYTES);
478
+ return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
479
+ status: response.status,
480
+ statusText: response.statusText
481
+ });
482
+ }, globalThis.fetch);
483
+ async function createOpenKeyRequest(endpoints, input) {
484
+ const signingKey = ed25519PrivateJwk(input.jwk);
485
+ const signer = signerFromJwk(signingKey);
486
+ const relay = generateRelayKey();
487
+ const request = {
488
+ issuer: signer.did,
489
+ requestVersion: 1,
490
+ targetDid: signer.did,
491
+ targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
492
+ nodeOrigin: new URL(input.nodeHost).origin,
493
+ permissions: input.permissions.map(requestPermission),
494
+ reason: input.reason,
495
+ grantLifetimeSeconds: input.grantLifetimeSeconds,
496
+ resultEncryptionPublicJwk: relay.publicJwk,
497
+ ...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
498
+ };
499
+ const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
500
+ const created = await createApprovalRequest({
501
+ request,
502
+ issuerKey: signer,
503
+ apiOrigin: endpoints.linksApiOrigin,
504
+ openkeyOrigin: endpoints.openkeyOrigin,
505
+ expiresAt
506
+ });
507
+ return {
508
+ requestId: created.id,
509
+ bodyCid: created.bodyCid,
510
+ record: { header: created.record.header, signature: created.record.signature },
511
+ link: created.link,
512
+ request,
513
+ expiresAt: created.expiresAt,
514
+ relayPrivateKey: relay.privateKey,
515
+ ackId: randomUUID(),
516
+ apiOrigin: endpoints.openkeyApiOrigin
517
+ };
518
+ }
519
+ async function collectOpenKeyResult(state, jwk, timeoutMs) {
520
+ const requester = requesterState(state, jwk);
521
+ if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
522
+ const discovered = await discoverApprovalResult(requester, { timeoutMs, fetch: boundedFetch });
523
+ if (discovered.status === "pending") return discovered;
524
+ return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
525
+ }
526
+ const relay = await fetchApprovalResult(
527
+ requester,
528
+ { resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
529
+ { timeoutMs, fetch: boundedFetch }
530
+ );
531
+ const opened = await openRelayResult(relay, state.requestId, state.relayPrivateKey);
532
+ return {
533
+ status: "ready",
534
+ checked: checkApprovalResultBinding(opened, {
535
+ requestId: state.requestId,
536
+ bodyCid: state.bodyCid,
537
+ request: state.request
538
+ })
539
+ };
540
+ }
541
+ async function ackOpenKeyResult(state, jwk, timeoutMs) {
542
+ if (state.resultRef === void 0) return;
543
+ await ackApprovalResult(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
544
+ }
545
+ function lifetimeSeconds(value) {
546
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
547
+ const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
548
+ const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
549
+ if (!Number.isSafeInteger(seconds) || seconds < 60) {
550
+ throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
551
+ }
552
+ return seconds;
553
+ }
554
+ function requesterState(state, jwk) {
555
+ return {
556
+ requestId: state.requestId,
557
+ bodyCid: state.bodyCid,
558
+ record: state.record,
559
+ apiOrigin: state.apiOrigin,
560
+ signingKey: ed25519PrivateJwk(jwk)
561
+ };
562
+ }
563
+ function requestPermission(entry) {
564
+ if (entry.space === void 0 || entry.space.length === 0) {
565
+ throw new Error("An approval request needs a space for every permission.");
566
+ }
567
+ return {
568
+ service: entry.service,
569
+ space: entry.space,
570
+ path: entry.path,
571
+ actions: [...entry.actions],
572
+ ...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
573
+ };
574
+ }
575
+ function ed25519PrivateJwk(jwk) {
576
+ const { kty, crv, x, d } = jwk;
577
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
578
+ throw new Error("The tenant key is not an Ed25519 private key.");
579
+ }
580
+ return { kty, crv, x, d };
581
+ }
582
+
452
583
  // src/remote-store.ts
453
584
  var PROFILE = "agent";
454
585
  var MAX_CALLBACK_BYTES = 256 * 1024;
586
+ var PENDING_VERSION = 2;
587
+ var CALL_COLLECTION_TIMEOUT_MS = 3e3;
588
+ var CALL_COLLECTION_BUDGET_MS = 3e3;
589
+ var POLL_COLLECTION_TIMEOUT_MS = 1e4;
590
+ var FAST_POLL_WINDOW_MS = 6e4;
591
+ var SLOW_POLL_INTERVAL_MS = 1e4;
592
+ var MAX_COLLECTION_POLLS = 64;
593
+ var RESULT_COLLECTION_GRACE_MS = 6e5;
594
+ var PROCESSING_STALE_MS = 12e4;
595
+ var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
455
596
  var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
456
597
  "DELEGATION_ARTIFACT_INVALID",
457
598
  "DELEGATION_EXPIRED",
@@ -492,6 +633,12 @@ var ApprovalStageError = class extends Error {
492
633
  this.reason = reason;
493
634
  }
494
635
  };
636
+ var RenewalAdmissionUnavailableError = class extends Error {
637
+ constructor(cause) {
638
+ super("The renewal lease could not be admitted yet.", { cause });
639
+ this.name = "RenewalAdmissionUnavailableError";
640
+ }
641
+ };
495
642
  var ApprovalRequestError = class extends Error {
496
643
  detail;
497
644
  constructor(detail, message, cause) {
@@ -500,6 +647,12 @@ var ApprovalRequestError = class extends Error {
500
647
  this.detail = detail;
501
648
  }
502
649
  };
650
+ var ApprovalLinkUnavailableError = class extends Error {
651
+ constructor(cause) {
652
+ super("The approval link could not be created.", { cause });
653
+ this.name = "ApprovalLinkUnavailableError";
654
+ }
655
+ };
503
656
  var NativeGrantValidationError = class extends Error {
504
657
  code;
505
658
  constructor(status) {
@@ -521,10 +674,25 @@ var RemoteTenantStore = class {
521
674
  #scopedClearing = /* @__PURE__ */ new Map();
522
675
  #clearedScoped = /* @__PURE__ */ new Map();
523
676
  #approvalProcessing = /* @__PURE__ */ new Map();
677
+ #linkCreations = /* @__PURE__ */ new Map();
678
+ #collections = /* @__PURE__ */ new Map();
679
+ #polls = /* @__PURE__ */ new Map();
680
+ #closed = false;
681
+ #endpoints;
682
+ #grantLifetimeSeconds;
524
683
  #nativeIdentity;
525
684
  #nativeGrantQueues = /* @__PURE__ */ new Map();
526
685
  constructor(config) {
527
686
  this.#config = config;
687
+ const openkeyOrigin = new URL(config.openkeyHost).origin;
688
+ this.#endpoints = {
689
+ openkeyOrigin,
690
+ openkeyApiOrigin: new URL(
691
+ config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
692
+ ).origin,
693
+ linksApiOrigin: new URL(config.linksApiOrigin ?? DEFAULT_LINKS_API_ORIGIN).origin
694
+ };
695
+ this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
528
696
  }
529
697
  async nativeServiceIdentity() {
530
698
  const identity = await this.#loadNativeServiceKey();
@@ -710,10 +878,13 @@ var RemoteTenantStore = class {
710
878
  }
711
879
  /** Check stored node authority before an authenticated operation uses it. */
712
880
  async validateTenant(subject, ownerDids) {
713
- await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);
881
+ const tenant = await this.#ensureTenant(subject);
882
+ await this.#collectApprovals(tenant);
883
+ await this.#hasValidSession(tenant, ownerDids);
714
884
  }
715
885
  async connectStatus(subject, ownerDids = []) {
716
886
  const tenant = await this.#ensureTenant(subject);
887
+ await this.#collectApprovals(tenant);
717
888
  const state = await this.#sessionState(tenant, ownerDids, true);
718
889
  if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
719
890
  if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
@@ -873,77 +1044,267 @@ var RemoteTenantStore = class {
873
1044
  await clearing;
874
1045
  return "scoped";
875
1046
  }
876
- async approvalRedirect(state) {
877
- const pending = await this.#readPending(state, false);
1047
+ /**
1048
+ * The OpenKey link behind one of this server's `/connect?state=` links. The
1049
+ * first visit creates the OpenKey approval request, signed by the tenant's
1050
+ * own key; later visits reuse it. Collection starts in the background and on
1051
+ * the tenant's next call.
1052
+ */
1053
+ async approvalLink(state) {
1054
+ const located = await this.#readPending(state);
1055
+ const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
1056
+ const prior = this.#linkCreations.get(path);
1057
+ if (prior) return prior;
1058
+ const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
1059
+ this.#linkCreations.set(path, creating);
1060
+ return creating;
1061
+ }
1062
+ async #createApprovalLink(stateRoot, initial) {
1063
+ const path = this.#pendingPath(stateRoot, initial.nonce);
1064
+ const pending = await readJson(path);
1065
+ if (pending === null || pending.version !== PENDING_VERSION) {
1066
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1067
+ }
1068
+ if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
1069
+ if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
1070
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1071
+ }
1072
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1073
+ return pending.openkey.link;
1074
+ }
1075
+ if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
878
1076
  const tenant = await this.#readTenant(pending.tenantId);
879
- const callback = new URL(`${this.#config.approvalPath ?? "/connect"}/callback`, this.#config.publicUrl);
880
- callback.searchParams.set("state", state);
881
- const params = new URLSearchParams({
882
- did: tenant.sessionDid,
883
- callback: callback.toString(),
884
- host: this.#config.nodeHost,
885
- requesterOrigin: this.#config.publicUrl.origin,
886
- jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString("base64url"),
887
- permissions: Buffer.from(JSON.stringify({
1077
+ let openkey;
1078
+ try {
1079
+ openkey = await createOpenKeyRequest(this.#endpoints, {
1080
+ jwk: tenant.jwk,
1081
+ nodeHost: this.#config.nodeHost,
888
1082
  permissions: pending.permissions,
889
- reason: [
890
- pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : tcAppsApprovalReason(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
891
- // Owner DIDs come from the verified OpenKey access token of the MCP
892
- // client that created this link, never from the link itself. The
893
- // callback refuses a signer outside them, so the approver isn't asked to check.
894
- ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
895
- ].join(" ")
896
- })).toString("base64url"),
897
- expiry: this.#config.delegationExpiry
898
- });
899
- return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
900
- }
901
- async completeApproval(state, request) {
902
- const length = Number(request.headers.get("content-length") ?? "0");
903
- if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
904
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1083
+ reason: approvalReason(pending),
1084
+ grantLifetimeSeconds: this.#grantLifetimeSeconds,
1085
+ ...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
1086
+ expiresAt: new Date(pending.expiresAt)
1087
+ });
1088
+ } catch (error) {
1089
+ throw new ApprovalLinkUnavailableError(error);
905
1090
  }
906
- const text = await request.text();
907
- if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {
908
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1091
+ if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
1092
+ throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
909
1093
  }
910
- let data;
1094
+ const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
1095
+ await secureWrite(path, { ...pending, expiresAt, openkey });
1096
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1097
+ return openkey.link;
1098
+ }
1099
+ /**
1100
+ * Collect every approval result this tenant has open in OpenKey before a
1101
+ * call decides whether it is connected. The call waits at most
1102
+ * `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
1103
+ * finishes in the background, and a failure leaves the pending approval for
1104
+ * the next call or poll.
1105
+ */
1106
+ async #collectApprovals(tenant) {
1107
+ const budget = new AbortController();
1108
+ await Promise.race([
1109
+ this.#collectEach(tenant),
1110
+ sleep(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
1111
+ ]).finally(() => budget.abort());
1112
+ }
1113
+ async #collectEach(tenant) {
1114
+ const directory = this.#pendingDirectory(tenant.stateRoot);
1115
+ let names;
911
1116
  try {
912
- data = JSON.parse(text);
1117
+ names = await readdir(directory);
913
1118
  } catch (error) {
914
- throw new ApprovalRequestError("body_invalid", "Callback body is invalid.", error);
1119
+ if (isRecord(error) && error.code === "ENOENT") return;
1120
+ throw error;
1121
+ }
1122
+ for (const name of names) {
1123
+ if (name.endsWith(".json.processing")) await this.#recoverProcessing(join2(directory, name));
1124
+ }
1125
+ const nonces = (await readdir(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
1126
+ for (const nonce of nonces) {
1127
+ await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
1128
+ }
1129
+ }
1130
+ /**
1131
+ * A claimed result whose processing never finished (the server stopped
1132
+ * mid-way). Once it is stored only the acknowledgement remains; otherwise,
1133
+ * after a grace period, it becomes collectable again.
1134
+ */
1135
+ async #recoverProcessing(claimed) {
1136
+ const pending = await readJson(claimed).catch(() => null);
1137
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
1138
+ await rm(claimed, { force: true });
1139
+ return;
915
1140
  }
916
- if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
917
- const pending = await this.#readPending(state, true);
918
1141
  const stateRoot = join2(this.#config.stateDir, "tenants", pending.tenantId);
1142
+ if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
1143
+ if (pending.openkey.storedCid !== void 0) {
1144
+ await this.#acknowledge(stateRoot, pending.openkey);
1145
+ await rm(claimed, { force: true });
1146
+ return;
1147
+ }
1148
+ const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
1149
+ if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
1150
+ const { claimedAt: _claimed, ...fresh } = pending;
1151
+ await secureWrite(claimed.slice(0, -".processing".length), fresh);
1152
+ await rm(claimed, { force: true });
1153
+ }
1154
+ /** One collection attempt for one pending approval, single-flight per approval. */
1155
+ async #collectApproval(stateRoot, nonce, timeoutMs) {
1156
+ const path = this.#pendingPath(stateRoot, nonce);
1157
+ const running = this.#collections.get(path);
1158
+ if (running) return running;
1159
+ const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
1160
+ writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
1161
+ return "retry";
1162
+ }).finally(() => this.#collections.delete(path));
1163
+ this.#collections.set(path, collecting);
1164
+ return collecting;
1165
+ }
1166
+ async #collectStep(stateRoot, nonce, timeoutMs) {
1167
+ const path = this.#pendingPath(stateRoot, nonce);
1168
+ const pending = await readJson(path).catch(() => null);
1169
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
1170
+ const openkey = pending.openkey;
1171
+ if (!this.#currentRequest(openkey)) {
1172
+ writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1173
+ await rm(path, { force: true });
1174
+ return "done";
1175
+ }
1176
+ if (Date.now() >= collectionDeadline(openkey)) {
1177
+ await rm(path, { force: true });
1178
+ return "done";
1179
+ }
1180
+ const tenant = await this.#readTenant(pending.tenantId);
1181
+ if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1182
+ await rm(path, { force: true });
1183
+ return "done";
1184
+ }
1185
+ let collected;
1186
+ try {
1187
+ collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
1188
+ } catch (error) {
1189
+ if (!isApprovalClientError(error)) throw error;
1190
+ return this.#collectionRefused(path, pending, error);
1191
+ }
1192
+ if (collected.status === "pending") return "pending";
1193
+ if (collected.status === "discovered") {
1194
+ await secureWrite(path, {
1195
+ ...pending,
1196
+ openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
1197
+ });
1198
+ return this.#collectStep(stateRoot, nonce, timeoutMs);
1199
+ }
1200
+ const claimed = `${path}.processing`;
1201
+ try {
1202
+ await rename(path, claimed);
1203
+ } catch (error) {
1204
+ if (isRecord(error) && error.code === "ENOENT") return "done";
1205
+ throw error;
1206
+ }
1207
+ await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
919
1208
  const prior = this.#approvalProcessing.get(stateRoot);
920
1209
  const processing = (async () => {
921
1210
  if (prior) await prior.catch(() => void 0);
922
- try {
923
- const tenant = await this.#readTenant(pending.tenantId);
924
- if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
925
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
926
- }
927
- if (pending.kind === "bootstrap") {
928
- await this.#storeBootstrap(tenant, pending, data);
929
- } else {
930
- await this.#storeDelegation(tenant, pending, data);
931
- }
932
- await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
933
- } catch (error) {
934
- await this.#restorePending(pending).catch(() => void 0);
935
- throw error;
1211
+ const current = await this.#readTenant(pending.tenantId);
1212
+ if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
1213
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
936
1214
  }
1215
+ const { checked } = collected;
1216
+ 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);
1217
+ await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
937
1218
  })();
938
1219
  this.#approvalProcessing.set(stateRoot, processing);
939
1220
  try {
940
1221
  await processing;
1222
+ } catch (error) {
1223
+ if (error instanceof RenewalAdmissionUnavailableError) {
1224
+ await secureWrite(path, pending).catch(() => void 0);
1225
+ await rm(claimed, { force: true });
1226
+ writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
1227
+ return "retry";
1228
+ }
1229
+ const { openkey: _spent, ...fresh } = pending;
1230
+ await secureWrite(path, fresh).catch(() => void 0);
1231
+ await rm(claimed, { force: true });
1232
+ writeDiagnostic(approvalRefusalDiagnostic(error));
1233
+ return "done";
941
1234
  } finally {
942
1235
  if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
943
1236
  }
1237
+ await this.#acknowledge(stateRoot, openkey);
1238
+ await rm(claimed, { force: true });
1239
+ return "done";
1240
+ }
1241
+ async #collectionRefused(path, pending, error) {
1242
+ switch (error.code) {
1243
+ case "network":
1244
+ case "unavailable":
1245
+ return "retry";
1246
+ case "request_expired":
1247
+ if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
1248
+ await rm(path, { force: true });
1249
+ return "done";
1250
+ case "acknowledged":
1251
+ await rm(path, { force: true });
1252
+ return "done";
1253
+ default: {
1254
+ const { openkey: _spent, ...fresh } = pending;
1255
+ await secureWrite(path, fresh);
1256
+ writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
1257
+ return "done";
1258
+ }
1259
+ }
1260
+ }
1261
+ async #acknowledge(stateRoot, openkey) {
1262
+ try {
1263
+ const tenant = await this.#readTenant(basename(stateRoot));
1264
+ await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
1265
+ } catch (error) {
1266
+ writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
1267
+ }
1268
+ }
1269
+ /**
1270
+ * Poll one opened approval until it is collected or its request and result
1271
+ * window end: every 2 s for the first minute, then every 10 s. At most
1272
+ * `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
1273
+ * collects.
1274
+ */
1275
+ #startCollectionPoll(stateRoot, nonce) {
1276
+ const key = this.#pendingPath(stateRoot, nonce);
1277
+ if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
1278
+ const startedAt = Date.now();
1279
+ const schedule = () => {
1280
+ const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
1281
+ const timer = setTimeout(() => void tick(), delay);
1282
+ timer.unref();
1283
+ this.#polls.set(key, timer);
1284
+ };
1285
+ const tick = async () => {
1286
+ const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
1287
+ if (this.#closed || outcome === "done" || outcome === "idle") {
1288
+ this.#polls.delete(key);
1289
+ return;
1290
+ }
1291
+ schedule();
1292
+ };
1293
+ schedule();
1294
+ }
1295
+ /** Stop background collection. Pending approvals stay on disk for the next start. */
1296
+ async close() {
1297
+ this.#closed = true;
1298
+ for (const timer of this.#polls.values()) clearTimeout(timer);
1299
+ this.#polls.clear();
1300
+ await Promise.allSettled([...this.#collections.values()]);
944
1301
  }
945
- async #storeBootstrap(tenant, pending, data) {
946
- const { node, session } = await this.#restoreApproval(tenant, data);
1302
+ /** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
1303
+ #currentRequest(openkey) {
1304
+ 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;
1305
+ }
1306
+ async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
1307
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
947
1308
  this.#assertCurrentApproval(pending, session);
948
1309
  if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
949
1310
  throw new ApprovalOwnerMismatchError();
@@ -951,6 +1312,7 @@ var RemoteTenantStore = class {
951
1312
  if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
952
1313
  throw new Error("The approved delegation does not cover the requested account access.");
953
1314
  }
1315
+ if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
954
1316
  const profile = await readJson(this.#profilePath(tenant.stateRoot));
955
1317
  await secureWrite(this.#profilePath(tenant.stateRoot), {
956
1318
  ...profile,
@@ -959,14 +1321,51 @@ var RemoteTenantStore = class {
959
1321
  });
960
1322
  await secureWrite(this.#sessionPath(tenant.stateRoot), {
961
1323
  authMethod: "openkey",
962
- ...session
1324
+ ...session,
1325
+ ...renewal === void 0 ? {} : { renewal }
963
1326
  });
964
1327
  this.#renewalRequired.delete(tenant.stateRoot);
965
1328
  this.#activeSessions.delete(tenant.stateRoot);
1329
+ return session.delegationCid;
966
1330
  }
967
- async #storeDelegation(tenant, pending, data) {
1331
+ /**
1332
+ * Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
1333
+ * session is stored. Admission replays the exact signed lease, so a retry admits the same one.
1334
+ */
1335
+ async #admitRenewal(tenant, ownerDid, session, renewal) {
1336
+ let signed;
1337
+ try {
1338
+ signed = await verifyOwnerRenewalLease(session, ownerDid, renewal);
1339
+ } catch (error) {
1340
+ throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
1341
+ }
1342
+ if (Date.parse(signed.originalExpiresAt) - Date.now() < RENEWAL_ADMISSION_LEAD_MS) {
1343
+ throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
1344
+ }
1345
+ try {
1346
+ await admitOwnerRenewalLease({
1347
+ host: new URL(this.#config.nodeHost).origin,
1348
+ originalAuthorization: session.delegationHeader.Authorization,
1349
+ originalCid: session.delegationCid,
1350
+ ownerDid,
1351
+ agentDid: tenant.sessionDid.split("#")[0],
1352
+ spaceId: session.spaceId,
1353
+ nodeIdentity: renewal.receipt.nodeIdentity,
1354
+ leaseAuthorization: renewal.receipt.leaseAuthorization,
1355
+ leaseCid: renewal.receipt.leaseCid,
1356
+ leaseExpiresAt: signed.leaseSignedExpiresAt
1357
+ });
1358
+ } catch (error) {
1359
+ const code = isRecord(error) ? error.code : void 0;
1360
+ if (code === RENEWAL_RENEWER_CHANGED || code === RENEWAL_LEASE_ORIGINAL_EXPIRED) {
1361
+ throw new ApprovalStageError("renewal", code, void 0, error);
1362
+ }
1363
+ throw new RenewalAdmissionUnavailableError(error);
1364
+ }
1365
+ }
1366
+ async #storeDelegation(tenant, pending, data, resultOwner) {
968
1367
  if (pending.requestId === void 0) throw new Error("Authority request is missing.");
969
- const { node, session } = await this.#restoreApproval(tenant, data);
1368
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
970
1369
  this.#assertCurrentApproval(pending, session);
971
1370
  if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
972
1371
  let delegation;
@@ -1010,6 +1409,7 @@ var RemoteTenantStore = class {
1010
1409
  );
1011
1410
  }
1012
1411
  if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
1412
+ return session.delegationCid;
1013
1413
  }
1014
1414
  #assertCurrentApproval(pending, session) {
1015
1415
  const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
@@ -1018,13 +1418,14 @@ var RemoteTenantStore = class {
1018
1418
  }
1019
1419
  }
1020
1420
  /**
1021
- * Verify the OpenKey callback as a SIWE session for this tenant's key. The
1022
- * callback must carry the full signed proof (SIWE, signature, address and
1023
- * chain), so the WASM verifier always runs: it binds the authorization bytes
1024
- * and CID to the signed SIWE, and `node.did` is the wallet that signed
1025
- * exactly the delegation being stored.
1421
+ * Verify OpenKey's delegation as a SIWE session for this tenant's key. It
1422
+ * must carry the full signed proof (SIWE, signature, address and chain), so
1423
+ * the WASM verifier always runs: it binds the authorization bytes and CID to
1424
+ * the signed SIWE, and `node.did` is the wallet that signed exactly the
1425
+ * delegation being stored. That wallet must be the owner OpenKey's result
1426
+ * names.
1026
1427
  */
1027
- async #restoreApproval(tenant, data) {
1428
+ async #restoreApproval(tenant, data, resultOwner) {
1028
1429
  let session;
1029
1430
  try {
1030
1431
  session = sessionFromCallback(data, tenant.jwk);
@@ -1045,6 +1446,9 @@ var RemoteTenantStore = class {
1045
1446
  if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
1046
1447
  throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
1047
1448
  }
1449
+ if (!samePrincipal(node.did, resultOwner)) {
1450
+ throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
1451
+ }
1048
1452
  return { node, session };
1049
1453
  }
1050
1454
  async #ensureTenant(subject) {
@@ -1083,13 +1487,16 @@ var RemoteTenantStore = class {
1083
1487
  if (raw === null) return "invalid";
1084
1488
  const node = new TinyCloudNode({ host: this.#config.nodeHost });
1085
1489
  try {
1086
- await node.restoreSession(raw);
1087
- } catch {
1490
+ await restoreStoredSession(node, raw, raw);
1491
+ } catch (error) {
1088
1492
  const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
1089
1493
  const signedExpiry = typeof header === "string" ? signedCompactUcanExpiry(header) : void 0;
1090
1494
  const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
1091
1495
  const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
1092
- if (expiry !== void 0 && expiry.getTime() <= Date.now()) return "invalid";
1496
+ if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
1497
+ const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
1498
+ return liveStoredLease(raw) !== void 0 && !ended ? "unknown" : "invalid";
1499
+ }
1093
1500
  await this.#clearAuthority(tenant);
1094
1501
  return "invalid";
1095
1502
  }
@@ -1224,15 +1631,17 @@ var RemoteTenantStore = class {
1224
1631
  return writing;
1225
1632
  }
1226
1633
  async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
1634
+ const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
1227
1635
  const reusable = await reusablePending(
1228
1636
  this.#pendingDirectory(tenant.stateRoot),
1229
- { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
1637
+ { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
1638
+ (openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
1230
1639
  );
1231
1640
  if (reusable !== void 0) return reusable;
1232
1641
  const nonce = randomBytes(24).toString("base64url");
1233
1642
  const created = Date.now();
1234
1643
  const pending = {
1235
- version: 1,
1644
+ version: PENDING_VERSION,
1236
1645
  nonce,
1237
1646
  tenantId,
1238
1647
  approvalEpoch: tenant.approvalEpoch,
@@ -1246,7 +1655,7 @@ var RemoteTenantStore = class {
1246
1655
  await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
1247
1656
  return pending;
1248
1657
  }
1249
- async #readPending(state, consume) {
1658
+ async #readPending(state) {
1250
1659
  const [tenantId, nonce, signature] = state.split(".");
1251
1660
  if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
1252
1661
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
@@ -1259,46 +1668,30 @@ var RemoteTenantStore = class {
1259
1668
  }
1260
1669
  const stateRoot = join2(this.#config.stateDir, "tenants", tenantId);
1261
1670
  const path = this.#pendingPath(stateRoot, nonce);
1262
- const claimed = `${path}.processing`;
1263
- if (consume) {
1264
- try {
1265
- await rename(path, claimed);
1266
- } catch (error) {
1267
- if (!isRecord(error) || error.code !== "ENOENT") throw error;
1268
- const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1269
- (jwk) => jwk !== null,
1270
- () => true
1271
- );
1272
- if (!tenantExists) {
1273
- throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
1274
- }
1275
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
1276
- }
1671
+ const pending = await readJson(path);
1672
+ if (pending === null) {
1673
+ const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
1674
+ (jwk) => jwk !== null,
1675
+ () => true
1676
+ );
1677
+ if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
1678
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1277
1679
  }
1278
- try {
1279
- const pending = await readJson(consume ? claimed : path);
1280
- if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1281
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1282
- }
1283
- const profile = await readJson(this.#profilePath(stateRoot));
1284
- const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1285
- if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1286
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1287
- }
1288
- if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1289
- await rm(consume ? claimed : path, { force: true });
1290
- throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1680
+ if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
1681
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1682
+ }
1683
+ const profile = await readJson(this.#profilePath(stateRoot));
1684
+ const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
1685
+ if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
1686
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1687
+ }
1688
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
1689
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
1690
+ await rm(path, { force: true });
1291
1691
  }
1292
- return pending;
1293
- } catch (error) {
1294
- if (consume) await rename(claimed, path).catch(() => void 0);
1295
- throw error;
1692
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1296
1693
  }
1297
- }
1298
- async #restorePending(pending) {
1299
- const stateRoot = join2(this.#config.stateDir, "tenants", pending.tenantId);
1300
- const path = this.#pendingPath(stateRoot, pending.nonce);
1301
- await rename(`${path}.processing`, path);
1694
+ return { stateRoot, pending };
1302
1695
  }
1303
1696
  #connectUrl(pending) {
1304
1697
  const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
@@ -1499,6 +1892,37 @@ function sessionFromCallback(data, privateJwk) {
1499
1892
  signature: data.signature
1500
1893
  };
1501
1894
  }
1895
+ function approvalReason(pending) {
1896
+ return [
1897
+ pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : tcAppsApprovalReason(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
1898
+ // Owner DIDs come from the verified OpenKey access token of the MCP
1899
+ // client that created this link, never from the link itself. Collection
1900
+ // refuses a signer outside them, so the approver isn't asked to check.
1901
+ ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
1902
+ ].join(" ");
1903
+ }
1904
+ function collectionDeadline(openkey) {
1905
+ return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
1906
+ }
1907
+ function collectionErrorCode(error) {
1908
+ if (isApprovalClientError(error)) return error.code.toUpperCase();
1909
+ if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
1910
+ return "UNKNOWN";
1911
+ }
1912
+ function approvalRefusalDiagnostic(error) {
1913
+ if (error instanceof ApprovalOwnerMismatchError) {
1914
+ return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
1915
+ }
1916
+ const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
1917
+ const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
1918
+ const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
1919
+ const detail = error instanceof ApprovalRequestError ? error.detail : "none";
1920
+ return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
1921
+ }
1922
+ function writeDiagnostic(message) {
1923
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
1924
+ `);
1925
+ }
1502
1926
  function samePrincipal(left, right) {
1503
1927
  if (typeof left !== "string") return false;
1504
1928
  try {
@@ -1573,7 +1997,7 @@ async function restoreOptionalText(path, contents) {
1573
1997
  await writeFile(path, contents, { mode: 384 });
1574
1998
  await chmod(path, 384);
1575
1999
  }
1576
- async function reusablePending(directory, expected) {
2000
+ async function reusablePending(directory, expected, currentRequest) {
1577
2001
  let names;
1578
2002
  try {
1579
2003
  names = await readdir(directory);
@@ -1586,12 +2010,18 @@ async function reusablePending(directory, expected) {
1586
2010
  if (!name.endsWith(".json")) continue;
1587
2011
  const path = join2(directory, name);
1588
2012
  const pending = await readJson(path).catch(() => null);
1589
- if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
2013
+ if (pending === null) {
1590
2014
  await rm(path, { force: true });
1591
2015
  continue;
1592
2016
  }
2017
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2018
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2019
+ await rm(path, { force: true });
2020
+ }
2021
+ continue;
2022
+ }
1593
2023
  active.push(pending);
1594
- if (samePendingRequest(pending, expected)) return pending;
2024
+ if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
1595
2025
  }
1596
2026
  if (active.length >= 64) {
1597
2027
  active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
@@ -1600,7 +2030,7 @@ async function reusablePending(directory, expected) {
1600
2030
  return void 0;
1601
2031
  }
1602
2032
  function samePendingRequest(pending, expected) {
1603
- 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);
2033
+ 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);
1604
2034
  }
1605
2035
 
1606
2036
  // src/server.ts
@@ -2115,7 +2545,7 @@ function outcomeCode(result) {
2115
2545
  // package.json
2116
2546
  var package_default = {
2117
2547
  name: "@tinycloud/mcp",
2118
- version: "0.11.1-beta.9",
2548
+ version: "0.12.0-beta.11",
2119
2549
  description: "TinyCloud delegated operations MCP server",
2120
2550
  keywords: [
2121
2551
  "tinycloud",
@@ -2186,10 +2616,11 @@ var package_default = {
2186
2616
  dependencies: {
2187
2617
  "@modelcontextprotocol/node": "2.0.0-beta.5",
2188
2618
  "@modelcontextprotocol/server": "2.0.0-beta.5",
2189
- "@tinycloud/node-sdk": "3.14.0-beta.11",
2190
- "@tinycloud/sdk-core": "3.14.0-beta.11",
2619
+ "@tinycloud/node-sdk": "3.14.0-beta.13",
2620
+ "@tinycloud/sdk-core": "3.14.0-beta.13",
2191
2621
  "@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
2192
- "@tinycloud/operations": "0.9.2-beta.9",
2622
+ "@tinycloud/operations": "0.9.2-beta.11",
2623
+ "@tinycloud/share-envelope": "1.6.0",
2193
2624
  jose: "6.2.4"
2194
2625
  },
2195
2626
  devDependencies: {
@@ -2241,7 +2672,6 @@ function createHostedMcpApp(config) {
2241
2672
  for (const owned of [
2242
2673
  restrictedUrl,
2243
2674
  connectUrl,
2244
- new URL("./connect/callback", restrictedUrl),
2245
2675
  new URL(getOAuthProtectedResourceMetadataUrl(restrictedUrl))
2246
2676
  ]) {
2247
2677
  restrictedByPath.set(owned.pathname, restricted);
@@ -2256,7 +2686,6 @@ function createHostedMcpApp(config) {
2256
2686
  }
2257
2687
  function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
2258
2688
  const connectPath = config.approvalPath ?? "/connect";
2259
- const callbackPath = `${connectPath}/callback`;
2260
2689
  const issuer = String(config.oauthMetadata.issuer);
2261
2690
  const jwksUri = String(config.oauthMetadata.jwks_uri);
2262
2691
  const verifier = createOpenKeyTokenVerifier({
@@ -2307,7 +2736,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
2307
2736
  return server;
2308
2737
  }, {
2309
2738
  legacy: "stateless",
2310
- onerror: () => writeDiagnostic("MCP request failed")
2739
+ onerror: () => writeDiagnostic2("MCP request failed")
2311
2740
  });
2312
2741
  const metadataOptions = {
2313
2742
  oauthMetadata: config.oauthMetadata,
@@ -2535,16 +2964,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2535
2964
  if (url.pathname === connectPath) {
2536
2965
  if (request.method !== "GET") return methodNotAllowed("GET");
2537
2966
  try {
2538
- const destination = await store.approvalRedirect(requiredState(url));
2967
+ const destination = await store.approvalLink(requiredState(url));
2539
2968
  return Response.redirect(destination, 302);
2540
2969
  } catch (error) {
2541
- const reason = error instanceof ApprovalRequestError ? error.detail : "unknown";
2542
- writeDiagnostic(`connect rejected: reason=${reason} path=${connectPath}`);
2970
+ const unavailable = error instanceof ApprovalLinkUnavailableError;
2971
+ const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
2972
+ writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
2543
2973
  if (request.headers.get("accept")?.includes("text/html")) {
2544
2974
  return new Response(
2545
- '<!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>',
2975
+ 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>',
2546
2976
  {
2547
- status: 400,
2977
+ status: unavailable ? 503 : 400,
2548
2978
  headers: {
2549
2979
  "content-type": "text/html; charset=utf-8",
2550
2980
  "cache-control": "no-store",
@@ -2556,37 +2986,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2556
2986
  }
2557
2987
  );
2558
2988
  }
2559
- return json({ error: "The approval link is invalid or expired." }, 400);
2560
- }
2561
- }
2562
- if (url.pathname === callbackPath) {
2563
- if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
2564
- if (request.method !== "POST") return methodNotAllowed("POST");
2565
- const originFailure = validateCallbackOrigin(request, config.openkeyHost);
2566
- if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
2567
- try {
2568
- await store.completeApproval(requiredState(url), request);
2569
- return callbackCors(json({ success: true }), config.openkeyHost);
2570
- } catch (error) {
2571
- if (error instanceof ApprovalOwnerMismatchError) {
2572
- return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
2573
- }
2574
- const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2575
- const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2576
- const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2577
- const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2578
- writeDiagnostic(
2579
- `connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
2580
- );
2581
- return callbackCors(
2582
- json({
2583
- error: stage,
2584
- code,
2585
- ...reason === void 0 ? {} : { reason },
2586
- message: "TinyCloud could not accept this delegation."
2587
- }, 400),
2588
- config.openkeyHost
2589
- );
2989
+ 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);
2590
2990
  }
2591
2991
  }
2592
2992
  if (url.pathname === "/native/grant" && surface === "hosted") {
@@ -2661,7 +3061,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2661
3061
  const auth = await authenticate(request);
2662
3062
  return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
2663
3063
  },
2664
- close: () => handler.close()
3064
+ close: async () => {
3065
+ await store.close();
3066
+ await handler.close();
3067
+ }
2665
3068
  };
2666
3069
  }
2667
3070
  function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
@@ -2760,18 +3163,6 @@ function mcpCors(response, request) {
2760
3163
  }
2761
3164
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
2762
3165
  }
2763
- function validateCallbackOrigin(request, openkeyHost) {
2764
- const origin = request.headers.get("origin");
2765
- return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
2766
- }
2767
- function callbackCors(response, openkeyHost) {
2768
- const headers = new Headers(response.headers);
2769
- headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
2770
- headers.set("access-control-allow-methods", "POST, OPTIONS");
2771
- headers.set("access-control-allow-headers", "content-type");
2772
- headers.set("vary", "Origin");
2773
- return new Response(response.body, { status: response.status, headers });
2774
- }
2775
3166
  async function readBoundedBodyText(request, maxBytes) {
2776
3167
  const contentLength = request.headers.get("content-length");
2777
3168
  if (contentLength !== null) {
@@ -2846,7 +3237,7 @@ function publicText(text, contentType) {
2846
3237
  function methodNotAllowed(allow) {
2847
3238
  return new Response("Method not allowed", { status: 405, headers: { allow } });
2848
3239
  }
2849
- function writeDiagnostic(message) {
3240
+ function writeDiagnostic2(message) {
2850
3241
  process.stderr.write(`[tinycloud-mcp-http] ${message}
2851
3242
  `);
2852
3243
  }
@@ -2869,6 +3260,8 @@ async function main() {
2869
3260
  stateSecret,
2870
3261
  nodeHost: process.env.TC_HOST ?? "https://node.tinycloud.xyz",
2871
3262
  openkeyHost,
3263
+ ...process.env.TC_OPENKEY_API_HOST === void 0 ? {} : { openkeyApiHost: process.env.TC_OPENKEY_API_HOST },
3264
+ ...process.env.TC_LINKS_API_ORIGIN === void 0 ? {} : { linksApiOrigin: process.env.TC_LINKS_API_ORIGIN },
2872
3265
  approvalTtlSeconds: positiveInteger(process.env.TC_MCP_APPROVAL_TTL_SECONDS, 300),
2873
3266
  delegationExpiry: process.env.TC_MCP_DELEGATION_EXPIRY ?? "1h",
2874
3267
  ...process.env.TC_MCP_NATIVE_SERVICE_CREDENTIAL === void 0 ? {} : { nativeServiceCredential: process.env.TC_MCP_NATIVE_SERVICE_CREDENTIAL },