@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/index.cjs CHANGED
@@ -592,7 +592,7 @@ function outcomeCode(result) {
592
592
  // package.json
593
593
  var package_default = {
594
594
  name: "@tinycloud/mcp",
595
- version: "0.11.1-beta.9",
595
+ version: "0.12.0-beta.11",
596
596
  description: "TinyCloud delegated operations MCP server",
597
597
  keywords: [
598
598
  "tinycloud",
@@ -663,10 +663,11 @@ var package_default = {
663
663
  dependencies: {
664
664
  "@modelcontextprotocol/node": "2.0.0-beta.5",
665
665
  "@modelcontextprotocol/server": "2.0.0-beta.5",
666
- "@tinycloud/node-sdk": "3.14.0-beta.11",
667
- "@tinycloud/sdk-core": "3.14.0-beta.11",
666
+ "@tinycloud/node-sdk": "3.14.0-beta.13",
667
+ "@tinycloud/sdk-core": "3.14.0-beta.13",
668
668
  "@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
669
- "@tinycloud/operations": "0.9.2-beta.9",
669
+ "@tinycloud/operations": "0.9.2-beta.11",
670
+ "@tinycloud/share-envelope": "1.6.0",
670
671
  jose: "6.2.4"
671
672
  },
672
673
  devDependencies: {
@@ -807,7 +808,6 @@ if (isDirectInvocation()) {
807
808
  // src/http.ts
808
809
  var import_node_path5 = require("path");
809
810
  var import_server5 = require("@modelcontextprotocol/server");
810
- var import_node_sdk3 = require("@tinycloud/node-sdk");
811
811
 
812
812
  // src/agent-discovery.ts
813
813
  var import_node_crypto = require("crypto");
@@ -1135,16 +1135,21 @@ function claims(token) {
1135
1135
 
1136
1136
  // src/remote-store.ts
1137
1137
  var import_sdk_core = require("@tinycloud/sdk-core");
1138
- var import_node_crypto4 = require("crypto");
1138
+ var import_renewal = require("@tinycloud/sdk-core/delegations/renewal");
1139
+ var import_renewal_receipt = require("@tinycloud/sdk-core/delegations/renewal-receipt");
1140
+ var import_node_crypto5 = require("crypto");
1139
1141
  var import_promises = require("fs/promises");
1140
1142
  var import_node_path4 = require("path");
1143
+ var import_promises2 = require("timers/promises");
1141
1144
  var import_node_sdk2 = require("@tinycloud/node-sdk");
1142
1145
  var import_node_sdk_wasm = require("@tinycloud/node-sdk-wasm");
1143
1146
  var import_artifacts = require("@tinycloud/operations/artifacts");
1144
1147
  var import_state = require("@tinycloud/operations/state");
1145
1148
  var import_operations2 = require("@tinycloud/operations");
1149
+ var import_profile2 = require("@tinycloud/operations/profile");
1146
1150
  var import_mcp_authority = require("@tinycloud/operations/mcp-authority");
1147
1151
  var import_tc_apps2 = require("@tinycloud/operations/tc-apps");
1152
+ var import_links2 = require("@tinycloud/share-envelope/links");
1148
1153
 
1149
1154
  // src/native-auth.ts
1150
1155
  var import_node_crypto3 = require("crypto");
@@ -1204,9 +1209,133 @@ function hasCaveats(permission) {
1204
1209
  return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
1205
1210
  }
1206
1211
 
1212
+ // src/openkey-approval.ts
1213
+ var import_node_crypto4 = require("crypto");
1214
+ var import_links = require("@tinycloud/share-envelope/links");
1215
+ var import_registry_publication = require("@tinycloud/sdk-core/registry-publication");
1216
+ var MIN_REQUEST_LIFE_MS = 18e4;
1217
+ var MAX_RESULT_REPLY_BYTES = 256 * 1024;
1218
+ var boundedFetch = Object.assign(async (input, init) => {
1219
+ const response = await fetch(input, init);
1220
+ const bytes = await (0, import_registry_publication.boundedResponseBytes)(response, MAX_RESULT_REPLY_BYTES);
1221
+ return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
1222
+ status: response.status,
1223
+ statusText: response.statusText
1224
+ });
1225
+ }, globalThis.fetch);
1226
+ async function createOpenKeyRequest(endpoints, input) {
1227
+ const signingKey = ed25519PrivateJwk(input.jwk);
1228
+ const signer = (0, import_links.signerFromJwk)(signingKey);
1229
+ const relay = (0, import_links.generateRelayKey)();
1230
+ const request = {
1231
+ issuer: signer.did,
1232
+ requestVersion: 1,
1233
+ targetDid: signer.did,
1234
+ targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
1235
+ nodeOrigin: new URL(input.nodeHost).origin,
1236
+ permissions: input.permissions.map(requestPermission),
1237
+ reason: input.reason,
1238
+ grantLifetimeSeconds: input.grantLifetimeSeconds,
1239
+ resultEncryptionPublicJwk: relay.publicJwk,
1240
+ ...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
1241
+ };
1242
+ const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
1243
+ const created = await (0, import_links.createApprovalRequest)({
1244
+ request,
1245
+ issuerKey: signer,
1246
+ apiOrigin: endpoints.linksApiOrigin,
1247
+ openkeyOrigin: endpoints.openkeyOrigin,
1248
+ expiresAt
1249
+ });
1250
+ return {
1251
+ requestId: created.id,
1252
+ bodyCid: created.bodyCid,
1253
+ record: { header: created.record.header, signature: created.record.signature },
1254
+ link: created.link,
1255
+ request,
1256
+ expiresAt: created.expiresAt,
1257
+ relayPrivateKey: relay.privateKey,
1258
+ ackId: (0, import_node_crypto4.randomUUID)(),
1259
+ apiOrigin: endpoints.openkeyApiOrigin
1260
+ };
1261
+ }
1262
+ async function collectOpenKeyResult(state, jwk, timeoutMs) {
1263
+ const requester = requesterState(state, jwk);
1264
+ if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
1265
+ const discovered = await (0, import_links.discoverApprovalResult)(requester, { timeoutMs, fetch: boundedFetch });
1266
+ if (discovered.status === "pending") return discovered;
1267
+ return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
1268
+ }
1269
+ const relay = await (0, import_links.fetchApprovalResult)(
1270
+ requester,
1271
+ { resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
1272
+ { timeoutMs, fetch: boundedFetch }
1273
+ );
1274
+ const opened = await (0, import_links.openRelayResult)(relay, state.requestId, state.relayPrivateKey);
1275
+ return {
1276
+ status: "ready",
1277
+ checked: (0, import_links.checkApprovalResultBinding)(opened, {
1278
+ requestId: state.requestId,
1279
+ bodyCid: state.bodyCid,
1280
+ request: state.request
1281
+ })
1282
+ };
1283
+ }
1284
+ async function ackOpenKeyResult(state, jwk, timeoutMs) {
1285
+ if (state.resultRef === void 0) return;
1286
+ await (0, import_links.ackApprovalResult)(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
1287
+ }
1288
+ function lifetimeSeconds(value) {
1289
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
1290
+ const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
1291
+ const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
1292
+ if (!Number.isSafeInteger(seconds) || seconds < 60) {
1293
+ throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
1294
+ }
1295
+ return seconds;
1296
+ }
1297
+ function requesterState(state, jwk) {
1298
+ return {
1299
+ requestId: state.requestId,
1300
+ bodyCid: state.bodyCid,
1301
+ record: state.record,
1302
+ apiOrigin: state.apiOrigin,
1303
+ signingKey: ed25519PrivateJwk(jwk)
1304
+ };
1305
+ }
1306
+ function requestPermission(entry) {
1307
+ if (entry.space === void 0 || entry.space.length === 0) {
1308
+ throw new Error("An approval request needs a space for every permission.");
1309
+ }
1310
+ return {
1311
+ service: entry.service,
1312
+ space: entry.space,
1313
+ path: entry.path,
1314
+ actions: [...entry.actions],
1315
+ ...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
1316
+ };
1317
+ }
1318
+ function ed25519PrivateJwk(jwk) {
1319
+ const { kty, crv, x, d } = jwk;
1320
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
1321
+ throw new Error("The tenant key is not an Ed25519 private key.");
1322
+ }
1323
+ return { kty, crv, x, d };
1324
+ }
1325
+
1207
1326
  // src/remote-store.ts
1208
1327
  var PROFILE = "agent";
1209
1328
  var MAX_CALLBACK_BYTES = 256 * 1024;
1329
+ var PENDING_VERSION = 2;
1330
+ var CALL_COLLECTION_TIMEOUT_MS = 3e3;
1331
+ var CALL_COLLECTION_BUDGET_MS = 3e3;
1332
+ var POLL_COLLECTION_TIMEOUT_MS = 1e4;
1333
+ var FAST_POLL_WINDOW_MS = 6e4;
1334
+ var SLOW_POLL_INTERVAL_MS = 1e4;
1335
+ var MAX_COLLECTION_POLLS = 64;
1336
+ var RESULT_COLLECTION_GRACE_MS = 6e5;
1337
+ var PROCESSING_STALE_MS = 12e4;
1338
+ var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
1210
1339
  var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
1211
1340
  "DELEGATION_ARTIFACT_INVALID",
1212
1341
  "DELEGATION_EXPIRED",
@@ -1247,6 +1376,12 @@ var ApprovalStageError = class extends Error {
1247
1376
  this.reason = reason;
1248
1377
  }
1249
1378
  };
1379
+ var RenewalAdmissionUnavailableError = class extends Error {
1380
+ constructor(cause) {
1381
+ super("The renewal lease could not be admitted yet.", { cause });
1382
+ this.name = "RenewalAdmissionUnavailableError";
1383
+ }
1384
+ };
1250
1385
  var ApprovalRequestError = class extends Error {
1251
1386
  detail;
1252
1387
  constructor(detail, message, cause) {
@@ -1255,6 +1390,12 @@ var ApprovalRequestError = class extends Error {
1255
1390
  this.detail = detail;
1256
1391
  }
1257
1392
  };
1393
+ var ApprovalLinkUnavailableError = class extends Error {
1394
+ constructor(cause) {
1395
+ super("The approval link could not be created.", { cause });
1396
+ this.name = "ApprovalLinkUnavailableError";
1397
+ }
1398
+ };
1258
1399
  var NativeGrantValidationError = class extends Error {
1259
1400
  code;
1260
1401
  constructor(status) {
@@ -1276,10 +1417,25 @@ var RemoteTenantStore = class {
1276
1417
  #scopedClearing = /* @__PURE__ */ new Map();
1277
1418
  #clearedScoped = /* @__PURE__ */ new Map();
1278
1419
  #approvalProcessing = /* @__PURE__ */ new Map();
1420
+ #linkCreations = /* @__PURE__ */ new Map();
1421
+ #collections = /* @__PURE__ */ new Map();
1422
+ #polls = /* @__PURE__ */ new Map();
1423
+ #closed = false;
1424
+ #endpoints;
1425
+ #grantLifetimeSeconds;
1279
1426
  #nativeIdentity;
1280
1427
  #nativeGrantQueues = /* @__PURE__ */ new Map();
1281
1428
  constructor(config) {
1282
1429
  this.#config = config;
1430
+ const openkeyOrigin = new URL(config.openkeyHost).origin;
1431
+ this.#endpoints = {
1432
+ openkeyOrigin,
1433
+ openkeyApiOrigin: new URL(
1434
+ config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
1435
+ ).origin,
1436
+ linksApiOrigin: new URL(config.linksApiOrigin ?? import_links2.DEFAULT_LINKS_API_ORIGIN).origin
1437
+ };
1438
+ this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
1283
1439
  }
1284
1440
  async nativeServiceIdentity() {
1285
1441
  const identity = await this.#loadNativeServiceKey();
@@ -1288,7 +1444,7 @@ var RemoteTenantStore = class {
1288
1444
  nativeTenantStateRoot(ownerDid) {
1289
1445
  const canonical = canonicalOwnerDid(ownerDid);
1290
1446
  if (canonical === void 0) throw new NativeGrantValidationError("rejected");
1291
- const tenant = (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
1447
+ const tenant = (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`native-tenant:${canonical}`).digest("hex");
1292
1448
  return (0, import_node_path4.join)(this.#config.stateDir, "native-tenants", tenant);
1293
1449
  }
1294
1450
  async acceptNativeGrant(serializedDelegation) {
@@ -1465,10 +1621,13 @@ var RemoteTenantStore = class {
1465
1621
  }
1466
1622
  /** Check stored node authority before an authenticated operation uses it. */
1467
1623
  async validateTenant(subject, ownerDids) {
1468
- await this.#hasValidSession(await this.#ensureTenant(subject), ownerDids);
1624
+ const tenant = await this.#ensureTenant(subject);
1625
+ await this.#collectApprovals(tenant);
1626
+ await this.#hasValidSession(tenant, ownerDids);
1469
1627
  }
1470
1628
  async connectStatus(subject, ownerDids = []) {
1471
1629
  const tenant = await this.#ensureTenant(subject);
1630
+ await this.#collectApprovals(tenant);
1472
1631
  const state = await this.#sessionState(tenant, ownerDids, true);
1473
1632
  if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
1474
1633
  if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
@@ -1628,77 +1787,267 @@ var RemoteTenantStore = class {
1628
1787
  await clearing;
1629
1788
  return "scoped";
1630
1789
  }
1631
- async approvalRedirect(state) {
1632
- const pending = await this.#readPending(state, false);
1790
+ /**
1791
+ * The OpenKey link behind one of this server's `/connect?state=` links. The
1792
+ * first visit creates the OpenKey approval request, signed by the tenant's
1793
+ * own key; later visits reuse it. Collection starts in the background and on
1794
+ * the tenant's next call.
1795
+ */
1796
+ async approvalLink(state) {
1797
+ const located = await this.#readPending(state);
1798
+ const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
1799
+ const prior = this.#linkCreations.get(path);
1800
+ if (prior) return prior;
1801
+ const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
1802
+ this.#linkCreations.set(path, creating);
1803
+ return creating;
1804
+ }
1805
+ async #createApprovalLink(stateRoot, initial) {
1806
+ const path = this.#pendingPath(stateRoot, initial.nonce);
1807
+ const pending = await readJson(path);
1808
+ if (pending === null || pending.version !== PENDING_VERSION) {
1809
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1810
+ }
1811
+ if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
1812
+ if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
1813
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
1814
+ }
1815
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1816
+ return pending.openkey.link;
1817
+ }
1818
+ if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1633
1819
  const tenant = await this.#readTenant(pending.tenantId);
1634
- const callback = new URL(`${this.#config.approvalPath ?? "/connect"}/callback`, this.#config.publicUrl);
1635
- callback.searchParams.set("state", state);
1636
- const params = new URLSearchParams({
1637
- did: tenant.sessionDid,
1638
- callback: callback.toString(),
1639
- host: this.#config.nodeHost,
1640
- requesterOrigin: this.#config.publicUrl.origin,
1641
- jwk: Buffer.from(JSON.stringify((0, import_node_sdk2.publicJwk)(tenant.jwk))).toString("base64url"),
1642
- permissions: Buffer.from(JSON.stringify({
1820
+ let openkey;
1821
+ try {
1822
+ openkey = await createOpenKeyRequest(this.#endpoints, {
1823
+ jwk: tenant.jwk,
1824
+ nodeHost: this.#config.nodeHost,
1643
1825
  permissions: pending.permissions,
1644
- reason: [
1645
- pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : (0, import_tc_apps2.tcAppsApprovalReason)(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
1646
- // Owner DIDs come from the verified OpenKey access token of the MCP
1647
- // client that created this link, never from the link itself. The
1648
- // callback refuses a signer outside them, so the approver isn't asked to check.
1649
- ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
1650
- ].join(" ")
1651
- })).toString("base64url"),
1652
- expiry: this.#config.delegationExpiry
1653
- });
1654
- return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
1655
- }
1656
- async completeApproval(state, request) {
1657
- const length = Number(request.headers.get("content-length") ?? "0");
1658
- if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
1659
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1826
+ reason: approvalReason(pending),
1827
+ grantLifetimeSeconds: this.#grantLifetimeSeconds,
1828
+ ...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
1829
+ expiresAt: new Date(pending.expiresAt)
1830
+ });
1831
+ } catch (error) {
1832
+ throw new ApprovalLinkUnavailableError(error);
1660
1833
  }
1661
- const text = await request.text();
1662
- if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) {
1663
- throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
1834
+ if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
1835
+ throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
1664
1836
  }
1665
- let data;
1837
+ const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
1838
+ await secureWrite(path, { ...pending, expiresAt, openkey });
1839
+ this.#startCollectionPoll(stateRoot, pending.nonce);
1840
+ return openkey.link;
1841
+ }
1842
+ /**
1843
+ * Collect every approval result this tenant has open in OpenKey before a
1844
+ * call decides whether it is connected. The call waits at most
1845
+ * `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
1846
+ * finishes in the background, and a failure leaves the pending approval for
1847
+ * the next call or poll.
1848
+ */
1849
+ async #collectApprovals(tenant) {
1850
+ const budget = new AbortController();
1851
+ await Promise.race([
1852
+ this.#collectEach(tenant),
1853
+ (0, import_promises2.setTimeout)(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
1854
+ ]).finally(() => budget.abort());
1855
+ }
1856
+ async #collectEach(tenant) {
1857
+ const directory = this.#pendingDirectory(tenant.stateRoot);
1858
+ let names;
1666
1859
  try {
1667
- data = JSON.parse(text);
1860
+ names = await (0, import_promises.readdir)(directory);
1668
1861
  } catch (error) {
1669
- throw new ApprovalRequestError("body_invalid", "Callback body is invalid.", error);
1862
+ if (isRecord(error) && error.code === "ENOENT") return;
1863
+ throw error;
1864
+ }
1865
+ for (const name of names) {
1866
+ if (name.endsWith(".json.processing")) await this.#recoverProcessing((0, import_node_path4.join)(directory, name));
1867
+ }
1868
+ const nonces = (await (0, import_promises.readdir)(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
1869
+ for (const nonce of nonces) {
1870
+ await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
1871
+ }
1872
+ }
1873
+ /**
1874
+ * A claimed result whose processing never finished (the server stopped
1875
+ * mid-way). Once it is stored only the acknowledgement remains; otherwise,
1876
+ * after a grace period, it becomes collectable again.
1877
+ */
1878
+ async #recoverProcessing(claimed) {
1879
+ const pending = await readJson(claimed).catch(() => null);
1880
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
1881
+ await (0, import_promises.rm)(claimed, { force: true });
1882
+ return;
1670
1883
  }
1671
- if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
1672
- const pending = await this.#readPending(state, true);
1673
1884
  const stateRoot = (0, import_node_path4.join)(this.#config.stateDir, "tenants", pending.tenantId);
1885
+ if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
1886
+ if (pending.openkey.storedCid !== void 0) {
1887
+ await this.#acknowledge(stateRoot, pending.openkey);
1888
+ await (0, import_promises.rm)(claimed, { force: true });
1889
+ return;
1890
+ }
1891
+ const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
1892
+ if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
1893
+ const { claimedAt: _claimed, ...fresh } = pending;
1894
+ await secureWrite(claimed.slice(0, -".processing".length), fresh);
1895
+ await (0, import_promises.rm)(claimed, { force: true });
1896
+ }
1897
+ /** One collection attempt for one pending approval, single-flight per approval. */
1898
+ async #collectApproval(stateRoot, nonce, timeoutMs) {
1899
+ const path = this.#pendingPath(stateRoot, nonce);
1900
+ const running = this.#collections.get(path);
1901
+ if (running) return running;
1902
+ const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
1903
+ writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
1904
+ return "retry";
1905
+ }).finally(() => this.#collections.delete(path));
1906
+ this.#collections.set(path, collecting);
1907
+ return collecting;
1908
+ }
1909
+ async #collectStep(stateRoot, nonce, timeoutMs) {
1910
+ const path = this.#pendingPath(stateRoot, nonce);
1911
+ const pending = await readJson(path).catch(() => null);
1912
+ if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
1913
+ const openkey = pending.openkey;
1914
+ if (!this.#currentRequest(openkey)) {
1915
+ writeDiagnostic("approval dropped: reason=openkey_origin_changed");
1916
+ await (0, import_promises.rm)(path, { force: true });
1917
+ return "done";
1918
+ }
1919
+ if (Date.now() >= collectionDeadline(openkey)) {
1920
+ await (0, import_promises.rm)(path, { force: true });
1921
+ return "done";
1922
+ }
1923
+ const tenant = await this.#readTenant(pending.tenantId);
1924
+ if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1925
+ await (0, import_promises.rm)(path, { force: true });
1926
+ return "done";
1927
+ }
1928
+ let collected;
1929
+ try {
1930
+ collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
1931
+ } catch (error) {
1932
+ if (!(0, import_links2.isApprovalClientError)(error)) throw error;
1933
+ return this.#collectionRefused(path, pending, error);
1934
+ }
1935
+ if (collected.status === "pending") return "pending";
1936
+ if (collected.status === "discovered") {
1937
+ await secureWrite(path, {
1938
+ ...pending,
1939
+ openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
1940
+ });
1941
+ return this.#collectStep(stateRoot, nonce, timeoutMs);
1942
+ }
1943
+ const claimed = `${path}.processing`;
1944
+ try {
1945
+ await (0, import_promises.rename)(path, claimed);
1946
+ } catch (error) {
1947
+ if (isRecord(error) && error.code === "ENOENT") return "done";
1948
+ throw error;
1949
+ }
1950
+ await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
1674
1951
  const prior = this.#approvalProcessing.get(stateRoot);
1675
1952
  const processing = (async () => {
1676
1953
  if (prior) await prior.catch(() => void 0);
1677
- try {
1678
- const tenant = await this.#readTenant(pending.tenantId);
1679
- if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
1680
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1681
- }
1682
- if (pending.kind === "bootstrap") {
1683
- await this.#storeBootstrap(tenant, pending, data);
1684
- } else {
1685
- await this.#storeDelegation(tenant, pending, data);
1686
- }
1687
- await (0, import_promises.rm)(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
1688
- } catch (error) {
1689
- await this.#restorePending(pending).catch(() => void 0);
1690
- throw error;
1954
+ const current = await this.#readTenant(pending.tenantId);
1955
+ if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
1956
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
1691
1957
  }
1958
+ const { checked } = collected;
1959
+ 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);
1960
+ await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
1692
1961
  })();
1693
1962
  this.#approvalProcessing.set(stateRoot, processing);
1694
1963
  try {
1695
1964
  await processing;
1965
+ } catch (error) {
1966
+ if (error instanceof RenewalAdmissionUnavailableError) {
1967
+ await secureWrite(path, pending).catch(() => void 0);
1968
+ await (0, import_promises.rm)(claimed, { force: true });
1969
+ writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
1970
+ return "retry";
1971
+ }
1972
+ const { openkey: _spent, ...fresh } = pending;
1973
+ await secureWrite(path, fresh).catch(() => void 0);
1974
+ await (0, import_promises.rm)(claimed, { force: true });
1975
+ writeDiagnostic(approvalRefusalDiagnostic(error));
1976
+ return "done";
1696
1977
  } finally {
1697
1978
  if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
1698
1979
  }
1980
+ await this.#acknowledge(stateRoot, openkey);
1981
+ await (0, import_promises.rm)(claimed, { force: true });
1982
+ return "done";
1983
+ }
1984
+ async #collectionRefused(path, pending, error) {
1985
+ switch (error.code) {
1986
+ case "network":
1987
+ case "unavailable":
1988
+ return "retry";
1989
+ case "request_expired":
1990
+ if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
1991
+ await (0, import_promises.rm)(path, { force: true });
1992
+ return "done";
1993
+ case "acknowledged":
1994
+ await (0, import_promises.rm)(path, { force: true });
1995
+ return "done";
1996
+ default: {
1997
+ const { openkey: _spent, ...fresh } = pending;
1998
+ await secureWrite(path, fresh);
1999
+ writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
2000
+ return "done";
2001
+ }
2002
+ }
2003
+ }
2004
+ async #acknowledge(stateRoot, openkey) {
2005
+ try {
2006
+ const tenant = await this.#readTenant((0, import_node_path4.basename)(stateRoot));
2007
+ await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
2008
+ } catch (error) {
2009
+ writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
2010
+ }
2011
+ }
2012
+ /**
2013
+ * Poll one opened approval until it is collected or its request and result
2014
+ * window end: every 2 s for the first minute, then every 10 s. At most
2015
+ * `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
2016
+ * collects.
2017
+ */
2018
+ #startCollectionPoll(stateRoot, nonce) {
2019
+ const key = this.#pendingPath(stateRoot, nonce);
2020
+ if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
2021
+ const startedAt = Date.now();
2022
+ const schedule = () => {
2023
+ const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? import_links2.APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
2024
+ const timer = setTimeout(() => void tick(), delay);
2025
+ timer.unref();
2026
+ this.#polls.set(key, timer);
2027
+ };
2028
+ const tick = async () => {
2029
+ const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
2030
+ if (this.#closed || outcome === "done" || outcome === "idle") {
2031
+ this.#polls.delete(key);
2032
+ return;
2033
+ }
2034
+ schedule();
2035
+ };
2036
+ schedule();
2037
+ }
2038
+ /** Stop background collection. Pending approvals stay on disk for the next start. */
2039
+ async close() {
2040
+ this.#closed = true;
2041
+ for (const timer of this.#polls.values()) clearTimeout(timer);
2042
+ this.#polls.clear();
2043
+ await Promise.allSettled([...this.#collections.values()]);
1699
2044
  }
1700
- async #storeBootstrap(tenant, pending, data) {
1701
- const { node, session } = await this.#restoreApproval(tenant, data);
2045
+ /** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
2046
+ #currentRequest(openkey) {
2047
+ 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;
2048
+ }
2049
+ async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
2050
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
1702
2051
  this.#assertCurrentApproval(pending, session);
1703
2052
  if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
1704
2053
  throw new ApprovalOwnerMismatchError();
@@ -1706,6 +2055,7 @@ var RemoteTenantStore = class {
1706
2055
  if (!(0, import_node_sdk2.isCapabilitySubset)(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
1707
2056
  throw new Error("The approved delegation does not cover the requested account access.");
1708
2057
  }
2058
+ if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
1709
2059
  const profile = await readJson(this.#profilePath(tenant.stateRoot));
1710
2060
  await secureWrite(this.#profilePath(tenant.stateRoot), {
1711
2061
  ...profile,
@@ -1714,14 +2064,51 @@ var RemoteTenantStore = class {
1714
2064
  });
1715
2065
  await secureWrite(this.#sessionPath(tenant.stateRoot), {
1716
2066
  authMethod: "openkey",
1717
- ...session
2067
+ ...session,
2068
+ ...renewal === void 0 ? {} : { renewal }
1718
2069
  });
1719
2070
  this.#renewalRequired.delete(tenant.stateRoot);
1720
2071
  this.#activeSessions.delete(tenant.stateRoot);
2072
+ return session.delegationCid;
1721
2073
  }
1722
- async #storeDelegation(tenant, pending, data) {
2074
+ /**
2075
+ * Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
2076
+ * session is stored. Admission replays the exact signed lease, so a retry admits the same one.
2077
+ */
2078
+ async #admitRenewal(tenant, ownerDid, session, renewal) {
2079
+ let signed;
2080
+ try {
2081
+ signed = await (0, import_renewal_receipt.verifyOwnerRenewalLease)(session, ownerDid, renewal);
2082
+ } catch (error) {
2083
+ throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
2084
+ }
2085
+ if (Date.parse(signed.originalExpiresAt) - Date.now() < import_renewal_receipt.RENEWAL_ADMISSION_LEAD_MS) {
2086
+ throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
2087
+ }
2088
+ try {
2089
+ await (0, import_renewal.admitOwnerRenewalLease)({
2090
+ host: new URL(this.#config.nodeHost).origin,
2091
+ originalAuthorization: session.delegationHeader.Authorization,
2092
+ originalCid: session.delegationCid,
2093
+ ownerDid,
2094
+ agentDid: tenant.sessionDid.split("#")[0],
2095
+ spaceId: session.spaceId,
2096
+ nodeIdentity: renewal.receipt.nodeIdentity,
2097
+ leaseAuthorization: renewal.receipt.leaseAuthorization,
2098
+ leaseCid: renewal.receipt.leaseCid,
2099
+ leaseExpiresAt: signed.leaseSignedExpiresAt
2100
+ });
2101
+ } catch (error) {
2102
+ const code = isRecord(error) ? error.code : void 0;
2103
+ if (code === import_renewal.RENEWAL_RENEWER_CHANGED || code === import_renewal.RENEWAL_LEASE_ORIGINAL_EXPIRED) {
2104
+ throw new ApprovalStageError("renewal", code, void 0, error);
2105
+ }
2106
+ throw new RenewalAdmissionUnavailableError(error);
2107
+ }
2108
+ }
2109
+ async #storeDelegation(tenant, pending, data, resultOwner) {
1723
2110
  if (pending.requestId === void 0) throw new Error("Authority request is missing.");
1724
- const { node, session } = await this.#restoreApproval(tenant, data);
2111
+ const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
1725
2112
  this.#assertCurrentApproval(pending, session);
1726
2113
  if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
1727
2114
  let delegation;
@@ -1765,6 +2152,7 @@ var RemoteTenantStore = class {
1765
2152
  );
1766
2153
  }
1767
2154
  if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
2155
+ return session.delegationCid;
1768
2156
  }
1769
2157
  #assertCurrentApproval(pending, session) {
1770
2158
  const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
@@ -1773,13 +2161,14 @@ var RemoteTenantStore = class {
1773
2161
  }
1774
2162
  }
1775
2163
  /**
1776
- * Verify the OpenKey callback as a SIWE session for this tenant's key. The
1777
- * callback must carry the full signed proof (SIWE, signature, address and
1778
- * chain), so the WASM verifier always runs: it binds the authorization bytes
1779
- * and CID to the signed SIWE, and `node.did` is the wallet that signed
1780
- * exactly the delegation being stored.
2164
+ * Verify OpenKey's delegation as a SIWE session for this tenant's key. It
2165
+ * must carry the full signed proof (SIWE, signature, address and chain), so
2166
+ * the WASM verifier always runs: it binds the authorization bytes and CID to
2167
+ * the signed SIWE, and `node.did` is the wallet that signed exactly the
2168
+ * delegation being stored. That wallet must be the owner OpenKey's result
2169
+ * names.
1781
2170
  */
1782
- async #restoreApproval(tenant, data) {
2171
+ async #restoreApproval(tenant, data, resultOwner) {
1783
2172
  let session;
1784
2173
  try {
1785
2174
  session = sessionFromCallback(data, tenant.jwk);
@@ -1800,6 +2189,9 @@ var RemoteTenantStore = class {
1800
2189
  if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
1801
2190
  throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
1802
2191
  }
2192
+ if (!samePrincipal(node.did, resultOwner)) {
2193
+ throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
2194
+ }
1803
2195
  return { node, session };
1804
2196
  }
1805
2197
  async #ensureTenant(subject) {
@@ -1838,13 +2230,16 @@ var RemoteTenantStore = class {
1838
2230
  if (raw === null) return "invalid";
1839
2231
  const node = new import_node_sdk2.TinyCloudNode({ host: this.#config.nodeHost });
1840
2232
  try {
1841
- await node.restoreSession(raw);
1842
- } catch {
2233
+ await (0, import_profile2.restoreStoredSession)(node, raw, raw);
2234
+ } catch (error) {
1843
2235
  const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
1844
2236
  const signedExpiry = typeof header === "string" ? (0, import_node_sdk2.signedCompactUcanExpiry)(header) : void 0;
1845
2237
  const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
1846
2238
  const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
1847
- if (expiry !== void 0 && expiry.getTime() <= Date.now()) return "invalid";
2239
+ if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
2240
+ const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
2241
+ return (0, import_profile2.liveStoredLease)(raw) !== void 0 && !ended ? "unknown" : "invalid";
2242
+ }
1848
2243
  await this.#clearAuthority(tenant);
1849
2244
  return "invalid";
1850
2245
  }
@@ -1979,15 +2374,17 @@ var RemoteTenantStore = class {
1979
2374
  return writing;
1980
2375
  }
1981
2376
  async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
2377
+ const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
1982
2378
  const reusable = await reusablePending(
1983
2379
  this.#pendingDirectory(tenant.stateRoot),
1984
- { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
2380
+ { tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
2381
+ (openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
1985
2382
  );
1986
2383
  if (reusable !== void 0) return reusable;
1987
- const nonce = (0, import_node_crypto4.randomBytes)(24).toString("base64url");
2384
+ const nonce = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
1988
2385
  const created = Date.now();
1989
2386
  const pending = {
1990
- version: 1,
2387
+ version: PENDING_VERSION,
1991
2388
  nonce,
1992
2389
  tenantId,
1993
2390
  approvalEpoch: tenant.approvalEpoch,
@@ -2001,7 +2398,7 @@ var RemoteTenantStore = class {
2001
2398
  await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
2002
2399
  return pending;
2003
2400
  }
2004
- async #readPending(state, consume) {
2401
+ async #readPending(state) {
2005
2402
  const [tenantId, nonce, signature] = state.split(".");
2006
2403
  if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
2007
2404
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
@@ -2009,51 +2406,35 @@ var RemoteTenantStore = class {
2009
2406
  const expected = this.#signState(tenantId, nonce);
2010
2407
  const supplied = Buffer.from(signature, "base64url");
2011
2408
  const expectedBytes = Buffer.from(expected, "base64url");
2012
- if (supplied.length !== expectedBytes.length || !(0, import_node_crypto4.timingSafeEqual)(supplied, expectedBytes)) {
2409
+ if (supplied.length !== expectedBytes.length || !(0, import_node_crypto5.timingSafeEqual)(supplied, expectedBytes)) {
2013
2410
  throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
2014
2411
  }
2015
2412
  const stateRoot = (0, import_node_path4.join)(this.#config.stateDir, "tenants", tenantId);
2016
2413
  const path = this.#pendingPath(stateRoot, nonce);
2017
- const claimed = `${path}.processing`;
2018
- if (consume) {
2019
- try {
2020
- await (0, import_promises.rename)(path, claimed);
2021
- } catch (error) {
2022
- if (!isRecord(error) || error.code !== "ENOENT") throw error;
2023
- const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
2024
- (jwk) => jwk !== null,
2025
- () => true
2026
- );
2027
- if (!tenantExists) {
2028
- throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
2029
- }
2030
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
2031
- }
2414
+ const pending = await readJson(path);
2415
+ if (pending === null) {
2416
+ const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
2417
+ (jwk) => jwk !== null,
2418
+ () => true
2419
+ );
2420
+ if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
2421
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2032
2422
  }
2033
- try {
2034
- const pending = await readJson(consume ? claimed : path);
2035
- if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
2036
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2037
- }
2038
- const profile = await readJson(this.#profilePath(stateRoot));
2039
- const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
2040
- if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
2041
- throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2042
- }
2043
- if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2044
- await (0, import_promises.rm)(consume ? claimed : path, { force: true });
2045
- throw new ApprovalRequestError("state_expired", "Approval state has expired.");
2423
+ if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
2424
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2425
+ }
2426
+ const profile = await readJson(this.#profilePath(stateRoot));
2427
+ const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
2428
+ if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
2429
+ throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
2430
+ }
2431
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2432
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2433
+ await (0, import_promises.rm)(path, { force: true });
2046
2434
  }
2047
- return pending;
2048
- } catch (error) {
2049
- if (consume) await (0, import_promises.rename)(claimed, path).catch(() => void 0);
2050
- throw error;
2435
+ throw new ApprovalRequestError("state_expired", "Approval state has expired.");
2051
2436
  }
2052
- }
2053
- async #restorePending(pending) {
2054
- const stateRoot = (0, import_node_path4.join)(this.#config.stateDir, "tenants", pending.tenantId);
2055
- const path = this.#pendingPath(stateRoot, pending.nonce);
2056
- await (0, import_promises.rename)(`${path}.processing`, path);
2437
+ return { stateRoot, pending };
2057
2438
  }
2058
2439
  #connectUrl(pending) {
2059
2440
  const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
@@ -2178,10 +2559,10 @@ var RemoteTenantStore = class {
2178
2559
  return (0, import_node_path4.join)(stateRoot, ".tinycloud", "native-grant.json");
2179
2560
  }
2180
2561
  #tenantId(subject) {
2181
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
2562
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
2182
2563
  }
2183
2564
  #signState(tenantId, nonce) {
2184
- return (0, import_node_crypto4.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
2565
+ return (0, import_node_crypto5.createHmac)("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
2185
2566
  }
2186
2567
  #profilePath(stateRoot) {
2187
2568
  return (0, import_node_path4.join)(stateRoot, ".tinycloud", "profiles", PROFILE, "profile.json");
@@ -2254,6 +2635,37 @@ function sessionFromCallback(data, privateJwk) {
2254
2635
  signature: data.signature
2255
2636
  };
2256
2637
  }
2638
+ function approvalReason(pending) {
2639
+ return [
2640
+ pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : (0, import_tc_apps2.tcAppsApprovalReason)(pending.permissions) ?? "Approve the exact capabilities requested by the TinyCloud MCP operation.",
2641
+ // Owner DIDs come from the verified OpenKey access token of the MCP
2642
+ // client that created this link, never from the link itself. Collection
2643
+ // refuses a signer outside them, so the approver isn't asked to check.
2644
+ ...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
2645
+ ].join(" ");
2646
+ }
2647
+ function collectionDeadline(openkey) {
2648
+ return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
2649
+ }
2650
+ function collectionErrorCode(error) {
2651
+ if ((0, import_links2.isApprovalClientError)(error)) return error.code.toUpperCase();
2652
+ if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
2653
+ return "UNKNOWN";
2654
+ }
2655
+ function approvalRefusalDiagnostic(error) {
2656
+ if (error instanceof ApprovalOwnerMismatchError) {
2657
+ return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
2658
+ }
2659
+ const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2660
+ const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2661
+ const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk2.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2662
+ const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2663
+ return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
2664
+ }
2665
+ function writeDiagnostic(message) {
2666
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
2667
+ `);
2668
+ }
2257
2669
  function samePrincipal(left, right) {
2258
2670
  if (typeof left !== "string") return false;
2259
2671
  try {
@@ -2294,7 +2706,7 @@ async function secureDirectory(path) {
2294
2706
  async function secureWrite(path, value) {
2295
2707
  const directory = (0, import_node_path4.dirname)(path);
2296
2708
  await secureDirectory(directory);
2297
- const temporary = `${path}.${process.pid}.${(0, import_node_crypto4.randomBytes)(8).toString("hex")}.tmp`;
2709
+ const temporary = `${path}.${process.pid}.${(0, import_node_crypto5.randomBytes)(8).toString("hex")}.tmp`;
2298
2710
  await (0, import_promises.writeFile)(temporary, `${JSON.stringify(value, jsonReplacer, 2)}
2299
2711
  `, { mode: 384 });
2300
2712
  await (0, import_promises.rename)(temporary, path);
@@ -2328,7 +2740,7 @@ async function restoreOptionalText(path, contents) {
2328
2740
  await (0, import_promises.writeFile)(path, contents, { mode: 384 });
2329
2741
  await (0, import_promises.chmod)(path, 384);
2330
2742
  }
2331
- async function reusablePending(directory, expected) {
2743
+ async function reusablePending(directory, expected, currentRequest) {
2332
2744
  let names;
2333
2745
  try {
2334
2746
  names = await (0, import_promises.readdir)(directory);
@@ -2341,12 +2753,18 @@ async function reusablePending(directory, expected) {
2341
2753
  if (!name.endsWith(".json")) continue;
2342
2754
  const path = (0, import_node_path4.join)(directory, name);
2343
2755
  const pending = await readJson(path).catch(() => null);
2344
- if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
2756
+ if (pending === null) {
2345
2757
  await (0, import_promises.rm)(path, { force: true });
2346
2758
  continue;
2347
2759
  }
2760
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
2761
+ if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
2762
+ await (0, import_promises.rm)(path, { force: true });
2763
+ }
2764
+ continue;
2765
+ }
2348
2766
  active.push(pending);
2349
- if (samePendingRequest(pending, expected)) return pending;
2767
+ if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
2350
2768
  }
2351
2769
  if (active.length >= 64) {
2352
2770
  active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
@@ -2355,7 +2773,7 @@ async function reusablePending(directory, expected) {
2355
2773
  return void 0;
2356
2774
  }
2357
2775
  function samePendingRequest(pending, expected) {
2358
- 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);
2776
+ 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);
2359
2777
  }
2360
2778
 
2361
2779
  // src/http.ts
@@ -2388,7 +2806,6 @@ function createHostedMcpApp(config) {
2388
2806
  for (const owned of [
2389
2807
  restrictedUrl,
2390
2808
  connectUrl,
2391
- new URL("./connect/callback", restrictedUrl),
2392
2809
  new URL((0, import_server5.getOAuthProtectedResourceMetadataUrl)(restrictedUrl))
2393
2810
  ]) {
2394
2811
  restrictedByPath.set(owned.pathname, restricted);
@@ -2403,7 +2820,6 @@ function createHostedMcpApp(config) {
2403
2820
  }
2404
2821
  function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
2405
2822
  const connectPath = config.approvalPath ?? "/connect";
2406
- const callbackPath = `${connectPath}/callback`;
2407
2823
  const issuer = String(config.oauthMetadata.issuer);
2408
2824
  const jwksUri = String(config.oauthMetadata.jwks_uri);
2409
2825
  const verifier = createOpenKeyTokenVerifier({
@@ -2454,7 +2870,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
2454
2870
  return server;
2455
2871
  }, {
2456
2872
  legacy: "stateless",
2457
- onerror: () => writeDiagnostic("MCP request failed")
2873
+ onerror: () => writeDiagnostic2("MCP request failed")
2458
2874
  });
2459
2875
  const metadataOptions = {
2460
2876
  oauthMetadata: config.oauthMetadata,
@@ -2682,16 +3098,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2682
3098
  if (url.pathname === connectPath) {
2683
3099
  if (request.method !== "GET") return methodNotAllowed("GET");
2684
3100
  try {
2685
- const destination = await store.approvalRedirect(requiredState(url));
3101
+ const destination = await store.approvalLink(requiredState(url));
2686
3102
  return Response.redirect(destination, 302);
2687
3103
  } catch (error) {
2688
- const reason = error instanceof ApprovalRequestError ? error.detail : "unknown";
2689
- writeDiagnostic(`connect rejected: reason=${reason} path=${connectPath}`);
3104
+ const unavailable = error instanceof ApprovalLinkUnavailableError;
3105
+ const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
3106
+ writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
2690
3107
  if (request.headers.get("accept")?.includes("text/html")) {
2691
3108
  return new Response(
2692
- '<!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>',
3109
+ 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>',
2693
3110
  {
2694
- status: 400,
3111
+ status: unavailable ? 503 : 400,
2695
3112
  headers: {
2696
3113
  "content-type": "text/html; charset=utf-8",
2697
3114
  "cache-control": "no-store",
@@ -2703,37 +3120,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2703
3120
  }
2704
3121
  );
2705
3122
  }
2706
- return json({ error: "The approval link is invalid or expired." }, 400);
2707
- }
2708
- }
2709
- if (url.pathname === callbackPath) {
2710
- if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
2711
- if (request.method !== "POST") return methodNotAllowed("POST");
2712
- const originFailure = validateCallbackOrigin(request, config.openkeyHost);
2713
- if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
2714
- try {
2715
- await store.completeApproval(requiredState(url), request);
2716
- return callbackCors(json({ success: true }), config.openkeyHost);
2717
- } catch (error) {
2718
- if (error instanceof ApprovalOwnerMismatchError) {
2719
- return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
2720
- }
2721
- const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
2722
- const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
2723
- const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : import_node_sdk3.RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
2724
- const detail = error instanceof ApprovalRequestError ? error.detail : "none";
2725
- writeDiagnostic(
2726
- `connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
2727
- );
2728
- return callbackCors(
2729
- json({
2730
- error: stage,
2731
- code,
2732
- ...reason === void 0 ? {} : { reason },
2733
- message: "TinyCloud could not accept this delegation."
2734
- }, 400),
2735
- config.openkeyHost
2736
- );
3123
+ 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);
2737
3124
  }
2738
3125
  }
2739
3126
  if (url.pathname === "/native/grant" && surface === "hosted") {
@@ -2808,7 +3195,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
2808
3195
  const auth = await authenticate(request);
2809
3196
  return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
2810
3197
  },
2811
- close: () => handler.close()
3198
+ close: async () => {
3199
+ await store.close();
3200
+ await handler.close();
3201
+ }
2812
3202
  };
2813
3203
  }
2814
3204
  function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
@@ -2907,18 +3297,6 @@ function mcpCors(response, request) {
2907
3297
  }
2908
3298
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
2909
3299
  }
2910
- function validateCallbackOrigin(request, openkeyHost) {
2911
- const origin = request.headers.get("origin");
2912
- return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
2913
- }
2914
- function callbackCors(response, openkeyHost) {
2915
- const headers = new Headers(response.headers);
2916
- headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
2917
- headers.set("access-control-allow-methods", "POST, OPTIONS");
2918
- headers.set("access-control-allow-headers", "content-type");
2919
- headers.set("vary", "Origin");
2920
- return new Response(response.body, { status: response.status, headers });
2921
- }
2922
3300
  async function readBoundedBodyText(request, maxBytes) {
2923
3301
  const contentLength = request.headers.get("content-length");
2924
3302
  if (contentLength !== null) {
@@ -2993,7 +3371,7 @@ function publicText(text, contentType) {
2993
3371
  function methodNotAllowed(allow) {
2994
3372
  return new Response("Method not allowed", { status: 405, headers: { allow } });
2995
3373
  }
2996
- function writeDiagnostic(message) {
3374
+ function writeDiagnostic2(message) {
2997
3375
  process.stderr.write(`[tinycloud-mcp-http] ${message}
2998
3376
  `);
2999
3377
  }