@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/README.md +21 -4
- package/dist/cli.cjs +5 -4
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +5 -4
- package/dist/cli.js.map +1 -1
- package/dist/http-cli.cjs +553 -173
- package/dist/http-cli.cjs.map +1 -1
- package/dist/http-cli.js +561 -168
- package/dist/http-cli.js.map +1 -1
- package/dist/http.cjs +551 -173
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +9 -1
- package/dist/http.d.ts +9 -1
- package/dist/http.js +559 -168
- package/dist/http.js.map +1 -1
- package/dist/index.cjs +551 -173
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +559 -168
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +5 -4
- package/dist/server.cjs.map +1 -1
- package/dist/server.js +5 -4
- package/dist/server.js.map +1 -1
- package/package.json +5 -4
package/dist/http.js
CHANGED
|
@@ -9,7 +9,6 @@ import {
|
|
|
9
9
|
oauthMetadataResponse,
|
|
10
10
|
requireBearerAuth
|
|
11
11
|
} from "@modelcontextprotocol/server";
|
|
12
|
-
import { RUNTIME_DELEGATION_REJECTIONS } from "@tinycloud/node-sdk";
|
|
13
12
|
|
|
14
13
|
// src/agent-discovery.ts
|
|
15
14
|
import { createHash } from "crypto";
|
|
@@ -350,9 +349,12 @@ function logToolCall(tool, code, startedAt, replayedGrants) {
|
|
|
350
349
|
|
|
351
350
|
// src/remote-store.ts
|
|
352
351
|
import { sameTinyCloudNode } from "@tinycloud/sdk-core";
|
|
352
|
+
import { admitOwnerRenewalLease, RENEWAL_LEASE_ORIGINAL_EXPIRED, RENEWAL_RENEWER_CHANGED } from "@tinycloud/sdk-core/delegations/renewal";
|
|
353
|
+
import { RENEWAL_ADMISSION_LEAD_MS, verifyOwnerRenewalLease } from "@tinycloud/sdk-core/delegations/renewal-receipt";
|
|
353
354
|
import { createHmac, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
354
355
|
import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
|
|
355
|
-
import { dirname as dirname2, join as join2 } from "path";
|
|
356
|
+
import { basename, dirname as dirname2, join as join2 } from "path";
|
|
357
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
356
358
|
import {
|
|
357
359
|
activateValidatedRuntimeDelegation,
|
|
358
360
|
deserializeDelegation,
|
|
@@ -363,7 +365,7 @@ import {
|
|
|
363
365
|
UnsupportedSessionRestoreError,
|
|
364
366
|
isCapabilitySubset,
|
|
365
367
|
principalDidEquals,
|
|
366
|
-
|
|
368
|
+
RUNTIME_DELEGATION_REJECTIONS,
|
|
367
369
|
siweRuntimeDelegation,
|
|
368
370
|
signedCompactUcanExpiry
|
|
369
371
|
} from "@tinycloud/node-sdk";
|
|
@@ -371,8 +373,14 @@ import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk
|
|
|
371
373
|
import { createOrReusePermissionRequest } from "@tinycloud/operations/artifacts";
|
|
372
374
|
import { withTinyCloudStateRoot } from "@tinycloud/operations/state";
|
|
373
375
|
import { invokeOperation } from "@tinycloud/operations";
|
|
376
|
+
import { liveStoredLease, restoreStoredSession } from "@tinycloud/operations/profile";
|
|
374
377
|
import { nodeRevocationOf, operationRetryDescriptor } from "@tinycloud/operations/mcp-authority";
|
|
375
378
|
import { tcAppsApprovalMessage, tcAppsApprovalReason } from "@tinycloud/operations/tc-apps";
|
|
379
|
+
import {
|
|
380
|
+
APPROVAL_POLL_INTERVAL_MS,
|
|
381
|
+
DEFAULT_LINKS_API_ORIGIN,
|
|
382
|
+
isApprovalClientError
|
|
383
|
+
} from "@tinycloud/share-envelope/links";
|
|
376
384
|
|
|
377
385
|
// src/native-auth.ts
|
|
378
386
|
import { timingSafeEqual } from "crypto";
|
|
@@ -432,9 +440,142 @@ function hasCaveats(permission) {
|
|
|
432
440
|
return Object.hasOwn(permission, "caveats") && permission.caveats !== void 0;
|
|
433
441
|
}
|
|
434
442
|
|
|
443
|
+
// src/openkey-approval.ts
|
|
444
|
+
import { randomUUID } from "crypto";
|
|
445
|
+
import {
|
|
446
|
+
ackApprovalResult,
|
|
447
|
+
checkApprovalResultBinding,
|
|
448
|
+
createApprovalRequest,
|
|
449
|
+
discoverApprovalResult,
|
|
450
|
+
fetchApprovalResult,
|
|
451
|
+
generateRelayKey,
|
|
452
|
+
openRelayResult,
|
|
453
|
+
signerFromJwk
|
|
454
|
+
} from "@tinycloud/share-envelope/links";
|
|
455
|
+
import { boundedResponseBytes } from "@tinycloud/sdk-core/registry-publication";
|
|
456
|
+
var MIN_REQUEST_LIFE_MS = 18e4;
|
|
457
|
+
var MAX_RESULT_REPLY_BYTES = 256 * 1024;
|
|
458
|
+
var boundedFetch = Object.assign(async (input, init) => {
|
|
459
|
+
const response = await fetch(input, init);
|
|
460
|
+
const bytes = await boundedResponseBytes(response, MAX_RESULT_REPLY_BYTES);
|
|
461
|
+
return new Response(bytes === null || bytes.byteLength === 0 ? null : bytes, {
|
|
462
|
+
status: response.status,
|
|
463
|
+
statusText: response.statusText
|
|
464
|
+
});
|
|
465
|
+
}, globalThis.fetch);
|
|
466
|
+
async function createOpenKeyRequest(endpoints, input) {
|
|
467
|
+
const signingKey = ed25519PrivateJwk(input.jwk);
|
|
468
|
+
const signer = signerFromJwk(signingKey);
|
|
469
|
+
const relay = generateRelayKey();
|
|
470
|
+
const request = {
|
|
471
|
+
issuer: signer.did,
|
|
472
|
+
requestVersion: 1,
|
|
473
|
+
targetDid: signer.did,
|
|
474
|
+
targetPublicJwk: { kty: signingKey.kty, crv: signingKey.crv, x: signingKey.x },
|
|
475
|
+
nodeOrigin: new URL(input.nodeHost).origin,
|
|
476
|
+
permissions: input.permissions.map(requestPermission),
|
|
477
|
+
reason: input.reason,
|
|
478
|
+
grantLifetimeSeconds: input.grantLifetimeSeconds,
|
|
479
|
+
resultEncryptionPublicJwk: relay.publicJwk,
|
|
480
|
+
...input.leaseLifetimeSeconds === void 0 ? {} : { renewal: { version: 1, leaseLifetimeSeconds: input.leaseLifetimeSeconds } }
|
|
481
|
+
};
|
|
482
|
+
const expiresAt = new Date(Math.max(input.expiresAt.getTime(), Date.now() + MIN_REQUEST_LIFE_MS));
|
|
483
|
+
const created = await createApprovalRequest({
|
|
484
|
+
request,
|
|
485
|
+
issuerKey: signer,
|
|
486
|
+
apiOrigin: endpoints.linksApiOrigin,
|
|
487
|
+
openkeyOrigin: endpoints.openkeyOrigin,
|
|
488
|
+
expiresAt
|
|
489
|
+
});
|
|
490
|
+
return {
|
|
491
|
+
requestId: created.id,
|
|
492
|
+
bodyCid: created.bodyCid,
|
|
493
|
+
record: { header: created.record.header, signature: created.record.signature },
|
|
494
|
+
link: created.link,
|
|
495
|
+
request,
|
|
496
|
+
expiresAt: created.expiresAt,
|
|
497
|
+
relayPrivateKey: relay.privateKey,
|
|
498
|
+
ackId: randomUUID(),
|
|
499
|
+
apiOrigin: endpoints.openkeyApiOrigin
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
async function collectOpenKeyResult(state, jwk, timeoutMs) {
|
|
503
|
+
const requester = requesterState(state, jwk);
|
|
504
|
+
if (state.resultRef === void 0 || state.resultExpiresAt === void 0) {
|
|
505
|
+
const discovered = await discoverApprovalResult(requester, { timeoutMs, fetch: boundedFetch });
|
|
506
|
+
if (discovered.status === "pending") return discovered;
|
|
507
|
+
return { status: "discovered", resultRef: discovered.resultRef, resultExpiresAt: discovered.expiresAt };
|
|
508
|
+
}
|
|
509
|
+
const relay = await fetchApprovalResult(
|
|
510
|
+
requester,
|
|
511
|
+
{ resultRef: state.resultRef, expiresAt: state.resultExpiresAt },
|
|
512
|
+
{ timeoutMs, fetch: boundedFetch }
|
|
513
|
+
);
|
|
514
|
+
const opened = await openRelayResult(relay, state.requestId, state.relayPrivateKey);
|
|
515
|
+
return {
|
|
516
|
+
status: "ready",
|
|
517
|
+
checked: checkApprovalResultBinding(opened, {
|
|
518
|
+
requestId: state.requestId,
|
|
519
|
+
bodyCid: state.bodyCid,
|
|
520
|
+
request: state.request
|
|
521
|
+
})
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
async function ackOpenKeyResult(state, jwk, timeoutMs) {
|
|
525
|
+
if (state.resultRef === void 0) return;
|
|
526
|
+
await ackApprovalResult(requesterState(state, jwk), state.resultRef, state.ackId, { timeoutMs, fetch: boundedFetch });
|
|
527
|
+
}
|
|
528
|
+
function lifetimeSeconds(value) {
|
|
529
|
+
const match = /^(\d+)(s|m|h|d|w)$/.exec(value);
|
|
530
|
+
const unit = match === null ? void 0 : { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2]];
|
|
531
|
+
const seconds = match === null || unit === void 0 ? Number.NaN : Number(match[1]) * unit;
|
|
532
|
+
if (!Number.isSafeInteger(seconds) || seconds < 60) {
|
|
533
|
+
throw new Error("TC_MCP_DELEGATION_EXPIRY must be a duration of at least 60 seconds, such as 1h or 30d.");
|
|
534
|
+
}
|
|
535
|
+
return seconds;
|
|
536
|
+
}
|
|
537
|
+
function requesterState(state, jwk) {
|
|
538
|
+
return {
|
|
539
|
+
requestId: state.requestId,
|
|
540
|
+
bodyCid: state.bodyCid,
|
|
541
|
+
record: state.record,
|
|
542
|
+
apiOrigin: state.apiOrigin,
|
|
543
|
+
signingKey: ed25519PrivateJwk(jwk)
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function requestPermission(entry) {
|
|
547
|
+
if (entry.space === void 0 || entry.space.length === 0) {
|
|
548
|
+
throw new Error("An approval request needs a space for every permission.");
|
|
549
|
+
}
|
|
550
|
+
return {
|
|
551
|
+
service: entry.service,
|
|
552
|
+
space: entry.space,
|
|
553
|
+
path: entry.path,
|
|
554
|
+
actions: [...entry.actions],
|
|
555
|
+
...entry.caveats === void 0 ? {} : { caveats: [...entry.caveats] }
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function ed25519PrivateJwk(jwk) {
|
|
559
|
+
const { kty, crv, x, d } = jwk;
|
|
560
|
+
if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") {
|
|
561
|
+
throw new Error("The tenant key is not an Ed25519 private key.");
|
|
562
|
+
}
|
|
563
|
+
return { kty, crv, x, d };
|
|
564
|
+
}
|
|
565
|
+
|
|
435
566
|
// src/remote-store.ts
|
|
436
567
|
var PROFILE = "agent";
|
|
437
568
|
var MAX_CALLBACK_BYTES = 256 * 1024;
|
|
569
|
+
var PENDING_VERSION = 2;
|
|
570
|
+
var CALL_COLLECTION_TIMEOUT_MS = 3e3;
|
|
571
|
+
var CALL_COLLECTION_BUDGET_MS = 3e3;
|
|
572
|
+
var POLL_COLLECTION_TIMEOUT_MS = 1e4;
|
|
573
|
+
var FAST_POLL_WINDOW_MS = 6e4;
|
|
574
|
+
var SLOW_POLL_INTERVAL_MS = 1e4;
|
|
575
|
+
var MAX_COLLECTION_POLLS = 64;
|
|
576
|
+
var RESULT_COLLECTION_GRACE_MS = 6e5;
|
|
577
|
+
var PROCESSING_STALE_MS = 12e4;
|
|
578
|
+
var BOOTSTRAP_LEASE_SECONDS = 90 * 86400;
|
|
438
579
|
var NATIVE_GRANT_IMPORT_REJECTION_CODES = /* @__PURE__ */ new Set([
|
|
439
580
|
"DELEGATION_ARTIFACT_INVALID",
|
|
440
581
|
"DELEGATION_EXPIRED",
|
|
@@ -475,6 +616,12 @@ var ApprovalStageError = class extends Error {
|
|
|
475
616
|
this.reason = reason;
|
|
476
617
|
}
|
|
477
618
|
};
|
|
619
|
+
var RenewalAdmissionUnavailableError = class extends Error {
|
|
620
|
+
constructor(cause) {
|
|
621
|
+
super("The renewal lease could not be admitted yet.", { cause });
|
|
622
|
+
this.name = "RenewalAdmissionUnavailableError";
|
|
623
|
+
}
|
|
624
|
+
};
|
|
478
625
|
var ApprovalRequestError = class extends Error {
|
|
479
626
|
detail;
|
|
480
627
|
constructor(detail, message, cause) {
|
|
@@ -483,6 +630,12 @@ var ApprovalRequestError = class extends Error {
|
|
|
483
630
|
this.detail = detail;
|
|
484
631
|
}
|
|
485
632
|
};
|
|
633
|
+
var ApprovalLinkUnavailableError = class extends Error {
|
|
634
|
+
constructor(cause) {
|
|
635
|
+
super("The approval link could not be created.", { cause });
|
|
636
|
+
this.name = "ApprovalLinkUnavailableError";
|
|
637
|
+
}
|
|
638
|
+
};
|
|
486
639
|
var NativeGrantValidationError = class extends Error {
|
|
487
640
|
code;
|
|
488
641
|
constructor(status) {
|
|
@@ -504,10 +657,25 @@ var RemoteTenantStore = class {
|
|
|
504
657
|
#scopedClearing = /* @__PURE__ */ new Map();
|
|
505
658
|
#clearedScoped = /* @__PURE__ */ new Map();
|
|
506
659
|
#approvalProcessing = /* @__PURE__ */ new Map();
|
|
660
|
+
#linkCreations = /* @__PURE__ */ new Map();
|
|
661
|
+
#collections = /* @__PURE__ */ new Map();
|
|
662
|
+
#polls = /* @__PURE__ */ new Map();
|
|
663
|
+
#closed = false;
|
|
664
|
+
#endpoints;
|
|
665
|
+
#grantLifetimeSeconds;
|
|
507
666
|
#nativeIdentity;
|
|
508
667
|
#nativeGrantQueues = /* @__PURE__ */ new Map();
|
|
509
668
|
constructor(config) {
|
|
510
669
|
this.#config = config;
|
|
670
|
+
const openkeyOrigin = new URL(config.openkeyHost).origin;
|
|
671
|
+
this.#endpoints = {
|
|
672
|
+
openkeyOrigin,
|
|
673
|
+
openkeyApiOrigin: new URL(
|
|
674
|
+
config.openkeyApiHost ?? (openkeyOrigin === "https://openkey.so" ? "https://api.openkey.so" : openkeyOrigin)
|
|
675
|
+
).origin,
|
|
676
|
+
linksApiOrigin: new URL(config.linksApiOrigin ?? DEFAULT_LINKS_API_ORIGIN).origin
|
|
677
|
+
};
|
|
678
|
+
this.#grantLifetimeSeconds = lifetimeSeconds(config.delegationExpiry);
|
|
511
679
|
}
|
|
512
680
|
async nativeServiceIdentity() {
|
|
513
681
|
const identity = await this.#loadNativeServiceKey();
|
|
@@ -693,10 +861,13 @@ var RemoteTenantStore = class {
|
|
|
693
861
|
}
|
|
694
862
|
/** Check stored node authority before an authenticated operation uses it. */
|
|
695
863
|
async validateTenant(subject, ownerDids) {
|
|
696
|
-
|
|
864
|
+
const tenant = await this.#ensureTenant(subject);
|
|
865
|
+
await this.#collectApprovals(tenant);
|
|
866
|
+
await this.#hasValidSession(tenant, ownerDids);
|
|
697
867
|
}
|
|
698
868
|
async connectStatus(subject, ownerDids = []) {
|
|
699
869
|
const tenant = await this.#ensureTenant(subject);
|
|
870
|
+
await this.#collectApprovals(tenant);
|
|
700
871
|
const state = await this.#sessionState(tenant, ownerDids, true);
|
|
701
872
|
if (state === "valid") return { connected: true, sessionDid: tenant.sessionDid };
|
|
702
873
|
if (state === "unknown") return { connected: false, sessionDid: tenant.sessionDid };
|
|
@@ -856,77 +1027,267 @@ var RemoteTenantStore = class {
|
|
|
856
1027
|
await clearing;
|
|
857
1028
|
return "scoped";
|
|
858
1029
|
}
|
|
859
|
-
|
|
860
|
-
|
|
1030
|
+
/**
|
|
1031
|
+
* The OpenKey link behind one of this server's `/connect?state=` links. The
|
|
1032
|
+
* first visit creates the OpenKey approval request, signed by the tenant's
|
|
1033
|
+
* own key; later visits reuse it. Collection starts in the background and on
|
|
1034
|
+
* the tenant's next call.
|
|
1035
|
+
*/
|
|
1036
|
+
async approvalLink(state) {
|
|
1037
|
+
const located = await this.#readPending(state);
|
|
1038
|
+
const path = this.#pendingPath(located.stateRoot, located.pending.nonce);
|
|
1039
|
+
const prior = this.#linkCreations.get(path);
|
|
1040
|
+
if (prior) return prior;
|
|
1041
|
+
const creating = this.#createApprovalLink(located.stateRoot, located.pending).finally(() => this.#linkCreations.delete(path));
|
|
1042
|
+
this.#linkCreations.set(path, creating);
|
|
1043
|
+
return creating;
|
|
1044
|
+
}
|
|
1045
|
+
async #createApprovalLink(stateRoot, initial) {
|
|
1046
|
+
const path = this.#pendingPath(stateRoot, initial.nonce);
|
|
1047
|
+
const pending = await readJson(path);
|
|
1048
|
+
if (pending === null || pending.version !== PENDING_VERSION) {
|
|
1049
|
+
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
1050
|
+
}
|
|
1051
|
+
if (pending.openkey !== void 0 && this.#currentRequest(pending.openkey)) {
|
|
1052
|
+
if (Date.parse(pending.openkey.expiresAt) <= Date.now()) {
|
|
1053
|
+
throw new ApprovalRequestError("state_expired", "Approval state has expired.");
|
|
1054
|
+
}
|
|
1055
|
+
this.#startCollectionPoll(stateRoot, pending.nonce);
|
|
1056
|
+
return pending.openkey.link;
|
|
1057
|
+
}
|
|
1058
|
+
if (pending.openkey !== void 0) writeDiagnostic("approval dropped: reason=openkey_origin_changed");
|
|
861
1059
|
const tenant = await this.#readTenant(pending.tenantId);
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
host: this.#config.nodeHost,
|
|
868
|
-
requesterOrigin: this.#config.publicUrl.origin,
|
|
869
|
-
jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString("base64url"),
|
|
870
|
-
permissions: Buffer.from(JSON.stringify({
|
|
1060
|
+
let openkey;
|
|
1061
|
+
try {
|
|
1062
|
+
openkey = await createOpenKeyRequest(this.#endpoints, {
|
|
1063
|
+
jwk: tenant.jwk,
|
|
1064
|
+
nodeHost: this.#config.nodeHost,
|
|
871
1065
|
permissions: pending.permissions,
|
|
872
|
-
reason:
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
})).toString("base64url"),
|
|
880
|
-
expiry: this.#config.delegationExpiry
|
|
881
|
-
});
|
|
882
|
-
return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
|
|
883
|
-
}
|
|
884
|
-
async completeApproval(state, request) {
|
|
885
|
-
const length = Number(request.headers.get("content-length") ?? "0");
|
|
886
|
-
if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) {
|
|
887
|
-
throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
|
|
1066
|
+
reason: approvalReason(pending),
|
|
1067
|
+
grantLifetimeSeconds: this.#grantLifetimeSeconds,
|
|
1068
|
+
...pending.kind === "bootstrap" ? { leaseLifetimeSeconds: BOOTSTRAP_LEASE_SECONDS } : {},
|
|
1069
|
+
expiresAt: new Date(pending.expiresAt)
|
|
1070
|
+
});
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
throw new ApprovalLinkUnavailableError(error);
|
|
888
1073
|
}
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
throw new ApprovalRequestError("body_invalid", "Callback body is too large.");
|
|
1074
|
+
if (!samePrincipal(openkey.request.issuer, tenant.sessionDid)) {
|
|
1075
|
+
throw new ApprovalLinkUnavailableError(new Error("The approval request does not name this tenant's key."));
|
|
892
1076
|
}
|
|
893
|
-
|
|
1077
|
+
const expiresAt = new Date(Math.max(Date.parse(pending.expiresAt), Date.parse(openkey.expiresAt))).toISOString();
|
|
1078
|
+
await secureWrite(path, { ...pending, expiresAt, openkey });
|
|
1079
|
+
this.#startCollectionPoll(stateRoot, pending.nonce);
|
|
1080
|
+
return openkey.link;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Collect every approval result this tenant has open in OpenKey before a
|
|
1084
|
+
* call decides whether it is connected. The call waits at most
|
|
1085
|
+
* `CALL_COLLECTION_BUDGET_MS` in total; whatever is still running then
|
|
1086
|
+
* finishes in the background, and a failure leaves the pending approval for
|
|
1087
|
+
* the next call or poll.
|
|
1088
|
+
*/
|
|
1089
|
+
async #collectApprovals(tenant) {
|
|
1090
|
+
const budget = new AbortController();
|
|
1091
|
+
await Promise.race([
|
|
1092
|
+
this.#collectEach(tenant),
|
|
1093
|
+
sleep(CALL_COLLECTION_BUDGET_MS, void 0, { signal: budget.signal, ref: false }).catch(() => void 0)
|
|
1094
|
+
]).finally(() => budget.abort());
|
|
1095
|
+
}
|
|
1096
|
+
async #collectEach(tenant) {
|
|
1097
|
+
const directory = this.#pendingDirectory(tenant.stateRoot);
|
|
1098
|
+
let names;
|
|
894
1099
|
try {
|
|
895
|
-
|
|
1100
|
+
names = await readdir(directory);
|
|
896
1101
|
} catch (error) {
|
|
897
|
-
|
|
1102
|
+
if (isRecord(error) && error.code === "ENOENT") return;
|
|
1103
|
+
throw error;
|
|
1104
|
+
}
|
|
1105
|
+
for (const name of names) {
|
|
1106
|
+
if (name.endsWith(".json.processing")) await this.#recoverProcessing(join2(directory, name));
|
|
1107
|
+
}
|
|
1108
|
+
const nonces = (await readdir(directory).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -".json".length));
|
|
1109
|
+
for (const nonce of nonces) {
|
|
1110
|
+
await this.#collectApproval(tenant.stateRoot, nonce, CALL_COLLECTION_TIMEOUT_MS);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* A claimed result whose processing never finished (the server stopped
|
|
1115
|
+
* mid-way). Once it is stored only the acknowledgement remains; otherwise,
|
|
1116
|
+
* after a grace period, it becomes collectable again.
|
|
1117
|
+
*/
|
|
1118
|
+
async #recoverProcessing(claimed) {
|
|
1119
|
+
const pending = await readJson(claimed).catch(() => null);
|
|
1120
|
+
if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) {
|
|
1121
|
+
await rm(claimed, { force: true });
|
|
1122
|
+
return;
|
|
898
1123
|
}
|
|
899
|
-
if (!isRecord(data)) throw new ApprovalRequestError("body_invalid", "Callback body is invalid.");
|
|
900
|
-
const pending = await this.#readPending(state, true);
|
|
901
1124
|
const stateRoot = join2(this.#config.stateDir, "tenants", pending.tenantId);
|
|
1125
|
+
if (this.#collections.has(this.#pendingPath(stateRoot, pending.nonce))) return;
|
|
1126
|
+
if (pending.openkey.storedCid !== void 0) {
|
|
1127
|
+
await this.#acknowledge(stateRoot, pending.openkey);
|
|
1128
|
+
await rm(claimed, { force: true });
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
const claimedAt = pending.claimedAt === void 0 ? Number.NaN : Date.parse(pending.claimedAt);
|
|
1132
|
+
if (Date.now() - claimedAt < PROCESSING_STALE_MS) return;
|
|
1133
|
+
const { claimedAt: _claimed, ...fresh } = pending;
|
|
1134
|
+
await secureWrite(claimed.slice(0, -".processing".length), fresh);
|
|
1135
|
+
await rm(claimed, { force: true });
|
|
1136
|
+
}
|
|
1137
|
+
/** One collection attempt for one pending approval, single-flight per approval. */
|
|
1138
|
+
async #collectApproval(stateRoot, nonce, timeoutMs) {
|
|
1139
|
+
const path = this.#pendingPath(stateRoot, nonce);
|
|
1140
|
+
const running = this.#collections.get(path);
|
|
1141
|
+
if (running) return running;
|
|
1142
|
+
const collecting = this.#collectStep(stateRoot, nonce, timeoutMs).catch((error) => {
|
|
1143
|
+
writeDiagnostic(`approval collection failed: code=${collectionErrorCode(error)}`);
|
|
1144
|
+
return "retry";
|
|
1145
|
+
}).finally(() => this.#collections.delete(path));
|
|
1146
|
+
this.#collections.set(path, collecting);
|
|
1147
|
+
return collecting;
|
|
1148
|
+
}
|
|
1149
|
+
async #collectStep(stateRoot, nonce, timeoutMs) {
|
|
1150
|
+
const path = this.#pendingPath(stateRoot, nonce);
|
|
1151
|
+
const pending = await readJson(path).catch(() => null);
|
|
1152
|
+
if (pending === null || pending.version !== PENDING_VERSION || pending.openkey === void 0) return "idle";
|
|
1153
|
+
const openkey = pending.openkey;
|
|
1154
|
+
if (!this.#currentRequest(openkey)) {
|
|
1155
|
+
writeDiagnostic("approval dropped: reason=openkey_origin_changed");
|
|
1156
|
+
await rm(path, { force: true });
|
|
1157
|
+
return "done";
|
|
1158
|
+
}
|
|
1159
|
+
if (Date.now() >= collectionDeadline(openkey)) {
|
|
1160
|
+
await rm(path, { force: true });
|
|
1161
|
+
return "done";
|
|
1162
|
+
}
|
|
1163
|
+
const tenant = await this.#readTenant(pending.tenantId);
|
|
1164
|
+
if ((pending.approvalEpoch ?? 0) !== tenant.approvalEpoch) {
|
|
1165
|
+
await rm(path, { force: true });
|
|
1166
|
+
return "done";
|
|
1167
|
+
}
|
|
1168
|
+
let collected;
|
|
1169
|
+
try {
|
|
1170
|
+
collected = await collectOpenKeyResult(openkey, tenant.jwk, timeoutMs);
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
if (!isApprovalClientError(error)) throw error;
|
|
1173
|
+
return this.#collectionRefused(path, pending, error);
|
|
1174
|
+
}
|
|
1175
|
+
if (collected.status === "pending") return "pending";
|
|
1176
|
+
if (collected.status === "discovered") {
|
|
1177
|
+
await secureWrite(path, {
|
|
1178
|
+
...pending,
|
|
1179
|
+
openkey: { ...openkey, resultRef: collected.resultRef, resultExpiresAt: collected.resultExpiresAt }
|
|
1180
|
+
});
|
|
1181
|
+
return this.#collectStep(stateRoot, nonce, timeoutMs);
|
|
1182
|
+
}
|
|
1183
|
+
const claimed = `${path}.processing`;
|
|
1184
|
+
try {
|
|
1185
|
+
await rename(path, claimed);
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
if (isRecord(error) && error.code === "ENOENT") return "done";
|
|
1188
|
+
throw error;
|
|
1189
|
+
}
|
|
1190
|
+
await secureWrite(claimed, { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
902
1191
|
const prior = this.#approvalProcessing.get(stateRoot);
|
|
903
1192
|
const processing = (async () => {
|
|
904
1193
|
if (prior) await prior.catch(() => void 0);
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
909
|
-
}
|
|
910
|
-
if (pending.kind === "bootstrap") {
|
|
911
|
-
await this.#storeBootstrap(tenant, pending, data);
|
|
912
|
-
} else {
|
|
913
|
-
await this.#storeDelegation(tenant, pending, data);
|
|
914
|
-
}
|
|
915
|
-
await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
|
|
916
|
-
} catch (error) {
|
|
917
|
-
await this.#restorePending(pending).catch(() => void 0);
|
|
918
|
-
throw error;
|
|
1194
|
+
const current = await this.#readTenant(pending.tenantId);
|
|
1195
|
+
if ((pending.approvalEpoch ?? 0) !== current.approvalEpoch) {
|
|
1196
|
+
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
919
1197
|
}
|
|
1198
|
+
const { checked } = collected;
|
|
1199
|
+
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);
|
|
1200
|
+
await secureWrite(claimed, { ...pending, openkey: { ...openkey, storedCid } });
|
|
920
1201
|
})();
|
|
921
1202
|
this.#approvalProcessing.set(stateRoot, processing);
|
|
922
1203
|
try {
|
|
923
1204
|
await processing;
|
|
1205
|
+
} catch (error) {
|
|
1206
|
+
if (error instanceof RenewalAdmissionUnavailableError) {
|
|
1207
|
+
await secureWrite(path, pending).catch(() => void 0);
|
|
1208
|
+
await rm(claimed, { force: true });
|
|
1209
|
+
writeDiagnostic("approval renewal admission deferred: code=NODE_UNAVAILABLE");
|
|
1210
|
+
return "retry";
|
|
1211
|
+
}
|
|
1212
|
+
const { openkey: _spent, ...fresh } = pending;
|
|
1213
|
+
await secureWrite(path, fresh).catch(() => void 0);
|
|
1214
|
+
await rm(claimed, { force: true });
|
|
1215
|
+
writeDiagnostic(approvalRefusalDiagnostic(error));
|
|
1216
|
+
return "done";
|
|
924
1217
|
} finally {
|
|
925
1218
|
if (this.#approvalProcessing.get(stateRoot) === processing) this.#approvalProcessing.delete(stateRoot);
|
|
926
1219
|
}
|
|
1220
|
+
await this.#acknowledge(stateRoot, openkey);
|
|
1221
|
+
await rm(claimed, { force: true });
|
|
1222
|
+
return "done";
|
|
1223
|
+
}
|
|
1224
|
+
async #collectionRefused(path, pending, error) {
|
|
1225
|
+
switch (error.code) {
|
|
1226
|
+
case "network":
|
|
1227
|
+
case "unavailable":
|
|
1228
|
+
return "retry";
|
|
1229
|
+
case "request_expired":
|
|
1230
|
+
if (pending.openkey !== void 0 && Date.now() < Date.parse(pending.openkey.expiresAt)) return "retry";
|
|
1231
|
+
await rm(path, { force: true });
|
|
1232
|
+
return "done";
|
|
1233
|
+
case "acknowledged":
|
|
1234
|
+
await rm(path, { force: true });
|
|
1235
|
+
return "done";
|
|
1236
|
+
default: {
|
|
1237
|
+
const { openkey: _spent, ...fresh } = pending;
|
|
1238
|
+
await secureWrite(path, fresh);
|
|
1239
|
+
writeDiagnostic(`approval result rejected: stage=collect code=${error.code.toUpperCase()}`);
|
|
1240
|
+
return "done";
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
async #acknowledge(stateRoot, openkey) {
|
|
1245
|
+
try {
|
|
1246
|
+
const tenant = await this.#readTenant(basename(stateRoot));
|
|
1247
|
+
await ackOpenKeyResult(openkey, tenant.jwk, POLL_COLLECTION_TIMEOUT_MS);
|
|
1248
|
+
} catch (error) {
|
|
1249
|
+
writeDiagnostic(`approval acknowledgement failed: code=${collectionErrorCode(error)}`);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Poll one opened approval until it is collected or its request and result
|
|
1254
|
+
* window end: every 2 s for the first minute, then every 10 s. At most
|
|
1255
|
+
* `MAX_COLLECTION_POLLS` run at once; beyond that the tenant's next call
|
|
1256
|
+
* collects.
|
|
1257
|
+
*/
|
|
1258
|
+
#startCollectionPoll(stateRoot, nonce) {
|
|
1259
|
+
const key = this.#pendingPath(stateRoot, nonce);
|
|
1260
|
+
if (this.#closed || this.#polls.has(key) || this.#polls.size >= MAX_COLLECTION_POLLS) return;
|
|
1261
|
+
const startedAt = Date.now();
|
|
1262
|
+
const schedule = () => {
|
|
1263
|
+
const delay = Date.now() - startedAt < FAST_POLL_WINDOW_MS ? APPROVAL_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
|
|
1264
|
+
const timer = setTimeout(() => void tick(), delay);
|
|
1265
|
+
timer.unref();
|
|
1266
|
+
this.#polls.set(key, timer);
|
|
1267
|
+
};
|
|
1268
|
+
const tick = async () => {
|
|
1269
|
+
const outcome = await this.#collectApproval(stateRoot, nonce, POLL_COLLECTION_TIMEOUT_MS);
|
|
1270
|
+
if (this.#closed || outcome === "done" || outcome === "idle") {
|
|
1271
|
+
this.#polls.delete(key);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
schedule();
|
|
1275
|
+
};
|
|
1276
|
+
schedule();
|
|
1277
|
+
}
|
|
1278
|
+
/** Stop background collection. Pending approvals stay on disk for the next start. */
|
|
1279
|
+
async close() {
|
|
1280
|
+
this.#closed = true;
|
|
1281
|
+
for (const timer of this.#polls.values()) clearTimeout(timer);
|
|
1282
|
+
this.#polls.clear();
|
|
1283
|
+
await Promise.allSettled([...this.#collections.values()]);
|
|
927
1284
|
}
|
|
928
|
-
|
|
929
|
-
|
|
1285
|
+
/** Whether a stored request opens on, and is collected from, the OpenKey origins this server is configured with. */
|
|
1286
|
+
#currentRequest(openkey) {
|
|
1287
|
+
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;
|
|
1288
|
+
}
|
|
1289
|
+
async #storeBootstrap(tenant, pending, data, resultOwner, renewal) {
|
|
1290
|
+
const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
|
|
930
1291
|
this.#assertCurrentApproval(pending, session);
|
|
931
1292
|
if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
|
|
932
1293
|
throw new ApprovalOwnerMismatchError();
|
|
@@ -934,6 +1295,7 @@ var RemoteTenantStore = class {
|
|
|
934
1295
|
if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {
|
|
935
1296
|
throw new Error("The approved delegation does not cover the requested account access.");
|
|
936
1297
|
}
|
|
1298
|
+
if (renewal !== void 0) await this.#admitRenewal(tenant, node.did, session, renewal);
|
|
937
1299
|
const profile = await readJson(this.#profilePath(tenant.stateRoot));
|
|
938
1300
|
await secureWrite(this.#profilePath(tenant.stateRoot), {
|
|
939
1301
|
...profile,
|
|
@@ -942,14 +1304,51 @@ var RemoteTenantStore = class {
|
|
|
942
1304
|
});
|
|
943
1305
|
await secureWrite(this.#sessionPath(tenant.stateRoot), {
|
|
944
1306
|
authMethod: "openkey",
|
|
945
|
-
...session
|
|
1307
|
+
...session,
|
|
1308
|
+
...renewal === void 0 ? {} : { renewal }
|
|
946
1309
|
});
|
|
947
1310
|
this.#renewalRequired.delete(tenant.stateRoot);
|
|
948
1311
|
this.#activeSessions.delete(tenant.stateRoot);
|
|
1312
|
+
return session.delegationCid;
|
|
949
1313
|
}
|
|
950
|
-
|
|
1314
|
+
/**
|
|
1315
|
+
* Check the owner's renewal lease against the grant it renews, then admit it at the node, before the
|
|
1316
|
+
* session is stored. Admission replays the exact signed lease, so a retry admits the same one.
|
|
1317
|
+
*/
|
|
1318
|
+
async #admitRenewal(tenant, ownerDid, session, renewal) {
|
|
1319
|
+
let signed;
|
|
1320
|
+
try {
|
|
1321
|
+
signed = await verifyOwnerRenewalLease(session, ownerDid, renewal);
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
throw new ApprovalStageError("renewal", "RENEWAL_LEASE_MISMATCH", void 0, error);
|
|
1324
|
+
}
|
|
1325
|
+
if (Date.parse(signed.originalExpiresAt) - Date.now() < RENEWAL_ADMISSION_LEAD_MS) {
|
|
1326
|
+
throw new ApprovalStageError("renewal", "RENEWAL_GRANT_ENDS_TOO_SOON");
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
await admitOwnerRenewalLease({
|
|
1330
|
+
host: new URL(this.#config.nodeHost).origin,
|
|
1331
|
+
originalAuthorization: session.delegationHeader.Authorization,
|
|
1332
|
+
originalCid: session.delegationCid,
|
|
1333
|
+
ownerDid,
|
|
1334
|
+
agentDid: tenant.sessionDid.split("#")[0],
|
|
1335
|
+
spaceId: session.spaceId,
|
|
1336
|
+
nodeIdentity: renewal.receipt.nodeIdentity,
|
|
1337
|
+
leaseAuthorization: renewal.receipt.leaseAuthorization,
|
|
1338
|
+
leaseCid: renewal.receipt.leaseCid,
|
|
1339
|
+
leaseExpiresAt: signed.leaseSignedExpiresAt
|
|
1340
|
+
});
|
|
1341
|
+
} catch (error) {
|
|
1342
|
+
const code = isRecord(error) ? error.code : void 0;
|
|
1343
|
+
if (code === RENEWAL_RENEWER_CHANGED || code === RENEWAL_LEASE_ORIGINAL_EXPIRED) {
|
|
1344
|
+
throw new ApprovalStageError("renewal", code, void 0, error);
|
|
1345
|
+
}
|
|
1346
|
+
throw new RenewalAdmissionUnavailableError(error);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
async #storeDelegation(tenant, pending, data, resultOwner) {
|
|
951
1350
|
if (pending.requestId === void 0) throw new Error("Authority request is missing.");
|
|
952
|
-
const { node, session } = await this.#restoreApproval(tenant, data);
|
|
1351
|
+
const { node, session } = await this.#restoreApproval(tenant, data, resultOwner);
|
|
953
1352
|
this.#assertCurrentApproval(pending, session);
|
|
954
1353
|
if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();
|
|
955
1354
|
let delegation;
|
|
@@ -993,6 +1392,7 @@ var RemoteTenantStore = class {
|
|
|
993
1392
|
);
|
|
994
1393
|
}
|
|
995
1394
|
if (result.status !== "ok") throw new ApprovalStageError("auth_import", "AUTHORITY_REQUIRED");
|
|
1395
|
+
return session.delegationCid;
|
|
996
1396
|
}
|
|
997
1397
|
#assertCurrentApproval(pending, session) {
|
|
998
1398
|
const issuedAt = /^Issued At: ([^\r\n]+)\r?$/m.exec(session.siwe)?.[1];
|
|
@@ -1001,13 +1401,14 @@ var RemoteTenantStore = class {
|
|
|
1001
1401
|
}
|
|
1002
1402
|
}
|
|
1003
1403
|
/**
|
|
1004
|
-
* Verify
|
|
1005
|
-
*
|
|
1006
|
-
*
|
|
1007
|
-
*
|
|
1008
|
-
*
|
|
1404
|
+
* Verify OpenKey's delegation as a SIWE session for this tenant's key. It
|
|
1405
|
+
* must carry the full signed proof (SIWE, signature, address and chain), so
|
|
1406
|
+
* the WASM verifier always runs: it binds the authorization bytes and CID to
|
|
1407
|
+
* the signed SIWE, and `node.did` is the wallet that signed exactly the
|
|
1408
|
+
* delegation being stored. That wallet must be the owner OpenKey's result
|
|
1409
|
+
* names.
|
|
1009
1410
|
*/
|
|
1010
|
-
async #restoreApproval(tenant, data) {
|
|
1411
|
+
async #restoreApproval(tenant, data, resultOwner) {
|
|
1011
1412
|
let session;
|
|
1012
1413
|
try {
|
|
1013
1414
|
session = sessionFromCallback(data, tenant.jwk);
|
|
@@ -1028,6 +1429,9 @@ var RemoteTenantStore = class {
|
|
|
1028
1429
|
if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
|
|
1029
1430
|
throw new ApprovalStageError("restore_approval", "SESSION_MISMATCH");
|
|
1030
1431
|
}
|
|
1432
|
+
if (!samePrincipal(node.did, resultOwner)) {
|
|
1433
|
+
throw new ApprovalStageError("restore_approval", "RESULT_OWNER_MISMATCH");
|
|
1434
|
+
}
|
|
1031
1435
|
return { node, session };
|
|
1032
1436
|
}
|
|
1033
1437
|
async #ensureTenant(subject) {
|
|
@@ -1066,13 +1470,16 @@ var RemoteTenantStore = class {
|
|
|
1066
1470
|
if (raw === null) return "invalid";
|
|
1067
1471
|
const node = new TinyCloudNode({ host: this.#config.nodeHost });
|
|
1068
1472
|
try {
|
|
1069
|
-
await node
|
|
1070
|
-
} catch {
|
|
1473
|
+
await restoreStoredSession(node, raw, raw);
|
|
1474
|
+
} catch (error) {
|
|
1071
1475
|
const header = isRecord(raw.delegationHeader) ? raw.delegationHeader.Authorization : void 0;
|
|
1072
1476
|
const signedExpiry = typeof header === "string" ? signedCompactUcanExpiry(header) : void 0;
|
|
1073
1477
|
const siweExpiry = typeof raw.siwe === "string" ? /^Expiration Time: ([^\r\n]+)\r?$/m.exec(raw.siwe)?.[1] : void 0;
|
|
1074
1478
|
const expiry = signedExpiry ?? (siweExpiry === void 0 ? void 0 : new Date(siweExpiry));
|
|
1075
|
-
if (expiry !== void 0 && expiry.getTime() <= Date.now())
|
|
1479
|
+
if (expiry !== void 0 && expiry.getTime() <= Date.now()) {
|
|
1480
|
+
const ended = isRecord(error) && error.code === "AUTH_EXPIRED";
|
|
1481
|
+
return liveStoredLease(raw) !== void 0 && !ended ? "unknown" : "invalid";
|
|
1482
|
+
}
|
|
1076
1483
|
await this.#clearAuthority(tenant);
|
|
1077
1484
|
return "invalid";
|
|
1078
1485
|
}
|
|
@@ -1207,15 +1614,17 @@ var RemoteTenantStore = class {
|
|
|
1207
1614
|
return writing;
|
|
1208
1615
|
}
|
|
1209
1616
|
async #writePending(tenant, tenantId, kind, permissions, ownerDids, requestId) {
|
|
1617
|
+
const leaseAsk = kind === "bootstrap" ? BOOTSTRAP_LEASE_SECONDS : void 0;
|
|
1210
1618
|
const reusable = await reusablePending(
|
|
1211
1619
|
this.#pendingDirectory(tenant.stateRoot),
|
|
1212
|
-
{ tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids }
|
|
1620
|
+
{ tenantId, approvalEpoch: tenant.approvalEpoch, kind, requestId, permissions, ownerDids },
|
|
1621
|
+
(openkey) => this.#currentRequest(openkey) && openkey.request.renewal?.leaseLifetimeSeconds === leaseAsk
|
|
1213
1622
|
);
|
|
1214
1623
|
if (reusable !== void 0) return reusable;
|
|
1215
1624
|
const nonce = randomBytes(24).toString("base64url");
|
|
1216
1625
|
const created = Date.now();
|
|
1217
1626
|
const pending = {
|
|
1218
|
-
version:
|
|
1627
|
+
version: PENDING_VERSION,
|
|
1219
1628
|
nonce,
|
|
1220
1629
|
tenantId,
|
|
1221
1630
|
approvalEpoch: tenant.approvalEpoch,
|
|
@@ -1229,7 +1638,7 @@ var RemoteTenantStore = class {
|
|
|
1229
1638
|
await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
|
|
1230
1639
|
return pending;
|
|
1231
1640
|
}
|
|
1232
|
-
async #readPending(state
|
|
1641
|
+
async #readPending(state) {
|
|
1233
1642
|
const [tenantId, nonce, signature] = state.split(".");
|
|
1234
1643
|
if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
|
|
1235
1644
|
throw new ApprovalRequestError("state_invalid", "Approval state is invalid.");
|
|
@@ -1242,46 +1651,30 @@ var RemoteTenantStore = class {
|
|
|
1242
1651
|
}
|
|
1243
1652
|
const stateRoot = join2(this.#config.stateDir, "tenants", tenantId);
|
|
1244
1653
|
const path = this.#pendingPath(stateRoot, nonce);
|
|
1245
|
-
const
|
|
1246
|
-
if (
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
() => true
|
|
1254
|
-
);
|
|
1255
|
-
if (!tenantExists) {
|
|
1256
|
-
throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.", error);
|
|
1257
|
-
}
|
|
1258
|
-
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.", error);
|
|
1259
|
-
}
|
|
1654
|
+
const pending = await readJson(path);
|
|
1655
|
+
if (pending === null) {
|
|
1656
|
+
const tenantExists = await readJson(this.#keyPath(stateRoot)).then(
|
|
1657
|
+
(jwk) => jwk !== null,
|
|
1658
|
+
() => true
|
|
1659
|
+
);
|
|
1660
|
+
if (!tenantExists) throw new ApprovalRequestError("tenant_missing", "The TinyCloud delegate no longer exists.");
|
|
1661
|
+
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
1260
1662
|
}
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
await rm(consume ? claimed : path, { force: true });
|
|
1273
|
-
throw new ApprovalRequestError("state_expired", "Approval state has expired.");
|
|
1663
|
+
if (pending.version !== PENDING_VERSION || pending.tenantId !== tenantId || pending.nonce !== nonce) {
|
|
1664
|
+
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
1665
|
+
}
|
|
1666
|
+
const profile = await readJson(this.#profilePath(stateRoot));
|
|
1667
|
+
const approvalEpoch = this.#approvalEpochs.get(stateRoot) ?? (typeof profile?.approvalEpoch === "number" ? profile.approvalEpoch : 0);
|
|
1668
|
+
if ((pending.approvalEpoch ?? 0) !== approvalEpoch) {
|
|
1669
|
+
throw new ApprovalRequestError("state_not_pending", "Approval state is invalid or already used.");
|
|
1670
|
+
}
|
|
1671
|
+
if (new Date(pending.expiresAt).getTime() <= Date.now()) {
|
|
1672
|
+
if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
|
|
1673
|
+
await rm(path, { force: true });
|
|
1274
1674
|
}
|
|
1275
|
-
|
|
1276
|
-
} catch (error) {
|
|
1277
|
-
if (consume) await rename(claimed, path).catch(() => void 0);
|
|
1278
|
-
throw error;
|
|
1675
|
+
throw new ApprovalRequestError("state_expired", "Approval state has expired.");
|
|
1279
1676
|
}
|
|
1280
|
-
|
|
1281
|
-
async #restorePending(pending) {
|
|
1282
|
-
const stateRoot = join2(this.#config.stateDir, "tenants", pending.tenantId);
|
|
1283
|
-
const path = this.#pendingPath(stateRoot, pending.nonce);
|
|
1284
|
-
await rename(`${path}.processing`, path);
|
|
1677
|
+
return { stateRoot, pending };
|
|
1285
1678
|
}
|
|
1286
1679
|
#connectUrl(pending) {
|
|
1287
1680
|
const url = new URL(this.#config.approvalPath ?? "/connect", this.#config.publicUrl);
|
|
@@ -1482,6 +1875,37 @@ function sessionFromCallback(data, privateJwk) {
|
|
|
1482
1875
|
signature: data.signature
|
|
1483
1876
|
};
|
|
1484
1877
|
}
|
|
1878
|
+
function approvalReason(pending) {
|
|
1879
|
+
return [
|
|
1880
|
+
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.",
|
|
1881
|
+
// Owner DIDs come from the verified OpenKey access token of the MCP
|
|
1882
|
+
// client that created this link, never from the link itself. Collection
|
|
1883
|
+
// refuses a signer outside them, so the approver isn't asked to check.
|
|
1884
|
+
...pending.ownerDids.length === 0 ? [] : [`Requested by TinyCloud account ${pending.ownerDids.join(", ")}.`]
|
|
1885
|
+
].join(" ");
|
|
1886
|
+
}
|
|
1887
|
+
function collectionDeadline(openkey) {
|
|
1888
|
+
return Date.parse(openkey.expiresAt) + RESULT_COLLECTION_GRACE_MS;
|
|
1889
|
+
}
|
|
1890
|
+
function collectionErrorCode(error) {
|
|
1891
|
+
if (isApprovalClientError(error)) return error.code.toUpperCase();
|
|
1892
|
+
if (error instanceof ApprovalRequestError) return error.detail.toUpperCase();
|
|
1893
|
+
return "UNKNOWN";
|
|
1894
|
+
}
|
|
1895
|
+
function approvalRefusalDiagnostic(error) {
|
|
1896
|
+
if (error instanceof ApprovalOwnerMismatchError) {
|
|
1897
|
+
return "approval result rejected: stage=owner code=APPROVAL_OWNER_MISMATCH detail=none";
|
|
1898
|
+
}
|
|
1899
|
+
const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
|
|
1900
|
+
const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
|
|
1901
|
+
const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
|
|
1902
|
+
const detail = error instanceof ApprovalRequestError ? error.detail : "none";
|
|
1903
|
+
return `approval result rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`;
|
|
1904
|
+
}
|
|
1905
|
+
function writeDiagnostic(message) {
|
|
1906
|
+
process.stderr.write(`[tinycloud-mcp-http] ${message}
|
|
1907
|
+
`);
|
|
1908
|
+
}
|
|
1485
1909
|
function samePrincipal(left, right) {
|
|
1486
1910
|
if (typeof left !== "string") return false;
|
|
1487
1911
|
try {
|
|
@@ -1556,7 +1980,7 @@ async function restoreOptionalText(path, contents) {
|
|
|
1556
1980
|
await writeFile(path, contents, { mode: 384 });
|
|
1557
1981
|
await chmod(path, 384);
|
|
1558
1982
|
}
|
|
1559
|
-
async function reusablePending(directory, expected) {
|
|
1983
|
+
async function reusablePending(directory, expected, currentRequest) {
|
|
1560
1984
|
let names;
|
|
1561
1985
|
try {
|
|
1562
1986
|
names = await readdir(directory);
|
|
@@ -1569,12 +1993,18 @@ async function reusablePending(directory, expected) {
|
|
|
1569
1993
|
if (!name.endsWith(".json")) continue;
|
|
1570
1994
|
const path = join2(directory, name);
|
|
1571
1995
|
const pending = await readJson(path).catch(() => null);
|
|
1572
|
-
if (pending === null
|
|
1996
|
+
if (pending === null) {
|
|
1573
1997
|
await rm(path, { force: true });
|
|
1574
1998
|
continue;
|
|
1575
1999
|
}
|
|
2000
|
+
if (new Date(pending.expiresAt).getTime() <= Date.now()) {
|
|
2001
|
+
if (pending.openkey === void 0 || Date.now() >= collectionDeadline(pending.openkey)) {
|
|
2002
|
+
await rm(path, { force: true });
|
|
2003
|
+
}
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
1576
2006
|
active.push(pending);
|
|
1577
|
-
if (samePendingRequest(pending, expected)) return pending;
|
|
2007
|
+
if (samePendingRequest(pending, expected) && (pending.openkey === void 0 || currentRequest(pending.openkey))) return pending;
|
|
1578
2008
|
}
|
|
1579
2009
|
if (active.length >= 64) {
|
|
1580
2010
|
active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
|
|
@@ -1583,7 +2013,7 @@ async function reusablePending(directory, expected) {
|
|
|
1583
2013
|
return void 0;
|
|
1584
2014
|
}
|
|
1585
2015
|
function samePendingRequest(pending, expected) {
|
|
1586
|
-
return pending.version ===
|
|
2016
|
+
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);
|
|
1587
2017
|
}
|
|
1588
2018
|
|
|
1589
2019
|
// src/server.ts
|
|
@@ -2098,7 +2528,7 @@ function outcomeCode(result) {
|
|
|
2098
2528
|
// package.json
|
|
2099
2529
|
var package_default = {
|
|
2100
2530
|
name: "@tinycloud/mcp",
|
|
2101
|
-
version: "0.
|
|
2531
|
+
version: "0.12.0-beta.11",
|
|
2102
2532
|
description: "TinyCloud delegated operations MCP server",
|
|
2103
2533
|
keywords: [
|
|
2104
2534
|
"tinycloud",
|
|
@@ -2169,10 +2599,11 @@ var package_default = {
|
|
|
2169
2599
|
dependencies: {
|
|
2170
2600
|
"@modelcontextprotocol/node": "2.0.0-beta.5",
|
|
2171
2601
|
"@modelcontextprotocol/server": "2.0.0-beta.5",
|
|
2172
|
-
"@tinycloud/node-sdk": "3.14.0-beta.
|
|
2173
|
-
"@tinycloud/sdk-core": "3.14.0-beta.
|
|
2602
|
+
"@tinycloud/node-sdk": "3.14.0-beta.13",
|
|
2603
|
+
"@tinycloud/sdk-core": "3.14.0-beta.13",
|
|
2174
2604
|
"@tinycloud/node-sdk-wasm": "1.8.0-beta.0",
|
|
2175
|
-
"@tinycloud/operations": "0.9.2-beta.
|
|
2605
|
+
"@tinycloud/operations": "0.9.2-beta.11",
|
|
2606
|
+
"@tinycloud/share-envelope": "1.6.0",
|
|
2176
2607
|
jose: "6.2.4"
|
|
2177
2608
|
},
|
|
2178
2609
|
devDependencies: {
|
|
@@ -2224,7 +2655,6 @@ function createHostedMcpApp(config) {
|
|
|
2224
2655
|
for (const owned of [
|
|
2225
2656
|
restrictedUrl,
|
|
2226
2657
|
connectUrl,
|
|
2227
|
-
new URL("./connect/callback", restrictedUrl),
|
|
2228
2658
|
new URL(getOAuthProtectedResourceMetadataUrl(restrictedUrl))
|
|
2229
2659
|
]) {
|
|
2230
2660
|
restrictedByPath.set(owned.pathname, restricted);
|
|
@@ -2239,7 +2669,6 @@ function createHostedMcpApp(config) {
|
|
|
2239
2669
|
}
|
|
2240
2670
|
function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotationTitles = false) {
|
|
2241
2671
|
const connectPath = config.approvalPath ?? "/connect";
|
|
2242
|
-
const callbackPath = `${connectPath}/callback`;
|
|
2243
2672
|
const issuer = String(config.oauthMetadata.issuer);
|
|
2244
2673
|
const jwksUri = String(config.oauthMetadata.jwks_uri);
|
|
2245
2674
|
const verifier = createOpenKeyTokenVerifier({
|
|
@@ -2290,7 +2719,7 @@ function createHostedSurface(config, resourceUrl, surface, tokenStatus, annotati
|
|
|
2290
2719
|
return server;
|
|
2291
2720
|
}, {
|
|
2292
2721
|
legacy: "stateless",
|
|
2293
|
-
onerror: () =>
|
|
2722
|
+
onerror: () => writeDiagnostic2("MCP request failed")
|
|
2294
2723
|
});
|
|
2295
2724
|
const metadataOptions = {
|
|
2296
2725
|
oauthMetadata: config.oauthMetadata,
|
|
@@ -2518,16 +2947,17 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
|
|
|
2518
2947
|
if (url.pathname === connectPath) {
|
|
2519
2948
|
if (request.method !== "GET") return methodNotAllowed("GET");
|
|
2520
2949
|
try {
|
|
2521
|
-
const destination = await store.
|
|
2950
|
+
const destination = await store.approvalLink(requiredState(url));
|
|
2522
2951
|
return Response.redirect(destination, 302);
|
|
2523
2952
|
} catch (error) {
|
|
2524
|
-
const
|
|
2525
|
-
|
|
2953
|
+
const unavailable = error instanceof ApprovalLinkUnavailableError;
|
|
2954
|
+
const reason = error instanceof ApprovalRequestError ? error.detail : unavailable ? "openkey_unavailable" : "unknown";
|
|
2955
|
+
writeDiagnostic2(`connect rejected: reason=${reason} path=${connectPath}`);
|
|
2526
2956
|
if (request.headers.get("accept")?.includes("text/html")) {
|
|
2527
2957
|
return new Response(
|
|
2528
|
-
'<!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>',
|
|
2958
|
+
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>',
|
|
2529
2959
|
{
|
|
2530
|
-
status: 400,
|
|
2960
|
+
status: unavailable ? 503 : 400,
|
|
2531
2961
|
headers: {
|
|
2532
2962
|
"content-type": "text/html; charset=utf-8",
|
|
2533
2963
|
"cache-control": "no-store",
|
|
@@ -2539,37 +2969,7 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
|
|
|
2539
2969
|
}
|
|
2540
2970
|
);
|
|
2541
2971
|
}
|
|
2542
|
-
return json({ error: "The approval link is invalid or expired." }, 400);
|
|
2543
|
-
}
|
|
2544
|
-
}
|
|
2545
|
-
if (url.pathname === callbackPath) {
|
|
2546
|
-
if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
|
|
2547
|
-
if (request.method !== "POST") return methodNotAllowed("POST");
|
|
2548
|
-
const originFailure = validateCallbackOrigin(request, config.openkeyHost);
|
|
2549
|
-
if (originFailure !== void 0) return callbackCors(originFailure, config.openkeyHost);
|
|
2550
|
-
try {
|
|
2551
|
-
await store.completeApproval(requiredState(url), request);
|
|
2552
|
-
return callbackCors(json({ success: true }), config.openkeyHost);
|
|
2553
|
-
} catch (error) {
|
|
2554
|
-
if (error instanceof ApprovalOwnerMismatchError) {
|
|
2555
|
-
return callbackCors(json({ error: error.message, code: "approval_owner_mismatch" }, 403), config.openkeyHost);
|
|
2556
|
-
}
|
|
2557
|
-
const stage = error instanceof ApprovalStageError ? error.stage : "unknown";
|
|
2558
|
-
const code = error instanceof ApprovalStageError && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code) ? error.code : "UNKNOWN";
|
|
2559
|
-
const reason = !(error instanceof ApprovalStageError) || error.reason === void 0 ? void 0 : RUNTIME_DELEGATION_REJECTIONS.find((known) => known === error.reason) ?? "unknown";
|
|
2560
|
-
const detail = error instanceof ApprovalRequestError ? error.detail : "none";
|
|
2561
|
-
writeDiagnostic(
|
|
2562
|
-
`connect callback rejected: stage=${stage} code=${code}${reason === void 0 ? "" : ` reason=${reason}`} detail=${detail}`
|
|
2563
|
-
);
|
|
2564
|
-
return callbackCors(
|
|
2565
|
-
json({
|
|
2566
|
-
error: stage,
|
|
2567
|
-
code,
|
|
2568
|
-
...reason === void 0 ? {} : { reason },
|
|
2569
|
-
message: "TinyCloud could not accept this delegation."
|
|
2570
|
-
}, 400),
|
|
2571
|
-
config.openkeyHost
|
|
2572
|
-
);
|
|
2972
|
+
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);
|
|
2573
2973
|
}
|
|
2574
2974
|
}
|
|
2575
2975
|
if (url.pathname === "/native/grant" && surface === "hosted") {
|
|
@@ -2644,7 +3044,10 @@ Local alternative: install \`${LOCAL_CLI_PACKAGE}\` and \`${LOCAL_MCP_PACKAGE}\`
|
|
|
2644
3044
|
const auth = await authenticate(request);
|
|
2645
3045
|
return mcpCors(auth instanceof Response ? auth : await handler.fetch(request, { authInfo: auth }), request);
|
|
2646
3046
|
},
|
|
2647
|
-
close: () =>
|
|
3047
|
+
close: async () => {
|
|
3048
|
+
await store.close();
|
|
3049
|
+
await handler.close();
|
|
3050
|
+
}
|
|
2648
3051
|
};
|
|
2649
3052
|
}
|
|
2650
3053
|
function registerConnectTool(server, validator, store, identity, surface, annotationTitles) {
|
|
@@ -2743,18 +3146,6 @@ function mcpCors(response, request) {
|
|
|
2743
3146
|
}
|
|
2744
3147
|
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
2745
3148
|
}
|
|
2746
|
-
function validateCallbackOrigin(request, openkeyHost) {
|
|
2747
|
-
const origin = request.headers.get("origin");
|
|
2748
|
-
return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
|
|
2749
|
-
}
|
|
2750
|
-
function callbackCors(response, openkeyHost) {
|
|
2751
|
-
const headers = new Headers(response.headers);
|
|
2752
|
-
headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
|
|
2753
|
-
headers.set("access-control-allow-methods", "POST, OPTIONS");
|
|
2754
|
-
headers.set("access-control-allow-headers", "content-type");
|
|
2755
|
-
headers.set("vary", "Origin");
|
|
2756
|
-
return new Response(response.body, { status: response.status, headers });
|
|
2757
|
-
}
|
|
2758
3149
|
async function readBoundedBodyText(request, maxBytes) {
|
|
2759
3150
|
const contentLength = request.headers.get("content-length");
|
|
2760
3151
|
if (contentLength !== null) {
|
|
@@ -2829,7 +3220,7 @@ function publicText(text, contentType) {
|
|
|
2829
3220
|
function methodNotAllowed(allow) {
|
|
2830
3221
|
return new Response("Method not allowed", { status: 405, headers: { allow } });
|
|
2831
3222
|
}
|
|
2832
|
-
function
|
|
3223
|
+
function writeDiagnostic2(message) {
|
|
2833
3224
|
process.stderr.write(`[tinycloud-mcp-http] ${message}
|
|
2834
3225
|
`);
|
|
2835
3226
|
}
|