@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/index.js CHANGED
@@ -555,7 +555,7 @@ function outcomeCode(result) {
555
555
  // package.json
556
556
  var package_default = {
557
557
  name: "@tinycloud/mcp",
558
- version: "0.11.1-beta.8",
558
+ version: "0.12.0-beta.11",
559
559
  description: "TinyCloud delegated operations MCP server",
560
560
  keywords: [
561
561
  "tinycloud",
@@ -626,10 +626,11 @@ var package_default = {
626
626
  dependencies: {
627
627
  "@modelcontextprotocol/node": "2.0.0-beta.5",
628
628
  "@modelcontextprotocol/server": "2.0.0-beta.5",
629
- "@tinycloud/node-sdk": "3.14.0-beta.10",
630
- "@tinycloud/sdk-core": "3.14.0-beta.10",
629
+ "@tinycloud/node-sdk": "3.14.0-beta.13",
630
+ "@tinycloud/sdk-core": "3.14.0-beta.13",
631
631
  "@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
632
- "@tinycloud/operations": "0.9.2-beta.8",
632
+ "@tinycloud/operations": "0.9.2-beta.11",
633
+ "@tinycloud/share-envelope": "1.6.0",
633
634
  jose: "6.2.4"
634
635
  },
635
636
  devDependencies: {
@@ -778,7 +779,6 @@ import {
778
779
  oauthMetadataResponse,
779
780
  requireBearerAuth
780
781
  } from "@modelcontextprotocol/server";
781
- import { RUNTIME_DELEGATION_REJECTIONS } from "@tinycloud/node-sdk";
782
782
 
783
783
  // src/agent-discovery.ts
784
784
  import { createHash } from "crypto";
@@ -1108,9 +1108,12 @@ function claims(token) {
1108
1108
 
1109
1109
  // src/remote-store.ts
1110
1110
  import { sameTinyCloudNode } from "@tinycloud/sdk-core";
1111
+ import { admitOwnerRenewalLease, RENEWAL_LEASE_ORIGINAL_EXPIRED, RENEWAL_RENEWER_CHANGED } from "@tinycloud/sdk-core/delegations/renewal";
1112
+ import { RENEWAL_ADMISSION_LEAD_MS, verifyOwnerRenewalLease } from "@tinycloud/sdk-core/delegations/renewal-receipt";
1111
1113
  import { createHmac, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
1112
1114
  import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
1113
- import { dirname as dirname2, join as join3 } from "path";
1115
+ import { basename as basename2, dirname as dirname2, join as join3 } from "path";
1116
+ import { setTimeout as sleep } from "timers/promises";
1114
1117
  import {
1115
1118
  activateValidatedRuntimeDelegation,
1116
1119
  deserializeDelegation,
@@ -1121,7 +1124,7 @@ import {
1121
1124
  UnsupportedSessionRestoreError,
1122
1125
  isCapabilitySubset,
1123
1126
  principalDidEquals,
1124
- publicJwk,
1127
+ RUNTIME_DELEGATION_REJECTIONS,
1125
1128
  siweRuntimeDelegation,
1126
1129
  signedCompactUcanExpiry
1127
1130
  } from "@tinycloud/node-sdk";
@@ -1129,8 +1132,14 @@ import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk
1129
1132
  import { createOrReusePermissionRequest } from "@tinycloud/operations/artifacts";
1130
1133
  import { withTinyCloudStateRoot } from "@tinycloud/operations/state";
1131
1134
  import { invokeOperation as invokeOperation2 } from "@tinycloud/operations";
1135
+ import { liveStoredLease, restoreStoredSession } from "@tinycloud/operations/profile";
1132
1136
  import { nodeRevocationOf, operationRetryDescriptor } from "@tinycloud/operations/mcp-authority";
1133
1137
  import { tcAppsApprovalMessage, tcAppsApprovalReason } from "@tinycloud/operations/tc-apps";
1138
+ import {
1139
+ APPROVAL_POLL_INTERVAL_MS,
1140
+ DEFAULT_LINKS_API_ORIGIN,
1141
+ isApprovalClientError
1142
+ } from "@tinycloud/share-envelope/links";
1134
1143
 
1135
1144
  // src/native-auth.ts
1136
1145
  import { timingSafeEqual } from "crypto";
@@ -1190,9 +1199,142 @@ function hasCaveats(permission) {
1190
1199
  return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
1191
1200
  }
1192
1201
 
1202
+ // src/openkey-approval.ts
1203
+ import { randomUUID } from "crypto";
1204
+ import {
1205
+ ackApprovalResult,
1206
+ checkApprovalResultBinding,
1207
+ createApprovalRequest,
1208
+ discoverApprovalResult,
1209
+ fetchApprovalResult,
1210
+ generateRelayKey,
1211
+ openRelayResult,
1212
+ signerFromJwk
1213
+ } from "@tinycloud/share-envelope/links";
1214
+ import { boundedResponseBytes } from "@tinycloud/sdk-core/registry-publication";
1215
+ var MIN_REQUEST_LIFE_MS = 18e4;
1216
+ var MAX_RESULT_REPLY_BYTES = 256 * 1024;
1217
+ var boundedFetch = Object.assign(async (input, init) => {
1218
+ const response = await fetch(input, init);
1219
+ const bytes = await boundedResponseBytes(response, MAX_RESULT_REPLY_BYTES);
1220
+ return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
1221
+ status: response.status,
1222
+ statusText: response.statusText
1223
+ });
1224
+ }, globalThis.fetch);
1225
+ async function createOpenKeyRequest(endpoints, input) {
1226
+ const signingKey = ed25519PrivateJwk(input.jwk);
1227
+ const signer = signerFromJwk(signingKey);
1228
+ const relay = generateRelayKey();
1229
+ const request = {
1230
+ issuer: signer.did,
1231
+ requestVersion: 1,
1232
+ targetDid: signer.did,
1233
+ targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
1234
+ nodeOrigin: new URL(input.nodeHost).origin,
1235
+ permissions: input.permissions.map(requestPermission),
1236
+ reason: input.reason,
1237
+ grantLifetimeSeconds: input.grantLifetimeSeconds,
1238
+ resultEncryptionPublicJwk: relay.publicJwk,
1239
+ ...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
1240
+ };
1241
+ const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
1242
+ const created = await createApprovalRequest({
1243
+ request,
1244
+ issuerKey: signer,
1245
+ apiOrigin: endpoints.linksApiOrigin,
1246
+ openkeyOrigin: endpoints.openkeyOrigin,
1247
+ expiresAt
1248
+ });
1249
+ return {
1250
+ requestId: created.id,
1251
+ bodyCid: created.bodyCid,
1252
+ record: { header: created.record.header, signature: created.record.signature },
1253
+ link: created.link,
1254
+ request,
1255
+ expiresAt: created.expiresAt,
1256
+ relayPrivateKey: relay.privateKey,
1257
+ ackId: randomUUID(),
1258
+ apiOrigin: endpoints.openkeyApiOrigin
1259
+ };
1260
+ }
1261
+ async function collectOpenKeyResult(state, jwk, timeoutMs) {
1262
+ const requester = requesterState(state, jwk);
1263
+ if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
1264
+ const discovered = await discoverApprovalResult(requester, { timeoutMs, fetch: boundedFetch });
1265
+ if (discovered.status === "pending") return discovered;
1266
+ return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
1267
+ }
1268
+ const relay = await fetchApprovalResult(
1269
+ requester,
1270
+ { resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
1271
+ { timeoutMs, fetch: boundedFetch }
1272
+ );
1273
+ const opened = await openRelayResult(relay, state.requestId, state.relayPrivateKey);
1274
+ return {
1275
+ status: "ready",
1276
+ checked: checkApprovalResultBinding(opened, {
1277
+ requestId: state.requestId,
1278
+ bodyCid: state.bodyCid,
1279
+ request: state.request
1280
+ })
1281
+ };
1282
+ }
1283
+ async function ackOpenKeyResult(state, jwk, timeoutMs) {
1284
+ if (state.resultRef === void 0) return;
1285
+ await ackApprovalResult(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
1286
+ }
1287
+ function lifetimeSeconds(value) {
1288
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
1289
+ const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
1290
+ const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
1291
+ if (!Number.isSafeInteger(seconds) || seconds < 60) {
1292
+ throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
1293
+ }
1294
+ return seconds;
1295
+ }
1296
+ function requesterState(state, jwk) {
1297
+ return {
1298
+ requestId: state.requestId,
1299
+ bodyCid: state.bodyCid,
1300
+ record: state.record,
1301
+ apiOrigin: state.apiOrigin,
1302
+ signingKey: ed25519PrivateJwk(jwk)
1303
+ };
1304
+ }
1305
+ function requestPermission(entry) {
1306
+ if (entry.space === void 0 || entry.space.length === 0) {
1307
+ throw new Error("An approval request needs a space for every permission.");
1308
+ }
1309
+ return {
1310
+ service: entry.service,
1311
+ space: entry.space,
1312
+ path: entry.path,
1313
+ actions: [...entry.actions],
1314
+ ...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
1315
+ };
1316
+ }
1317
+ function ed25519PrivateJwk(jwk) {
1318
+ const { kty, crv, x, d } = jwk;
1319
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
1320
+ throw new Error("The tenant key is not an Ed25519 private key.");
1321
+ }
1322
+ return { kty, crv, x, d };
1323
+ }
1324
+
1193
1325
  // src/remote-store.ts
1194
1326
  var PROFILE = "agent";
1195
1327
  var MAX_CALLBACK_BYTES = 256 * 1024;
1328
+ var PENDING_VERSION = 2;
1329
+ var CALL_COLLECTION_TIMEOUT_MS = 3e3;
1330
+ var CALL_COLLECTION_BUDGET_MS = 3e3;
1331
+ var POLL_COLLECTION_TIMEOUT_MS = 1e4;
1332
+ var FAST_POLL_WINDOW_MS = 6e4;
1333
+ var SLOW_POLL_INTERVAL_MS = 1e4;
1334
+ var MAX_COLLECTION_POLLS = 64;
1335
+ var RESULT_COLLECTION_GRACE_MS = 6e5;
1336
+ var PROCESSING_STALE_MS = 12e4;
1337
+ var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
1196
1338
  var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
1197
1339
  "DELEGATION_ARTIFACT_INVALID",
1198
1340
  "DELEGATION_EXPIRED",
@@ -1233,6 +1375,12 @@ var ApprovalStageError = class extends Error {
1233
1375
  this.reason = reason;
1234
1376
  }
1235
1377
  };
1378
+ var RenewalAdmissionUnavailableError = class extends Error {
1379
+ constructor(cause) {
1380
+ super("The renewal lease could not be admitted yet.", { cause });
1381
+ this.name = "RenewalAdmissionUnavailableError";
1382
+ }
1383
+ };
1236
1384
  var ApprovalRequestError = class extends Error {
1237
1385
  detail;
1238
1386
  constructor(detail, message, cause) {
@@ -1241,6 +1389,12 @@ var ApprovalRequestError = class extends Error {
1241
1389
  this.detail = detail;
1242
1390
  }
1243
1391
  };
1392
+ var ApprovalLinkUnavailableError = class extends Error {
1393
+ constructor(cause) {
1394
+ super("The approval link could not be created.", { cause });
1395
+ this.name = "ApprovalLinkUnavailableError";
1396
+ }
1397
+ };
1244
1398
  var NativeGrantValidationError = class extends Error {
1245
1399
  code;
1246
1400
  constructor(status) {
@@ -1262,10 +1416,25 @@ var RemoteTenantStore = class {
1262
1416
  #scopedClearing = /* @__PURE__ */ new Map();
1263
1417
  #clearedScoped = /* @__PURE__ */ new Map();
1264
1418
  #approvalProcessing = /* @__PURE__ */ new Map();
1419
+ #linkCreations = /* @__PURE__ */ new Map();
1420
+ #collections = /* @__PURE__ */ new Map();
1421
+ #polls = /* @__PURE__ */ new Map();
1422
+ #closed = false;
1423
+ #endpoints;
1424
+ #grantLifetimeSeconds;
1265
1425
  #nativeIdentity;
1266
1426
  #nativeGrantQueues = /* @__PURE__ */ new Map();
1267
1427
  constructor(config) {
1268
1428
  this.#config = config;
1429
+ const openkeyOrigin = new URL(config.openkeyHost).origin;
1430
+ this.#endpoints = {
1431
+ openkeyOrigin,
1432
+ openkeyApiOrigin: new URL(
1433
+ config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
1434
+ ).origin,
1435
+ linksApiOrigin: new URL(config.linksApiOrigin ?? DEFAULT_LINKS_API_ORIGIN).origin
1436
+ };
1437
+ this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
1269
1438
  }
1270
1439
  async nativeServiceIdentity() {
1271
1440
  const identity = await this.#loadNativeServiceKey();
@@ -1451,10 +1620,13 @@ var RemoteTenantStore = class {
1451
1620
  }
1452
1621
  /** Check stored node authority before an authenticated operation uses it. */
1453
1622
  async validateTenant(subject, ownerDids) {
1454
- await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);
1623
+ const tenant = await this.#ensureTenant(subject);
1624
+ await this.#collectApprovals(tenant);
1625
+ await this.#hasValidSession(tenant, ownerDids);
1455
1626
  }
1456
1627
  async connectStatus(subject, ownerDids = []) {
1457
1628
  const tenant = await this.#ensureTenant(subject);
1629
+ await this.#collectApprovals(tenant);
1458
1630
  const state = await this.#sessionState(tenant, ownerDids, true);
1459
1631
  if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
1460
1632
  if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
@@ -1614,77 +1786,267 @@ var RemoteTenantStore = class {
1614
1786
  await clearing;
1615
1787
  return "scoped";
1616
1788
  }
1617
- async approvalRedirect(state) {
1618
- const pending = await this.#readPending(state, false);
1789
+ /**
1790
+ * The OpenKey link behind one of this server's `/connect?state=` links. The
1791
+ * first visit creates the OpenKey approval request, signed by the tenant's
1792
+ * own key; later visits reuse it. Collection starts in the background and on
1793
+ * the tenant's next call.
1794
+ */
1795
+ async approvalLink(state) {
1796
+ const located = await this.#readPending(state);
1797
+ const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
1798
+ const prior = this.#linkCreations.get(path);
1799
+ if (prior) return prior;
1800
+ const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
1801
+ this.#linkCreations.set(path, creating);
1802
+ return creating;
1803
+ }
1804
+ async #createApprovalLink(stateRoot, initial) {
1805
+ const path = this.#pendingPath(stateRoot, initial.nonce);
1806
+ const pending = await readJson(path);
1807
+ if (pending === null || pending.version !== PENDING_VERSION) {
1808
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1809
+ }
1810
+ if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
1811
+ if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
1812
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1813
+ }
1814
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1815
+ return pending.openkey.link;
1816
+ }
1817
+ if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1619
1818
  const tenant = await this.#readTenant(pending.tenantId);
1620
- const callback = new URL(`${this.#config.approvalPath ?? "/connect"}/callback`, this.#config.publicUrl);
1621
- callback.searchParams.set("state", state);
1622
- const params = new URLSearchParams({
1623
- did: tenant.sessionDid,
1624
- callback: callback.toString(),
1625
- host: this.#config.nodeHost,
1626
- requesterOrigin: this.#config.publicUrl.origin,
1627
- jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString("base64url"),
1628
- permissions: Buffer.from(JSON.stringify({
1819
+ let openkey;
1820
+ try {
1821
+ openkey = await createOpenKeyRequest(this.#endpoints, {
1822
+ jwk: tenant.jwk,
1823
+ nodeHost: this.#config.nodeHost,
1629
1824
  permissions: pending.permissions,
1630
- reason: [
1631
- 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.",
1632
- // Owner DIDs come from the verified OpenKey access token of the MCP
1633
- // client that created this link, never from the link itself. The
1634
- // callback refuses a signer outside them, so the approver isn't asked to check.
1635
- ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
1636
- ].join(" ")
1637
- })).toString("base64url"),
1638
- expiry: this.#config.delegationExpiry
1639
- });
1640
- return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
1641
- }
1642
- async completeApproval(state, request) {
1643
- const length = Number(request.headers.get("content-length") ?? "0");
1644
- if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
1645
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1825
+ reason: approvalReason(pending),
1826
+ grantLifetimeSeconds: this.#grantLifetimeSeconds,
1827
+ ...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
1828
+ expiresAt: new Date(pending.expiresAt)
1829
+ });
1830
+ } catch (error) {
1831
+ throw new ApprovalLinkUnavailableError(error);
1646
1832
  }
1647
- const text = await request.text();
1648
- if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {
1649
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1833
+ if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
1834
+ throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
1650
1835
  }
1651
- let data;
1836
+ const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
1837
+ await secureWrite(path, { ...pending, expiresAt, openkey });
1838
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1839
+ return openkey.link;
1840
+ }
1841
+ /**
1842
+ * Collect every approval result this tenant has open in OpenKey before a
1843
+ * call decides whether it is connected. The call waits at most
1844
+ * `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
1845
+ * finishes in the background, and a failure leaves the pending approval for
1846
+ * the next call or poll.
1847
+ */
1848
+ async #collectApprovals(tenant) {
1849
+ const budget = new AbortController();
1850
+ await Promise.race([
1851
+ this.#collectEach(tenant),
1852
+ sleep(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
1853
+ ]).finally(() => budget.abort());
1854
+ }
1855
+ async #collectEach(tenant) {
1856
+ const directory = this.#pendingDirectory(tenant.stateRoot);
1857
+ let names;
1652
1858
  try {
1653
- data = JSON.parse(text);
1859
+ names = await readdir(directory);
1654
1860
  } catch (error) {
1655
- throw new ApprovalRequestError("body_invalid", "Callback body is invalid.", error);
1861
+ if (isRecord(error) && error.code === "ENOENT") return;
1862
+ throw error;
1863
+ }
1864
+ for (const name of names) {
1865
+ if (name.endsWith(".json.processing")) await this.#recoverProcessing(join3(directory, name));
1866
+ }
1867
+ const nonces = (await readdir(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
1868
+ for (const nonce of nonces) {
1869
+ await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
1870
+ }
1871
+ }
1872
+ /**
1873
+ * A claimed result whose processing never finished (the server stopped
1874
+ * mid-way). Once it is stored only the acknowledgement remains; otherwise,
1875
+ * after a grace period, it becomes collectable again.
1876
+ */
1877
+ async #recoverProcessing(claimed) {
1878
+ const pending = await readJson(claimed).catch(() => null);
1879
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
1880
+ await rm(claimed, { force: true });
1881
+ return;
1656
1882
  }
1657
- if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
1658
- const pending = await this.#readPending(state, true);
1659
1883
  const stateRoot = join3(this.#config.stateDir, "tenants", pending.tenantId);
1884
+ if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
1885
+ if (pending.openkey.storedCid !== void 0) {
1886
+ await this.#acknowledge(stateRoot, pending.openkey);
1887
+ await rm(claimed, { force: true });
1888
+ return;
1889
+ }
1890
+ const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
1891
+ if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
1892
+ const { claimedAt: _claimed, ...fresh } = pending;
1893
+ await secureWrite(claimed.slice(0, -".processing".length), fresh);
1894
+ await rm(claimed, { force: true });
1895
+ }
1896
+ /** One collection attempt for one pending approval, single-flight per approval. */
1897
+ async #collectApproval(stateRoot, nonce, timeoutMs) {
1898
+ const path = this.#pendingPath(stateRoot, nonce);
1899
+ const running = this.#collections.get(path);
1900
+ if (running) return running;
1901
+ const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
1902
+ writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
1903
+ return "retry";
1904
+ }).finally(() => this.#collections.delete(path));
1905
+ this.#collections.set(path, collecting);
1906
+ return collecting;
1907
+ }
1908
+ async #collectStep(stateRoot, nonce, timeoutMs) {
1909
+ const path = this.#pendingPath(stateRoot, nonce);
1910
+ const pending = await readJson(path).catch(() => null);
1911
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
1912
+ const openkey = pending.openkey;
1913
+ if (!this.#currentRequest(openkey)) {
1914
+ writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1915
+ await rm(path, { force: true });
1916
+ return "done";
1917
+ }
1918
+ if (Date.now() >= collectionDeadline(openkey)) {
1919
+ await rm(path, { force: true });
1920
+ return "done";
1921
+ }
1922
+ const tenant = await this.#readTenant(pending.tenantId);
1923
+ if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1924
+ await rm(path, { force: true });
1925
+ return "done";
1926
+ }
1927
+ let collected;
1928
+ try {
1929
+ collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
1930
+ } catch (error) {
1931
+ if (!isApprovalClientError(error)) throw error;
1932
+ return this.#collectionRefused(path, pending, error);
1933
+ }
1934
+ if (collected.status === "pending") return "pending";
1935
+ if (collected.status === "discovered") {
1936
+ await secureWrite(path, {
1937
+ ...pending,
1938
+ openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
1939
+ });
1940
+ return this.#collectStep(stateRoot, nonce, timeoutMs);
1941
+ }
1942
+ const claimed = `${path}.processing`;
1943
+ try {
1944
+ await rename(path, claimed);
1945
+ } catch (error) {
1946
+ if (isRecord(error) && error.code === "ENOENT") return "done";
1947
+ throw error;
1948
+ }
1949
+ await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
1660
1950
  const prior = this.#approvalProcessing.get(stateRoot);
1661
1951
  const processing = (async () => {
1662
1952
  if (prior) await prior.catch(() => void 0);
1663
- try {
1664
- const tenant = await this.#readTenant(pending.tenantId);
1665
- if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1666
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1667
- }
1668
- if (pending.kind === "bootstrap") {
1669
- await this.#storeBootstrap(tenant, pending, data);
1670
- } else {
1671
- await this.#storeDelegation(tenant, pending, data);
1672
- }
1673
- await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
1674
- } catch (error) {
1675
- await this.#restorePending(pending).catch(() => void 0);
1676
- throw error;
1953
+ const current = await this.#readTenant(pending.tenantId);
1954
+ if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
1955
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1677
1956
  }
1957
+ const { checked } = collected;
1958
+ 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);
1959
+ await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
1678
1960
  })();
1679
1961
  this.#approvalProcessing.set(stateRoot, processing);
1680
1962
  try {
1681
1963
  await processing;
1964
+ } catch (error) {
1965
+ if (error instanceof RenewalAdmissionUnavailableError) {
1966
+ await secureWrite(path, pending).catch(() => void 0);
1967
+ await rm(claimed, { force: true });
1968
+ writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
1969
+ return "retry";
1970
+ }
1971
+ const { openkey: _spent, ...fresh } = pending;
1972
+ await secureWrite(path, fresh).catch(() => void 0);
1973
+ await rm(claimed, { force: true });
1974
+ writeDiagnostic(approvalRefusalDiagnostic(error));
1975
+ return "done";
1682
1976
  } finally {
1683
1977
  if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
1684
1978
  }
1979
+ await this.#acknowledge(stateRoot, openkey);
1980
+ await rm(claimed, { force: true });
1981
+ return "done";
1982
+ }
1983
+ async #collectionRefused(path, pending, error) {
1984
+ switch (error.code) {
1985
+ case "network":
1986
+ case "unavailable":
1987
+ return "retry";
1988
+ case "request_expired":
1989
+ if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
1990
+ await rm(path, { force: true });
1991
+ return "done";
1992
+ case "acknowledged":
1993
+ await rm(path, { force: true });
1994
+ return "done";
1995
+ default: {
1996
+ const { openkey: _spent, ...fresh } = pending;
1997
+ await secureWrite(path, fresh);
1998
+ writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
1999
+ return "done";
2000
+ }
2001
+ }
2002
+ }
2003
+ async #acknowledge(stateRoot, openkey) {
2004
+ try {
2005
+ const tenant = await this.#readTenant(basename2(stateRoot));
2006
+ await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
2007
+ } catch (error) {
2008
+ writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Poll one opened approval until it is collected or its request and result
2013
+ * window end: every 2 s for the first minute, then every 10 s. At most
2014
+ * `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
2015
+ * collects.
2016
+ */
2017
+ #startCollectionPoll(stateRoot, nonce) {
2018
+ const key = this.#pendingPath(stateRoot, nonce);
2019
+ if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
2020
+ const startedAt = Date.now();
2021
+ const schedule = () => {
2022
+ const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
2023
+ const timer = setTimeout(() => void tick(), delay);
2024
+ timer.unref();
2025
+ this.#polls.set(key, timer);
2026
+ };
2027
+ const tick = async () => {
2028
+ const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
2029
+ if (this.#closed || outcome === "done" || outcome === "idle") {
2030
+ this.#polls.delete(key);
2031
+ return;
2032
+ }
2033
+ schedule();
2034
+ };
2035
+ schedule();
2036
+ }
2037
+ /** Stop background collection. Pending approvals stay on disk for the next start. */
2038
+ async close() {
2039
+ this.#closed = true;
2040
+ for (const timer of this.#polls.values()) clearTimeout(timer);
2041
+ this.#polls.clear();
2042
+ await Promise.allSettled([...this.#collections.values()]);
1685
2043
  }
1686
- async #storeBootstrap(tenant, pending, data) {
1687
- const { node, session } = await this.#restoreApproval(tenant, data);
2044
+ /** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
2045
+ #currentRequest(openkey) {
2046
+ 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;
2047
+ }
2048
+ async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
2049
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
1688
2050
  this.#assertCurrentApproval(pending, session);
1689
2051
  if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
1690
2052
  throw new ApprovalOwnerMismatchError();
@@ -1692,6 +2054,7 @@ var RemoteTenantStore = class {
1692
2054
  if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
1693
2055
  throw new Error("The approved delegation does not cover the requested account access.");
1694
2056
  }
2057
+ if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
1695
2058
  const profile = await readJson(this.#profilePath(tenant.stateRoot));
1696
2059
  await secureWrite(this.#profilePath(tenant.stateRoot), {
1697
2060
  ...profile,
@@ -1700,14 +2063,51 @@ var RemoteTenantStore = class {
1700
2063
  });
1701
2064
  await secureWrite(this.#sessionPath(tenant.stateRoot), {
1702
2065
  authMethod: "openkey",
1703
- ...session
2066
+ ...session,
2067
+ ...renewal === void 0 ? {} : { renewal }
1704
2068
  });
1705
2069
  this.#renewalRequired.delete(tenant.stateRoot);
1706
2070
  this.#activeSessions.delete(tenant.stateRoot);
2071
+ return session.delegationCid;
1707
2072
  }
1708
- async #storeDelegation(tenant, pending, data) {
2073
+ /**
2074
+ * Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
2075
+ * session is stored. Admission replays the exact signed lease, so a retry admits the same one.
2076
+ */
2077
+ async #admitRenewal(tenant, ownerDid, session, renewal) {
2078
+ let signed;
2079
+ try {
2080
+ signed = await verifyOwnerRenewalLease(session, ownerDid, renewal);
2081
+ } catch (error) {
2082
+ throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
2083
+ }
2084
+ if (Date.parse(signed.originalExpiresAt) - Date.now() < RENEWAL_ADMISSION_LEAD_MS) {
2085
+ throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
2086
+ }
2087
+ try {
2088
+ await admitOwnerRenewalLease({
2089
+ host: new URL(this.#config.nodeHost).origin,
2090
+ originalAuthorization: session.delegationHeader.Authorization,
2091
+ originalCid: session.delegationCid,
2092
+ ownerDid,
2093
+ agentDid: tenant.sessionDid.split("#")[0],
2094
+ spaceId: session.spaceId,
2095
+ nodeIdentity: renewal.receipt.nodeIdentity,
2096
+ leaseAuthorization: renewal.receipt.leaseAuthorization,
2097
+ leaseCid: renewal.receipt.leaseCid,
2098
+ leaseExpiresAt: signed.leaseSignedExpiresAt
2099
+ });
2100
+ } catch (error) {
2101
+ const code = isRecord(error) ? error.code : void 0;
2102
+ if (code === RENEWAL_RENEWER_CHANGED || code === RENEWAL_LEASE_ORIGINAL_EXPIRED) {
2103
+ throw new ApprovalStageError("renewal", code, void 0, error);
2104
+ }
2105
+ throw new RenewalAdmissionUnavailableError(error);
2106
+ }
2107
+ }
2108
+ async #storeDelegation(tenant, pending, data, resultOwner) {
1709
2109
  if (pending.requestId === void 0) throw new Error("Authority request is missing.");
1710
- const { node, session } = await this.#restoreApproval(tenant, data);
2110
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
1711
2111
  this.#assertCurrentApproval(pending, session);
1712
2112
  if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
1713
2113
  let delegation;
@@ -1751,6 +2151,7 @@ var RemoteTenantStore = class {
1751
2151
  );
1752
2152
  }
1753
2153
  if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
2154
+ return session.delegationCid;
1754
2155
  }
1755
2156
  #assertCurrentApproval(pending, session) {
1756
2157
  const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
@@ -1759,13 +2160,14 @@ var RemoteTenantStore = class {
1759
2160
  }
1760
2161
  }
1761
2162
  /**
1762
- * Verify the OpenKey callback as a SIWE session for this tenant's key. The
1763
- * callback must carry the full signed proof (SIWE, signature, address and
1764
- * chain), so the WASM verifier always runs: it binds the authorization bytes
1765
- * and CID to the signed SIWE, and `node.did` is the wallet that signed
1766
- * exactly the delegation being stored.
2163
+ * Verify OpenKey's delegation as a SIWE session for this tenant's key. It
2164
+ * must carry the full signed proof (SIWE, signature, address and chain), so
2165
+ * the WASM verifier always runs: it binds the authorization bytes and CID to
2166
+ * the signed SIWE, and `node.did` is the wallet that signed exactly the
2167
+ * delegation being stored. That wallet must be the owner OpenKey's result
2168
+ * names.
1767
2169
  */
1768
- async #restoreApproval(tenant, data) {
2170
+ async #restoreApproval(tenant, data, resultOwner) {
1769
2171
  let session;
1770
2172
  try {
1771
2173
  session = sessionFromCallback(data, tenant.jwk);
@@ -1786,6 +2188,9 @@ var RemoteTenantStore = class {
1786
2188
  if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
1787
2189
  throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
1788
2190
  }
2191
+ if (!samePrincipal(node.did, resultOwner)) {
2192
+ throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
2193
+ }
1789
2194
  return { node, session };
1790
2195
  }
1791
2196
  async #ensureTenant(subject) {
@@ -1824,13 +2229,16 @@ var RemoteTenantStore = class {
1824
2229
  if (raw === null) return "invalid";
1825
2230
  const node = new TinyCloudNode({ host: this.#config.nodeHost });
1826
2231
  try {
1827
- await node.restoreSession(raw);
1828
- } catch {
2232
+ await restoreStoredSession(node, raw, raw);
2233
+ } catch (error) {
1829
2234
  const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
1830
2235
  const signedExpiry = typeof header === "string" ? signedCompactUcanExpiry(header) : void 0;
1831
2236
  const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
1832
2237
  const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
1833
- if (expiry !== void 0 && expiry.getTime() <= Date.now()) return "invalid";
2238
+ if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
2239
+ const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
2240
+ return liveStoredLease(raw) !== void 0 && !ended ? "unknown" : "invalid";
2241
+ }
1834
2242
  await this.#clearAuthority(tenant);
1835
2243
  return "invalid";
1836
2244
  }
@@ -1965,15 +2373,17 @@ var RemoteTenantStore = class {
1965
2373
  return writing;
1966
2374
  }
1967
2375
  async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
2376
+ const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
1968
2377
  const reusable = await reusablePending(
1969
2378
  this.#pendingDirectory(tenant.stateRoot),
1970
- { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
2379
+ { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
2380
+ (openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
1971
2381
  );
1972
2382
  if (reusable !== void 0) return reusable;
1973
2383
  const nonce = randomBytes(24).toString("base64url");
1974
2384
  const created = Date.now();
1975
2385
  const pending = {
1976
- version: 1,
2386
+ version: PENDING_VERSION,
1977
2387
  nonce,
1978
2388
  tenantId,
1979
2389
  approvalEpoch: tenant.approvalEpoch,
@@ -1987,7 +2397,7 @@ var RemoteTenantStore = class {
1987
2397
  await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
1988
2398
  return pending;
1989
2399
  }
1990
- async #readPending(state, consume) {
2400
+ async #readPending(state) {
1991
2401
  const [tenantId, nonce, signature] = state.split(".");
1992
2402
  if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
1993
2403
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
@@ -2000,46 +2410,30 @@ var RemoteTenantStore = class {
2000
2410
  }
2001
2411
  const stateRoot = join3(this.#config.stateDir, "tenants", tenantId);
2002
2412
  const path = this.#pendingPath(stateRoot, nonce);
2003
- const claimed = `${path}.processing`;
2004
- if (consume) {
2005
- try {
2006
- await rename(path, claimed);
2007
- } catch (error) {
2008
- if (!isRecord(error) || error.code !== "ENOENT") throw error;
2009
- const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
2010
- (jwk) => jwk !== null,
2011
- () => true
2012
- );
2013
- if (!tenantExists) {
2014
- throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
2015
- }
2016
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
2017
- }
2413
+ const pending = await readJson(path);
2414
+ if (pending === null) {
2415
+ const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
2416
+ (jwk) => jwk !== null,
2417
+ () => true
2418
+ );
2419
+ if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
2420
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2018
2421
  }
2019
- try {
2020
- const pending = await readJson(consume ? claimed : path);
2021
- if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
2022
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2023
- }
2024
- const profile = await readJson(this.#profilePath(stateRoot));
2025
- const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
2026
- if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
2027
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2028
- }
2029
- if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2030
- await rm(consume ? claimed : path, { force: true });
2031
- throw new ApprovalRequestError("state_expired", "Approval state has expired.");
2422
+ if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
2423
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2424
+ }
2425
+ const profile = await readJson(this.#profilePath(stateRoot));
2426
+ const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
2427
+ if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
2428
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2429
+ }
2430
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2431
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2432
+ await rm(path, { force: true });
2032
2433
  }
2033
- return pending;
2034
- } catch (error) {
2035
- if (consume) await rename(claimed, path).catch(() => void 0);
2036
- throw error;
2434
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
2037
2435
  }
2038
- }
2039
- async #restorePending(pending) {
2040
- const stateRoot = join3(this.#config.stateDir, "tenants", pending.tenantId);
2041
- const path = this.#pendingPath(stateRoot, pending.nonce);
2042
- await rename(`${path}.processing`, path);
2436
+ return { stateRoot, pending };
2043
2437
  }
2044
2438
  #connectUrl(pending) {
2045
2439
  const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
@@ -2240,6 +2634,37 @@ function sessionFromCallback(data, privateJwk) {
2240
2634
  signature: data.signature
2241
2635
  };
2242
2636
  }
2637
+ function approvalReason(pending) {
2638
+ return [
2639
+ 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.",
2640
+ // Owner DIDs come from the verified OpenKey access token of the MCP
2641
+ // client that created this link, never from the link itself. Collection
2642
+ // refuses a signer outside them, so the approver isn't asked to check.
2643
+ ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
2644
+ ].join(" ");
2645
+ }
2646
+ function collectionDeadline(openkey) {
2647
+ return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
2648
+ }
2649
+ function collectionErrorCode(error) {
2650
+ if (isApprovalClientError(error)) return error.code.toUpperCase();
2651
+ if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
2652
+ return "UNKNOWN";
2653
+ }
2654
+ function approvalRefusalDiagnostic(error) {
2655
+ if (error instanceof ApprovalOwnerMismatchError) {
2656
+ return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
2657
+ }
2658
+ const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2659
+ const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2660
+ const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2661
+ const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2662
+ return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
2663
+ }
2664
+ function writeDiagnostic(message) {
2665
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
2666
+ `);
2667
+ }
2243
2668
  function samePrincipal(left, right) {
2244
2669
  if (typeof left !== "string") return false;
2245
2670
  try {
@@ -2314,7 +2739,7 @@ async function restoreOptionalText(path, contents) {
2314
2739
  await writeFile(path, contents, { mode: 384 });
2315
2740
  await chmod(path, 384);
2316
2741
  }
2317
- async function reusablePending(directory, expected) {
2742
+ async function reusablePending(directory, expected, currentRequest) {
2318
2743
  let names;
2319
2744
  try {
2320
2745
  names = await readdir(directory);
@@ -2327,12 +2752,18 @@ async function reusablePending(directory, expected) {
2327
2752
  if (!name.endsWith(".json")) continue;
2328
2753
  const path = join3(directory, name);
2329
2754
  const pending = await readJson(path).catch(() => null);
2330
- if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
2755
+ if (pending === null) {
2331
2756
  await rm(path, { force: true });
2332
2757
  continue;
2333
2758
  }
2759
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2760
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2761
+ await rm(path, { force: true });
2762
+ }
2763
+ continue;
2764
+ }
2334
2765
  active.push(pending);
2335
- if (samePendingRequest(pending, expected)) return pending;
2766
+ if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
2336
2767
  }
2337
2768
  if (active.length >= 64) {
2338
2769
  active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
@@ -2341,7 +2772,7 @@ async function reusablePending(directory, expected) {
2341
2772
  return void 0;
2342
2773
  }
2343
2774
  function samePendingRequest(pending, expected) {
2344
- 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);
2775
+ 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);
2345
2776
  }
2346
2777
 
2347
2778
  // src/http.ts
@@ -2374,7 +2805,6 @@ function createHostedMcpApp(config) {
2374
2805
  for (const owned of [
2375
2806
  restrictedUrl,
2376
2807
  connectUrl,
2377
- new URL("./connect/callback", restrictedUrl),
2378
2808
  new URL(getOAuthProtectedResourceMetadataUrl(restrictedUrl))
2379
2809
  ]) {
2380
2810
  restrictedByPath.set(owned.pathname, restricted);
@@ -2389,7 +2819,6 @@ function createHostedMcpApp(config) {
2389
2819
  }
2390
2820
  function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
2391
2821
  const connectPath = config.approvalPath ?? "/connect";
2392
- const callbackPath = `${connectPath}/callback`;
2393
2822
  const issuer = String(config.oauthMetadata.issuer);
2394
2823
  const jwksUri = String(config.oauthMetadata.jwks_uri);
2395
2824
  const verifier = createOpenKeyTokenVerifier({
@@ -2440,7 +2869,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
2440
2869
  return server;
2441
2870
  }, {
2442
2871
  legacy: "stateless",
2443
- onerror: () => writeDiagnostic("MCP request failed")
2872
+ onerror: () => writeDiagnostic2("MCP request failed")
2444
2873
  });
2445
2874
  const metadataOptions = {
2446
2875
  oauthMetadata: config.oauthMetadata,
@@ -2668,16 +3097,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2668
3097
  if (url.pathname === connectPath) {
2669
3098
  if (request.method !== "GET") return methodNotAllowed("GET");
2670
3099
  try {
2671
- const destination = await store.approvalRedirect(requiredState(url));
3100
+ const destination = await store.approvalLink(requiredState(url));
2672
3101
  return Response.redirect(destination, 302);
2673
3102
  } catch (error) {
2674
- const reason = error instanceof ApprovalRequestError ? error.detail : "unknown";
2675
- writeDiagnostic(`connect rejected: reason=${reason} path=${connectPath}`);
3103
+ const unavailable = error instanceof ApprovalLinkUnavailableError;
3104
+ const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
3105
+ writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
2676
3106
  if (request.headers.get("accept")?.includes("text/html")) {
2677
3107
  return new Response(
2678
- '<!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>',
3108
+ 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>',
2679
3109
  {
2680
- status: 400,
3110
+ status: unavailable ? 503 : 400,
2681
3111
  headers: {
2682
3112
  "content-type": "text/html; charset=utf-8",
2683
3113
  "cache-control": "no-store",
@@ -2689,37 +3119,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2689
3119
  }
2690
3120
  );
2691
3121
  }
2692
- return json({ error: "The approval link is invalid or expired." }, 400);
2693
- }
2694
- }
2695
- if (url.pathname === callbackPath) {
2696
- if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
2697
- if (request.method !== "POST") return methodNotAllowed("POST");
2698
- const originFailure = validateCallbackOrigin(request, config.openkeyHost);
2699
- if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
2700
- try {
2701
- await store.completeApproval(requiredState(url), request);
2702
- return callbackCors(json({ success: true }), config.openkeyHost);
2703
- } catch (error) {
2704
- if (error instanceof ApprovalOwnerMismatchError) {
2705
- return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
2706
- }
2707
- const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2708
- const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2709
- const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2710
- const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2711
- writeDiagnostic(
2712
- `connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
2713
- );
2714
- return callbackCors(
2715
- json({
2716
- error: stage,
2717
- code,
2718
- ...reason === void 0 ? {} : { reason },
2719
- message: "TinyCloud could not accept this delegation."
2720
- }, 400),
2721
- config.openkeyHost
2722
- );
3122
+ 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);
2723
3123
  }
2724
3124
  }
2725
3125
  if (url.pathname === "/native/grant" && surface === "hosted") {
@@ -2794,7 +3194,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2794
3194
  const auth = await authenticate(request);
2795
3195
  return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
2796
3196
  },
2797
- close: () => handler.close()
3197
+ close: async () => {
3198
+ await store.close();
3199
+ await handler.close();
3200
+ }
2798
3201
  };
2799
3202
  }
2800
3203
  function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
@@ -2893,18 +3296,6 @@ function mcpCors(response, request) {
2893
3296
  }
2894
3297
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
2895
3298
  }
2896
- function validateCallbackOrigin(request, openkeyHost) {
2897
- const origin = request.headers.get("origin");
2898
- return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
2899
- }
2900
- function callbackCors(response, openkeyHost) {
2901
- const headers = new Headers(response.headers);
2902
- headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
2903
- headers.set("access-control-allow-methods", "POST, OPTIONS");
2904
- headers.set("access-control-allow-headers", "content-type");
2905
- headers.set("vary", "Origin");
2906
- return new Response(response.body, { status: response.status, headers });
2907
- }
2908
3299
  async function readBoundedBodyText(request, maxBytes) {
2909
3300
  const contentLength = request.headers.get("content-length");
2910
3301
  if (contentLength !== null) {
@@ -2979,7 +3370,7 @@ function publicText(text, contentType) {
2979
3370
  function methodNotAllowed(allow) {
2980
3371
  return new Response("Method not allowed", { status: 405, headers: { allow } });
2981
3372
  }
2982
- function writeDiagnostic(message) {
3373
+ function writeDiagnostic2(message) {
2983
3374
  process.stderr.write(`[tinycloud-mcp-http] ${message}
2984
3375
  `);
2985
3376
  }