@mostra/runtime 0.10.0 → 0.11.0
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/bin.js +4058 -310
- package/dist/bin.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-FExcyENK.js → instance-DCiUHvgZ.js} +682 -47
- package/dist/instance-DCiUHvgZ.js.map +1 -0
- package/dist/reference/cli.md +1322 -0
- package/dist/reference/diagnostics.json +1552 -0
- package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
- package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
- package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
- package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
- package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
- package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
- package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
- package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
- package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
- package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
- package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
- package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
- package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
- package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
- package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
- package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
- package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
- package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
- package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
- package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
- package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
- package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
- package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
- package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
- package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
- package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
- package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
- package/dist/reference/self-hosting.md +130 -0
- package/dist/reference/telemetry.md +84 -0
- package/dist/skill/SKILL.md +122 -0
- package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
- package/dist/skill/assets/examples/dashboard/live.ts +25 -0
- package/dist/skill/assets/examples/dashboard/styles.css +125 -0
- package/dist/skill/assets/examples/decision/index.tsx +95 -0
- package/dist/skill/assets/examples/decision/styles.css +125 -0
- package/dist/skill/assets/examples/inbox/actions.ts +23 -0
- package/dist/skill/assets/examples/inbox/index.tsx +109 -0
- package/dist/skill/assets/examples/inbox/styles.css +125 -0
- package/dist/skill/assets/studio.css +125 -0
- package/dist/skill/references/answers.md +217 -0
- package/dist/skill/references/design.md +154 -0
- package/dist/skill/references/libraries.md +167 -0
- package/dist/skill/references/long-lived.md +148 -0
- package/dist/skill/references/mcp.md +68 -0
- package/dist/skill/references/page.md +131 -0
- package/dist/skill/references/server.md +146 -0
- package/dist/skill/references/sharing.md +123 -0
- package/dist/skill/references/verify.md +71 -0
- package/package.json +10 -5
- package/src/gateway/actions.ts +20 -0
- package/src/gateway/browser.ts +44 -0
- package/src/gateway/capabilities.ts +8 -0
- package/src/gateway/http.ts +12 -1
- package/src/gateway/index.ts +170 -5
- package/src/gateway/listener.ts +31 -6
- package/src/gateway/routes.ts +8 -0
- package/src/gc/index.ts +5 -0
- package/src/instance/index.ts +20 -1
- package/src/interaction/index.ts +60 -0
- package/src/interaction/pause.ts +106 -0
- package/src/interaction/submissions.ts +42 -1
- package/src/interaction/viewers.ts +34 -1
- package/src/ledger/index.ts +20 -1
- package/src/ledger/migrations.ts +51 -0
- package/src/link/author.ts +215 -0
- package/src/link/hosted.ts +37 -1
- package/src/link/http.ts +6 -1
- package/src/link/index.ts +3 -1
- package/src/link/manager.ts +138 -34
- package/src/protocol-server/client.ts +53 -0
- package/src/protocol-server/index.ts +1 -1
- package/src/server/api.ts +514 -72
- package/src/server/auth.ts +600 -74
- package/src/server/authorize.ts +816 -0
- package/src/server/clients.ts +235 -0
- package/src/server/config.ts +7 -0
- package/src/server/data.ts +59 -1
- package/src/server/directory.ts +69 -0
- package/src/server/feed.ts +191 -0
- package/src/server/handle.ts +172 -0
- package/src/server/hosted-pages.ts +532 -0
- package/src/server/hosted.ts +519 -18
- package/src/server/index.ts +343 -61
- package/src/server/mcp.ts +330 -0
- package/src/server/metering.ts +156 -0
- package/src/server/oauth-clients.ts +510 -0
- package/src/server/operator.ts +498 -0
- package/src/server/providers.ts +284 -0
- package/src/server/remove.ts +148 -0
- package/src/server/routing.ts +275 -0
- package/src/verify/runner.ts +23 -2
- package/dist/instance-FExcyENK.js.map +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { A as
|
|
3
|
-
import { s as realPath } from "./files-DGeWuE4I.js";
|
|
4
|
-
import { i as ownedDirectory } from "./directories-BLJjeSPD.js";
|
|
2
|
+
import { A as markRunning, B as handler, C as jsonResponse, D as createEphemeralBus, E as createInteraction, F as BINDING_SUBPROTOCOL, G as readFieldCoverage, H as openLedger, I as MAX_FRAME_BYTES, J as coverageMatcher, K as readServerFunctions, L as serveWebSocket, M as markWaiting, N as runState, O as appendRunOutput, P as appendEvent, R as attachInProcess, S as isRefusal, T as openRegistry, U as faultsFrom, V as holdLock, W as noFaults, Y as openFileLog, _ as resetOnClose, a as uninstallService, b as BASE_HEADERS$1, c as resolveHomePath, d as versionIdFor, f as createLive, g as shellAssetResponse, h as locateShell, i as serviceStatus, j as markUnknown, k as finishRun, l as canonicalRef, m as createGateway, n as startInstance, o as checkPlatform, p as liveMethods, q as readProcess, r as installService, s as platformName, t as runtimeVersion, u as listingDigest, v as Capabilities, w as readJsonObject, x as documentHeaders, y as capabilityKey, z as ProtocolServer } from "./instance-DCiUHvgZ.js";
|
|
3
|
+
import { c as removeTree, s as realPath } from "./files-DGeWuE4I.js";
|
|
4
|
+
import { d as runtimeRoot, i as ownedDirectory } from "./directories-BLJjeSPD.js";
|
|
5
5
|
import { createWriteStream, existsSync, linkSync, mkdirSync, readFileSync, renameSync, statfsSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { isAbsolute, join, parse, relative } from "node:path";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
-
import { ACTION_ARGS_MAX, AccountId, ArtifactManifest, Duration, HOSTED_OFFLINE_LIMIT_DEFAULT, HomeId, LineSplitter, LinkId, RouteId, RpcError, RpcPeer, TALLY_LIVE_PREFIX, artifactGetMethod, artifactListMethod, checkArgumentFrames, createDiagnostic, durationMs, encodeLine, hostedPushMethod, hostedSubmissionMethod, isFinalRunStatus, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteTokenMethod } from "@mostra/protocol";
|
|
9
|
-
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
|
+
import { ACTION_ARGS_MAX, AccountId, ArtifactManifest, Duration, HOSTED_OFFLINE_LIMIT_DEFAULT, HomeId, LineSplitter, LinkId, RouteId, RpcError, RpcPeer, TALLY_LIVE_PREFIX, artifactGetMethod, artifactListMethod, artifactPauseMethod, checkArgumentFrames, createDiagnostic, durationMs, encodeLine, hostedPushMethod, hostedSubmissionMethod, isFinalRunStatus, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteTokenMethod, viewDefaultMethod, viewUrlMethod } from "@mostra/protocol";
|
|
9
|
+
import { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
|
|
10
|
+
import { isIP, isIPv4, isIPv6 } from "node:net";
|
|
10
11
|
import { execFileSync } from "node:child_process";
|
|
11
|
-
import { copyFile, readFile, rm } from "node:fs/promises";
|
|
12
|
+
import { copyFile, readFile, rm, stat } from "node:fs/promises";
|
|
12
13
|
import * as z from "zod";
|
|
13
|
-
import { createServer } from "node:http";
|
|
14
|
+
import { createServer as createServer$1, request } from "node:http";
|
|
14
15
|
import { getRequestListener } from "@hono/node-server";
|
|
16
|
+
import { createAuthorizedEndpoint, fileDocs } from "@mostra/mcp";
|
|
15
17
|
import { WebSocketServer } from "ws";
|
|
18
|
+
import { request as request$1 } from "node:https";
|
|
19
|
+
import { lookup } from "node:dns/promises";
|
|
16
20
|
import { parseArgs } from "node:util";
|
|
21
|
+
import { AccountResolution, AuthenticatedCredential, ChatHostPolicy, LimitAnswer, LinkHost, LinkPolicy, OPERATOR_REVISION, OPERATOR_TIME_LIMITS, PushedAnswer, RoutingAnswer, SignInIdentity } from "@mostra/protocol/operator";
|
|
22
|
+
import * as oidc from "openid-client";
|
|
17
23
|
//#region src/platform/filesystems.ts
|
|
18
24
|
/**
|
|
19
25
|
* Whether a directory is on a network filesystem (D165 item 0b, DATA_MODEL §7.1): a remote
|
|
@@ -103,6 +109,10 @@ function networkFilesystem(dir) {
|
|
|
103
109
|
*/
|
|
104
110
|
/** How often an open binding's grant is checked again: a revocation closes it within 60 s. */
|
|
105
111
|
const GRANT_RECHECK_MS = 3e4;
|
|
112
|
+
/** How often the operator is asked again whether an account is suspended (`accounts.status`). */
|
|
113
|
+
const STATUS_RECHECK_MS = 3e4;
|
|
114
|
+
/** Dynamic Client Registrations an address may make a minute (D167). */
|
|
115
|
+
const REGISTRATIONS_PER_MINUTE = 10;
|
|
106
116
|
/** The largest version file accepted (per file; an operator's storage limit is WP-30's). */
|
|
107
117
|
const MAX_FILE_BYTES = 268435456;
|
|
108
118
|
const BASE_HEADERS = {
|
|
@@ -141,11 +151,11 @@ async function readBody(request, limit) {
|
|
|
141
151
|
}
|
|
142
152
|
return Buffer.concat(chunks);
|
|
143
153
|
}
|
|
144
|
-
function escapeHtml(text) {
|
|
154
|
+
function escapeHtml$1(text) {
|
|
145
155
|
return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
146
156
|
}
|
|
147
157
|
/** The development identity provider, when the configuration names one (§18.5, WP-29). */
|
|
148
|
-
function developmentProvider(config) {
|
|
158
|
+
function developmentProvider$1(config) {
|
|
149
159
|
const provider = config.identityProviders?.find((candidate) => candidate.kind === "development");
|
|
150
160
|
return provider ? {
|
|
151
161
|
id: provider.id,
|
|
@@ -158,20 +168,35 @@ function devicePage(options) {
|
|
|
158
168
|
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
|
|
159
169
|
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
160
170
|
input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
|
|
161
|
-
<body><h1>Link a machine to Mostra</h1>${options.done ? `<p>${escapeHtml(options.message ?? "Done.")}</p><p>You can close this page.</p>` : `${options.message ? `<p role="alert">${escapeHtml(options.message)}</p>` : ""}
|
|
171
|
+
<body><h1>Link a machine to Mostra</h1>${options.done ? `<p>${escapeHtml$1(options.message ?? "Done.")}</p><p>You can close this page.</p>` : `${options.message ? `<p role="alert">${escapeHtml$1(options.message)}</p>` : ""}
|
|
162
172
|
<p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host
|
|
163
173
|
pages under your account and receives their answers. Continue only if you started this sign-in
|
|
164
174
|
yourself, on that machine.</p>
|
|
165
175
|
${options.provider ? `<form method="post" action="/device">
|
|
166
|
-
<label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
|
|
167
|
-
<p>${escapeHtml(options.provider.label)}: this server signs people in with a development provider,
|
|
176
|
+
<label>Code <input name="user_code" value="${escapeHtml$1(options.code)}" autocomplete="off" required></label>
|
|
177
|
+
<p>${escapeHtml$1(options.provider.label)}: this server signs people in with a development provider,
|
|
168
178
|
which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
|
|
169
179
|
<label>Your name <input name="name" required maxlength="64"></label>
|
|
170
|
-
<input type="hidden" name="provider" value="${escapeHtml(options.provider.id)}">
|
|
180
|
+
<input type="hidden" name="provider" value="${escapeHtml$1(options.provider.id)}">
|
|
171
181
|
<p><button name="decision" value="approve">Approve this machine</button>
|
|
172
182
|
<button name="decision" value="deny">Refuse</button></p>
|
|
173
183
|
</form>` : "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"}`}</body></html>`;
|
|
174
184
|
}
|
|
185
|
+
/** The device page for a browser already signed in: approving links a machine (§18.5). */
|
|
186
|
+
function deviceApproval(options) {
|
|
187
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
|
|
188
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
|
|
189
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
190
|
+
input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
|
|
191
|
+
<body><h1>Link a machine to Mostra</h1>
|
|
192
|
+
<p><strong>Approving links a machine to your account, ${escapeHtml$1(options.name)}.</strong> That machine's
|
|
193
|
+
Mostra can then host pages under your account and receives their answers. Continue only if you started
|
|
194
|
+
this sign-in yourself, on that machine.</p>
|
|
195
|
+
<form method="post" action="/device"><input type="hidden" name="csrf" value="${escapeHtml$1(options.csrf)}">
|
|
196
|
+
<label>Code <input name="user_code" value="${escapeHtml$1(options.code)}" autocomplete="off" required></label>
|
|
197
|
+
<p><button name="session_decision" value="approve">Approve this machine</button>
|
|
198
|
+
<button name="session_decision" value="deny">Refuse</button></p></form></body></html>`;
|
|
199
|
+
}
|
|
175
200
|
/** Creates the API origin. */
|
|
176
201
|
function createApi(options) {
|
|
177
202
|
const { config, auth, log } = options;
|
|
@@ -183,46 +208,150 @@ function createApi(options) {
|
|
|
183
208
|
handleProtocols: (protocols) => protocols.has("mostra.host") ? BINDING_SUBPROTOCOL : false
|
|
184
209
|
});
|
|
185
210
|
const bindings = /* @__PURE__ */ new Set();
|
|
186
|
-
const
|
|
211
|
+
const bindingHomes = /* @__PURE__ */ new Map();
|
|
212
|
+
/**
|
|
213
|
+
* Whether the device page offers the development provider's form (D166 item 4): only while it is
|
|
214
|
+
* the one provider a sign-in may use now, none other configured and none the operator supplies.
|
|
215
|
+
* The page's GET and its POST judge by this one rule.
|
|
216
|
+
*/
|
|
217
|
+
const devFormOffered = async () => {
|
|
218
|
+
const development = developmentProvider$1(config);
|
|
219
|
+
if (development === void 0) return false;
|
|
220
|
+
const offered = await options.authorize.providers();
|
|
221
|
+
return offered.length === 1 && offered[0]?.id === development.id;
|
|
222
|
+
};
|
|
223
|
+
/**
|
|
224
|
+
* The operator's word on accounts (`accounts.status`, §18.6), asked at most every 30 s per
|
|
225
|
+
* account and written into the directory, so a suspension reaches every grant: its refreshes, its
|
|
226
|
+
* bindings, its MCP calls (Fable review of WP-30, 6). An operator that doesn't answer leaves the
|
|
227
|
+
* last word standing.
|
|
228
|
+
*/
|
|
229
|
+
const statusAsked = /* @__PURE__ */ new Map();
|
|
230
|
+
const accountStanding = async (accountId) => {
|
|
231
|
+
if (options.operator?.has.status === true) {
|
|
232
|
+
const last = statusAsked.get(accountId);
|
|
233
|
+
const every = Math.min(STATUS_RECHECK_MS, options.recheckMs ?? STATUS_RECHECK_MS);
|
|
234
|
+
if (last === void 0 || Date.now() - last >= every) {
|
|
235
|
+
statusAsked.set(accountId, Date.now());
|
|
236
|
+
if (statusAsked.size > 1e4) statusAsked.delete(statusAsked.keys().next().value);
|
|
237
|
+
const said = await options.operator.status(accountId);
|
|
238
|
+
if (said !== void 0) auth.setAccountStatus(accountId, said);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return auth.accountStatus(accountId);
|
|
242
|
+
};
|
|
243
|
+
/**
|
|
244
|
+
* Whether an authenticated caller may act now: its home not suspended by the operator, its
|
|
245
|
+
* account not suspended (D165 item 9). One place for `/host`, `/files`, `/mcp` and `/link`
|
|
246
|
+
* (Fable review of WP-30, 1).
|
|
247
|
+
*/
|
|
248
|
+
const standing = async (who) => {
|
|
249
|
+
if (options.suspended?.(who.homeId) || await accountStanding(who.accountId) === "suspended") return createDiagnostic("MOSTRA_REMOTE_HOME_SUSPENDED", { message: "This account's pages are suspended by the server's operator." });
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* The account a bearer token names for one resource (`host`, `files` or `mcp`): a token this
|
|
253
|
+
* server issued for exactly that audience (RFC 8707; a token for `/mcp` opens no binding), or a
|
|
254
|
+
* credential the operator issued (`accounts.authenticate`, §18.6); or why it may not act now.
|
|
255
|
+
*/
|
|
256
|
+
const bearer = async (request, resource) => {
|
|
187
257
|
const header = request.headers.authorization ?? "";
|
|
188
258
|
const match = /^bearer\s+(\S+)$/i.exec(header);
|
|
189
|
-
|
|
259
|
+
if (!match) return void 0;
|
|
260
|
+
const token = match[1];
|
|
261
|
+
const audience = `${apiOrigin}/${resource === "files" ? "host" : resource}`;
|
|
262
|
+
const issued = auth.authenticate(token);
|
|
263
|
+
let who;
|
|
264
|
+
if (issued) {
|
|
265
|
+
if (issued.resource !== audience) return void 0;
|
|
266
|
+
who = issued;
|
|
267
|
+
} else {
|
|
268
|
+
if (!options.operator?.has.authenticate) return void 0;
|
|
269
|
+
const credential = await options.operator.authenticate(token, resource);
|
|
270
|
+
if (!credential?.scope.includes("mostra")) return void 0;
|
|
271
|
+
who = auth.credentialSession({
|
|
272
|
+
account: credential.account,
|
|
273
|
+
subject: credential.subject ?? "default",
|
|
274
|
+
resource: audience,
|
|
275
|
+
link: resource === "host"
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
const refused = await standing(who);
|
|
279
|
+
return refused ? { refused } : who;
|
|
190
280
|
};
|
|
191
281
|
const unauthorized = (response, message) => send(response, 401, {
|
|
192
282
|
code: "MOSTRA_REMOTE_LOGIN_FAILED",
|
|
193
283
|
message
|
|
194
284
|
}, { "www-authenticate": `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"` });
|
|
285
|
+
/**
|
|
286
|
+
* RFC 8414 metadata (INTERFACES §18.5): Client ID Metadata Documents with `none` among the token
|
|
287
|
+
* endpoint's methods, which Claude needs before it uses one, Dynamic Client Registration as the
|
|
288
|
+
* fallback, PKCE S256, `iss` in responses, and `offline_access` for rotating refresh tokens.
|
|
289
|
+
*/
|
|
195
290
|
const metadata = () => ({
|
|
196
291
|
issuer: apiOrigin,
|
|
292
|
+
authorization_endpoint: `${apiOrigin}/oauth/authorize`,
|
|
197
293
|
token_endpoint: `${apiOrigin}/oauth/token`,
|
|
294
|
+
registration_endpoint: `${apiOrigin}/oauth/register`,
|
|
198
295
|
device_authorization_endpoint: `${apiOrigin}/oauth/device`,
|
|
199
296
|
revocation_endpoint: `${apiOrigin}/oauth/revoke`,
|
|
200
|
-
|
|
297
|
+
response_types_supported: ["code"],
|
|
298
|
+
response_modes_supported: ["query"],
|
|
299
|
+
grant_types_supported: [
|
|
300
|
+
"authorization_code",
|
|
301
|
+
"refresh_token",
|
|
302
|
+
"urn:ietf:params:oauth:grant-type:device_code"
|
|
303
|
+
],
|
|
201
304
|
token_endpoint_auth_methods_supported: ["none"],
|
|
305
|
+
revocation_endpoint_auth_methods_supported: ["none"],
|
|
202
306
|
code_challenge_methods_supported: ["S256"],
|
|
203
307
|
scopes_supported: ["mostra", "offline_access"],
|
|
308
|
+
client_id_metadata_document_supported: true,
|
|
204
309
|
authorization_response_iss_parameter_supported: true
|
|
205
310
|
});
|
|
311
|
+
const sessionDevicePage = (code, signed) => deviceApproval({
|
|
312
|
+
code,
|
|
313
|
+
name: auth.accountName(signed.accountId).name ?? "your account",
|
|
314
|
+
csrf: options.authorize.csrf(signed.hash, "device")
|
|
315
|
+
});
|
|
206
316
|
const form = async (request) => {
|
|
207
317
|
if (!(request.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) return void 0;
|
|
208
318
|
const body = await readBody(request, 65536);
|
|
209
319
|
return body === void 0 ? void 0 : new URLSearchParams(body.toString("utf8"));
|
|
210
320
|
};
|
|
211
321
|
const upload = async (request, response, sha) => {
|
|
212
|
-
const who = bearer(request);
|
|
322
|
+
const who = await bearer(request, "files");
|
|
213
323
|
if (!who) {
|
|
214
324
|
unauthorized(response, "Version files need the binding's access token.");
|
|
215
325
|
return;
|
|
216
326
|
}
|
|
327
|
+
if ("refused" in who) {
|
|
328
|
+
send(response, 403, who.refused);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
217
331
|
const home = await options.home(who.homeId);
|
|
218
332
|
options.touch(who.homeId);
|
|
219
|
-
|
|
333
|
+
const declared = home.wanted(sha);
|
|
334
|
+
if (declared === void 0) {
|
|
220
335
|
send(response, 409, {
|
|
221
336
|
code: "MOSTRA_HOME_INTEGRITY",
|
|
222
337
|
message: "No pending push of this home names that file as missing."
|
|
223
338
|
});
|
|
224
339
|
return;
|
|
225
340
|
}
|
|
341
|
+
/** Refuses the upload and closes its connection once the answer is out: the rest isn't read. */
|
|
342
|
+
const refuseUpload = (status, message) => {
|
|
343
|
+
response.once("finish", () => request.destroy());
|
|
344
|
+
send(response, status, {
|
|
345
|
+
code: "MOSTRA_HOME_INTEGRITY",
|
|
346
|
+
message
|
|
347
|
+
}, { connection: "close" });
|
|
348
|
+
};
|
|
349
|
+
const sizeMessage = "The file's bytes aren't the size its push gave them.";
|
|
350
|
+
const announced = request.headers["content-length"];
|
|
351
|
+
if (announced !== void 0 && Number(announced) !== declared) {
|
|
352
|
+
refuseUpload(declared > MAX_FILE_BYTES ? 413 : 400, sizeMessage);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
226
355
|
const target = join(options.filesDir, sha);
|
|
227
356
|
const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString("hex")}`);
|
|
228
357
|
const hash = createHash("sha256");
|
|
@@ -230,33 +359,35 @@ function createApi(options) {
|
|
|
230
359
|
let tooLarge = false;
|
|
231
360
|
await new Promise((resolve, reject) => {
|
|
232
361
|
const out = createWriteStream(scratch, { mode: 384 });
|
|
233
|
-
|
|
362
|
+
const onData = (chunk) => {
|
|
234
363
|
size += chunk.length;
|
|
235
|
-
if (size > MAX_FILE_BYTES) {
|
|
364
|
+
if (size > MAX_FILE_BYTES || size > declared) {
|
|
236
365
|
tooLarge = true;
|
|
237
|
-
request.
|
|
366
|
+
request.off("data", onData);
|
|
367
|
+
request.pause();
|
|
368
|
+
out.end(() => resolve());
|
|
238
369
|
return;
|
|
239
370
|
}
|
|
240
371
|
hash.update(chunk);
|
|
241
372
|
out.write(chunk);
|
|
373
|
+
};
|
|
374
|
+
request.on("data", onData);
|
|
375
|
+
request.on("end", () => {
|
|
376
|
+
if (!tooLarge) out.end(() => resolve());
|
|
242
377
|
});
|
|
243
|
-
request.on("end", () => out.end(() => resolve()));
|
|
244
378
|
request.on("error", reject);
|
|
245
|
-
request.on("close", () =>
|
|
246
|
-
if (tooLarge) out.end(() => resolve());
|
|
247
|
-
});
|
|
379
|
+
request.on("close", () => out.end(() => resolve()));
|
|
248
380
|
}).catch(() => void 0);
|
|
249
|
-
|
|
381
|
+
const shortOrLong = !tooLarge && size !== declared;
|
|
382
|
+
if (tooLarge || shortOrLong || hash.digest("hex") !== sha) {
|
|
250
383
|
await rm(scratch, { force: true });
|
|
251
|
-
|
|
252
|
-
code: "MOSTRA_HOME_INTEGRITY",
|
|
253
|
-
message: tooLarge ? "The file is too large." : "The bytes don't hash to the file's name."
|
|
254
|
-
});
|
|
384
|
+
refuseUpload(tooLarge && size > MAX_FILE_BYTES ? 413 : 400, tooLarge || shortOrLong ? sizeMessage : "The bytes don't hash to the file's name.");
|
|
255
385
|
return;
|
|
256
386
|
}
|
|
257
387
|
if (existsSync(target)) await rm(scratch, { force: true });
|
|
258
388
|
else renameSync(scratch, target);
|
|
259
389
|
home.uploaded(sha);
|
|
390
|
+
options.stored?.(who.homeId, size);
|
|
260
391
|
send(response, 201, {
|
|
261
392
|
sha256: sha,
|
|
262
393
|
size
|
|
@@ -269,6 +400,83 @@ function createApi(options) {
|
|
|
269
400
|
send(response, 200, metadata());
|
|
270
401
|
return;
|
|
271
402
|
}
|
|
403
|
+
if (await options.authorize.handle(request, response, path)) return;
|
|
404
|
+
if (method === "GET" && path === "/.well-known/oauth-protected-resource/mcp") {
|
|
405
|
+
send(response, 200, {
|
|
406
|
+
resource: `${apiOrigin}/mcp`,
|
|
407
|
+
authorization_servers: [apiOrigin],
|
|
408
|
+
scopes_supported: ["mostra"],
|
|
409
|
+
bearer_methods_supported: ["header"],
|
|
410
|
+
resource_name: "Mostra"
|
|
411
|
+
});
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (method === "POST" && path === "/link") {
|
|
415
|
+
const who = await bearer(request, "host");
|
|
416
|
+
if (who && "refused" in who) {
|
|
417
|
+
send(response, 403, who.refused);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
if (!who || who.linkId === void 0) {
|
|
421
|
+
unauthorized(response, "This credential links no instance on this server.");
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const body = await form(request);
|
|
425
|
+
const linked = auth.linkState(who.linkId, body?.get("default") === "1");
|
|
426
|
+
send(response, 200, {
|
|
427
|
+
account: {
|
|
428
|
+
id: who.accountId,
|
|
429
|
+
...who.accountName !== void 0 ? { name: who.accountName } : {}
|
|
430
|
+
},
|
|
431
|
+
instanceId: who.linkId,
|
|
432
|
+
default: linked.default
|
|
433
|
+
});
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
if (method === "POST" && path === "/oauth/register") {
|
|
437
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/json")) {
|
|
438
|
+
send(response, 400, {
|
|
439
|
+
error: "invalid_client_metadata",
|
|
440
|
+
error_description: "Send JSON."
|
|
441
|
+
});
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const body = await readBody(request, 65536);
|
|
445
|
+
let metadata;
|
|
446
|
+
try {
|
|
447
|
+
metadata = JSON.parse(body?.toString("utf8") ?? "");
|
|
448
|
+
} catch {
|
|
449
|
+
send(response, 400, {
|
|
450
|
+
error: "invalid_client_metadata",
|
|
451
|
+
error_description: "Send JSON."
|
|
452
|
+
});
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
if (options.registrations) {
|
|
456
|
+
const { addresses, rates } = options.registrations;
|
|
457
|
+
const taken = rates.take(`register:${addresses.keyOf(addresses.of(request))}`, {
|
|
458
|
+
count: REGISTRATIONS_PER_MINUTE,
|
|
459
|
+
perMs: 6e4
|
|
460
|
+
});
|
|
461
|
+
if (!taken.ok) {
|
|
462
|
+
send(response, 429, {
|
|
463
|
+
error: "slow_down",
|
|
464
|
+
error_description: "Too many registrations from this address; try again shortly."
|
|
465
|
+
}, { "retry-after": String(taken.retryAfterS) });
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const registered = options.clients.register(metadata);
|
|
470
|
+
if ("error" in registered && "description" in registered) {
|
|
471
|
+
send(response, 400, {
|
|
472
|
+
error: registered["error"],
|
|
473
|
+
error_description: registered["description"]
|
|
474
|
+
});
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
send(response, 201, registered);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
272
480
|
if (method === "GET" && path === "/.well-known/oauth-protected-resource/host") {
|
|
273
481
|
send(response, 200, {
|
|
274
482
|
resource: `${apiOrigin}/host`,
|
|
@@ -307,6 +515,10 @@ function createApi(options) {
|
|
|
307
515
|
});
|
|
308
516
|
return;
|
|
309
517
|
}
|
|
518
|
+
if (body.get("grant_type") === "refresh_token") {
|
|
519
|
+
const account = auth.refreshAccount(body.get("refresh_token") ?? "");
|
|
520
|
+
if (account !== void 0) await accountStanding(account);
|
|
521
|
+
}
|
|
310
522
|
const answer = auth.token(body);
|
|
311
523
|
if ("error" in answer) {
|
|
312
524
|
send(response, answer.status, {
|
|
@@ -325,14 +537,56 @@ function createApi(options) {
|
|
|
325
537
|
return;
|
|
326
538
|
}
|
|
327
539
|
if (path === "/device") {
|
|
328
|
-
const provider = developmentProvider(config);
|
|
540
|
+
const provider = developmentProvider$1(config);
|
|
541
|
+
const signed = options.authorize.sessionAccount(request);
|
|
329
542
|
if (method === "GET") {
|
|
543
|
+
const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
|
|
544
|
+
if (signed) {
|
|
545
|
+
page(response, 200, sessionDevicePage(code, signed));
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (!await devFormOffered()) {
|
|
549
|
+
await options.authorize.signInPage(response, `/device?user_code=${encodeURIComponent(code)}`);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
330
552
|
page(response, 200, devicePage({
|
|
331
|
-
code
|
|
553
|
+
code,
|
|
332
554
|
provider
|
|
333
555
|
}));
|
|
334
556
|
return;
|
|
335
557
|
}
|
|
558
|
+
let posted;
|
|
559
|
+
if (method === "POST" && signed && request.headers.origin === apiOrigin) {
|
|
560
|
+
const body = await form(request);
|
|
561
|
+
posted = body;
|
|
562
|
+
const decision = body?.get("session_decision");
|
|
563
|
+
if (body && decision !== null && decision !== void 0) {
|
|
564
|
+
const code = body.get("user_code") ?? "";
|
|
565
|
+
if (body.get("csrf") !== options.authorize.csrf(signed.hash, "device")) {
|
|
566
|
+
page(response, 403, devicePage({
|
|
567
|
+
code: "",
|
|
568
|
+
provider,
|
|
569
|
+
message: "This form must be sent from this page."
|
|
570
|
+
}));
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const approve = decision === "approve";
|
|
574
|
+
const decided = auth.decideFor({
|
|
575
|
+
code,
|
|
576
|
+
approve,
|
|
577
|
+
accountId: signed.accountId
|
|
578
|
+
});
|
|
579
|
+
page(response, decided.ok ? 200 : 400, devicePage({
|
|
580
|
+
code,
|
|
581
|
+
provider,
|
|
582
|
+
...decided.ok ? {
|
|
583
|
+
done: true,
|
|
584
|
+
message: approve ? "The machine is linked to your account." : "The sign-in was refused."
|
|
585
|
+
} : { message: decided.reason }
|
|
586
|
+
}));
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
336
590
|
if (method === "POST") {
|
|
337
591
|
if (request.headers.origin !== apiOrigin) {
|
|
338
592
|
page(response, 403, devicePage({
|
|
@@ -342,10 +596,10 @@ function createApi(options) {
|
|
|
342
596
|
}));
|
|
343
597
|
return;
|
|
344
598
|
}
|
|
345
|
-
const body = await form(request);
|
|
599
|
+
const body = posted ?? await form(request);
|
|
346
600
|
const code = body?.get("user_code") ?? "";
|
|
347
601
|
const name = (body?.get("name") ?? "").trim().slice(0, 64);
|
|
348
|
-
if (!body || !provider || body.get("provider") !== provider.id || name === "") {
|
|
602
|
+
if (!body || !provider || !await devFormOffered() || body.get("provider") !== provider.id || name === "") {
|
|
349
603
|
page(response, 400, devicePage({
|
|
350
604
|
code,
|
|
351
605
|
provider,
|
|
@@ -354,15 +608,43 @@ function createApi(options) {
|
|
|
354
608
|
return;
|
|
355
609
|
}
|
|
356
610
|
const approve = body.get("decision") === "approve";
|
|
357
|
-
const
|
|
611
|
+
const pending = auth.pendingCode(code);
|
|
612
|
+
if (!pending.ok) {
|
|
613
|
+
page(response, 400, devicePage({
|
|
614
|
+
code,
|
|
615
|
+
provider,
|
|
616
|
+
message: pending.reason
|
|
617
|
+
}));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const identity = {
|
|
621
|
+
provider: provider.id,
|
|
622
|
+
subject: name.toLowerCase(),
|
|
623
|
+
name
|
|
624
|
+
};
|
|
625
|
+
let decided;
|
|
626
|
+
if (!approve) decided = auth.decide({
|
|
358
627
|
code,
|
|
359
|
-
approve,
|
|
360
|
-
identity
|
|
361
|
-
provider: provider.id,
|
|
362
|
-
subject: name.toLowerCase(),
|
|
363
|
-
name
|
|
364
|
-
}
|
|
628
|
+
approve: false,
|
|
629
|
+
identity
|
|
365
630
|
});
|
|
631
|
+
else {
|
|
632
|
+
const account = await auth.resolveAccount(identity, 0);
|
|
633
|
+
if (account.kind !== "account") {
|
|
634
|
+
const reason = account.kind === "unavailable" ? "Sign-in is unavailable for a moment; try again shortly." : account.kind === "refused" ? account.message : account.kind === "suspended" ? "This account is suspended." : "This server asks for a step before a first sign-in, which the development sign-in can't take.";
|
|
635
|
+
page(response, account.kind === "unavailable" ? 503 : 403, devicePage({
|
|
636
|
+
code,
|
|
637
|
+
provider,
|
|
638
|
+
message: reason
|
|
639
|
+
}));
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
decided = auth.decideFor({
|
|
643
|
+
code,
|
|
644
|
+
approve: true,
|
|
645
|
+
accountId: account.accountId
|
|
646
|
+
});
|
|
647
|
+
}
|
|
366
648
|
if (!decided.ok) {
|
|
367
649
|
page(response, 400, devicePage({
|
|
368
650
|
code,
|
|
@@ -380,6 +662,30 @@ function createApi(options) {
|
|
|
380
662
|
return;
|
|
381
663
|
}
|
|
382
664
|
}
|
|
665
|
+
if (path === "/mcp" && options.mcp) {
|
|
666
|
+
const who = await bearer(request, "mcp");
|
|
667
|
+
const challenge = `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/mcp"`;
|
|
668
|
+
if (!who) {
|
|
669
|
+
send(response, 401, {
|
|
670
|
+
error: "invalid_token",
|
|
671
|
+
error_description: "Sign in to use Mostra here."
|
|
672
|
+
}, { "www-authenticate": challenge });
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if ("refused" in who) {
|
|
676
|
+
send(response, 403, who.refused);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
if (!who.scope.split(" ").includes("mostra")) {
|
|
680
|
+
send(response, 403, {
|
|
681
|
+
error: "insufficient_scope",
|
|
682
|
+
error_description: "The token lacks the mostra scope."
|
|
683
|
+
}, { "www-authenticate": `${challenge}, error="insufficient_scope", scope="mostra"` });
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
await options.mcp.handle(request, response, who);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
383
689
|
const file = /^\/files\/([0-9a-f]{64})$/.exec(path);
|
|
384
690
|
if (file && method === "PUT") {
|
|
385
691
|
await upload(request, response, file[1]);
|
|
@@ -398,55 +704,83 @@ function createApi(options) {
|
|
|
398
704
|
refuse(404, "Not Found");
|
|
399
705
|
return;
|
|
400
706
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
refuse(
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
707
|
+
bearer(request, "host").then((who) => upgradeFor(who), (error) => {
|
|
708
|
+
log.error("binding.auth_failed", { error });
|
|
709
|
+
refuse(503, "Service Unavailable");
|
|
710
|
+
});
|
|
711
|
+
const upgradeFor = (who) => {
|
|
712
|
+
if (who && "refused" in who) {
|
|
713
|
+
refuse(403, "Forbidden");
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (!who) {
|
|
717
|
+
refuse(401, "Unauthorized", `www-authenticate: Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"\r\n`);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
options.home(who.homeId).then((home) => {
|
|
721
|
+
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
722
|
+
bindings.add(ws);
|
|
723
|
+
bindingHomes.set(ws, who.homeId);
|
|
724
|
+
let expiresAt = who.expiresAt;
|
|
725
|
+
const attributes = {
|
|
726
|
+
accountId: who.accountId,
|
|
727
|
+
grantId: who.grantId,
|
|
728
|
+
homeId: who.homeId,
|
|
729
|
+
linkId: who.linkId,
|
|
730
|
+
replaceToken: (next) => {
|
|
731
|
+
expiresAt = next;
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
const watch = setInterval(() => {
|
|
735
|
+
if (Date.now() >= expiresAt) {
|
|
736
|
+
log.info("binding.token_expired", { home: who.homeId });
|
|
737
|
+
ws.close(4401, "token expired");
|
|
738
|
+
} else if (who.grantId.startsWith("credential:")) bearer(request, "host").then((still) => {
|
|
739
|
+
if (!still || "refused" in still) {
|
|
740
|
+
log.info("binding.credential_revoked", { home: who.homeId });
|
|
741
|
+
ws.close(4403, "credential revoked");
|
|
742
|
+
} else expiresAt = still.expiresAt;
|
|
743
|
+
}, () => void 0);
|
|
744
|
+
else if (!auth.grantLive(who.grantId)) {
|
|
745
|
+
log.info("binding.grant_revoked", { home: who.homeId });
|
|
746
|
+
ws.close(4403, "grant revoked");
|
|
747
|
+
} else standing(who).then((refused) => {
|
|
748
|
+
if (refused) {
|
|
749
|
+
log.info("binding.account_suspended", { home: who.homeId });
|
|
750
|
+
ws.close(4403, "account suspended");
|
|
751
|
+
}
|
|
752
|
+
}, () => void 0);
|
|
753
|
+
}, Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS));
|
|
754
|
+
watch.unref();
|
|
755
|
+
ws.once("close", () => {
|
|
756
|
+
clearInterval(watch);
|
|
757
|
+
bindings.delete(ws);
|
|
758
|
+
bindingHomes.delete(ws);
|
|
759
|
+
});
|
|
760
|
+
ws.on("message", () => {
|
|
761
|
+
options.touch(who.homeId);
|
|
762
|
+
options.message?.(who.homeId);
|
|
763
|
+
});
|
|
764
|
+
serveWebSocket(home.protocol, ws, {
|
|
765
|
+
attributes,
|
|
766
|
+
log
|
|
767
|
+
});
|
|
768
|
+
log.info("binding.opened", {
|
|
769
|
+
home: who.homeId,
|
|
770
|
+
link: who.linkId
|
|
771
|
+
});
|
|
437
772
|
});
|
|
438
|
-
|
|
773
|
+
}, (error) => {
|
|
774
|
+
log.error("binding.home_failed", {
|
|
439
775
|
home: who.homeId,
|
|
440
|
-
|
|
776
|
+
error
|
|
441
777
|
});
|
|
778
|
+
refuse(503, "Service Unavailable");
|
|
442
779
|
});
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
});
|
|
448
|
-
refuse(503, "Service Unavailable");
|
|
449
|
-
});
|
|
780
|
+
};
|
|
781
|
+
},
|
|
782
|
+
closeHome(homeId) {
|
|
783
|
+
for (const [ws, home] of bindingHomes) if (home === homeId) ws.close(4403, "home unavailable");
|
|
450
784
|
},
|
|
451
785
|
close() {
|
|
452
786
|
for (const ws of bindings) ws.terminate();
|
|
@@ -476,6 +810,10 @@ const REFRESH_TTL_MS = 7776e6;
|
|
|
476
810
|
const DEVICE_TTL_MS = 6e5;
|
|
477
811
|
const DEVICE_INTERVAL_S = 5;
|
|
478
812
|
const ROTATION_GRACE_MS = 3e4;
|
|
813
|
+
/** An authorization code lives a minute (OAuth 2.1 §4.1.2: short-lived). */
|
|
814
|
+
const CODE_TTL_MS = 6e4;
|
|
815
|
+
/** How long a used or expired code is kept to recognize its reuse (an hour). */
|
|
816
|
+
const CODE_KEPT_MS = 36e5;
|
|
479
817
|
/** User codes: eight letters a person can't confuse (RFC 8628 §6.1), shown as `ABCD-EFGH`. */
|
|
480
818
|
const USER_CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
|
|
481
819
|
/** The SHA-256 of a secret, as the directory stores it. */
|
|
@@ -490,6 +828,25 @@ function userCode() {
|
|
|
490
828
|
for (let index = 0; index < 8; index++) code += USER_CODE_LETTERS[randomInt(20)];
|
|
491
829
|
return code;
|
|
492
830
|
}
|
|
831
|
+
/** Whether a PKCE verifier hashes to the S256 challenge (RFC 7636 §4.6), in constant time. */
|
|
832
|
+
function pkceMatches(verifier, challenge) {
|
|
833
|
+
if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return false;
|
|
834
|
+
const computed = createHash("sha256").update(verifier).digest("base64url");
|
|
835
|
+
return computed.length === challenge.length && timingSafeEqual(Buffer.from(computed), Buffer.from(challenge));
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* A resource indicator in its canonical form (RFC 8707; the MCP specification): scheme and host in
|
|
839
|
+
* lower case, no trailing slash, no fragment. An unusable one answers `""`.
|
|
840
|
+
*/
|
|
841
|
+
function canonicalResource(resource) {
|
|
842
|
+
try {
|
|
843
|
+
const url = new URL(resource);
|
|
844
|
+
if (url.hash !== "" || url.search !== "") return "";
|
|
845
|
+
return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, "")}`;
|
|
846
|
+
} catch {
|
|
847
|
+
return "";
|
|
848
|
+
}
|
|
849
|
+
}
|
|
493
850
|
/** `abcd-efgh`, `ABCDEFGH` → `ABCDEFGH`. */
|
|
494
851
|
function normalizeUserCode(input) {
|
|
495
852
|
return input.toUpperCase().replace(/[^A-Z]/g, "");
|
|
@@ -506,12 +863,21 @@ function createAuthorization(options) {
|
|
|
506
863
|
const { directory, config, log } = options;
|
|
507
864
|
const now = options.now ?? (() => Date.now());
|
|
508
865
|
const accessTtlMs = options.accessTtlMs ?? ACCESS_TTL_MS;
|
|
866
|
+
const rotationGraceMs = options.rotationGraceMs ?? ROTATION_GRACE_MS;
|
|
509
867
|
const iso = (ms) => new Date(ms).toISOString();
|
|
510
868
|
const verificationUri = `${config.apiOrigin}/device`;
|
|
511
869
|
directory.write((db) => {
|
|
512
870
|
db.run("INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'cli', ?, ?)", CLI_CLIENT_ID, JSON.stringify({ client_name: "Mostra CLI" }), iso(now()));
|
|
513
871
|
});
|
|
514
872
|
const deviceRow = (db, hash) => db.get("SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'device'", hash);
|
|
873
|
+
/** An account the operator names: kept in the directory under the operator's own ID. */
|
|
874
|
+
const operatorAccount = (db, identity, account, name, status) => {
|
|
875
|
+
db.run(`INSERT INTO account (id, name, status, created_at) VALUES (?, ?, ?, ?)
|
|
876
|
+
ON CONFLICT (id) DO UPDATE SET name = COALESCE(excluded.name, name), status = excluded.status`, account, name ?? identity.name ?? null, status, iso(now()));
|
|
877
|
+
db.run(`INSERT INTO identity (provider, subject, account_id, email, name, linked_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
878
|
+
ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id,
|
|
879
|
+
email = excluded.email, name = excluded.name`, identity.provider, identity.subject, account, identity.email ?? null, identity.name ?? null, iso(now()));
|
|
880
|
+
};
|
|
515
881
|
/** The account for a sign-in identity, made on the first sign-in. */
|
|
516
882
|
const accountFor = (db, identity) => {
|
|
517
883
|
const found = db.get("SELECT account_id FROM identity WHERE provider = ? AND subject = ?", identity.provider, identity.subject);
|
|
@@ -554,7 +920,7 @@ function createAuthorization(options) {
|
|
|
554
920
|
};
|
|
555
921
|
};
|
|
556
922
|
const answer = (db, grantId, tokens) => {
|
|
557
|
-
const row = db.get(`SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id
|
|
923
|
+
const row = db.get(`SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id, g.scope
|
|
558
924
|
FROM "grant" g JOIN account a ON a.id = g.account_id
|
|
559
925
|
LEFT JOIN instance_link l ON l.id = g.link_id WHERE g.id = ?`, grantId);
|
|
560
926
|
if (!row) throw new Error("grant vanished");
|
|
@@ -563,14 +929,16 @@ function createAuthorization(options) {
|
|
|
563
929
|
token_type: "Bearer",
|
|
564
930
|
expires_in: Math.max(1, Math.floor(accessTtlMs / 1e3)),
|
|
565
931
|
refresh_token: tokens.refresh,
|
|
566
|
-
scope:
|
|
932
|
+
scope: row.scope,
|
|
567
933
|
mostra_account: {
|
|
568
934
|
id: row.account_id,
|
|
569
935
|
...row.name !== null ? { name: row.name } : {}
|
|
570
936
|
},
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
937
|
+
...row.link_id !== null ? {
|
|
938
|
+
mostra_instance: row.link_id,
|
|
939
|
+
mostra_default: row.is_default === 1,
|
|
940
|
+
mostra_home: row.home_id ?? ""
|
|
941
|
+
} : {}
|
|
574
942
|
};
|
|
575
943
|
};
|
|
576
944
|
/**
|
|
@@ -580,11 +948,44 @@ function createAuthorization(options) {
|
|
|
580
948
|
*/
|
|
581
949
|
const recent = /* @__PURE__ */ new Map();
|
|
582
950
|
const forgetOld = () => {
|
|
583
|
-
for (const [hash, entry] of recent) if (now() - entry.at >
|
|
951
|
+
for (const [hash, entry] of recent) if (now() - entry.at > rotationGraceMs) recent.delete(hash);
|
|
584
952
|
};
|
|
585
|
-
|
|
953
|
+
/** `grant_type=refresh_token`: rotation with a 30 s grace, reuse after it revokes the grant. */
|
|
954
|
+
const refresh = (form, clientId) => {
|
|
955
|
+
const hash = hashSecret(form.get("refresh_token") ?? "");
|
|
956
|
+
return directory.write((db) => {
|
|
957
|
+
const row = db.get("SELECT grant_id, expires_at, used_at FROM token WHERE hash = ? AND kind = 'refresh'", hash);
|
|
958
|
+
if (!row || !grantLiveIn(db, row.grant_id, { anyStatus: true }) || grantClient(db, row.grant_id) !== clientId) return oauthError(400, "invalid_grant", "The refresh token isn't valid; sign in again.");
|
|
959
|
+
if (!grantLiveIn(db, row.grant_id)) return oauthError(403, "temporarily_unavailable", "This account is suspended; its sign-in works again once the server's operator lifts the suspension.");
|
|
960
|
+
if (Date.parse(row.expires_at) <= now()) return oauthError(400, "invalid_grant", "The refresh token expired; sign in again.");
|
|
961
|
+
if (row.used_at !== null) {
|
|
962
|
+
const used = Date.parse(row.used_at);
|
|
963
|
+
forgetOld();
|
|
964
|
+
if (now() - used <= rotationGraceMs) {
|
|
965
|
+
const kept = recent.get(hash);
|
|
966
|
+
if (kept) return answer(db, row.grant_id, kept.tokens);
|
|
967
|
+
return oauthError(400, "invalid_grant", "This refresh token was just used; use its successor.");
|
|
968
|
+
}
|
|
969
|
+
db.run("UPDATE \"grant\" SET revoked_at = ? WHERE id = ?", iso(now()), row.grant_id);
|
|
970
|
+
log.warn("auth.refresh_reused", { grant: row.grant_id });
|
|
971
|
+
return oauthError(400, "invalid_grant", "The refresh token was used before; sign in again.");
|
|
972
|
+
}
|
|
973
|
+
const tokens = issue(db, row.grant_id);
|
|
974
|
+
db.run("UPDATE token SET used_at = ?, successor_hash = ? WHERE hash = ?", iso(now()), hashSecret(tokens.refresh), hash);
|
|
975
|
+
forgetOld();
|
|
976
|
+
recent.set(hash, {
|
|
977
|
+
tokens,
|
|
978
|
+
at: now()
|
|
979
|
+
});
|
|
980
|
+
return answer(db, row.grant_id, tokens);
|
|
981
|
+
});
|
|
982
|
+
};
|
|
983
|
+
/** The client a grant is for. */
|
|
984
|
+
const grantClient = (db, grantId) => db.get("SELECT client_id FROM \"grant\" WHERE id = ?", grantId)?.client_id;
|
|
985
|
+
const grantLiveIn = (db, grantId, options = {}) => {
|
|
986
|
+
if (grantId.startsWith("credential:")) return true;
|
|
586
987
|
const row = db.get("SELECT g.revoked_at, a.status FROM \"grant\" g JOIN account a ON a.id = g.account_id WHERE g.id = ?", grantId);
|
|
587
|
-
return row !== void 0 && row.revoked_at === null && row.status === "active";
|
|
988
|
+
return row !== void 0 && row.revoked_at === null && (options.anyStatus === true || row.status === "active");
|
|
588
989
|
};
|
|
589
990
|
return {
|
|
590
991
|
verificationUri,
|
|
@@ -615,7 +1016,44 @@ function createAuthorization(options) {
|
|
|
615
1016
|
},
|
|
616
1017
|
token(form) {
|
|
617
1018
|
const grantType = form.get("grant_type");
|
|
618
|
-
|
|
1019
|
+
const clientId = form.get("client_id") ?? "";
|
|
1020
|
+
if (grantType === "authorization_code") {
|
|
1021
|
+
const hash = hashSecret(form.get("code") ?? "");
|
|
1022
|
+
return directory.write((db) => {
|
|
1023
|
+
const row = db.get("SELECT data_json, expires_at, used_at FROM token WHERE hash = ? AND kind = 'code'", hash);
|
|
1024
|
+
if (row?.used_at != null) {
|
|
1025
|
+
const spent = JSON.parse(row.data_json);
|
|
1026
|
+
if (spent.grantId !== void 0) {
|
|
1027
|
+
db.run("UPDATE \"grant\" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL", iso(now()), spent.grantId);
|
|
1028
|
+
log.warn("auth.code_reused", { grant: spent.grantId });
|
|
1029
|
+
}
|
|
1030
|
+
return oauthError(400, "invalid_grant", "The code is unknown, used or expired.");
|
|
1031
|
+
}
|
|
1032
|
+
db.run("UPDATE token SET used_at = ? WHERE hash = ? AND kind = 'code'", iso(now()), hash);
|
|
1033
|
+
if (!row || Date.parse(row.expires_at) <= now()) return oauthError(400, "invalid_grant", "The code is unknown, used or expired.");
|
|
1034
|
+
const grant = JSON.parse(row.data_json);
|
|
1035
|
+
if (grant.viewerSignin !== void 0) return oauthError(400, "invalid_grant", "This code is a page's sign-in, not a client's.");
|
|
1036
|
+
if (grant.clientId !== clientId) return oauthError(400, "invalid_grant", "The code was issued to another client.");
|
|
1037
|
+
const redirectUri = form.get("redirect_uri");
|
|
1038
|
+
if (redirectUri === null && grant.redirectGiven !== false || redirectUri !== null && redirectUri !== grant.redirectUri) return oauthError(400, "invalid_grant", "redirect_uri isn't the one the code was issued for.");
|
|
1039
|
+
if (!pkceMatches(form.get("code_verifier") ?? "", grant.challenge)) return oauthError(400, "invalid_grant", "The PKCE code_verifier doesn't match.");
|
|
1040
|
+
const resource = form.get("resource");
|
|
1041
|
+
if (resource !== null && canonicalResource(resource) !== grant.resource) return oauthError(400, "invalid_target", "resource isn't the one the code was issued for.");
|
|
1042
|
+
const grantId = `grt_${randomBytes(16).toString("hex")}`;
|
|
1043
|
+
db.run("INSERT INTO \"grant\" (id, account_id, client_id, scope, resource, link_id, created_at) VALUES (?, ?, ?, ?, ?, NULL, ?)", grantId, grant.accountId, grant.clientId, grant.scope, grant.resource, iso(now()));
|
|
1044
|
+
db.run("UPDATE token SET data_json = ? WHERE hash = ? AND kind = 'code'", JSON.stringify({
|
|
1045
|
+
...grant,
|
|
1046
|
+
grantId
|
|
1047
|
+
}), hash);
|
|
1048
|
+
log.info("auth.code_redeemed", {
|
|
1049
|
+
client: grant.clientId,
|
|
1050
|
+
grant: grantId
|
|
1051
|
+
});
|
|
1052
|
+
return answer(db, grantId, issue(db, grantId));
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
if (grantType === "refresh_token") return refresh(form, clientId);
|
|
1056
|
+
if (clientId !== "mostra-cli") return oauthError(401, "invalid_client", "Unknown client.");
|
|
619
1057
|
if (grantType === "urn:ietf:params:oauth:grant-type:device_code") {
|
|
620
1058
|
const hash = hashSecret(form.get("device_code") ?? "");
|
|
621
1059
|
return directory.write((db) => {
|
|
@@ -656,35 +1094,7 @@ function createAuthorization(options) {
|
|
|
656
1094
|
return answer(db, grantId, tokens);
|
|
657
1095
|
});
|
|
658
1096
|
}
|
|
659
|
-
|
|
660
|
-
const hash = hashSecret(form.get("refresh_token") ?? "");
|
|
661
|
-
return directory.write((db) => {
|
|
662
|
-
const row = db.get("SELECT grant_id, expires_at, used_at FROM token WHERE hash = ? AND kind = 'refresh'", hash);
|
|
663
|
-
if (!row || !grantLiveIn(db, row.grant_id)) return oauthError(400, "invalid_grant", "The refresh token isn't valid; sign in again.");
|
|
664
|
-
if (Date.parse(row.expires_at) <= now()) return oauthError(400, "invalid_grant", "The refresh token expired; sign in again.");
|
|
665
|
-
if (row.used_at !== null) {
|
|
666
|
-
const used = Date.parse(row.used_at);
|
|
667
|
-
forgetOld();
|
|
668
|
-
if (now() - used <= ROTATION_GRACE_MS) {
|
|
669
|
-
const kept = recent.get(hash);
|
|
670
|
-
if (kept) return answer(db, row.grant_id, kept.tokens);
|
|
671
|
-
return oauthError(400, "invalid_grant", "This refresh token was just used; use its successor.");
|
|
672
|
-
}
|
|
673
|
-
db.run("UPDATE \"grant\" SET revoked_at = ? WHERE id = ?", iso(now()), row.grant_id);
|
|
674
|
-
log.warn("auth.refresh_reused", { grant: row.grant_id });
|
|
675
|
-
return oauthError(400, "invalid_grant", "The refresh token was used before; sign in again.");
|
|
676
|
-
}
|
|
677
|
-
const tokens = issue(db, row.grant_id);
|
|
678
|
-
db.run("UPDATE token SET used_at = ?, successor_hash = ? WHERE hash = ?", iso(now()), hashSecret(tokens.refresh), hash);
|
|
679
|
-
forgetOld();
|
|
680
|
-
recent.set(hash, {
|
|
681
|
-
tokens,
|
|
682
|
-
at: now()
|
|
683
|
-
});
|
|
684
|
-
return answer(db, row.grant_id, tokens);
|
|
685
|
-
});
|
|
686
|
-
}
|
|
687
|
-
return oauthError(400, "unsupported_grant_type", "Use the device grant or a refresh token.");
|
|
1097
|
+
return oauthError(400, "unsupported_grant_type", "Use authorization_code, refresh_token or the device grant.");
|
|
688
1098
|
},
|
|
689
1099
|
revoke(form) {
|
|
690
1100
|
const hash = hashSecret(form.get("token") ?? "");
|
|
@@ -700,25 +1110,165 @@ function createAuthorization(options) {
|
|
|
700
1110
|
if (bearer.length < 20 || bearer.length > 200) return void 0;
|
|
701
1111
|
const hash = hashSecret(bearer);
|
|
702
1112
|
return directory.read((db) => {
|
|
703
|
-
const row = db.get(`SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name
|
|
1113
|
+
const row = db.get(`SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name, g.resource, g.client_id, g.scope
|
|
704
1114
|
FROM token t JOIN "grant" g ON g.id = t.grant_id JOIN account a ON a.id = g.account_id
|
|
705
1115
|
WHERE t.hash = ? AND t.kind = 'access'`, hash);
|
|
706
1116
|
if (!row) return void 0;
|
|
707
1117
|
if (!timingSafeEqual(Buffer.from(row.hash), Buffer.from(hash))) return void 0;
|
|
708
1118
|
const expiresAt = Date.parse(row.expires_at);
|
|
709
|
-
if (expiresAt <= now() || !grantLiveIn(db, row.grant_id)) return void 0;
|
|
1119
|
+
if (expiresAt <= now() || !grantLiveIn(db, row.grant_id, { anyStatus: true })) return void 0;
|
|
710
1120
|
const home = db.get("SELECT id FROM home WHERE owner_account_id = ?", row.account_id);
|
|
711
|
-
if (!home) return void 0;
|
|
1121
|
+
if (!home && row.resource.endsWith("/host")) return void 0;
|
|
712
1122
|
return {
|
|
1123
|
+
resource: row.resource,
|
|
1124
|
+
clientId: row.client_id,
|
|
1125
|
+
scope: row.scope,
|
|
713
1126
|
accountId: row.account_id,
|
|
714
1127
|
accountName: row.name ?? void 0,
|
|
715
1128
|
grantId: row.grant_id,
|
|
716
|
-
homeId: home
|
|
1129
|
+
homeId: home?.id ?? "",
|
|
717
1130
|
linkId: row.link_id ?? void 0,
|
|
718
1131
|
expiresAt
|
|
719
1132
|
};
|
|
720
1133
|
});
|
|
721
1134
|
},
|
|
1135
|
+
decideFor(input) {
|
|
1136
|
+
const wanted = normalizeUserCode(input.code);
|
|
1137
|
+
return directory.write((db) => {
|
|
1138
|
+
const row = db.all("SELECT hash, data_json FROM token WHERE kind = 'device' AND expires_at > ?", iso(now())).find((candidate) => JSON.parse(candidate.data_json).userCode === wanted);
|
|
1139
|
+
if (!row) return {
|
|
1140
|
+
ok: false,
|
|
1141
|
+
reason: "That code is unknown or has expired."
|
|
1142
|
+
};
|
|
1143
|
+
const state = JSON.parse(row.data_json);
|
|
1144
|
+
if (state.status !== "pending") return {
|
|
1145
|
+
ok: false,
|
|
1146
|
+
reason: "That code was already used."
|
|
1147
|
+
};
|
|
1148
|
+
db.run("UPDATE token SET data_json = ? WHERE hash = ?", JSON.stringify(input.approve ? {
|
|
1149
|
+
...state,
|
|
1150
|
+
status: "approved",
|
|
1151
|
+
accountId: input.accountId
|
|
1152
|
+
} : {
|
|
1153
|
+
...state,
|
|
1154
|
+
status: "denied"
|
|
1155
|
+
}), row.hash);
|
|
1156
|
+
if (input.approve) db.run("INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL", input.accountId, CLI_CLIENT_ID, iso(now()));
|
|
1157
|
+
return { ok: true };
|
|
1158
|
+
});
|
|
1159
|
+
},
|
|
1160
|
+
async resolveAccount(identity, steps) {
|
|
1161
|
+
const verdict = options.operator ? await options.operator.resolve(identity, steps) : { default: true };
|
|
1162
|
+
if (verdict === "unavailable") return { kind: "unavailable" };
|
|
1163
|
+
if ("default" in verdict) {
|
|
1164
|
+
const accountId = directory.write((db) => accountFor(db, identity));
|
|
1165
|
+
if (directory.read((db) => db.get("SELECT status FROM account WHERE id = ?", accountId)?.status) === "suspended") return { kind: "suspended" };
|
|
1166
|
+
return {
|
|
1167
|
+
kind: "account",
|
|
1168
|
+
accountId,
|
|
1169
|
+
name: identity.name
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
if ("step" in verdict) return {
|
|
1173
|
+
kind: "step",
|
|
1174
|
+
url: verdict.step.url
|
|
1175
|
+
};
|
|
1176
|
+
if ("refused" in verdict) return {
|
|
1177
|
+
kind: "refused",
|
|
1178
|
+
message: verdict.refused.message
|
|
1179
|
+
};
|
|
1180
|
+
directory.write((db) => operatorAccount(db, identity, verdict.account, verdict.name, verdict.status));
|
|
1181
|
+
if (verdict.status === "suspended") return { kind: "suspended" };
|
|
1182
|
+
return {
|
|
1183
|
+
kind: "account",
|
|
1184
|
+
accountId: verdict.account,
|
|
1185
|
+
name: verdict.name ?? identity.name
|
|
1186
|
+
};
|
|
1187
|
+
},
|
|
1188
|
+
accountName(accountId) {
|
|
1189
|
+
return directory.read((db) => {
|
|
1190
|
+
const row = db.get(`SELECT a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id
|
|
1191
|
+
ORDER BY i.linked_at LIMIT 1) AS provider FROM account a WHERE a.id = ?`, accountId);
|
|
1192
|
+
return {
|
|
1193
|
+
...row?.name ? { name: row.name } : {},
|
|
1194
|
+
...row?.provider ? { provider: row.provider } : {}
|
|
1195
|
+
};
|
|
1196
|
+
});
|
|
1197
|
+
},
|
|
1198
|
+
issueCode(grant) {
|
|
1199
|
+
const code = secret();
|
|
1200
|
+
directory.write((db) => {
|
|
1201
|
+
db.run("DELETE FROM token WHERE kind = 'code' AND expires_at < ?", iso(now() - CODE_KEPT_MS));
|
|
1202
|
+
db.run("INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'code', ?, ?)", hashSecret(code), iso(now() + CODE_TTL_MS), JSON.stringify(grant));
|
|
1203
|
+
});
|
|
1204
|
+
return code;
|
|
1205
|
+
},
|
|
1206
|
+
redeemViewerCode(input) {
|
|
1207
|
+
const hash = hashSecret(input.code);
|
|
1208
|
+
return directory.write((db) => {
|
|
1209
|
+
const row = db.get("SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'code'", hash);
|
|
1210
|
+
db.run("DELETE FROM token WHERE hash = ?", hash);
|
|
1211
|
+
if (!row || Date.parse(row.expires_at) <= now()) return { refused: "The sign-in code is unknown, used or expired." };
|
|
1212
|
+
const grant = JSON.parse(row.data_json);
|
|
1213
|
+
if (grant.viewerSignin === void 0 || grant.viewerSignin !== input.viewerSignin) return { refused: "This sign-in code was started for another page." };
|
|
1214
|
+
if (grant.clientId !== input.clientId) return { refused: "This sign-in code was issued to another shell." };
|
|
1215
|
+
if (!pkceMatches(input.verifier, grant.challenge)) return { refused: "The sign-in's PKCE verifier doesn't match." };
|
|
1216
|
+
return { accountId: grant.accountId };
|
|
1217
|
+
});
|
|
1218
|
+
},
|
|
1219
|
+
credentialSession(input) {
|
|
1220
|
+
return directory.write((db) => {
|
|
1221
|
+
db.run("INSERT INTO account (id, name, status, created_at) VALUES (?, NULL, 'active', ?) ON CONFLICT (id) DO NOTHING", input.account, iso(now()));
|
|
1222
|
+
const home = homeFor(db, input.account);
|
|
1223
|
+
let link = db.get("SELECT link_id FROM credential_link WHERE account_id = ? AND subject = ?", input.account, input.subject)?.link_id;
|
|
1224
|
+
if (link === void 0 && input.link) {
|
|
1225
|
+
link = linkFor(db, input.account, home, void 0, `Service key ${input.subject}`.slice(0, 128));
|
|
1226
|
+
db.run("INSERT INTO credential_link (account_id, subject, link_id) VALUES (?, ?, ?)", input.account, input.subject, link);
|
|
1227
|
+
}
|
|
1228
|
+
const name = db.get("SELECT name FROM account WHERE id = ?", input.account)?.name;
|
|
1229
|
+
return {
|
|
1230
|
+
resource: input.resource,
|
|
1231
|
+
clientId: "operator",
|
|
1232
|
+
scope: "mostra",
|
|
1233
|
+
accountId: input.account,
|
|
1234
|
+
accountName: name ?? void 0,
|
|
1235
|
+
grantId: `credential:${input.account}:${input.subject}`,
|
|
1236
|
+
homeId: home,
|
|
1237
|
+
linkId: link,
|
|
1238
|
+
expiresAt: now() + accessTtlMs
|
|
1239
|
+
};
|
|
1240
|
+
});
|
|
1241
|
+
},
|
|
1242
|
+
refreshAccount(refreshToken) {
|
|
1243
|
+
return directory.read((db) => db.get("SELECT g.account_id FROM token t JOIN \"grant\" g ON g.id = t.grant_id WHERE t.hash = ? AND t.kind = 'refresh'", hashSecret(refreshToken))?.account_id);
|
|
1244
|
+
},
|
|
1245
|
+
accountStatus(accountId) {
|
|
1246
|
+
return directory.read((db) => db.get("SELECT status FROM account WHERE id = ?", accountId)?.status === "suspended" ? "suspended" : "active");
|
|
1247
|
+
},
|
|
1248
|
+
setAccountStatus(accountId, status) {
|
|
1249
|
+
directory.write((db) => db.run("UPDATE account SET status = ? WHERE id = ? AND status != ?", status, accountId, status));
|
|
1250
|
+
},
|
|
1251
|
+
linkState(linkId, makeDefault) {
|
|
1252
|
+
return directory.write((db) => {
|
|
1253
|
+
if (makeDefault) {
|
|
1254
|
+
const owner = db.get("SELECT account_id FROM instance_link WHERE id = ?", linkId);
|
|
1255
|
+
if (owner) {
|
|
1256
|
+
db.run("UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?", owner.account_id, linkId);
|
|
1257
|
+
db.run("UPDATE instance_link SET is_default = 1 WHERE id = ?", linkId);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return { default: db.get("SELECT is_default FROM instance_link WHERE id = ?", linkId)?.is_default === 1 };
|
|
1261
|
+
});
|
|
1262
|
+
},
|
|
1263
|
+
ensureHome(accountId) {
|
|
1264
|
+
return directory.write((db) => homeFor(db, accountId));
|
|
1265
|
+
},
|
|
1266
|
+
consented(accountId, clientId) {
|
|
1267
|
+
return directory.read((db) => db.get("SELECT 1 FROM consent WHERE account_id = ? AND client_id = ? AND revoked_at IS NULL", accountId, clientId) !== void 0);
|
|
1268
|
+
},
|
|
1269
|
+
consent(accountId, clientId) {
|
|
1270
|
+
directory.write((db) => db.run("INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL, granted_at = excluded.granted_at", accountId, clientId, iso(now())));
|
|
1271
|
+
},
|
|
722
1272
|
grantLive(grantId) {
|
|
723
1273
|
return directory.read((db) => grantLiveIn(db, grantId));
|
|
724
1274
|
},
|
|
@@ -769,58 +1319,1068 @@ function createAuthorization(options) {
|
|
|
769
1319
|
};
|
|
770
1320
|
}
|
|
771
1321
|
//#endregion
|
|
772
|
-
//#region src/server/
|
|
773
|
-
/**
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1322
|
+
//#region src/server/oauth-clients.ts
|
|
1323
|
+
/**
|
|
1324
|
+
* The authorization server's clients (INTERFACES §18.5; VERIFIED_FACTS, WP-30): first-party ones
|
|
1325
|
+
* (the CLI, and one hosted shell per user-content domain), clients that registered through Dynamic
|
|
1326
|
+
* Client Registration (RFC 7591, deprecated by the MCP specification and still Claude's fallback),
|
|
1327
|
+
* and clients named by a Client ID Metadata Document: an `https` URL with a path whose document the
|
|
1328
|
+
* server fetches.
|
|
1329
|
+
*
|
|
1330
|
+
* A metadata document is fetched over `https` only, from a public address only: the name is
|
|
1331
|
+
* resolved once, every address it gives must be public (no loopback, private, link-local,
|
|
1332
|
+
* unique-local, carrier-grade NAT, multicast, reserved or cloud metadata address), and the request
|
|
1333
|
+
* goes to the address that was checked, so a second resolution can't move it (DNS rebinding). No
|
|
1334
|
+
* redirect is followed; at most 64 KiB, within 5 s; the document's `client_id` must equal its URL;
|
|
1335
|
+
* it is cached as its `Cache-Control` allows (at least a minute, at most a day).
|
|
1336
|
+
*
|
|
1337
|
+
* A redirect URI matches exactly, except that the port is ignored for `http://127.0.0.1`,
|
|
1338
|
+
* `http://[::1]` and `http://localhost` (RFC 8252 §7.3; Claude Code's loopback callback).
|
|
1339
|
+
*/
|
|
1340
|
+
/** The largest metadata document read. */
|
|
1341
|
+
const MAX_DOCUMENT_BYTES = 65536;
|
|
1342
|
+
/** How long fetching one may take. */
|
|
1343
|
+
const FETCH_TIMEOUT_MS = 5e3;
|
|
1344
|
+
/** Registered clients unused this long are removed (INTERFACES §18.5). */
|
|
1345
|
+
const UNUSED_CLIENT_MS = 2592e6;
|
|
1346
|
+
/**
|
|
1347
|
+
* An IPv6 address's eight 16-bit groups, whatever its written form (`::` compressed, a dotted
|
|
1348
|
+
* IPv4 tail, hex), or `undefined` when it isn't one.
|
|
1349
|
+
*/
|
|
1350
|
+
function ipv6Groups(address) {
|
|
1351
|
+
let text = address.toLowerCase();
|
|
1352
|
+
const zone = text.indexOf("%");
|
|
1353
|
+
if (zone !== -1) text = text.slice(0, zone);
|
|
1354
|
+
const colon = text.lastIndexOf(":");
|
|
1355
|
+
const dotted = text.slice(colon + 1);
|
|
1356
|
+
if (colon !== -1 && dotted.includes(".")) {
|
|
1357
|
+
const parts = dotted.split(".");
|
|
1358
|
+
if (parts.length !== 4 || parts.some((part) => !/^\d{1,3}$/.test(part))) return void 0;
|
|
1359
|
+
const [a, b, c, d] = parts.map(Number);
|
|
1360
|
+
if ([
|
|
1361
|
+
a,
|
|
1362
|
+
b,
|
|
1363
|
+
c,
|
|
1364
|
+
d
|
|
1365
|
+
].some((part) => part > 255)) return void 0;
|
|
1366
|
+
text = `${text.slice(0, colon + 1)}${(a << 8 | b).toString(16)}:${(c << 8 | d).toString(16)}`;
|
|
1367
|
+
}
|
|
1368
|
+
const halves = text.split("::");
|
|
1369
|
+
if (halves.length > 2) return void 0;
|
|
1370
|
+
const parse = (half) => half === "" ? [] : half.split(":").map((group) => Number.parseInt(group, 16));
|
|
1371
|
+
const head = parse(halves[0]);
|
|
1372
|
+
const tail = halves.length === 2 ? parse(halves[1]) : [];
|
|
1373
|
+
const missing = 8 - head.length - tail.length;
|
|
1374
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return void 0;
|
|
1375
|
+
const groups = [
|
|
1376
|
+
...head,
|
|
1377
|
+
...Array(halves.length === 2 ? missing : 0).fill(0),
|
|
1378
|
+
...tail
|
|
1379
|
+
];
|
|
1380
|
+
return groups.length === 8 && groups.every((group) => group >= 0 && group <= 65535) ? groups : void 0;
|
|
1381
|
+
}
|
|
1382
|
+
/** Whether an IP address is one no client document may come from. */
|
|
1383
|
+
function forbiddenAddress(address) {
|
|
1384
|
+
const family = isIP(address);
|
|
1385
|
+
if (family === 4) {
|
|
1386
|
+
const [a, b] = address.split(".").map(Number);
|
|
1387
|
+
return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 || a === 198 && (b === 18 || b === 19) || a >= 224;
|
|
1388
|
+
}
|
|
1389
|
+
if (family !== 6) return true;
|
|
1390
|
+
const groups = ipv6Groups(address);
|
|
1391
|
+
if (!groups) return true;
|
|
1392
|
+
const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;
|
|
1393
|
+
const embedded = `${g6 >> 8}.${g6 & 255}.${g7 >> 8}.${g7 & 255}`;
|
|
1394
|
+
if (g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && (g5 === 65535 || g5 === 0)) {
|
|
1395
|
+
if (g5 === 0 && g6 === 0 && (g7 === 0 || g7 === 1)) return true;
|
|
1396
|
+
return forbiddenAddress(embedded);
|
|
1397
|
+
}
|
|
1398
|
+
return (g0 & 65472) === 65152 || (g0 & 65024) === 64512 || (g0 & 65280) === 65280 || g0 === 100 && g1 === 65435 || g0 === 8194 || g0 === 8193 && g1 === 0 || g0 === 8193 && g1 === 3512 || g0 === 256 && g1 === 0 && g2 === 0 && g3 === 0;
|
|
1399
|
+
}
|
|
1400
|
+
/** Whether a redirect URI a request names is one the client's list allows. */
|
|
1401
|
+
function redirectAllowed(registered, asked) {
|
|
1402
|
+
if (registered.includes(asked)) return true;
|
|
1403
|
+
let url;
|
|
1404
|
+
try {
|
|
1405
|
+
url = new URL(asked);
|
|
1406
|
+
} catch {
|
|
1407
|
+
return false;
|
|
1408
|
+
}
|
|
1409
|
+
if (!(url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost"))) return false;
|
|
1410
|
+
return registered.some((entry) => {
|
|
1411
|
+
try {
|
|
1412
|
+
const known = new URL(entry);
|
|
1413
|
+
return known.protocol === "http:" && known.hostname === url.hostname && known.pathname === url.pathname && known.search === url.search;
|
|
1414
|
+
} catch {
|
|
1415
|
+
return false;
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
/** Whether a redirect URI may be registered at all: https, or http on a loopback name. */
|
|
1420
|
+
function redirectRegistrable(uri) {
|
|
1421
|
+
try {
|
|
1422
|
+
const url = new URL(uri);
|
|
1423
|
+
if (url.hash !== "") return false;
|
|
1424
|
+
if (url.protocol === "https:") return true;
|
|
1425
|
+
return url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost");
|
|
1426
|
+
} catch {
|
|
1427
|
+
return false;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
/** Whether a client ID names a metadata document: an https URL with a path. */
|
|
1431
|
+
function metadataClientId(clientId) {
|
|
1432
|
+
try {
|
|
1433
|
+
const url = new URL(clientId);
|
|
1434
|
+
return url.protocol === "https:" && url.pathname.length > 1 && url.hash === "" ? url : void 0;
|
|
1435
|
+
} catch {
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
/** The loopback addresses a test's metadata origin may resolve to (`MOSTRA_TEST_CIMD_ORIGIN`). */
|
|
1440
|
+
const LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "::1"]);
|
|
1441
|
+
/** Builds the clients over the directory. */
|
|
1442
|
+
function createClients(options) {
|
|
1443
|
+
const { directory, log } = options;
|
|
1444
|
+
const now = options.now ?? (() => Date.now());
|
|
1445
|
+
const fetched = /* @__PURE__ */ new Map();
|
|
1446
|
+
const testOrigin = options.env["MOSTRA_TEST_CIMD_ORIGIN"];
|
|
1447
|
+
const sweep = () => {
|
|
1448
|
+
directory.write((db) => db.run("DELETE FROM oauth_client WHERE kind = 'registered' AND COALESCE(last_used_at, created_at) < ? AND id NOT IN (SELECT client_id FROM \"grant\" WHERE revoked_at IS NULL)", (/* @__PURE__ */ new Date(now() - UNUSED_CLIENT_MS)).toISOString()));
|
|
1449
|
+
};
|
|
1450
|
+
/** Fetches a document from a checked public address, with no redirect, bounded. */
|
|
1451
|
+
const fetchDocument = (url) => new Promise((resolve, reject) => {
|
|
1452
|
+
const test = testOrigin !== void 0 && url.origin === testOrigin.replace(/^http:/, "https:");
|
|
1453
|
+
const pinned = (hostname, options, callback) => {
|
|
1454
|
+
lookup(hostname, {
|
|
1455
|
+
all: true,
|
|
1456
|
+
verbatim: true
|
|
1457
|
+
}).then((addresses) => {
|
|
1458
|
+
if (addresses.length === 0) throw new Error("no address");
|
|
1459
|
+
for (const found of addresses) if (!(test && LOOPBACK.has(found.address)) && forbiddenAddress(found.address)) throw new Error(`the name resolves to a non-public address (${found.address})`);
|
|
1460
|
+
if (options.all === true) {
|
|
1461
|
+
callback(null, addresses);
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
const chosen = addresses[0];
|
|
1465
|
+
callback(null, chosen.address, chosen.family);
|
|
1466
|
+
}).catch((error) => callback(error, "", 0));
|
|
1467
|
+
};
|
|
1468
|
+
const literal = isIP(url.hostname.replace(/^\[|\]$/g, ""));
|
|
1469
|
+
if (!test && literal !== 0 && forbiddenAddress(url.hostname.replace(/^\[|\]$/g, ""))) {
|
|
1470
|
+
reject(/* @__PURE__ */ new Error("the document's address isn't public"));
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
const target = test ? new URL(url.href.replace(/^https:/, "http:")) : url;
|
|
1474
|
+
const request$2 = (test ? request : request$1)(target, {
|
|
1475
|
+
method: "GET",
|
|
1476
|
+
headers: {
|
|
1477
|
+
accept: "application/json",
|
|
1478
|
+
"user-agent": "mostra-remote-server"
|
|
1479
|
+
},
|
|
1480
|
+
timeout: FETCH_TIMEOUT_MS,
|
|
1481
|
+
lookup: pinned
|
|
1482
|
+
}, (response) => {
|
|
1483
|
+
let size = 0;
|
|
1484
|
+
const chunks = [];
|
|
1485
|
+
response.on("data", (chunk) => {
|
|
1486
|
+
size += chunk.length;
|
|
1487
|
+
if (size > MAX_DOCUMENT_BYTES) {
|
|
1488
|
+
request$2.destroy(/* @__PURE__ */ new Error("the document is larger than 64 KiB"));
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
chunks.push(chunk);
|
|
1492
|
+
});
|
|
1493
|
+
response.on("end", () => {
|
|
1494
|
+
const cache = String(response.headers["cache-control"] ?? "");
|
|
1495
|
+
const age = /max-age=(\d+)/.exec(cache);
|
|
1496
|
+
const noStore = /no-store|no-cache/.test(cache);
|
|
1497
|
+
resolve({
|
|
1498
|
+
status: response.statusCode ?? 0,
|
|
1499
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
1500
|
+
maxAge: noStore ? 60 : Math.min(86400, Math.max(60, age ? Number(age[1]) : 300))
|
|
1501
|
+
});
|
|
1502
|
+
});
|
|
1503
|
+
response.on("error", reject);
|
|
1504
|
+
});
|
|
1505
|
+
const deadline = setTimeout(() => request$2.destroy(/* @__PURE__ */ new Error("the document took longer than 5 s")), FETCH_TIMEOUT_MS);
|
|
1506
|
+
request$2.on("close", () => clearTimeout(deadline));
|
|
1507
|
+
request$2.on("timeout", () => request$2.destroy(/* @__PURE__ */ new Error("the document took longer than 5 s")));
|
|
1508
|
+
request$2.on("error", reject);
|
|
1509
|
+
request$2.end();
|
|
1510
|
+
});
|
|
1511
|
+
const fromDocument = async (url) => {
|
|
1512
|
+
const cached = fetched.get(url.href);
|
|
1513
|
+
if (cached && cached.until > now()) return cached.client;
|
|
1514
|
+
let answer;
|
|
1515
|
+
try {
|
|
1516
|
+
answer = await fetchDocument(url);
|
|
1517
|
+
} catch (error) {
|
|
1518
|
+
log.warn("oauth.cimd_refused", {
|
|
1519
|
+
client: url.href,
|
|
1520
|
+
reason: error.message
|
|
1521
|
+
});
|
|
1522
|
+
return {
|
|
1523
|
+
error: "invalid_client",
|
|
1524
|
+
description: `The client's metadata document can't be fetched: ${error.message}.`
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
if (answer.status !== 200) return {
|
|
1528
|
+
error: "invalid_client",
|
|
1529
|
+
description: `The client's metadata document answered ${answer.status}, not 200.`
|
|
1530
|
+
};
|
|
1531
|
+
let document;
|
|
1532
|
+
try {
|
|
1533
|
+
document = JSON.parse(answer.body);
|
|
1534
|
+
} catch {
|
|
1535
|
+
return {
|
|
1536
|
+
error: "invalid_client",
|
|
1537
|
+
description: "The client's metadata document isn't JSON."
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
if (document.client_id !== url.href) return {
|
|
1541
|
+
error: "invalid_client",
|
|
1542
|
+
description: "The metadata document's client_id isn't its own URL."
|
|
1543
|
+
};
|
|
1544
|
+
const redirects = Array.isArray(document.redirect_uris) ? document.redirect_uris.filter((uri) => typeof uri === "string" && redirectRegistrable(uri)) : [];
|
|
1545
|
+
if (redirects.length === 0) return {
|
|
1546
|
+
error: "invalid_client",
|
|
1547
|
+
description: "The metadata document names no usable redirect_uris."
|
|
1548
|
+
};
|
|
1549
|
+
const client = {
|
|
1550
|
+
id: url.href,
|
|
1551
|
+
kind: "metadata",
|
|
1552
|
+
name: typeof document.client_name === "string" && document.client_name.trim() !== "" ? document.client_name.trim().slice(0, 128) : url.hostname,
|
|
1553
|
+
redirectUris: redirects,
|
|
1554
|
+
unverified: true
|
|
1555
|
+
};
|
|
1556
|
+
fetched.set(url.href, {
|
|
1557
|
+
client,
|
|
1558
|
+
until: now() + answer.maxAge * 1e3
|
|
1559
|
+
});
|
|
1560
|
+
if (fetched.size > 1e3) fetched.delete(fetched.keys().next().value);
|
|
1561
|
+
directory.write((db) => db.run(`INSERT INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'metadata', ?, ?)
|
|
1562
|
+
ON CONFLICT (id) DO UPDATE SET metadata_json = excluded.metadata_json`, client.id, JSON.stringify({
|
|
1563
|
+
client_name: client.name,
|
|
1564
|
+
redirect_uris: client.redirectUris
|
|
1565
|
+
}), new Date(now()).toISOString()));
|
|
1566
|
+
return client;
|
|
1567
|
+
};
|
|
1568
|
+
const shellClientId = (shellOrigin) => `${shellOrigin}/_mostra/signin`;
|
|
1569
|
+
return {
|
|
1570
|
+
shellClientId,
|
|
1571
|
+
async find(clientId) {
|
|
1572
|
+
if (clientId === "mostra-cli") return {
|
|
1573
|
+
id: clientId,
|
|
1574
|
+
kind: "cli",
|
|
1575
|
+
name: "Mostra CLI",
|
|
1576
|
+
redirectUris: [],
|
|
1577
|
+
unverified: false
|
|
1578
|
+
};
|
|
1579
|
+
const origin = clientId.endsWith("/_mostra/signin") ? clientId.slice(0, -15) : void 0;
|
|
1580
|
+
if (origin !== void 0 && options.isShellOrigin(origin)) {
|
|
1581
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'shell', ?, ?)", clientId, JSON.stringify({ client_name: "Mostra" }), new Date(now()).toISOString()));
|
|
1582
|
+
return {
|
|
1583
|
+
id: clientId,
|
|
1584
|
+
kind: "shell",
|
|
1585
|
+
name: "Mostra",
|
|
1586
|
+
redirectUris: [`${origin}/_mostra/signin`],
|
|
1587
|
+
unverified: false
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
const url = metadataClientId(clientId);
|
|
1591
|
+
if (url) return fromDocument(url);
|
|
1592
|
+
const row = directory.read((db) => db.get("SELECT metadata_json FROM oauth_client WHERE id = ? AND kind = 'registered'", clientId));
|
|
1593
|
+
if (!row) return {
|
|
1594
|
+
error: "invalid_client",
|
|
1595
|
+
description: "Unknown client."
|
|
1596
|
+
};
|
|
1597
|
+
const metadata = JSON.parse(row.metadata_json);
|
|
1598
|
+
return {
|
|
1599
|
+
id: clientId,
|
|
1600
|
+
kind: "registered",
|
|
1601
|
+
name: metadata.client_name ?? "An unnamed client",
|
|
1602
|
+
redirectUris: metadata.redirect_uris,
|
|
1603
|
+
unverified: true
|
|
1604
|
+
};
|
|
1605
|
+
},
|
|
1606
|
+
register(metadata) {
|
|
1607
|
+
sweep();
|
|
1608
|
+
const body = typeof metadata === "object" && metadata !== null ? metadata : {};
|
|
1609
|
+
const redirects = Array.isArray(body.redirect_uris) ? body.redirect_uris.filter((uri) => typeof uri === "string") : [];
|
|
1610
|
+
if (redirects.length === 0 || redirects.length > 10 || !redirects.every(redirectRegistrable)) return {
|
|
1611
|
+
error: "invalid_redirect_uri",
|
|
1612
|
+
description: "redirect_uris must list https: addresses, or http: on 127.0.0.1, [::1] or localhost."
|
|
1613
|
+
};
|
|
1614
|
+
if (body.token_endpoint_auth_method !== void 0 && body.token_endpoint_auth_method !== "none") return {
|
|
1615
|
+
error: "invalid_client_metadata",
|
|
1616
|
+
description: "This server registers public clients only (token_endpoint_auth_method none)."
|
|
1617
|
+
};
|
|
1618
|
+
const name = typeof body.client_name === "string" ? body.client_name.trim().slice(0, 128) : void 0;
|
|
1619
|
+
const id = `mcl_${randomBytes(16).toString("hex")}`;
|
|
1620
|
+
const at = new Date(now());
|
|
1621
|
+
directory.write((db) => db.run("INSERT INTO oauth_client (id, kind, metadata_json, created_at, last_used_at) VALUES (?, 'registered', ?, ?, ?)", id, JSON.stringify({
|
|
1622
|
+
client_name: name,
|
|
1623
|
+
redirect_uris: redirects
|
|
1624
|
+
}), at.toISOString(), at.toISOString()));
|
|
1625
|
+
log.info("oauth.client_registered", { client: id });
|
|
1626
|
+
return {
|
|
1627
|
+
client_id: id,
|
|
1628
|
+
client_id_issued_at: Math.floor(at.getTime() / 1e3),
|
|
1629
|
+
...name !== void 0 ? { client_name: name } : {},
|
|
1630
|
+
redirect_uris: redirects,
|
|
1631
|
+
token_endpoint_auth_method: "none",
|
|
1632
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
1633
|
+
response_types: ["code"]
|
|
1634
|
+
};
|
|
1635
|
+
},
|
|
1636
|
+
used(clientId) {
|
|
1637
|
+
directory.write((db) => db.run("UPDATE oauth_client SET last_used_at = ? WHERE id = ?", new Date(now()).toISOString(), clientId));
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
}
|
|
1641
|
+
//#endregion
|
|
1642
|
+
//#region src/server/authorize.ts
|
|
1643
|
+
/**
|
|
1644
|
+
* The authorization server's pages on the API origin (INTERFACES §18.5, D165 items 8, 10):
|
|
1645
|
+
*
|
|
1646
|
+
* - `GET /oauth/authorize`: the authorization code flow with PKCE (S256) for MCP clients (Client
|
|
1647
|
+
* ID Metadata Documents, registered clients) and for each hosted shell's viewer sign-in. The
|
|
1648
|
+
* client and its redirect URI are checked before anything is redirected anywhere; an `iss`
|
|
1649
|
+
* parameter goes with every answer (RFC 9207).
|
|
1650
|
+
* - Sign-in through an identity provider (`/signin/<id>/start`, its `callback`), into a browser
|
|
1651
|
+
* session on the API origin only, never the user-content domain; the operator's first sign-in
|
|
1652
|
+
* steps (`/signin/return`).
|
|
1653
|
+
* - The server's own consent page (`/oauth/consent`), for every client an account hasn't
|
|
1654
|
+
* approved, never skipped because a provider skipped its own; for a page's sign-in it names
|
|
1655
|
+
* the page's sender instead, once per account and home.
|
|
1656
|
+
*
|
|
1657
|
+
* Every in-progress record (an authorization request, a provider sign-in, a first sign-in step)
|
|
1658
|
+
* is kept only as the SHA-256 of its handle, lives minutes, is used once, and is bound to the
|
|
1659
|
+
* browser that started it by a cookie of the API origin.
|
|
1660
|
+
*/
|
|
1661
|
+
/** How long an authorization request, a provider sign-in or a step waits. */
|
|
1662
|
+
const PENDING_MS = 9e5;
|
|
1663
|
+
/** How long a browser stays signed in to the API origin. */
|
|
1664
|
+
const SESSION_MS = 6048e5;
|
|
1665
|
+
/** At most this many first sign-in steps per sign-in (D167). */
|
|
1666
|
+
const MAX_STEPS = 3;
|
|
1667
|
+
/**
|
|
1668
|
+
* How long an identity provider's own calls may take (its authorization address, the code's
|
|
1669
|
+
* exchange): inside the 10 s every endpoint of the authorization server answers in (D165 item 10),
|
|
1670
|
+
* whether the provider is built in or the operator's.
|
|
1671
|
+
*/
|
|
1672
|
+
const PROVIDER_MS = 8e3;
|
|
1673
|
+
/** A provider's call, or a refusal once it took longer than {@link PROVIDER_MS}. */
|
|
1674
|
+
async function bounded(call, what) {
|
|
1675
|
+
let timer;
|
|
1676
|
+
try {
|
|
1677
|
+
return await Promise.race([Promise.resolve().then(call), new Promise((_, reject) => {
|
|
1678
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} took too long`)), PROVIDER_MS);
|
|
1679
|
+
})]);
|
|
1680
|
+
} finally {
|
|
1681
|
+
clearTimeout(timer);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
const BASE = {
|
|
1685
|
+
"cache-control": "no-store",
|
|
1686
|
+
"cross-origin-resource-policy": "same-origin",
|
|
1687
|
+
"x-content-type-options": "nosniff",
|
|
1688
|
+
"x-frame-options": "DENY"
|
|
1689
|
+
};
|
|
1690
|
+
function escapeHtml(text) {
|
|
1691
|
+
return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
1692
|
+
}
|
|
1693
|
+
function shell(title, body) {
|
|
1694
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
|
|
1695
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
|
|
1696
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
1697
|
+
input{font:inherit;padding:.3rem}button,a.button{font:inherit;padding:.4rem .9rem;margin:.2rem .5rem .2rem 0;display:inline-block}
|
|
1698
|
+
.muted{color:#555}</style></head><body><h1>${escapeHtml(title)}</h1>${body}</body></html>`;
|
|
1699
|
+
}
|
|
1700
|
+
/** Builds the pages. */
|
|
1701
|
+
function createAuthorize(options) {
|
|
1702
|
+
const { apiOrigin, directory, auth, clients, operator, log } = options;
|
|
1703
|
+
const now = options.now ?? (() => Date.now());
|
|
1704
|
+
const secure = apiOrigin.startsWith("https:");
|
|
1705
|
+
const sessionCookie = secure ? "__Host-mostra-signin" : "mostra-signin";
|
|
1706
|
+
const flowCookie = secure ? "__Host-mostra-flow" : "mostra-flow";
|
|
1707
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
1708
|
+
const token = () => randomBytes(32).toString("base64url");
|
|
1709
|
+
const cookies = (request) => {
|
|
1710
|
+
const found = /* @__PURE__ */ new Map();
|
|
1711
|
+
for (const part of (request.headers.cookie ?? "").split(";")) {
|
|
1712
|
+
const at = part.indexOf("=");
|
|
1713
|
+
if (at <= 0) continue;
|
|
1714
|
+
const name = part.slice(0, at).trim();
|
|
1715
|
+
if (!found.has(name)) found.set(name, part.slice(at + 1).trim());
|
|
1716
|
+
}
|
|
1717
|
+
return found;
|
|
1718
|
+
};
|
|
1719
|
+
const setCookie = (name, value, maxAgeS) => `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}${secure ? "; Secure" : ""}`;
|
|
1720
|
+
const send = (response, status, html, extra = {}, formTargets = []) => {
|
|
1721
|
+
response.writeHead(status, {
|
|
1722
|
+
...BASE,
|
|
1723
|
+
"content-type": "text/html; charset=utf-8",
|
|
1724
|
+
"content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${formTargets.join(" ")}; frame-ancestors 'none'; base-uri 'none'`,
|
|
1725
|
+
"referrer-policy": "same-origin",
|
|
1726
|
+
...extra
|
|
1727
|
+
});
|
|
1728
|
+
response.end(html);
|
|
1729
|
+
};
|
|
1730
|
+
const redirect = (response, location, extra = {}) => {
|
|
1731
|
+
response.writeHead(303, {
|
|
1732
|
+
...BASE,
|
|
1733
|
+
location,
|
|
1734
|
+
"referrer-policy": "no-referrer",
|
|
1735
|
+
...extra
|
|
1736
|
+
});
|
|
1737
|
+
response.end();
|
|
1738
|
+
};
|
|
1739
|
+
const problem = (response, status, message) => send(response, status, shell("Sign-in can't continue", `<p role="alert">${escapeHtml(message)}</p>`));
|
|
1740
|
+
const keep = (kind, handle, data) => directory.write((db) => {
|
|
1741
|
+
db.run("DELETE FROM signin WHERE expires_at < ?", iso(now()));
|
|
1742
|
+
db.run("INSERT INTO signin (hash, kind, data_json, expires_at) VALUES (?, ?, ?, ?)", hashSecret(handle), kind, JSON.stringify(data), iso(now() + PENDING_MS));
|
|
1743
|
+
});
|
|
1744
|
+
const read = (kind, handle) => directory.read((db) => {
|
|
1745
|
+
const row = db.get("SELECT data_json, expires_at FROM signin WHERE hash = ? AND kind = ?", hashSecret(handle), kind);
|
|
1746
|
+
return row && Date.parse(row.expires_at) > now() ? JSON.parse(row.data_json) : void 0;
|
|
1747
|
+
});
|
|
1748
|
+
const spend = (handle) => directory.write((db) => db.run("DELETE FROM signin WHERE hash = ?", hashSecret(handle)).changes > 0);
|
|
1749
|
+
const sessionAccount = (request) => {
|
|
1750
|
+
const value = cookies(request).get(sessionCookie);
|
|
1751
|
+
if (value === void 0 || !/^[A-Za-z0-9_-]{43}$/.test(value)) return void 0;
|
|
1752
|
+
const hash = hashSecret(value);
|
|
1753
|
+
const row = directory.read((db) => db.get(`SELECT s.account_id, s.expires_at, a.status FROM browser_session s
|
|
1754
|
+
JOIN account a ON a.id = s.account_id WHERE s.hash = ?`, hash));
|
|
1755
|
+
if (!row || Date.parse(row.expires_at) <= now() || row.status !== "active") return void 0;
|
|
1756
|
+
return {
|
|
1757
|
+
accountId: row.account_id,
|
|
1758
|
+
hash
|
|
1759
|
+
};
|
|
1760
|
+
};
|
|
1761
|
+
const startSession = (accountId) => {
|
|
1762
|
+
const value = token();
|
|
1763
|
+
directory.write((db) => db.run("INSERT INTO browser_session (hash, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)", hashSecret(value), accountId, iso(now()), iso(now() + SESSION_MS)));
|
|
1764
|
+
return setCookie(sessionCookie, value, Math.floor(SESSION_MS / 1e3));
|
|
1765
|
+
};
|
|
1766
|
+
const csrf = (sessionHash, purpose) => createHash("sha256").update(`mostra csrf ${sessionHash} ${purpose}`).digest("base64url");
|
|
1767
|
+
/** The providers now: configured ones, then the operator's (asked each time, D167). */
|
|
1768
|
+
const providers = async () => {
|
|
1769
|
+
const supplied = await operator.providers();
|
|
1770
|
+
const ids = new Set(options.providers.map((provider) => provider.id));
|
|
1771
|
+
return [...options.providers, ...supplied.filter((provider) => !ids.has(provider.id))];
|
|
1772
|
+
};
|
|
1773
|
+
/** The page listing the providers; each starts a sign-in that returns to `next`. */
|
|
1774
|
+
const signInPage = async (response, next, message) => {
|
|
1775
|
+
const links = (await providers()).map((provider) => `<p><a class="button" href="/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}">Continue with ${escapeHtml(provider.label)}</a></p>`).join("");
|
|
1776
|
+
send(response, 200, shell("Sign in to Mostra", `${message ? `<p role="alert">${escapeHtml(message)}</p>` : ""}${links || "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"}`));
|
|
1777
|
+
};
|
|
1778
|
+
/** Where a finished sign-in continues: an address of the API origin only. */
|
|
1779
|
+
const safeNext = (next) => next?.startsWith("/") && !next.startsWith("//") ? next : "/";
|
|
1780
|
+
/** A resolved identity: a session and on to `next`, a step, or why not. */
|
|
1781
|
+
const resolved = async (response, identity, steps, flow, next) => {
|
|
1782
|
+
const account = await auth.resolveAccount(identity, steps);
|
|
1783
|
+
if (account.kind === "unavailable") {
|
|
1784
|
+
problem(response, 503, "Sign-in is unavailable for a moment; try again shortly.");
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
if (account.kind === "refused") {
|
|
1788
|
+
problem(response, 403, account.message);
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
if (account.kind === "suspended") {
|
|
1792
|
+
problem(response, 403, "This account is suspended.");
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
if (account.kind === "step") {
|
|
1796
|
+
if (steps >= MAX_STEPS) {
|
|
1797
|
+
problem(response, 403, "Sign-in asked for too many steps; try again later.");
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
const handle = token();
|
|
1801
|
+
keep("step", handle, {
|
|
1802
|
+
identity,
|
|
1803
|
+
steps: steps + 1,
|
|
1804
|
+
flow,
|
|
1805
|
+
next
|
|
1806
|
+
});
|
|
1807
|
+
const url = new URL(account.url);
|
|
1808
|
+
url.searchParams.set("mostra_return", `${apiOrigin}/signin/return?step=${handle}`);
|
|
1809
|
+
redirect(response, url.href);
|
|
1810
|
+
return;
|
|
1811
|
+
}
|
|
1812
|
+
log.info("signin.done", { provider: identity.provider });
|
|
1813
|
+
redirect(response, `${apiOrigin}${safeNext(next)}`, { "set-cookie": [startSession(account.accountId), setCookie(flowCookie, "", 0)] });
|
|
1814
|
+
};
|
|
1815
|
+
/** The answer to a client's redirect URI, with `iss` (RFC 9207). */
|
|
1816
|
+
const toClient = (response, redirectUri, params) => {
|
|
1817
|
+
const url = new URL(redirectUri);
|
|
1818
|
+
for (const [key, value] of Object.entries(params)) if (value !== null) url.searchParams.set(key, value);
|
|
1819
|
+
url.searchParams.set("iss", apiOrigin);
|
|
1820
|
+
redirect(response, url.href);
|
|
1821
|
+
};
|
|
1822
|
+
/** Consent, or the code: a signed-in account continuing an authorization request. */
|
|
1823
|
+
const proceed = async (request, response, handle, signed) => {
|
|
1824
|
+
const pending = read("authorize", handle);
|
|
1825
|
+
if (!pending) {
|
|
1826
|
+
problem(response, 400, "This sign-in expired or was already used; start again from the app.");
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
const client = await clients.find(pending.clientId);
|
|
1830
|
+
if ("error" in client) {
|
|
1831
|
+
problem(response, 400, client.description);
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
const homeId = (pending.viewerSignin !== void 0 ? read("authorize", pending.viewerSignin) : void 0)?.homeId;
|
|
1835
|
+
if ((client.kind === "shell" ? homeId !== void 0 && !senderShown(signed.accountId, homeId) : !auth.consented(signed.accountId, client.id)) && request.method !== "POST") {
|
|
1836
|
+
consentPage(response, pending, client, handle, signed, homeId);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
if (request.method === "POST") {
|
|
1840
|
+
const form = await readForm(request);
|
|
1841
|
+
if (request.headers.origin !== apiOrigin || !form || form.get("csrf") !== csrf(signed.hash, `consent ${handle}`)) {
|
|
1842
|
+
problem(response, 403, "This form must be sent from its own page.");
|
|
1843
|
+
return;
|
|
1844
|
+
}
|
|
1845
|
+
if (form.get("decision") !== "approve") {
|
|
1846
|
+
spend(handle);
|
|
1847
|
+
toClient(response, pending.redirectUri, {
|
|
1848
|
+
error: "access_denied",
|
|
1849
|
+
state: pending.state
|
|
1850
|
+
});
|
|
1851
|
+
return;
|
|
1852
|
+
}
|
|
1853
|
+
if (client.kind === "shell" && homeId !== void 0) markSenderShown(signed.accountId, homeId);
|
|
1854
|
+
else auth.consent(signed.accountId, client.id);
|
|
1855
|
+
}
|
|
1856
|
+
if (!spend(handle)) {
|
|
1857
|
+
problem(response, 400, "This sign-in was already used.");
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
clients.used(client.id);
|
|
1861
|
+
const code = auth.issueCode({
|
|
1862
|
+
clientId: client.id,
|
|
1863
|
+
redirectUri: pending.redirectUri,
|
|
1864
|
+
challenge: pending.challenge,
|
|
1865
|
+
resource: pending.resource,
|
|
1866
|
+
scope: pending.scope,
|
|
1867
|
+
accountId: signed.accountId,
|
|
1868
|
+
redirectGiven: pending.redirectGiven !== false,
|
|
1869
|
+
...pending.viewerSignin !== void 0 ? { viewerSignin: hashSecret(pending.viewerSignin) } : {}
|
|
1870
|
+
});
|
|
1871
|
+
log.info("oauth.code_issued", { client: client.id });
|
|
1872
|
+
toClient(response, pending.redirectUri, {
|
|
1873
|
+
code,
|
|
1874
|
+
state: pending.state
|
|
1875
|
+
});
|
|
1876
|
+
};
|
|
1877
|
+
const senderShown = (accountId, homeId) => directory.read((db) => db.get("SELECT 1 FROM sender_shown WHERE account_id = ? AND home_id = ?", accountId, homeId) !== void 0);
|
|
1878
|
+
const markSenderShown = (accountId, homeId) => {
|
|
1879
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO sender_shown (account_id, home_id, at) VALUES (?, ?, ?)", accountId, homeId, iso(now())));
|
|
1880
|
+
};
|
|
1881
|
+
const consentPage = (response, pending, client, handle, signed, homeId) => {
|
|
1882
|
+
const who = auth.accountName(signed.accountId).name ?? "your account";
|
|
1883
|
+
const redirectHost = new URL(pending.redirectUri).host;
|
|
1884
|
+
const loopback = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/.test(redirectHost);
|
|
1885
|
+
const body = client.kind === "shell" ? `<p>Continue as <strong>${escapeHtml(who)}</strong> to answer <strong>${escapeHtml((homeId !== void 0 ? options.ownerName(homeId) : void 0) ?? "this person")}</strong>'s page? They will see your name with your answers.</p>` : `<p><strong>${escapeHtml(client.name)}</strong>${client.unverified ? " <span class=\"muted\">(a name the app gives itself, not checked)</span>" : ""} asks to use Mostra as <strong>${escapeHtml(who)}</strong>: to read, create and change your hosted pages and their answers.</p>
|
|
1886
|
+
<p>It will send you back to <strong>${escapeHtml(redirectHost)}</strong>.${loopback ? " That is a program on your own computer: continue only if you started this there." : ""}</p>`;
|
|
1887
|
+
send(response, 200, shell(client.kind === "shell" ? "Answer as yourself" : "Allow access", `${body}<form method="post" action="/oauth/authorize/continue?authorize=${encodeURIComponent(handle)}">
|
|
1888
|
+
<input type="hidden" name="csrf" value="${csrf(signed.hash, `consent ${handle}`)}">
|
|
1889
|
+
<button name="decision" value="approve">${client.kind === "shell" ? "Continue" : "Allow"}</button>
|
|
1890
|
+
<button name="decision" value="deny">Cancel</button></form>`), {}, [new URL(pending.redirectUri).origin]);
|
|
1891
|
+
};
|
|
1892
|
+
const readForm = async (request) => {
|
|
1893
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) return;
|
|
1894
|
+
const chunks = [];
|
|
1895
|
+
let size = 0;
|
|
1896
|
+
for await (const chunk of request) {
|
|
1897
|
+
size += chunk.length;
|
|
1898
|
+
if (size > 16384) return void 0;
|
|
1899
|
+
chunks.push(chunk);
|
|
1900
|
+
}
|
|
1901
|
+
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
1902
|
+
};
|
|
1903
|
+
/** `GET /oauth/authorize`. */
|
|
1904
|
+
const authorize = async (response, query, request) => {
|
|
1905
|
+
for (const key of new Set(query.keys())) if (query.getAll(key).length > 1) {
|
|
1906
|
+
problem(response, 400, `The request names ${key} twice.`);
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
const clientId = query.get("client_id") ?? "";
|
|
1910
|
+
const client = await clients.find(clientId);
|
|
1911
|
+
if ("error" in client) {
|
|
1912
|
+
problem(response, 400, client.description);
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
const redirectUri = query.get("redirect_uri") ?? (client.redirectUris.length === 1 ? client.redirectUris[0] : "");
|
|
1916
|
+
if (!redirectAllowed(client.redirectUris, redirectUri)) {
|
|
1917
|
+
problem(response, 400, "The redirect address isn't one this app registered.");
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
const state = query.get("state");
|
|
1921
|
+
const fail = (error, description) => toClient(response, redirectUri, {
|
|
1922
|
+
error,
|
|
1923
|
+
error_description: description,
|
|
1924
|
+
state
|
|
1925
|
+
});
|
|
1926
|
+
if (query.get("response_type") !== "code") return fail("unsupported_response_type", "Only code.");
|
|
1927
|
+
const challenge = query.get("code_challenge") ?? "";
|
|
1928
|
+
if (query.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) return fail("invalid_request", "PKCE with S256 is required.");
|
|
1929
|
+
if (client.kind === "cli") return fail("unauthorized_client", "The CLI uses the device grant.");
|
|
1930
|
+
const scopes = (query.get("scope") ?? "mostra").split(" ").filter((part) => part !== "");
|
|
1931
|
+
if (!scopes.every((part) => part === "mostra" || part === "offline_access")) return fail("invalid_scope", "The scopes are mostra and offline_access.");
|
|
1932
|
+
const scope = ["mostra", ...scopes.includes("offline_access") ? ["offline_access"] : []].join(" ");
|
|
1933
|
+
let resource = "";
|
|
1934
|
+
let viewerSignin;
|
|
1935
|
+
if (client.kind === "shell") {
|
|
1936
|
+
viewerSignin = query.get("mostra_signin") ?? "";
|
|
1937
|
+
const started = read("authorize", viewerSignin);
|
|
1938
|
+
if (!started || started.clientId !== client.id || state !== viewerSignin) return fail("invalid_request", "This page sign-in wasn't started from its page.");
|
|
1939
|
+
resource = `${apiOrigin}/viewer`;
|
|
1940
|
+
} else {
|
|
1941
|
+
resource = canonicalResource(query.get("resource") ?? `${apiOrigin}/mcp`);
|
|
1942
|
+
if (resource !== `${apiOrigin}/mcp`) return fail("invalid_target", `The resource is ${apiOrigin}/mcp.`);
|
|
1943
|
+
}
|
|
1944
|
+
const handle = token();
|
|
1945
|
+
keep("authorize", handle, {
|
|
1946
|
+
clientId: client.id,
|
|
1947
|
+
redirectUri,
|
|
1948
|
+
state,
|
|
1949
|
+
challenge,
|
|
1950
|
+
resource,
|
|
1951
|
+
scope,
|
|
1952
|
+
...viewerSignin !== void 0 ? { viewerSignin } : {},
|
|
1953
|
+
redirectGiven: query.get("redirect_uri") !== null
|
|
1954
|
+
});
|
|
1955
|
+
const signed = sessionAccount(request);
|
|
1956
|
+
if (signed) {
|
|
1957
|
+
await proceed(request, response, handle, signed);
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);
|
|
1961
|
+
};
|
|
1962
|
+
return {
|
|
1963
|
+
sessionAccount,
|
|
1964
|
+
csrf,
|
|
1965
|
+
signInPage,
|
|
1966
|
+
providers: async () => (await providers()).map((provider) => ({
|
|
1967
|
+
id: provider.id,
|
|
1968
|
+
label: provider.label
|
|
1969
|
+
})),
|
|
1970
|
+
startViewerSignin(signin, challenge) {
|
|
1971
|
+
const state = token();
|
|
1972
|
+
const clientId = clients.shellClientId(signin.shellOrigin);
|
|
1973
|
+
keep("authorize", state, {
|
|
1974
|
+
...signin,
|
|
1975
|
+
clientId
|
|
1976
|
+
});
|
|
1977
|
+
const url = new URL(`${apiOrigin}/oauth/authorize`);
|
|
1978
|
+
url.searchParams.set("response_type", "code");
|
|
1979
|
+
url.searchParams.set("client_id", clientId);
|
|
1980
|
+
url.searchParams.set("redirect_uri", `${signin.shellOrigin}/_mostra/signin`);
|
|
1981
|
+
url.searchParams.set("state", state);
|
|
1982
|
+
url.searchParams.set("mostra_signin", state);
|
|
1983
|
+
url.searchParams.set("code_challenge", challenge);
|
|
1984
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
1985
|
+
return {
|
|
1986
|
+
url: url.href,
|
|
1987
|
+
state
|
|
1988
|
+
};
|
|
1989
|
+
},
|
|
1990
|
+
finishViewerSignin(input) {
|
|
1991
|
+
const started = read("authorize", input.state);
|
|
1992
|
+
if (!started || started.routeId !== input.routeId || started.sessionId !== input.sessionId) return { refused: "This sign-in was started for another page." };
|
|
1993
|
+
const redeemed = auth.redeemViewerCode({
|
|
1994
|
+
code: input.code,
|
|
1995
|
+
verifier: input.verifier,
|
|
1996
|
+
clientId: started.clientId,
|
|
1997
|
+
viewerSignin: hashSecret(input.state)
|
|
1998
|
+
});
|
|
1999
|
+
spend(input.state);
|
|
2000
|
+
if ("refused" in redeemed) return redeemed;
|
|
2001
|
+
const named = auth.accountName(redeemed.accountId);
|
|
2002
|
+
return {
|
|
2003
|
+
accountId: redeemed.accountId,
|
|
2004
|
+
...named.name !== void 0 ? { name: named.name } : {},
|
|
2005
|
+
...named.provider !== void 0 ? { provider: named.provider } : {}
|
|
2006
|
+
};
|
|
2007
|
+
},
|
|
2008
|
+
async handle(request, response, path) {
|
|
2009
|
+
const method = request.method ?? "GET";
|
|
2010
|
+
const url = new URL(request.url ?? "/", apiOrigin);
|
|
2011
|
+
if (method === "GET" && path === "/oauth/authorize") {
|
|
2012
|
+
await authorize(response, url.searchParams, request);
|
|
2013
|
+
return true;
|
|
2014
|
+
}
|
|
2015
|
+
if (path === "/oauth/authorize/continue" && (method === "GET" || method === "POST")) {
|
|
2016
|
+
const handle = url.searchParams.get("authorize") ?? "";
|
|
2017
|
+
const signed = sessionAccount(request);
|
|
2018
|
+
if (!signed) {
|
|
2019
|
+
await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);
|
|
2020
|
+
return true;
|
|
2021
|
+
}
|
|
2022
|
+
await proceed(request, response, handle, signed);
|
|
2023
|
+
return true;
|
|
2024
|
+
}
|
|
2025
|
+
const start = /^\/signin\/([a-z][a-z0-9-]{0,31})\/start$/.exec(path);
|
|
2026
|
+
if (method === "GET" && start) {
|
|
2027
|
+
const provider = (await providers()).find((candidate) => candidate.id === start[1]);
|
|
2028
|
+
if (!provider) {
|
|
2029
|
+
problem(response, 404, "No such sign-in.");
|
|
2030
|
+
return true;
|
|
2031
|
+
}
|
|
2032
|
+
const state = token();
|
|
2033
|
+
const verifier = token();
|
|
2034
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
2035
|
+
const nonce = token();
|
|
2036
|
+
const flow = token();
|
|
2037
|
+
keep("provider", state, {
|
|
2038
|
+
provider: provider.id,
|
|
2039
|
+
verifier,
|
|
2040
|
+
challenge,
|
|
2041
|
+
nonce,
|
|
2042
|
+
flow: hashSecret(flow),
|
|
2043
|
+
next: safeNext(url.searchParams.get("next"))
|
|
2044
|
+
});
|
|
2045
|
+
let target;
|
|
2046
|
+
try {
|
|
2047
|
+
target = await bounded(() => provider.authorize(state, {
|
|
2048
|
+
challenge,
|
|
2049
|
+
method: "S256",
|
|
2050
|
+
verifier
|
|
2051
|
+
}, {
|
|
2052
|
+
redirectUri: `${apiOrigin}/signin/${provider.id}/callback`,
|
|
2053
|
+
nonce
|
|
2054
|
+
}), "the provider's sign-in address");
|
|
2055
|
+
const parsed = new URL(target, apiOrigin);
|
|
2056
|
+
if (parsed.protocol !== "https:" && (secure || parsed.protocol !== "http:")) throw new Error("the provider's sign-in address isn't https:");
|
|
2057
|
+
target = parsed.href;
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
log.warn("signin.provider_failed", {
|
|
2060
|
+
provider: provider.id,
|
|
2061
|
+
message: error.message
|
|
2062
|
+
});
|
|
2063
|
+
problem(response, 503, `${provider.label} can't be reached right now; try again shortly.`);
|
|
2064
|
+
return true;
|
|
2065
|
+
}
|
|
2066
|
+
redirect(response, target, { "set-cookie": setCookie(flowCookie, flow, Math.floor(PENDING_MS / 1e3)) });
|
|
2067
|
+
return true;
|
|
2068
|
+
}
|
|
2069
|
+
const name = /^\/signin\/([a-z][a-z0-9-]{0,31})\/name$/.exec(path);
|
|
2070
|
+
const callback = /^\/signin\/([a-z][a-z0-9-]{0,31})\/callback$/.exec(path);
|
|
2071
|
+
if (method === "GET" && callback || name && (method === "GET" || method === "POST")) {
|
|
2072
|
+
const id = (callback ?? name)?.[1];
|
|
2073
|
+
const provider = (await providers()).find((candidate) => candidate.id === id);
|
|
2074
|
+
if (!provider) {
|
|
2075
|
+
problem(response, 404, "No such sign-in.");
|
|
2076
|
+
return true;
|
|
2077
|
+
}
|
|
2078
|
+
if (name && method === "GET") {
|
|
2079
|
+
const state = url.searchParams.get("state") ?? "";
|
|
2080
|
+
send(response, 200, shell("Development sign-in", `<p class="muted">This server signs people in with a development provider, which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
|
|
2081
|
+
<form method="post" action="/signin/${escapeHtml(id)}/name"><input type="hidden" name="state" value="${escapeHtml(state)}">
|
|
2082
|
+
<label>Your name <input name="name" required maxlength="64"></label> <button>Continue</button></form>`));
|
|
2083
|
+
return true;
|
|
2084
|
+
}
|
|
2085
|
+
let params;
|
|
2086
|
+
if (name) {
|
|
2087
|
+
const form = await readForm(request);
|
|
2088
|
+
if (request.headers.origin !== apiOrigin || !form) {
|
|
2089
|
+
problem(response, 403, "This form must be sent from its own page.");
|
|
2090
|
+
return true;
|
|
2091
|
+
}
|
|
2092
|
+
params = Object.fromEntries(form.entries());
|
|
2093
|
+
} else {
|
|
2094
|
+
params = {};
|
|
2095
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
2096
|
+
if (url.searchParams.getAll(key).length > 1) {
|
|
2097
|
+
problem(response, 400, `The provider's answer names ${key} twice.`);
|
|
2098
|
+
return true;
|
|
2099
|
+
}
|
|
2100
|
+
params[key] = url.searchParams.get(key);
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
const state = params["state"] ?? "";
|
|
2104
|
+
const pending = read("provider", state);
|
|
2105
|
+
const flow = cookies(request).get(flowCookie);
|
|
2106
|
+
if (!pending || pending.provider !== provider.id || flow === void 0 || hashSecret(flow) !== pending.flow || !spend(state)) {
|
|
2107
|
+
problem(response, 400, "This sign-in expired, was used, or was started in another browser.");
|
|
2108
|
+
return true;
|
|
2109
|
+
}
|
|
2110
|
+
let identity;
|
|
2111
|
+
try {
|
|
2112
|
+
const answered = await bounded(() => provider.callback(params, {
|
|
2113
|
+
redirectUri: `${apiOrigin}/signin/${provider.id}/callback`,
|
|
2114
|
+
nonce: pending.nonce,
|
|
2115
|
+
state,
|
|
2116
|
+
pkce: {
|
|
2117
|
+
challenge: pending.challenge,
|
|
2118
|
+
method: "S256",
|
|
2119
|
+
verifier: pending.verifier
|
|
2120
|
+
}
|
|
2121
|
+
}), "the provider's answer");
|
|
2122
|
+
const checked = SignInIdentity.safeParse({
|
|
2123
|
+
...answered,
|
|
2124
|
+
provider: provider.id
|
|
2125
|
+
});
|
|
2126
|
+
if (!checked.success) throw new Error("the provider named nobody this server can use");
|
|
2127
|
+
identity = checked.data;
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
log.warn("signin.callback_failed", {
|
|
2130
|
+
provider: provider.id,
|
|
2131
|
+
message: error.message
|
|
2132
|
+
});
|
|
2133
|
+
problem(response, 400, `${provider.label} didn't sign you in: ${error.message}`);
|
|
2134
|
+
return true;
|
|
2135
|
+
}
|
|
2136
|
+
await resolved(response, identity, 0, pending.flow, pending.next);
|
|
2137
|
+
return true;
|
|
2138
|
+
}
|
|
2139
|
+
if (method === "GET" && path === "/signin/return") {
|
|
2140
|
+
const handle = url.searchParams.get("step") ?? "";
|
|
2141
|
+
const step = read("step", handle);
|
|
2142
|
+
const flow = cookies(request).get(flowCookie);
|
|
2143
|
+
if (!step || flow === void 0 || hashSecret(flow) !== step.flow || !spend(handle)) {
|
|
2144
|
+
problem(response, 400, "This sign-in step expired, was used, or belongs to another browser.");
|
|
2145
|
+
return true;
|
|
2146
|
+
}
|
|
2147
|
+
await resolved(response, step.identity, step.steps, step.flow, step.next);
|
|
2148
|
+
return true;
|
|
2149
|
+
}
|
|
2150
|
+
return false;
|
|
2151
|
+
}
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
//#endregion
|
|
2155
|
+
//#region src/server/clients.ts
|
|
2156
|
+
/** An address as a number (IPv4 in 32 bits, IPv6 in 128), or `undefined` when it isn't one. */
|
|
2157
|
+
function addressBits(address) {
|
|
2158
|
+
let text = address.trim();
|
|
2159
|
+
if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
|
|
2160
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(text);
|
|
2161
|
+
if (mapped) text = mapped[1];
|
|
2162
|
+
if (isIPv4(text)) return {
|
|
2163
|
+
v6: false,
|
|
2164
|
+
bits: text.split(".").map(Number).reduce((sum, part) => sum << 8n | BigInt(part), 0n)
|
|
2165
|
+
};
|
|
2166
|
+
if (!isIPv6(text)) return void 0;
|
|
2167
|
+
const zone = text.indexOf("%");
|
|
2168
|
+
if (zone !== -1) text = text.slice(0, zone);
|
|
2169
|
+
const last = text.slice(text.lastIndexOf(":") + 1);
|
|
2170
|
+
if (last.includes(".")) {
|
|
2171
|
+
if (!isIPv4(last)) return void 0;
|
|
2172
|
+
const parts = last.split(".").map(Number);
|
|
2173
|
+
const high = (parts[0] << 8 | parts[1]).toString(16);
|
|
2174
|
+
const low = (parts[2] << 8 | parts[3]).toString(16);
|
|
2175
|
+
text = `${text.slice(0, -last.length)}${high}:${low}`;
|
|
2176
|
+
}
|
|
2177
|
+
const [head, tail] = text.split("::");
|
|
2178
|
+
const left = head === "" ? [] : head.split(":");
|
|
2179
|
+
const right = tail === void 0 ? [] : tail === "" ? [] : tail.split(":");
|
|
2180
|
+
const groups = tail === void 0 ? left : [
|
|
2181
|
+
...left,
|
|
2182
|
+
...new Array(8 - left.length - right.length).fill("0"),
|
|
2183
|
+
...right
|
|
2184
|
+
];
|
|
2185
|
+
if (groups.length !== 8) return void 0;
|
|
2186
|
+
return {
|
|
2187
|
+
v6: true,
|
|
2188
|
+
bits: groups.reduce((sum, group) => sum << 16n | BigInt(Number.parseInt(group, 16)), 0n)
|
|
2189
|
+
};
|
|
2190
|
+
}
|
|
2191
|
+
function parseRange(text) {
|
|
2192
|
+
const [address, prefixText] = text.split("/");
|
|
2193
|
+
const found = addressBits(address);
|
|
2194
|
+
if (!found) return void 0;
|
|
2195
|
+
const width = found.v6 ? 128 : 32;
|
|
2196
|
+
const prefix = prefixText === void 0 ? width : Number(prefixText);
|
|
2197
|
+
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return void 0;
|
|
2198
|
+
return {
|
|
2199
|
+
v6: found.v6,
|
|
2200
|
+
bits: found.bits,
|
|
2201
|
+
prefix
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
function inRange(range, address) {
|
|
2205
|
+
if (range.v6 !== address.v6) return false;
|
|
2206
|
+
const shift = (range.v6 ? 128n : 32n) - BigInt(range.prefix);
|
|
2207
|
+
return range.bits >> shift === address.bits >> shift;
|
|
2208
|
+
}
|
|
2209
|
+
/** Whether every entry of `trustedProxies` is an address or a CIDR block. */
|
|
2210
|
+
function validProxies(entries) {
|
|
2211
|
+
return entries.find((entry) => parseRange(entry) === void 0);
|
|
2212
|
+
}
|
|
2213
|
+
/** Builds the resolver; an entry that isn't an address or a block is ignored (checked at start). */
|
|
2214
|
+
function clientAddresses(options) {
|
|
2215
|
+
const proxies = (options.trustedProxies ?? []).map(parseRange).filter((range) => range !== void 0);
|
|
2216
|
+
const trusted = (address) => {
|
|
2217
|
+
const bits = addressBits(address);
|
|
2218
|
+
return bits !== void 0 && proxies.some((range) => inRange(range, bits));
|
|
2219
|
+
};
|
|
2220
|
+
const ipv6Prefix = options.ipv6Prefix ?? 64;
|
|
2221
|
+
const seen = /* @__PURE__ */ new WeakMap();
|
|
2222
|
+
return {
|
|
2223
|
+
of(incoming) {
|
|
2224
|
+
if (seen.has(incoming)) return seen.get(incoming);
|
|
2225
|
+
const peer = incoming.socket.remoteAddress;
|
|
2226
|
+
let client = peer;
|
|
2227
|
+
if (peer !== void 0 && trusted(peer)) {
|
|
2228
|
+
const header = incoming.headers["x-forwarded-for"];
|
|
2229
|
+
const entries = (Array.isArray(header) ? header.join(",") : header ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
2230
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
2231
|
+
const entry = entries[index];
|
|
2232
|
+
if (addressBits(entry) === void 0) break;
|
|
2233
|
+
client = entry;
|
|
2234
|
+
if (!trusted(entry)) break;
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
seen.set(incoming, client);
|
|
2238
|
+
return client;
|
|
2239
|
+
},
|
|
2240
|
+
keyOf(address) {
|
|
2241
|
+
if (address === void 0) return "unknown";
|
|
2242
|
+
const bits = addressBits(address);
|
|
2243
|
+
if (!bits) return `other:${address}`;
|
|
2244
|
+
if (!bits.v6) return `v4:${bits.bits.toString(16)}`;
|
|
2245
|
+
const shift = 128n - BigInt(ipv6Prefix);
|
|
2246
|
+
return `v6:${(bits.bits >> shift).toString(16)}/${ipv6Prefix}`;
|
|
2247
|
+
}
|
|
2248
|
+
};
|
|
2249
|
+
}
|
|
2250
|
+
/**
|
|
2251
|
+
* A token-bucket rate limiter over keys, in memory, bounded in the keys it keeps: each key holds up
|
|
2252
|
+
* to `count` tokens and earns them back at `count` per `perMs`, so a burst of `count` passes and
|
|
2253
|
+
* the sustained rate is exactly the rate.
|
|
2254
|
+
*/
|
|
2255
|
+
var RateLimiter = class {
|
|
2256
|
+
#buckets = /* @__PURE__ */ new Map();
|
|
2257
|
+
#now;
|
|
2258
|
+
#maxKeys;
|
|
2259
|
+
constructor(options = {}) {
|
|
2260
|
+
this.#now = options.now ?? (() => Date.now());
|
|
2261
|
+
this.#maxKeys = options.maxKeys ?? 1e5;
|
|
2262
|
+
}
|
|
2263
|
+
/** A key's bucket, refilled to now and marked most recently used, so the bound drops the least. */
|
|
2264
|
+
#bucket(key, rate, now) {
|
|
2265
|
+
const perToken = rate.perMs / rate.count;
|
|
2266
|
+
let bucket = this.#buckets.get(key);
|
|
2267
|
+
if (bucket) {
|
|
2268
|
+
bucket.tokens = Math.min(rate.count, bucket.tokens + (now - bucket.at) / perToken);
|
|
2269
|
+
bucket.at = now;
|
|
2270
|
+
this.#buckets.delete(key);
|
|
2271
|
+
} else {
|
|
2272
|
+
if (this.#buckets.size >= this.#maxKeys) this.#buckets.delete(this.#buckets.keys().next().value);
|
|
2273
|
+
bucket = {
|
|
2274
|
+
tokens: rate.count,
|
|
2275
|
+
at: now
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
this.#buckets.set(key, bucket);
|
|
2279
|
+
return bucket;
|
|
2280
|
+
}
|
|
2281
|
+
/** How long until every bucket holds a token: 0 when they all do now. */
|
|
2282
|
+
#wait(wanted, now) {
|
|
2283
|
+
let waitMs = 0;
|
|
2284
|
+
const buckets = wanted.map(({ key, rate }) => {
|
|
2285
|
+
const bucket = this.#bucket(key, rate, now);
|
|
2286
|
+
if (bucket.tokens < 1) waitMs = Math.max(waitMs, (1 - bucket.tokens) * (rate.perMs / rate.count));
|
|
2287
|
+
return bucket;
|
|
2288
|
+
});
|
|
2289
|
+
return {
|
|
2290
|
+
waitMs,
|
|
2291
|
+
buckets
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Takes one token under `key` when there is one. Without one, nothing is taken and the answer
|
|
2296
|
+
* says when to try again, in whole seconds (`Retry-After`).
|
|
2297
|
+
*/
|
|
2298
|
+
take(key, rate) {
|
|
2299
|
+
return this.takeAll([{
|
|
2300
|
+
key,
|
|
2301
|
+
rate
|
|
2302
|
+
}]);
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Gives back the token `takeAll` took under every key, as far as each bucket's size: an attempt
|
|
2306
|
+
* someone refused after the rates admitted it (the operator's `limits`) costs nothing (second
|
|
2307
|
+
* Fable review of WP-30, 2).
|
|
2308
|
+
*/
|
|
2309
|
+
refundAll(wanted) {
|
|
2310
|
+
const now = this.#now();
|
|
2311
|
+
for (const { key, rate } of wanted) {
|
|
2312
|
+
const bucket = this.#bucket(key, rate, now);
|
|
2313
|
+
bucket.tokens = Math.min(rate.count, bucket.tokens + 1);
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
/**
|
|
2317
|
+
* Takes one token under every key, or none: when any bucket is empty, nothing is taken from the
|
|
2318
|
+
* others, and the answer says when the slowest one has a token again (Fable review, 8).
|
|
2319
|
+
*/
|
|
2320
|
+
takeAll(wanted) {
|
|
2321
|
+
const { waitMs, buckets } = this.#wait(wanted, this.#now());
|
|
2322
|
+
if (waitMs > 0) return {
|
|
2323
|
+
ok: false,
|
|
2324
|
+
retryAfterS: Math.max(1, Math.ceil(waitMs / 1e3))
|
|
2325
|
+
};
|
|
2326
|
+
for (const bucket of buckets) bucket.tokens -= 1;
|
|
2327
|
+
return { ok: true };
|
|
2328
|
+
}
|
|
2329
|
+
};
|
|
2330
|
+
//#endregion
|
|
2331
|
+
//#region src/server/directory.ts
|
|
2332
|
+
/** The server directory's migrations: their own list, apart from a home's. */
|
|
2333
|
+
const SERVER_MIGRATIONS = [
|
|
2334
|
+
{
|
|
2335
|
+
version: 1,
|
|
2336
|
+
name: "server directory",
|
|
2337
|
+
up(db) {
|
|
2338
|
+
db.exec(`
|
|
2339
|
+
CREATE TABLE account (
|
|
2340
|
+
id TEXT PRIMARY KEY,
|
|
2341
|
+
name TEXT,
|
|
2342
|
+
status TEXT NOT NULL CHECK (status IN ('active', 'suspended')),
|
|
2343
|
+
created_at TEXT NOT NULL
|
|
2344
|
+
);
|
|
2345
|
+
CREATE TABLE identity (
|
|
2346
|
+
provider TEXT NOT NULL,
|
|
2347
|
+
subject TEXT NOT NULL,
|
|
2348
|
+
account_id TEXT NOT NULL REFERENCES account(id),
|
|
2349
|
+
email TEXT,
|
|
2350
|
+
name TEXT,
|
|
2351
|
+
linked_at TEXT NOT NULL,
|
|
2352
|
+
PRIMARY KEY (provider, subject)
|
|
2353
|
+
);
|
|
2354
|
+
CREATE TABLE home (
|
|
2355
|
+
id TEXT PRIMARY KEY,
|
|
2356
|
+
owner_account_id TEXT NOT NULL UNIQUE REFERENCES account(id),
|
|
2357
|
+
data_path TEXT NOT NULL,
|
|
2358
|
+
created_at TEXT NOT NULL,
|
|
2359
|
+
suspended_at TEXT
|
|
2360
|
+
);
|
|
2361
|
+
CREATE TABLE instance_link (
|
|
2362
|
+
id TEXT PRIMARY KEY,
|
|
2363
|
+
account_id TEXT NOT NULL REFERENCES account(id),
|
|
2364
|
+
home_id TEXT NOT NULL REFERENCES home(id),
|
|
2365
|
+
name TEXT NOT NULL,
|
|
2366
|
+
is_default INTEGER NOT NULL DEFAULT 0,
|
|
2367
|
+
relay_high INTEGER NOT NULL DEFAULT 0,
|
|
2368
|
+
linked_at TEXT NOT NULL,
|
|
2369
|
+
revoked_at TEXT
|
|
2370
|
+
);
|
|
2371
|
+
CREATE UNIQUE INDEX instance_link_default ON instance_link(account_id) WHERE is_default = 1;
|
|
2372
|
+
CREATE TABLE home_cursor (
|
|
2373
|
+
home_id TEXT PRIMARY KEY REFERENCES home(id),
|
|
2374
|
+
incarnation TEXT NOT NULL,
|
|
2375
|
+
high_cursor INTEGER NOT NULL,
|
|
2376
|
+
relay_high INTEGER NOT NULL,
|
|
2377
|
+
updated_at TEXT NOT NULL
|
|
2378
|
+
);
|
|
2379
|
+
CREATE TABLE artifact_route (
|
|
2380
|
+
id TEXT PRIMARY KEY,
|
|
2381
|
+
home_id TEXT NOT NULL REFERENCES home(id),
|
|
2382
|
+
artifact_id TEXT NOT NULL,
|
|
2383
|
+
owner_link_id TEXT NOT NULL REFERENCES instance_link(id),
|
|
824
2384
|
label TEXT NOT NULL UNIQUE,
|
|
825
2385
|
created_at TEXT NOT NULL,
|
|
826
2386
|
UNIQUE (home_id, artifact_id)
|
|
@@ -899,8 +2459,70 @@ const SERVER_MIGRATIONS = [{
|
|
|
899
2459
|
next_attempt_at TEXT NOT NULL
|
|
900
2460
|
);
|
|
901
2461
|
`);
|
|
2462
|
+
}
|
|
2463
|
+
},
|
|
2464
|
+
{
|
|
2465
|
+
version: 2,
|
|
2466
|
+
name: "operator, sign-in and links",
|
|
2467
|
+
up(db) {
|
|
2468
|
+
db.exec(`
|
|
2469
|
+
ALTER TABLE home ADD COLUMN drained_at TEXT;
|
|
2470
|
+
ALTER TABLE home ADD COLUMN suspend_reason TEXT;
|
|
2471
|
+
CREATE TABLE hosted_token (
|
|
2472
|
+
token_id TEXT PRIMARY KEY,
|
|
2473
|
+
home_id TEXT NOT NULL REFERENCES home(id),
|
|
2474
|
+
route_id TEXT NOT NULL
|
|
2475
|
+
);
|
|
2476
|
+
CREATE TABLE credential_link (
|
|
2477
|
+
account_id TEXT NOT NULL REFERENCES account(id),
|
|
2478
|
+
subject TEXT NOT NULL,
|
|
2479
|
+
link_id TEXT NOT NULL REFERENCES instance_link(id),
|
|
2480
|
+
PRIMARY KEY (account_id, subject)
|
|
2481
|
+
);
|
|
2482
|
+
CREATE TABLE signin (
|
|
2483
|
+
hash TEXT PRIMARY KEY,
|
|
2484
|
+
kind TEXT NOT NULL CHECK (kind IN ('provider', 'step', 'authorize')),
|
|
2485
|
+
data_json TEXT NOT NULL,
|
|
2486
|
+
expires_at TEXT NOT NULL
|
|
2487
|
+
);
|
|
2488
|
+
CREATE TABLE browser_session (
|
|
2489
|
+
hash TEXT PRIMARY KEY,
|
|
2490
|
+
account_id TEXT NOT NULL REFERENCES account(id),
|
|
2491
|
+
created_at TEXT NOT NULL,
|
|
2492
|
+
expires_at TEXT NOT NULL
|
|
2493
|
+
);
|
|
2494
|
+
CREATE INDEX browser_session_account ON browser_session(account_id);
|
|
2495
|
+
-- A host an operator supplies through routing (D165 item 7, D167): a hosted shell for one
|
|
2496
|
+
-- home (or one route of it), its frames on <label>.<frame_domain>. Recorded with its
|
|
2497
|
+
-- label_issued row when first served, kept forever and never moved to another home.
|
|
2498
|
+
CREATE TABLE operator_host (
|
|
2499
|
+
host TEXT PRIMARY KEY,
|
|
2500
|
+
home_id TEXT NOT NULL REFERENCES home(id),
|
|
2501
|
+
route_id TEXT,
|
|
2502
|
+
frame_domain TEXT NOT NULL,
|
|
2503
|
+
recorded_at TEXT NOT NULL
|
|
2504
|
+
);
|
|
2505
|
+
CREATE INDEX operator_host_frames ON operator_host(frame_domain);
|
|
2506
|
+
CREATE TRIGGER operator_host_kept BEFORE DELETE ON operator_host
|
|
2507
|
+
BEGIN
|
|
2508
|
+
SELECT RAISE(ABORT, 'an operator host is kept forever');
|
|
2509
|
+
END;
|
|
2510
|
+
CREATE TRIGGER operator_host_fixed BEFORE UPDATE ON operator_host
|
|
2511
|
+
WHEN NEW.host IS NOT OLD.host OR NEW.home_id IS NOT OLD.home_id
|
|
2512
|
+
BEGIN
|
|
2513
|
+
SELECT RAISE(ABORT, 'an operator host never moves to another home');
|
|
2514
|
+
END;
|
|
2515
|
+
`);
|
|
2516
|
+
}
|
|
2517
|
+
},
|
|
2518
|
+
{
|
|
2519
|
+
version: 3,
|
|
2520
|
+
name: "a route's removal in progress",
|
|
2521
|
+
up(db) {
|
|
2522
|
+
db.exec("ALTER TABLE artifact_route ADD COLUMN removing_json TEXT");
|
|
2523
|
+
}
|
|
902
2524
|
}
|
|
903
|
-
|
|
2525
|
+
];
|
|
904
2526
|
//#endregion
|
|
905
2527
|
//#region src/server/data.ts
|
|
906
2528
|
/**
|
|
@@ -994,8 +2616,9 @@ async function openDataDirectory(options) {
|
|
|
994
2616
|
const idleCloseMs = options.idleCloseMs ?? 6e5;
|
|
995
2617
|
let closed = false;
|
|
996
2618
|
const openHome = async (id) => {
|
|
997
|
-
const row = directory.read((db) => db.get("SELECT data_path FROM home WHERE id = ?", id));
|
|
2619
|
+
const row = directory.read((db) => db.get("SELECT data_path, drained_at FROM home WHERE id = ?", id));
|
|
998
2620
|
if (!row) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: `No hosted home ${id}.` }));
|
|
2621
|
+
if (row.drained_at !== null) throw new RpcError(createDiagnostic("MOSTRA_REMOTE_HOME_MOVING", { message: "This account's pages are moving to another machine; try again in a minute." }));
|
|
999
2622
|
const homeDir = join(dir, row.data_path);
|
|
1000
2623
|
mkdirSync(homeDir, {
|
|
1001
2624
|
recursive: true,
|
|
@@ -1142,6 +2765,33 @@ async function openDataDirectory(options) {
|
|
|
1142
2765
|
const entry = entries.get(id);
|
|
1143
2766
|
if (entry) entry.lastUsed = Date.now();
|
|
1144
2767
|
},
|
|
2768
|
+
async closeHome(id) {
|
|
2769
|
+
const entry = entries.get(id);
|
|
2770
|
+
if (!entry) return;
|
|
2771
|
+
entry.closing ??= closeHome(id, entry);
|
|
2772
|
+
await entry.closing;
|
|
2773
|
+
},
|
|
2774
|
+
async drain(id) {
|
|
2775
|
+
directory.write((db) => db.run("UPDATE home SET drained_at = COALESCE(drained_at, ?) WHERE id = ?", (/* @__PURE__ */ new Date()).toISOString(), id));
|
|
2776
|
+
const entry = entries.get(id);
|
|
2777
|
+
if (entry) {
|
|
2778
|
+
entry.closing ??= closeHome(id, entry);
|
|
2779
|
+
await entry.closing;
|
|
2780
|
+
}
|
|
2781
|
+
log.info("server.home_drained", { home: id });
|
|
2782
|
+
},
|
|
2783
|
+
undrain(id) {
|
|
2784
|
+
directory.write((db) => db.run("UPDATE home SET drained_at = NULL WHERE id = ?", id));
|
|
2785
|
+
log.info("server.home_released", { home: id });
|
|
2786
|
+
},
|
|
2787
|
+
async restored(id) {
|
|
2788
|
+
restores.add(id);
|
|
2789
|
+
const entry = entries.get(id);
|
|
2790
|
+
if (entry) {
|
|
2791
|
+
entry.closing ??= closeHome(id, entry);
|
|
2792
|
+
await entry.closing;
|
|
2793
|
+
}
|
|
2794
|
+
},
|
|
1145
2795
|
async close() {
|
|
1146
2796
|
if (closed) return;
|
|
1147
2797
|
closed = true;
|
|
@@ -1157,6 +2807,535 @@ async function openDataDirectory(options) {
|
|
|
1157
2807
|
};
|
|
1158
2808
|
}
|
|
1159
2809
|
//#endregion
|
|
2810
|
+
//#region src/server/handle.ts
|
|
2811
|
+
/**
|
|
2812
|
+
* The server handle an operator module receives (INTERFACES §18.6, D165 item 9): quarantine,
|
|
2813
|
+
* pause, suspension, link revocation, moving and restoring homes, and deletion. Every target names
|
|
2814
|
+
* a hosted route (`rte_…`), never a bare artifact or version ID, since those repeat across homes
|
|
2815
|
+
* when a project is copied: acting on one route never touches another home hosting the same
|
|
2816
|
+
* artifact ID or an identical version. Each call is durable when it resolves.
|
|
2817
|
+
*/
|
|
2818
|
+
function unknownTarget(message) {
|
|
2819
|
+
return new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message }));
|
|
2820
|
+
}
|
|
2821
|
+
/** Builds the handle. */
|
|
2822
|
+
function createHandle(options) {
|
|
2823
|
+
const { log } = options;
|
|
2824
|
+
/** A route's home and artifact; an unknown route is refused, never guessed. */
|
|
2825
|
+
const route = (routeId) => {
|
|
2826
|
+
const row = options.directory().read((db) => db.get("SELECT home_id, artifact_id FROM artifact_route WHERE id = ?", routeId));
|
|
2827
|
+
if (!row) throw unknownTarget(`No hosted route ${routeId}.`);
|
|
2828
|
+
return {
|
|
2829
|
+
home: row.home_id,
|
|
2830
|
+
artifactId: row.artifact_id
|
|
2831
|
+
};
|
|
2832
|
+
};
|
|
2833
|
+
const homeOf = async (homeId) => (await options.data().home(homeId)).assembled;
|
|
2834
|
+
const knownHome = (homeId) => {
|
|
2835
|
+
if (!options.directory().read((db) => db.get("SELECT 1 FROM home WHERE id = ?", homeId))) throw unknownTarget(`No hosted home ${homeId}.`);
|
|
2836
|
+
};
|
|
2837
|
+
return {
|
|
2838
|
+
revision: OPERATOR_REVISION,
|
|
2839
|
+
apiOrigin: options.apiOrigin,
|
|
2840
|
+
async quarantine(target, reason) {
|
|
2841
|
+
const found = route(target.routeId);
|
|
2842
|
+
(await homeOf(found.home)).quarantine(found.artifactId, "versionId" in target ? target.versionId : void 0, reason);
|
|
2843
|
+
log.info("operator.quarantine", { routeId: target.routeId });
|
|
2844
|
+
},
|
|
2845
|
+
async release(target) {
|
|
2846
|
+
const found = route(target.routeId);
|
|
2847
|
+
(await homeOf(found.home)).release(found.artifactId, "versionId" in target ? target.versionId : void 0);
|
|
2848
|
+
log.info("operator.release", { routeId: target.routeId });
|
|
2849
|
+
},
|
|
2850
|
+
async pause(routeId, reason) {
|
|
2851
|
+
const found = route(routeId);
|
|
2852
|
+
(await homeOf(found.home)).pause(found.artifactId, {
|
|
2853
|
+
paused: true,
|
|
2854
|
+
by: "operator",
|
|
2855
|
+
reason
|
|
2856
|
+
});
|
|
2857
|
+
log.info("operator.pause", { routeId });
|
|
2858
|
+
},
|
|
2859
|
+
async resume(routeId) {
|
|
2860
|
+
const found = route(routeId);
|
|
2861
|
+
(await homeOf(found.home)).pause(found.artifactId, {
|
|
2862
|
+
paused: false,
|
|
2863
|
+
by: "operator"
|
|
2864
|
+
});
|
|
2865
|
+
log.info("operator.resume", { routeId });
|
|
2866
|
+
},
|
|
2867
|
+
async suspendHome(homeId, reason) {
|
|
2868
|
+
knownHome(homeId);
|
|
2869
|
+
options.directory().write((db) => db.run("UPDATE home SET suspended_at = COALESCE(suspended_at, ?), suspend_reason = ? WHERE id = ?", (/* @__PURE__ */ new Date()).toISOString(), reason.slice(0, 1e3), homeId));
|
|
2870
|
+
options.suspended(homeId);
|
|
2871
|
+
await options.data().closeHome(homeId);
|
|
2872
|
+
log.info("operator.suspend_home", { home: homeId });
|
|
2873
|
+
},
|
|
2874
|
+
async resumeHome(homeId) {
|
|
2875
|
+
knownHome(homeId);
|
|
2876
|
+
options.directory().write((db) => db.run("UPDATE home SET suspended_at = NULL, suspend_reason = NULL WHERE id = ?", homeId));
|
|
2877
|
+
log.info("operator.resume_home", { home: homeId });
|
|
2878
|
+
},
|
|
2879
|
+
async revokeLinks(routeId) {
|
|
2880
|
+
const found = route(routeId);
|
|
2881
|
+
const count = (await homeOf(found.home)).revokeLinks(found.artifactId);
|
|
2882
|
+
log.info("operator.revoke_links", {
|
|
2883
|
+
routeId,
|
|
2884
|
+
count
|
|
2885
|
+
});
|
|
2886
|
+
return count;
|
|
2887
|
+
},
|
|
2888
|
+
async revokeLink(tokenId) {
|
|
2889
|
+
const row = options.directory().read((db) => db.get("SELECT home_id FROM hosted_token WHERE token_id = ?", tokenId));
|
|
2890
|
+
if (!row) throw unknownTarget(`No hosted link ${tokenId}.`);
|
|
2891
|
+
if (!(await homeOf(row.home_id)).revokeLink(tokenId)) throw unknownTarget(`No hosted link ${tokenId}.`);
|
|
2892
|
+
log.info("operator.revoke_link", { tokenId });
|
|
2893
|
+
},
|
|
2894
|
+
async drainHome(homeId) {
|
|
2895
|
+
knownHome(homeId);
|
|
2896
|
+
options.suspended(homeId);
|
|
2897
|
+
await options.data().drain(homeId);
|
|
2898
|
+
},
|
|
2899
|
+
async releaseHome(homeId) {
|
|
2900
|
+
knownHome(homeId);
|
|
2901
|
+
options.data().undrain(homeId);
|
|
2902
|
+
},
|
|
2903
|
+
async restored(homeId) {
|
|
2904
|
+
knownHome(homeId);
|
|
2905
|
+
await options.data().restored(homeId);
|
|
2906
|
+
log.info("operator.restored", { home: homeId });
|
|
2907
|
+
},
|
|
2908
|
+
async remove(routeId) {
|
|
2909
|
+
const found = route(routeId);
|
|
2910
|
+
const home = await homeOf(found.home);
|
|
2911
|
+
try {
|
|
2912
|
+
await home.remove(found.artifactId);
|
|
2913
|
+
} finally {
|
|
2914
|
+
await options.data().closeHome(found.home);
|
|
2915
|
+
}
|
|
2916
|
+
log.info("operator.remove", { routeId });
|
|
2917
|
+
}
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
//#endregion
|
|
2921
|
+
//#region src/server/feed.ts
|
|
2922
|
+
/** How many events one read takes. */
|
|
2923
|
+
const PAGE = 200;
|
|
2924
|
+
const RUN_ENDS = /* @__PURE__ */ new Map([
|
|
2925
|
+
["action.succeeded", "succeeded"],
|
|
2926
|
+
["action.failed", "failed"],
|
|
2927
|
+
["action.cancelled", "cancelled"],
|
|
2928
|
+
["action.unknown", "unknown"]
|
|
2929
|
+
]);
|
|
2930
|
+
/** Starts the feed of a home. */
|
|
2931
|
+
function createOperatorFeed(options) {
|
|
2932
|
+
const { ledger, operator, meter, log } = options;
|
|
2933
|
+
const wanted = operator.has.events || meter.on;
|
|
2934
|
+
let stopped = false;
|
|
2935
|
+
let scheduled = false;
|
|
2936
|
+
const cursorOf = () => ledger.read((db) => db.get("SELECT cursor FROM operator_cursor WHERE id = 1")?.cursor ?? -1);
|
|
2937
|
+
/**
|
|
2938
|
+
* Moves the cursor forward. It writes only when the cursor moves, since every write is a commit
|
|
2939
|
+
* that schedules another read: a write that changed nothing would read again for ever.
|
|
2940
|
+
*/
|
|
2941
|
+
const setCursor = (cursor) => {
|
|
2942
|
+
if (cursor <= cursorOf()) return;
|
|
2943
|
+
ledger.write((db) => db.run(`INSERT INTO operator_cursor (id, cursor) VALUES (1, ?)
|
|
2944
|
+
ON CONFLICT (id) DO UPDATE SET cursor = MAX(cursor, excluded.cursor)`, cursor));
|
|
2945
|
+
};
|
|
2946
|
+
const head = () => ledger.read((db) => db.get("SELECT MAX(cursor) AS head FROM event")?.head ?? 0);
|
|
2947
|
+
const toEvent = (row) => {
|
|
2948
|
+
if (row.artifact_id === null) return void 0;
|
|
2949
|
+
const route = options.routeOf(row.artifact_id);
|
|
2950
|
+
if (!route) return void 0;
|
|
2951
|
+
const payload = JSON.parse(row.payload_json);
|
|
2952
|
+
const base = {
|
|
2953
|
+
eventId: `${options.homeId}:${options.incarnation()}:${row.cursor}`,
|
|
2954
|
+
account: options.account(),
|
|
2955
|
+
home: options.homeId,
|
|
2956
|
+
routeId: route.id,
|
|
2957
|
+
label: route.label,
|
|
2958
|
+
artifactId: row.artifact_id,
|
|
2959
|
+
at: row.at
|
|
2960
|
+
};
|
|
2961
|
+
if (row.type === "submission.created") {
|
|
2962
|
+
const results = options.interaction.resultsOf(String(payload["submissionId"]));
|
|
2963
|
+
return results ? {
|
|
2964
|
+
...base,
|
|
2965
|
+
kind: "submission.accepted",
|
|
2966
|
+
payload: results
|
|
2967
|
+
} : void 0;
|
|
2968
|
+
}
|
|
2969
|
+
if (row.type === "version.published") return {
|
|
2970
|
+
...base,
|
|
2971
|
+
kind: "version.pushed",
|
|
2972
|
+
payload: {
|
|
2973
|
+
versionId: payload["versionId"],
|
|
2974
|
+
number: payload["number"]
|
|
2975
|
+
}
|
|
2976
|
+
};
|
|
2977
|
+
const status = RUN_ENDS.get(row.type);
|
|
2978
|
+
if (status !== void 0) return {
|
|
2979
|
+
...base,
|
|
2980
|
+
kind: "run.ended",
|
|
2981
|
+
payload: {
|
|
2982
|
+
runId: payload["runId"],
|
|
2983
|
+
action: payload["action"],
|
|
2984
|
+
status
|
|
2985
|
+
}
|
|
2986
|
+
};
|
|
2987
|
+
};
|
|
2988
|
+
const scan = () => {
|
|
2989
|
+
scheduled = false;
|
|
2990
|
+
if (stopped) return;
|
|
2991
|
+
try {
|
|
2992
|
+
let cursor = cursorOf();
|
|
2993
|
+
if (!wanted || cursor < 0) {
|
|
2994
|
+
setCursor(Math.max(0, head()));
|
|
2995
|
+
if (!wanted) return;
|
|
2996
|
+
cursor = Math.max(0, cursorOf());
|
|
2997
|
+
}
|
|
2998
|
+
for (;;) {
|
|
2999
|
+
const rows = ledger.read((db) => db.all(`SELECT cursor, artifact_id, type, payload_json, at FROM event WHERE cursor > ?
|
|
3000
|
+
AND type IN ('submission.created', 'version.published', 'action.succeeded',
|
|
3001
|
+
'action.failed', 'action.cancelled', 'action.unknown')
|
|
3002
|
+
ORDER BY cursor LIMIT ?`, cursor, PAGE));
|
|
3003
|
+
for (const row of rows) {
|
|
3004
|
+
const event = toEvent(row);
|
|
3005
|
+
if (!event) continue;
|
|
3006
|
+
if (event.kind === "submission.accepted") meter.add("submissions", {
|
|
3007
|
+
account: event.account,
|
|
3008
|
+
home: event.home,
|
|
3009
|
+
artifactId: event.artifactId,
|
|
3010
|
+
routeId: event.routeId
|
|
3011
|
+
});
|
|
3012
|
+
if (operator.has.events) operator.enqueue({
|
|
3013
|
+
port: "events",
|
|
3014
|
+
event
|
|
3015
|
+
});
|
|
3016
|
+
}
|
|
3017
|
+
const last = rows.at(-1)?.cursor;
|
|
3018
|
+
if (last === void 0) {
|
|
3019
|
+
setCursor(Math.max(cursor, head()));
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
3022
|
+
setCursor(last);
|
|
3023
|
+
cursor = last;
|
|
3024
|
+
if (rows.length < PAGE) return;
|
|
3025
|
+
}
|
|
3026
|
+
} catch (error) {
|
|
3027
|
+
log.warn("operator.feed_failed", {
|
|
3028
|
+
home: options.homeId,
|
|
3029
|
+
error
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
3032
|
+
};
|
|
3033
|
+
const unsubscribe = ledger.onCommit(() => {
|
|
3034
|
+
if (scheduled || stopped) return;
|
|
3035
|
+
scheduled = true;
|
|
3036
|
+
setImmediate(scan);
|
|
3037
|
+
});
|
|
3038
|
+
scan();
|
|
3039
|
+
return {
|
|
3040
|
+
scan,
|
|
3041
|
+
stop() {
|
|
3042
|
+
stopped = true;
|
|
3043
|
+
unsubscribe();
|
|
3044
|
+
}
|
|
3045
|
+
};
|
|
3046
|
+
}
|
|
3047
|
+
//#endregion
|
|
3048
|
+
//#region src/server/hosted-pages.ts
|
|
3049
|
+
/**
|
|
3050
|
+
* A hosted home's pages beyond the local gateway's (ARCHITECTURE §15.6 to §15.8, INTERFACES
|
|
3051
|
+
* §18.4, D161, D165 items 8, 9, 13, 14): who a browser is on a link minted without a viewer, what
|
|
3052
|
+
* the trusted chrome shows around a view, which views and submissions the server's rules refuse
|
|
3053
|
+
* before they reach the ledger, and the shell routes of a hosted home of its own (the report
|
|
3054
|
+
* control, an anonymous viewer's name; sign-in arrives with the authorization server).
|
|
3055
|
+
*
|
|
3056
|
+
* Everything here answers through the gateway's one checked route table and its hooks
|
|
3057
|
+
* (`HostedAddressing`), so every rule is applied in the same order as every other route's (D96).
|
|
3058
|
+
*/
|
|
3059
|
+
/** How long the server's reports from one address may come: 20 an hour (the operator's inbox). */
|
|
3060
|
+
const REPORT_RATE = {
|
|
3061
|
+
count: 20,
|
|
3062
|
+
perMs: 36e5
|
|
3063
|
+
};
|
|
3064
|
+
/** A refusal with any cataloged code (the gateway's own `refusal` takes HYGIENE codes only). */
|
|
3065
|
+
function refuseWith(code, message, status) {
|
|
3066
|
+
return {
|
|
3067
|
+
status,
|
|
3068
|
+
diagnostic: createDiagnostic(code, { message })
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
/** The milliseconds of a duration such as `7d` (checked by the operator's schema). */
|
|
3072
|
+
function durationMs$1(text) {
|
|
3073
|
+
const unit = {
|
|
3074
|
+
s: 1e3,
|
|
3075
|
+
m: 6e4,
|
|
3076
|
+
h: 36e5,
|
|
3077
|
+
d: 864e5
|
|
3078
|
+
}[text.slice(-1)] ?? 0;
|
|
3079
|
+
return Number(text.slice(0, -1)) * unit;
|
|
3080
|
+
}
|
|
3081
|
+
/** The gateway hooks of one hosted home's pages. */
|
|
3082
|
+
function hostedPages(options) {
|
|
3083
|
+
const { ledger, interaction, capabilities, operator, log } = options;
|
|
3084
|
+
const now = options.now ?? (() => Date.now());
|
|
3085
|
+
/** A route's quarantine: the whole route's, or this version's (D165 item 9). */
|
|
3086
|
+
const quarantineOf = (artifactId, versionId) => ledger.read((db) => db.get("SELECT reason FROM quarantine WHERE artifact_id = ? AND version_id IN ('', ?) LIMIT 1", artifactId, versionId)?.reason);
|
|
3087
|
+
const underReview = () => refuseWith("MOSTRA_REMOTE_UNDER_REVIEW", "This page is under review by the server's operator.", 403);
|
|
3088
|
+
const policyFor = (artifactId, tokenId) => {
|
|
3089
|
+
const route = options.routeOf(artifactId);
|
|
3090
|
+
if (!route) return Promise.resolve({});
|
|
3091
|
+
return operator.linkPolicy({
|
|
3092
|
+
account: options.owner().account,
|
|
3093
|
+
home: options.homeId,
|
|
3094
|
+
routeId: route.id,
|
|
3095
|
+
artifactId,
|
|
3096
|
+
...tokenId !== void 0 ? { tokenId } : {}
|
|
3097
|
+
});
|
|
3098
|
+
};
|
|
3099
|
+
/** A link past the operator's longest lifetime or idle limit: revoked now, 410 (D165 item 9). */
|
|
3100
|
+
const expired = (tokenId, policy) => {
|
|
3101
|
+
if (policy.maxTtl === void 0 && policy.idleExpiry === void 0) return void 0;
|
|
3102
|
+
const used = ledger.read((db) => db.get(`SELECT t.created_at, (SELECT MAX(last_seen_at) FROM session s WHERE s.token_id = t.id) AS last
|
|
3103
|
+
FROM token t WHERE t.id = ?`, tokenId));
|
|
3104
|
+
if (!used) return void 0;
|
|
3105
|
+
const minted = Date.parse(used.created_at);
|
|
3106
|
+
const lastUse = Math.max(minted, used.last === null ? 0 : Date.parse(used.last));
|
|
3107
|
+
const tooOld = policy.maxTtl !== void 0 && now() - minted > durationMs$1(policy.maxTtl);
|
|
3108
|
+
const idle = policy.idleExpiry !== void 0 && now() - lastUse > durationMs$1(policy.idleExpiry);
|
|
3109
|
+
if (!tooOld && !idle) return void 0;
|
|
3110
|
+
capabilities.revoke(tokenId);
|
|
3111
|
+
log.info("hosted.link_expired", {
|
|
3112
|
+
tokenId,
|
|
3113
|
+
why: tooOld ? "max-ttl" : "idle"
|
|
3114
|
+
});
|
|
3115
|
+
return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "This link has expired.", 410);
|
|
3116
|
+
};
|
|
3117
|
+
const limitRefusal = (verdict) => {
|
|
3118
|
+
if (verdict.allowed !== false) return void 0;
|
|
3119
|
+
return {
|
|
3120
|
+
...refuseWith("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message, 403),
|
|
3121
|
+
...verdict.retryAfterMs !== void 0 ? { retryAfter: Math.max(1, Math.ceil(verdict.retryAfterMs / 1e3)) } : {}
|
|
3122
|
+
};
|
|
3123
|
+
};
|
|
3124
|
+
const rateRefusal = (retryAfterS) => ({
|
|
3125
|
+
...refuseWith("MOSTRA_REMOTE_RATE_LIMITED", "Too many answers came through here in a short time; try again shortly.", 429),
|
|
3126
|
+
retryAfter: retryAfterS
|
|
3127
|
+
});
|
|
3128
|
+
const shellRoutes = (helpers) => {
|
|
3129
|
+
const meta = (context) => ({
|
|
3130
|
+
method: context.request.method,
|
|
3131
|
+
path: new URL(context.request.url).pathname,
|
|
3132
|
+
document: false
|
|
3133
|
+
});
|
|
3134
|
+
/** The report control (D161): reaches the operator's `abuse.report`. */
|
|
3135
|
+
const report = async (context) => {
|
|
3136
|
+
const artifactId = context.artifactId;
|
|
3137
|
+
const body = await readJsonObject(context.request, 16384);
|
|
3138
|
+
if (isRefusal(body)) return helpers.refuse(body, meta(context));
|
|
3139
|
+
const reason = body["reason"];
|
|
3140
|
+
const detail = body["detail"];
|
|
3141
|
+
if (typeof reason !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(reason) || detail !== void 0 && (typeof detail !== "string" || detail.length > 2e3)) return helpers.refuse(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "A report names a `reason` (a short word) and at most 2000 characters of `detail`."), meta(context));
|
|
3142
|
+
const limited = options.rates.take(`report:${options.clients.keyOf(context.client)}`, REPORT_RATE);
|
|
3143
|
+
if (!limited.ok) return helpers.refuse(rateRefusal(limited.retryAfterS), meta(context));
|
|
3144
|
+
const route = options.routeOf(artifactId);
|
|
3145
|
+
if (!route) return helpers.refuse(refusal("MOSTRA_HYGIENE_NOT_SERVED", "No route here."), meta(context));
|
|
3146
|
+
await operator.report({
|
|
3147
|
+
routeId: route.id,
|
|
3148
|
+
label: route.label,
|
|
3149
|
+
artifactId,
|
|
3150
|
+
home: options.homeId,
|
|
3151
|
+
...context.session?.versionId !== void 0 ? { versionId: context.session.versionId } : {},
|
|
3152
|
+
reason,
|
|
3153
|
+
...typeof detail === "string" && detail !== "" ? { detail } : {},
|
|
3154
|
+
at: new Date(now()).toISOString()
|
|
3155
|
+
});
|
|
3156
|
+
log.info("hosted.reported", {
|
|
3157
|
+
routeId: route.id,
|
|
3158
|
+
reason
|
|
3159
|
+
});
|
|
3160
|
+
return jsonResponse({}, { status: 202 });
|
|
3161
|
+
};
|
|
3162
|
+
/** An anonymous viewer's self-chosen name, recorded unverified (D165 item 8). */
|
|
3163
|
+
const name = async (context) => {
|
|
3164
|
+
const body = await readJsonObject(context.request, 4096);
|
|
3165
|
+
if (isRefusal(body)) return helpers.refuse(body, meta(context));
|
|
3166
|
+
const value = body["name"];
|
|
3167
|
+
const cleaned = value === null ? null : typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, 64) : void 0;
|
|
3168
|
+
if (cleaned === void 0 || cleaned === "") return helpers.refuse(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`name` is a short text, or null."), meta(context));
|
|
3169
|
+
const viewerId = interaction.viewerOf(context.session?.viewerId);
|
|
3170
|
+
if (!interaction.nameAnonymous(viewerId, cleaned)) return helpers.refuse(refusal("MOSTRA_HYGIENE_SCOPE_DENIED", "Only a viewer who isn't signed in names themselves here; a signed-in name is the account's."), meta(context));
|
|
3171
|
+
return jsonResponse({ viewer: interaction.viewer(viewerId) });
|
|
3172
|
+
};
|
|
3173
|
+
/**
|
|
3174
|
+
* A page's sign-in, from a click in the trusted chrome only (INTERFACES §18.4): the address of
|
|
3175
|
+
* the authorization server, with `state` bound to this route and this shell session.
|
|
3176
|
+
*/
|
|
3177
|
+
const signinStart = async (context) => {
|
|
3178
|
+
const body = await readJsonObject(context.request, 4096);
|
|
3179
|
+
if (isRefusal(body)) return helpers.refuse(body, meta(context));
|
|
3180
|
+
const challenge = body["challenge"];
|
|
3181
|
+
const route = options.routeOf(context.artifactId);
|
|
3182
|
+
if (typeof challenge !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(challenge) || !route || !options.signin || !context.session) return helpers.refuse(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "A sign-in starts with a PKCE S256 challenge."), meta(context));
|
|
3183
|
+
const started = options.signin.start({
|
|
3184
|
+
homeId: options.homeId,
|
|
3185
|
+
routeId: route.id,
|
|
3186
|
+
sessionId: context.session.id,
|
|
3187
|
+
shellOrigin: context.request.headers.get("origin") ?? ""
|
|
3188
|
+
}, challenge);
|
|
3189
|
+
return jsonResponse(started);
|
|
3190
|
+
};
|
|
3191
|
+
/** The code back from the authorization server: the session acts as the account from now on. */
|
|
3192
|
+
const signinFinish = async (context) => {
|
|
3193
|
+
const body = await readJsonObject(context.request, 8192);
|
|
3194
|
+
if (isRefusal(body)) return helpers.refuse(body, meta(context));
|
|
3195
|
+
const route = options.routeOf(context.artifactId);
|
|
3196
|
+
const { code, verifier, state } = body;
|
|
3197
|
+
if (typeof code !== "string" || typeof verifier !== "string" || typeof state !== "string" || !route || !options.signin || !context.session) return helpers.refuse(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "Send the sign-in's code, verifier and state."), meta(context));
|
|
3198
|
+
const finished = options.signin.finish({
|
|
3199
|
+
code,
|
|
3200
|
+
verifier,
|
|
3201
|
+
state,
|
|
3202
|
+
routeId: route.id,
|
|
3203
|
+
sessionId: context.session.id
|
|
3204
|
+
});
|
|
3205
|
+
if ("refused" in finished) {
|
|
3206
|
+
log.warn("hosted.signin_refused", { routeId: route.id });
|
|
3207
|
+
return helpers.refuse(refusal("MOSTRA_HYGIENE_SCOPE_DENIED", finished.refused, 403), meta(context));
|
|
3208
|
+
}
|
|
3209
|
+
const viewerId = interaction.viewerForAccount(finished.accountId, finished.name);
|
|
3210
|
+
if (context.session.grant.viewerId === void 0) {
|
|
3211
|
+
const sessionId = context.session.id;
|
|
3212
|
+
ledger.write((db) => db.run("UPDATE session SET viewer_id = ? WHERE id = ?", viewerId, sessionId));
|
|
3213
|
+
}
|
|
3214
|
+
log.info("hosted.signed_in", { routeId: route.id });
|
|
3215
|
+
return jsonResponse({ viewer: interaction.viewer(viewerId) });
|
|
3216
|
+
};
|
|
3217
|
+
return [
|
|
3218
|
+
{
|
|
3219
|
+
method: "POST",
|
|
3220
|
+
path: "/a/:artifactId/_mostra/session/signin/start",
|
|
3221
|
+
intent: "mutation",
|
|
3222
|
+
auth: "session",
|
|
3223
|
+
handler: signinStart
|
|
3224
|
+
},
|
|
3225
|
+
{
|
|
3226
|
+
method: "POST",
|
|
3227
|
+
path: "/a/:artifactId/_mostra/session/signin",
|
|
3228
|
+
intent: "mutation",
|
|
3229
|
+
auth: "session",
|
|
3230
|
+
handler: signinFinish
|
|
3231
|
+
},
|
|
3232
|
+
{
|
|
3233
|
+
method: "POST",
|
|
3234
|
+
path: "/a/:artifactId/_mostra/report",
|
|
3235
|
+
intent: "mutation",
|
|
3236
|
+
auth: "session",
|
|
3237
|
+
handler: report
|
|
3238
|
+
},
|
|
3239
|
+
{
|
|
3240
|
+
method: "POST",
|
|
3241
|
+
path: "/a/:artifactId/_mostra/session/name",
|
|
3242
|
+
intent: "mutation",
|
|
3243
|
+
auth: "session",
|
|
3244
|
+
handler: name
|
|
3245
|
+
}
|
|
3246
|
+
];
|
|
3247
|
+
};
|
|
3248
|
+
return {
|
|
3249
|
+
client: (incoming) => options.clients.of(incoming),
|
|
3250
|
+
anonymousViewer: (browser) => interaction.viewerForAnonymous(browser ?? `session:${randomBytes(16).toString("hex")}`),
|
|
3251
|
+
async admitView(input) {
|
|
3252
|
+
if (quarantineOf(input.artifactId, input.versionId) !== void 0) return underReview();
|
|
3253
|
+
const policy = await policyFor(input.artifactId, input.tokenId);
|
|
3254
|
+
const gone = expired(input.tokenId, policy);
|
|
3255
|
+
if (gone) return gone;
|
|
3256
|
+
const route = options.routeOf(input.artifactId);
|
|
3257
|
+
const verdict = await operator.limit({
|
|
3258
|
+
account: options.owner().account,
|
|
3259
|
+
home: options.homeId,
|
|
3260
|
+
artifact: input.artifactId,
|
|
3261
|
+
...route ? { routeId: route.id } : {},
|
|
3262
|
+
operation: "view"
|
|
3263
|
+
});
|
|
3264
|
+
const refused = limitRefusal(verdict);
|
|
3265
|
+
if (refused) return refused;
|
|
3266
|
+
},
|
|
3267
|
+
blocked: (artifactId, versionId) => quarantineOf(artifactId, versionId) !== void 0 ? underReview() : void 0,
|
|
3268
|
+
async chrome(input) {
|
|
3269
|
+
const owner = options.owner();
|
|
3270
|
+
const viewer = interaction.viewer(input.viewerId);
|
|
3271
|
+
const policy = await policyFor(input.artifactId, input.tokenId);
|
|
3272
|
+
options.viewed?.({
|
|
3273
|
+
artifactId: input.artifactId,
|
|
3274
|
+
viewerId: input.viewerId
|
|
3275
|
+
});
|
|
3276
|
+
return {
|
|
3277
|
+
...owner.name !== void 0 ? { sender: {
|
|
3278
|
+
name: owner.name,
|
|
3279
|
+
...owner.verifiedBy !== void 0 ? { verifiedBy: owner.verifiedBy } : {}
|
|
3280
|
+
} } : {},
|
|
3281
|
+
viewer: viewer.kind === "account" ? {
|
|
3282
|
+
kind: "account",
|
|
3283
|
+
...viewer.name ? { name: viewer.name } : {},
|
|
3284
|
+
verified: true
|
|
3285
|
+
} : viewer.kind === "anonymous" ? {
|
|
3286
|
+
kind: "anonymous",
|
|
3287
|
+
...viewer.name ? { name: viewer.name } : {},
|
|
3288
|
+
verified: false
|
|
3289
|
+
} : {
|
|
3290
|
+
kind: "named",
|
|
3291
|
+
...viewer.name ? { name: viewer.name } : {},
|
|
3292
|
+
verified: false
|
|
3293
|
+
},
|
|
3294
|
+
signIn: viewer.kind !== "account" && options.signInOffered(),
|
|
3295
|
+
...policy.footer !== void 0 ? { footer: policy.footer } : {},
|
|
3296
|
+
...policy.afterSubmit !== void 0 ? { afterSubmit: policy.afterSubmit } : {},
|
|
3297
|
+
...policy.madeWith?.show ?? options.madeWith !== void 0 ? { madeWith: { ...policy.madeWith?.href ?? options.madeWith?.href ? { href: policy.madeWith?.href ?? options.madeWith?.href } : {} } } : {},
|
|
3298
|
+
...policy.interstitial !== void 0 ? { interstitial: policy.interstitial } : {}
|
|
3299
|
+
};
|
|
3300
|
+
},
|
|
3301
|
+
async admitSubmit(page, context) {
|
|
3302
|
+
if (options.artifact(page.artifactId).manifest?.hosted?.submissions === "signed-in") {
|
|
3303
|
+
const viewer = interaction.viewer(page.viewerId);
|
|
3304
|
+
const named = context.session?.grant.viewerId !== void 0;
|
|
3305
|
+
if (viewer.kind !== "account" && !named) return refuseWith("MOSTRA_REMOTE_SIGN_IN_REQUIRED", "This page takes answers from signed-in viewers; sign in, then submit again. The draft is kept.", 403);
|
|
3306
|
+
}
|
|
3307
|
+
const limits = options.rateLimits;
|
|
3308
|
+
const wanted = [];
|
|
3309
|
+
if (limits.perIpSubmissions) wanted.push({
|
|
3310
|
+
key: `submit-ip:${options.clients.keyOf(context.client)}`,
|
|
3311
|
+
rate: limits.perIpSubmissions
|
|
3312
|
+
});
|
|
3313
|
+
if (limits.perLinkSubmissions && page.tokenId !== void 0) wanted.push({
|
|
3314
|
+
key: `submit-link:${page.tokenId}`,
|
|
3315
|
+
rate: limits.perLinkSubmissions
|
|
3316
|
+
});
|
|
3317
|
+
const taken = options.rates.takeAll(wanted);
|
|
3318
|
+
if (!taken.ok) return rateRefusal(taken.retryAfterS);
|
|
3319
|
+
const route = options.routeOf(page.artifactId);
|
|
3320
|
+
const verdict = await operator.limit({
|
|
3321
|
+
account: options.owner().account,
|
|
3322
|
+
home: options.homeId,
|
|
3323
|
+
artifact: page.artifactId,
|
|
3324
|
+
...route ? { routeId: route.id } : {},
|
|
3325
|
+
operation: "submit"
|
|
3326
|
+
});
|
|
3327
|
+
const refused = limitRefusal(verdict);
|
|
3328
|
+
if (refused) options.rates.refundAll(wanted);
|
|
3329
|
+
return refused;
|
|
3330
|
+
},
|
|
3331
|
+
shellRoutes
|
|
3332
|
+
};
|
|
3333
|
+
}
|
|
3334
|
+
/** A diagnostic for a hosted home this server won't serve now: suspended, or moving. */
|
|
3335
|
+
function homeUnavailable(why) {
|
|
3336
|
+
return why === "suspended" ? createDiagnostic("MOSTRA_REMOTE_HOME_SUSPENDED", { message: "This account's pages are suspended by the server's operator." }) : createDiagnostic("MOSTRA_REMOTE_HOME_MOVING", { message: "This account's pages are moving to another machine; try again in a minute." });
|
|
3337
|
+
}
|
|
3338
|
+
//#endregion
|
|
1160
3339
|
//#region src/server/relay.ts
|
|
1161
3340
|
/**
|
|
1162
3341
|
* The relay on a hosted home (D117, D165 item 4; ARCHITECTURE §15.5, INTERFACES §18.3, FAILURE_MODEL
|
|
@@ -1910,6 +4089,94 @@ function createHostedRelay(options) {
|
|
|
1910
4089
|
};
|
|
1911
4090
|
}
|
|
1912
4091
|
//#endregion
|
|
4092
|
+
//#region src/server/remove.ts
|
|
4093
|
+
/**
|
|
4094
|
+
* Deletes an artifact and everything referencing it from a home's ledger, in the caller's write
|
|
4095
|
+
* transaction. Answers the rows deleted per table.
|
|
4096
|
+
*/
|
|
4097
|
+
function purgeArtifact(db, artifactId) {
|
|
4098
|
+
const tables = db.all("SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").map((row) => row.name);
|
|
4099
|
+
const columns = /* @__PURE__ */ new Map();
|
|
4100
|
+
const children = /* @__PURE__ */ new Map();
|
|
4101
|
+
for (const table of tables) {
|
|
4102
|
+
columns.set(table, new Set(db.all(`PRAGMA table_info("${table}")`).map((row) => row.name)));
|
|
4103
|
+
for (const key of db.all(`PRAGMA foreign_key_list("${table}")`)) {
|
|
4104
|
+
const list = children.get(key.table) ?? [];
|
|
4105
|
+
list.push({
|
|
4106
|
+
table,
|
|
4107
|
+
from: key.from,
|
|
4108
|
+
to: key.to ?? "rowid"
|
|
4109
|
+
});
|
|
4110
|
+
children.set(key.table, list);
|
|
4111
|
+
}
|
|
4112
|
+
}
|
|
4113
|
+
const where = /* @__PURE__ */ new Map();
|
|
4114
|
+
for (const table of tables) if (table === "artifact") where.set(table, {
|
|
4115
|
+
sql: "id = ?",
|
|
4116
|
+
params: [artifactId]
|
|
4117
|
+
});
|
|
4118
|
+
else if (columns.get(table)?.has("artifact_id")) where.set(table, {
|
|
4119
|
+
sql: "artifact_id = ?",
|
|
4120
|
+
params: [artifactId]
|
|
4121
|
+
});
|
|
4122
|
+
let grew = true;
|
|
4123
|
+
for (let round = 0; grew && round < 16; round++) {
|
|
4124
|
+
grew = false;
|
|
4125
|
+
for (const [parent, list] of children) {
|
|
4126
|
+
const doomed = where.get(parent);
|
|
4127
|
+
if (!doomed) continue;
|
|
4128
|
+
for (const key of list) {
|
|
4129
|
+
const clause = {
|
|
4130
|
+
sql: `"${key.from}" IN (SELECT "${key.to}" FROM "${parent}" WHERE ${doomed.sql})`,
|
|
4131
|
+
params: doomed.params
|
|
4132
|
+
};
|
|
4133
|
+
const existing = where.get(key.table);
|
|
4134
|
+
if (!existing) {
|
|
4135
|
+
where.set(key.table, clause);
|
|
4136
|
+
grew = true;
|
|
4137
|
+
} else if (!existing.sql.includes(`"${key.from}" IN (SELECT "${key.to}" FROM "${parent}"`)) {
|
|
4138
|
+
where.set(key.table, {
|
|
4139
|
+
sql: `(${existing.sql}) OR (${clause.sql})`,
|
|
4140
|
+
params: [...existing.params, ...clause.params]
|
|
4141
|
+
});
|
|
4142
|
+
grew = true;
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
}
|
|
4147
|
+
const triggers = db.all(`SELECT name, sql FROM sqlite_schema WHERE type = 'trigger' AND tbl_name IN (${[...where.keys()].map(() => "?").join(", ")})`, ...where.keys());
|
|
4148
|
+
for (const trigger of triggers) db.exec(`DROP TRIGGER "${trigger.name}"`);
|
|
4149
|
+
db.exec("PRAGMA defer_foreign_keys = ON");
|
|
4150
|
+
const removed = {};
|
|
4151
|
+
const order = [...where.keys()].sort((a, b) => depth(b) - depth(a));
|
|
4152
|
+
function depth(table, seen = /* @__PURE__ */ new Set()) {
|
|
4153
|
+
if (table === "artifact" || seen.has(table)) return 0;
|
|
4154
|
+
seen.add(table);
|
|
4155
|
+
let deepest = 0;
|
|
4156
|
+
for (const [parent, list] of children) if (list.some((key) => key.table === table) && where.has(parent) && parent !== table) deepest = Math.max(deepest, depth(parent, seen) + 1);
|
|
4157
|
+
return deepest;
|
|
4158
|
+
}
|
|
4159
|
+
const doomedRows = /* @__PURE__ */ new Map();
|
|
4160
|
+
for (const table of order) {
|
|
4161
|
+
const clause = where.get(table);
|
|
4162
|
+
if (!clause) continue;
|
|
4163
|
+
doomedRows.set(table, db.all(`SELECT rowid AS row FROM "${table}" WHERE ${clause.sql}`, ...clause.params).map((found) => found.row));
|
|
4164
|
+
}
|
|
4165
|
+
for (const table of order) {
|
|
4166
|
+
const rows = doomedRows.get(table) ?? [];
|
|
4167
|
+
let count = 0;
|
|
4168
|
+
for (let index = 0; index < rows.length; index += 500) {
|
|
4169
|
+
const slice = rows.slice(index, index + 500);
|
|
4170
|
+
count += db.run(`DELETE FROM "${table}" WHERE rowid IN (${slice.map(() => "?").join(", ")})`, ...slice).changes;
|
|
4171
|
+
}
|
|
4172
|
+
if (count > 0) removed[table] = count;
|
|
4173
|
+
}
|
|
4174
|
+
for (const trigger of triggers) db.exec(trigger.sql);
|
|
4175
|
+
const dangling = db.all("PRAGMA foreign_key_check");
|
|
4176
|
+
if (dangling.length > 0) throw new Error(`Removing ${artifactId} would leave ${dangling.length} rows dangling (${[...new Set(dangling.map((row) => `${row.table} → ${row.parent}`))].join(", ")}).`);
|
|
4177
|
+
return removed;
|
|
4178
|
+
}
|
|
4179
|
+
//#endregion
|
|
1913
4180
|
//#region src/server/hosted.ts
|
|
1914
4181
|
/**
|
|
1915
4182
|
* A hosted home (ARCHITECTURE §15.2, DATA_MODEL §7.2, D165): a Mostra home on a remote server with
|
|
@@ -1949,12 +4216,13 @@ function refuse(code, message) {
|
|
|
1949
4216
|
}
|
|
1950
4217
|
/** Opens the parts of a hosted home over its ledger. */
|
|
1951
4218
|
async function openHostedHome(options) {
|
|
4219
|
+
const faults = options.faults ?? noFaults;
|
|
1952
4220
|
const { id, dir, ledger, directory, log } = options;
|
|
1953
4221
|
const registry = await openRegistry({
|
|
1954
4222
|
home: dir,
|
|
1955
4223
|
ledger
|
|
1956
4224
|
});
|
|
1957
|
-
/** Pending pushes: version ID →
|
|
4225
|
+
/** Pending pushes: version ID → each missing client file's SHA-256 and the size its listing gives. */
|
|
1958
4226
|
const pending = /* @__PURE__ */ new Map();
|
|
1959
4227
|
let incarnation = options.incarnation;
|
|
1960
4228
|
const ownerLinkOf = (artifactId) => directory.read((db) => db.get("SELECT owner_link_id FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId)?.owner_link_id);
|
|
@@ -1993,7 +4261,8 @@ async function openHostedHome(options) {
|
|
|
1993
4261
|
});
|
|
1994
4262
|
/** The route of an artifact on this home, minted on its first push by `link`. */
|
|
1995
4263
|
const routeFor = (artifactId, link) => directory.write((db) => {
|
|
1996
|
-
const found = db.get("SELECT id, label, owner_link_id FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId);
|
|
4264
|
+
const found = db.get("SELECT id, label, owner_link_id, removing_json FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId);
|
|
4265
|
+
if (found?.removing_json != null) throw refuse("MOSTRA_REMOTE_HOME_MOVING", "This artifact is being removed from the server; push it again once that's done.");
|
|
1997
4266
|
if (found) {
|
|
1998
4267
|
if (found.owner_link_id !== link) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", `The instance "${db.get("SELECT name FROM instance_link WHERE id = ?", found.owner_link_id)?.name ?? found.owner_link_id}" owns this hosted artifact; push it from there.`);
|
|
1999
4268
|
return {
|
|
@@ -2017,17 +4286,30 @@ async function openHostedHome(options) {
|
|
|
2017
4286
|
label
|
|
2018
4287
|
};
|
|
2019
4288
|
});
|
|
2020
|
-
const routeOf = (artifactId) => directory.read((db) => db.get("SELECT id, label FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId));
|
|
2021
|
-
const artifactOfRoute = (routeId) => directory.read((db) => db.get("SELECT artifact_id FROM artifact_route WHERE id = ? AND home_id = ?", routeId, id)?.artifact_id);
|
|
4289
|
+
const routeOf = (artifactId) => directory.read((db) => db.get("SELECT id, label FROM artifact_route WHERE home_id = ? AND artifact_id = ? AND removing_json IS NULL", id, artifactId));
|
|
4290
|
+
const artifactOfRoute = (routeId) => directory.read((db) => db.get("SELECT artifact_id FROM artifact_route WHERE id = ? AND home_id = ? AND removing_json IS NULL", routeId, id)?.artifact_id);
|
|
2022
4291
|
const domains = [options.domains.active, ...options.domains.spares];
|
|
2023
4292
|
const originOf = (host) => `${options.scheme}://${host}`;
|
|
4293
|
+
/** The host of one of this server's origins, or `undefined` for another scheme. */
|
|
4294
|
+
const hostOfOrigin = (origin) => origin.startsWith(`${options.scheme}://`) ? origin.slice(options.scheme.length + 3) : void 0;
|
|
4295
|
+
/** Whether a shell origin is this home's: a configured apex, or an operator host of it. */
|
|
4296
|
+
const servesShell = (origin) => {
|
|
4297
|
+
const host = hostOfOrigin(origin);
|
|
4298
|
+
if (host === void 0) return false;
|
|
4299
|
+
return options.services ? options.services.routing.servesShell(id, host) : domains.includes(host);
|
|
4300
|
+
};
|
|
2024
4301
|
const capabilities = new Capabilities({
|
|
2025
4302
|
ledger,
|
|
2026
4303
|
log,
|
|
2027
4304
|
key: capabilityKey(dir, log),
|
|
2028
4305
|
now: () => Date.now(),
|
|
2029
4306
|
shellOrigin: () => originOf(options.domains.active),
|
|
2030
|
-
servesShell
|
|
4307
|
+
servesShell,
|
|
4308
|
+
onMinted: ({ tokenId, artifactId }) => {
|
|
4309
|
+
const route = routeOf(artifactId);
|
|
4310
|
+
if (!route) return;
|
|
4311
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO hosted_token (token_id, home_id, route_id) VALUES (?, ?, ?)", tokenId, id, route.id));
|
|
4312
|
+
}
|
|
2031
4313
|
});
|
|
2032
4314
|
const addressing = {
|
|
2033
4315
|
bindAddress: "",
|
|
@@ -2100,13 +4382,55 @@ async function openHostedHome(options) {
|
|
|
2100
4382
|
activated: () => void 0,
|
|
2101
4383
|
hosted: {
|
|
2102
4384
|
shellOrigin: () => originOf(options.domains.active),
|
|
2103
|
-
servesShell
|
|
4385
|
+
servesShell,
|
|
2104
4386
|
shellPath: (artifactId) => `/a/${routeOf(artifactId)?.id ?? artifactId}`,
|
|
2105
4387
|
artifactOrigin: (artifactId, shellOrigin) => {
|
|
2106
4388
|
const route = routeOf(artifactId);
|
|
2107
|
-
const
|
|
2108
|
-
|
|
2109
|
-
|
|
4389
|
+
const host = hostOfOrigin(shellOrigin);
|
|
4390
|
+
if (!route || host === void 0) return void 0;
|
|
4391
|
+
const frameDomain = options.services ? options.services.routing.frameDomainOf(id, route.id, host) : domains.includes(host) ? host : void 0;
|
|
4392
|
+
return frameDomain === void 0 ? void 0 : originOf(`${route.label}.${frameDomain}`);
|
|
4393
|
+
},
|
|
4394
|
+
...options.services ? {
|
|
4395
|
+
linkOrigin: async (artifactId) => {
|
|
4396
|
+
const services = options.services;
|
|
4397
|
+
const route = routeOf(artifactId);
|
|
4398
|
+
if (!route || !services.operator.has.linkHost) return void 0;
|
|
4399
|
+
const wanted = await services.operator.linkHost({
|
|
4400
|
+
account: services.owner(id).account,
|
|
4401
|
+
home: id,
|
|
4402
|
+
routeId: route.id
|
|
4403
|
+
});
|
|
4404
|
+
if (wanted === null) return void 0;
|
|
4405
|
+
const host = await services.routing.linkHost(id, route.id, wanted);
|
|
4406
|
+
return host === void 0 ? void 0 : originOf(host);
|
|
4407
|
+
},
|
|
4408
|
+
frameAncestors: (artifactId, frameOrigin) => {
|
|
4409
|
+
const route = routeOf(artifactId);
|
|
4410
|
+
const host = hostOfOrigin(frameOrigin);
|
|
4411
|
+
if (!route || host === void 0) return "";
|
|
4412
|
+
const frameDomain = host.slice(host.indexOf(".") + 1);
|
|
4413
|
+
return options.services.routing.ancestorsOf(id, route.id, frameDomain).map(originOf).join(" ");
|
|
4414
|
+
}
|
|
4415
|
+
} : {},
|
|
4416
|
+
...options.services ? hostedPages({
|
|
4417
|
+
homeId: id,
|
|
4418
|
+
ledger,
|
|
4419
|
+
interaction,
|
|
4420
|
+
capabilities,
|
|
4421
|
+
artifact: (artifactId) => registry.get({ artifactId }),
|
|
4422
|
+
routeOf,
|
|
4423
|
+
owner: () => options.services.owner(id),
|
|
4424
|
+
signInOffered: options.services.signInOffered,
|
|
4425
|
+
operator: options.services.operator,
|
|
4426
|
+
clients: options.services.clients,
|
|
4427
|
+
rates: options.services.rates,
|
|
4428
|
+
rateLimits: options.services.rateLimits,
|
|
4429
|
+
madeWith: options.services.madeWith,
|
|
4430
|
+
...options.services.signin ? { signin: options.services.signin } : {},
|
|
4431
|
+
viewed: (input) => metered(input.artifactId, input.viewerId),
|
|
4432
|
+
log
|
|
4433
|
+
}) : {}
|
|
2110
4434
|
}
|
|
2111
4435
|
});
|
|
2112
4436
|
/** The faces of a domain: its shell, and a route's frames, opened when first asked for. */
|
|
@@ -2168,6 +4492,70 @@ async function openHostedHome(options) {
|
|
|
2168
4492
|
};
|
|
2169
4493
|
/** The client files of a listing this home doesn't hold yet. */
|
|
2170
4494
|
const missingOf = (files) => directory.read((db) => files.filter((sha) => !db.get("SELECT 1 FROM home_file WHERE home_id = ? AND sha256 = ?", id, sha)));
|
|
4495
|
+
/**
|
|
4496
|
+
* Quarantines a route's artifact, or one version of it, in this home only (D165 item 9): its
|
|
4497
|
+
* links show the neutral "under review" page and its files are withheld; data is kept. An
|
|
4498
|
+
* identical version in another home is untouched, since the row is this home's.
|
|
4499
|
+
*/
|
|
4500
|
+
const quarantine = (artifactId, versionId, reason) => {
|
|
4501
|
+
ledger.write((db) => db.run(`INSERT INTO quarantine (artifact_id, version_id, reason, at) VALUES (?, ?, ?, ?)
|
|
4502
|
+
ON CONFLICT (artifact_id, version_id) DO UPDATE SET reason = excluded.reason`, artifactId, versionId ?? "", reason.slice(0, 1e3), (/* @__PURE__ */ new Date()).toISOString()));
|
|
4503
|
+
log.info("server.quarantined", {
|
|
4504
|
+
home: id,
|
|
4505
|
+
artifactId,
|
|
4506
|
+
versionId: versionId ?? null
|
|
4507
|
+
});
|
|
4508
|
+
};
|
|
4509
|
+
/**
|
|
4510
|
+
* `view/url` on a hosted home under the operator's `limits` (`link`): refused with its words, and
|
|
4511
|
+
* refused for now when the operator doesn't answer, since a link creates something (D165 item 9).
|
|
4512
|
+
*/
|
|
4513
|
+
const limitedLinks = (method) => ({
|
|
4514
|
+
definition: method.definition,
|
|
4515
|
+
async handle(params, session) {
|
|
4516
|
+
const services = options.services;
|
|
4517
|
+
if (services) {
|
|
4518
|
+
const ref = params.artifact;
|
|
4519
|
+
const artifactId = registry.get(canonicalRef(ref)).id;
|
|
4520
|
+
const route = routeOf(artifactId);
|
|
4521
|
+
const verdict = await services.operator.limit({
|
|
4522
|
+
account: services.owner(id).account,
|
|
4523
|
+
home: id,
|
|
4524
|
+
artifact: artifactId,
|
|
4525
|
+
...route ? { routeId: route.id } : {},
|
|
4526
|
+
operation: "link"
|
|
4527
|
+
});
|
|
4528
|
+
if (verdict.allowed === "unavailable") throw refuse("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", "The server's operator didn't answer in time; try minting the link again.");
|
|
4529
|
+
if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
|
|
4530
|
+
}
|
|
4531
|
+
return method.handle(params, session);
|
|
4532
|
+
}
|
|
4533
|
+
});
|
|
4534
|
+
/**
|
|
4535
|
+
* A view for metering, under the viewer's monthly pseudonymous key (D167): the account for a
|
|
4536
|
+
* signed-in viewer, the viewer for a link minted with one, the route's key for anyone else.
|
|
4537
|
+
*/
|
|
4538
|
+
const metered = (artifactId, viewerId) => {
|
|
4539
|
+
const meter = options.services?.meter;
|
|
4540
|
+
if (!meter?.on) return;
|
|
4541
|
+
const viewer = ledger.read((db) => db.get("SELECT kind, external_ref FROM viewer WHERE id = ?", viewerId));
|
|
4542
|
+
const subject = viewer?.kind === "account" || viewer?.kind === "anonymous" ? `${viewer.kind}:${viewer.external_ref ?? viewerId}` : `viewer:${id}:${viewerId}`;
|
|
4543
|
+
const route = routeOf(artifactId);
|
|
4544
|
+
meter.add("views", {
|
|
4545
|
+
account: options.services.owner(id).account,
|
|
4546
|
+
home: id,
|
|
4547
|
+
artifactId,
|
|
4548
|
+
...route ? { routeId: route.id } : {},
|
|
4549
|
+
dimensions: { viewerKey: meter.viewerKey(subject) }
|
|
4550
|
+
});
|
|
4551
|
+
};
|
|
4552
|
+
/** The live links of an artifact, revoked; answers how many were live. */
|
|
4553
|
+
const revokeLinks = (artifactId) => {
|
|
4554
|
+
const tokens = ledger.read((db) => db.all("SELECT id FROM token WHERE artifact_id = ? AND revoked_at IS NULL", artifactId).map((row) => row.id));
|
|
4555
|
+
let revoked = 0;
|
|
4556
|
+
for (const tokenId of tokens) if (capabilities.revoke(tokenId) === "revoked") revoked += 1;
|
|
4557
|
+
return revoked;
|
|
4558
|
+
};
|
|
2171
4559
|
const push = async (params, session) => {
|
|
2172
4560
|
const link = session.link?.instanceId;
|
|
2173
4561
|
if (link === void 0 || session.attributes["linkId"] !== link) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", "Only an owner instance's binding pushes versions.");
|
|
@@ -2194,6 +4582,17 @@ async function openHostedHome(options) {
|
|
|
2194
4582
|
if (manifestDoc.artifactId !== params.artifactId || manifestDoc.versionId !== version.versionId) throw refuse("MOSTRA_HOME_INTEGRITY", "The pushed manifest.json names another version.");
|
|
2195
4583
|
const manifest = ArtifactManifest.safeParse(manifestDoc.manifest);
|
|
2196
4584
|
if (!manifest.success) throw refuse("MOSTRA_HOME_INTEGRITY", "The pushed artifact manifest isn't valid.");
|
|
4585
|
+
const services = options.services;
|
|
4586
|
+
if (services && routeOf(params.artifactId) === void 0) {
|
|
4587
|
+
const verdict = await services.operator.limit({
|
|
4588
|
+
account: services.owner(id).account,
|
|
4589
|
+
home: id,
|
|
4590
|
+
artifact: params.artifactId,
|
|
4591
|
+
operation: "share"
|
|
4592
|
+
});
|
|
4593
|
+
if (verdict.allowed === "unavailable") throw refuse("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", "The server's operator didn't answer in time; the share is tried again later.");
|
|
4594
|
+
if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
|
|
4595
|
+
}
|
|
2197
4596
|
const route = routeFor(params.artifactId, link);
|
|
2198
4597
|
if (registry.hasVersion(version.versionId)) {
|
|
2199
4598
|
const known = registry.get({ artifactId: params.artifactId }).versions.find((v) => v.id === version.versionId);
|
|
@@ -2205,9 +4604,34 @@ async function openHostedHome(options) {
|
|
|
2205
4604
|
};
|
|
2206
4605
|
}
|
|
2207
4606
|
const clientFiles = version.listing.filter(([path]) => path.startsWith("client/"));
|
|
4607
|
+
const sizes = /* @__PURE__ */ new Map();
|
|
4608
|
+
for (const [path, , sha, size] of clientFiles) {
|
|
4609
|
+
if (!Number.isSafeInteger(size) || size < 0 || (sizes.get(sha) ?? size) !== size) throw refuse("MOSTRA_HOME_INTEGRITY", `The listing gives ${path} a size its bytes can't have.`);
|
|
4610
|
+
sizes.set(sha, size);
|
|
4611
|
+
}
|
|
4612
|
+
for (const [sha, size] of sizes) {
|
|
4613
|
+
if (directory.read((db) => db.get("SELECT 1 FROM home_file WHERE home_id = ? AND sha256 = ?", id, sha)) === void 0) continue;
|
|
4614
|
+
const onDisk = await stat(join(options.filesDir, sha)).then((found) => found.size, () => void 0);
|
|
4615
|
+
if (onDisk !== void 0 && onDisk !== size) throw refuse("MOSTRA_HOME_INTEGRITY", "The listing gives a held file another size than its bytes.");
|
|
4616
|
+
}
|
|
4617
|
+
if (services) {
|
|
4618
|
+
const owner = services.owner(id).account;
|
|
4619
|
+
for (const [operation, quantity] of [["version.push", 1], ["storage", [...sizes.values()].reduce((sum, size) => sum + size, 0)]]) {
|
|
4620
|
+
const verdict = await services.operator.limit({
|
|
4621
|
+
account: owner,
|
|
4622
|
+
home: id,
|
|
4623
|
+
artifact: params.artifactId,
|
|
4624
|
+
routeId: route.routeId,
|
|
4625
|
+
operation,
|
|
4626
|
+
quantity
|
|
4627
|
+
});
|
|
4628
|
+
if (verdict.allowed === "unavailable") throw refuse("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", "The server's operator didn't answer in time; the push is tried again later.");
|
|
4629
|
+
if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
2208
4632
|
const missing = missingOf([...new Set(clientFiles.map(([, , sha]) => sha))]);
|
|
2209
4633
|
if (missing.length > 0) {
|
|
2210
|
-
pending.set(version.versionId, new
|
|
4634
|
+
pending.set(version.versionId, new Map(missing.map((sha) => [sha, sizes.get(sha)])));
|
|
2211
4635
|
return {
|
|
2212
4636
|
status: "missing",
|
|
2213
4637
|
files: missing,
|
|
@@ -2273,6 +4697,26 @@ async function openHostedHome(options) {
|
|
|
2273
4697
|
artifactId: params.artifactId,
|
|
2274
4698
|
versionId: version.versionId
|
|
2275
4699
|
});
|
|
4700
|
+
if (services?.operator.has.pushed) {
|
|
4701
|
+
const files = clientFiles.map(([path]) => path);
|
|
4702
|
+
const shaOf = new Map(clientFiles.map(([path, , sha]) => [path, sha]));
|
|
4703
|
+
services.operator.pushed({
|
|
4704
|
+
routeId: route.routeId,
|
|
4705
|
+
label: route.label,
|
|
4706
|
+
artifactId: params.artifactId,
|
|
4707
|
+
home: id,
|
|
4708
|
+
versionId: version.versionId,
|
|
4709
|
+
manifest: manifest.data,
|
|
4710
|
+
files,
|
|
4711
|
+
read: async (path) => {
|
|
4712
|
+
const sha = shaOf.get(path);
|
|
4713
|
+
if (sha === void 0) throw new Error(`No client file ${path} in this version.`);
|
|
4714
|
+
return new Uint8Array(await readFile(join(options.filesDir, sha)));
|
|
4715
|
+
}
|
|
4716
|
+
}, async (reason) => {
|
|
4717
|
+
quarantine(params.artifactId, version.versionId, reason);
|
|
4718
|
+
});
|
|
4719
|
+
}
|
|
2276
4720
|
return {
|
|
2277
4721
|
status: "complete",
|
|
2278
4722
|
versionId: version.versionId,
|
|
@@ -2317,97 +4761,1169 @@ async function openHostedHome(options) {
|
|
|
2317
4761
|
ledger.write((db) => db.run(`INSERT INTO relay_floor (link_id, floor) VALUES (?, ?)
|
|
2318
4762
|
ON CONFLICT (link_id) DO UPDATE SET floor = MAX(floor, excluded.floor)`, link.instanceId, link.relayMark));
|
|
2319
4763
|
}
|
|
2320
|
-
if (params.link !== void 0 && params.link.instanceId !== session.attributes["linkId"]) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", "This binding's sign-in is for another instance link.");
|
|
2321
|
-
if (params.link === void 0 && params.ports.length > 0) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", "A binding that registers ports must name its own instance link.");
|
|
4764
|
+
if (params.link !== void 0 && params.link.instanceId !== session.attributes["linkId"]) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", "This binding's sign-in is for another instance link.");
|
|
4765
|
+
if (params.link === void 0 && params.ports.length > 0) throw refuse("MOSTRA_REMOTE_NOT_OWNER_INSTANCE", "A binding that registers ports must name its own instance link.");
|
|
4766
|
+
},
|
|
4767
|
+
onInitialized: (session) => {
|
|
4768
|
+
interaction.connected(session);
|
|
4769
|
+
relay.connected(session);
|
|
4770
|
+
},
|
|
4771
|
+
onClosed: (session) => {
|
|
4772
|
+
interaction.disconnected(session);
|
|
4773
|
+
relay.disconnected(session);
|
|
4774
|
+
},
|
|
4775
|
+
handlers: [
|
|
4776
|
+
...interaction.methods(),
|
|
4777
|
+
handler(artifactListMethod, (params) => ({ artifacts: registry.list(params.filter ?? {}) })),
|
|
4778
|
+
handler(artifactGetMethod, (params) => registry.get(canonicalRef(params.artifact))),
|
|
4779
|
+
handler(hostedPushMethod, (params, session) => push(params, session)),
|
|
4780
|
+
handler(hostedSubmissionMethod, (params, session) => {
|
|
4781
|
+
const link = session.link?.instanceId;
|
|
4782
|
+
const envelope = link === void 0 ? void 0 : interaction.envelopeFor(params.submissionId, link);
|
|
4783
|
+
if (!envelope) throw refuse("MOSTRA_HOST_INVALID_PARAMS", `This home delivers no submission ${params.submissionId} to this instance.`);
|
|
4784
|
+
return envelope;
|
|
4785
|
+
}),
|
|
4786
|
+
...gateway.methods().map((method) => method.definition.method === viewUrlMethod.method ? limitedLinks(method) : method),
|
|
4787
|
+
handler(artifactPauseMethod, (params) => {
|
|
4788
|
+
const artifactId = registry.get(canonicalRef(params.artifact)).id;
|
|
4789
|
+
return interaction.pause(artifactId, {
|
|
4790
|
+
paused: params.paused,
|
|
4791
|
+
by: "owner",
|
|
4792
|
+
...params.reason !== void 0 ? { reason: params.reason } : {}
|
|
4793
|
+
});
|
|
4794
|
+
}),
|
|
4795
|
+
...relay.methods(),
|
|
4796
|
+
...liveMethods(live, (ref) => registry.get(canonicalRef(ref)).id),
|
|
4797
|
+
handler(remoteTokenMethod, (params, session) => {
|
|
4798
|
+
const found = options.auth.authenticate(params.accessToken);
|
|
4799
|
+
if (!found || found.grantId !== session.attributes["grantId"]) throw refuse("MOSTRA_REMOTE_LOGIN_FAILED", "That access token isn't this binding's grant's.");
|
|
4800
|
+
const replace = session.attributes["replaceToken"];
|
|
4801
|
+
replace?.(found.expiresAt);
|
|
4802
|
+
return { expiresAt: new Date(found.expiresAt).toISOString() };
|
|
4803
|
+
})
|
|
4804
|
+
]
|
|
4805
|
+
});
|
|
4806
|
+
interaction.start();
|
|
4807
|
+
live.start();
|
|
4808
|
+
const feed = options.services ? createOperatorFeed({
|
|
4809
|
+
homeId: id,
|
|
4810
|
+
ledger,
|
|
4811
|
+
interaction,
|
|
4812
|
+
operator: options.services.operator,
|
|
4813
|
+
meter: options.services.meter,
|
|
4814
|
+
account: () => options.services.owner(id).account,
|
|
4815
|
+
routeOf,
|
|
4816
|
+
incarnation: () => incarnation,
|
|
4817
|
+
log
|
|
4818
|
+
}) : void 0;
|
|
4819
|
+
return {
|
|
4820
|
+
id,
|
|
4821
|
+
dir,
|
|
4822
|
+
ledger,
|
|
4823
|
+
registry,
|
|
4824
|
+
interaction,
|
|
4825
|
+
protocol,
|
|
4826
|
+
incarnation: () => incarnation,
|
|
4827
|
+
wanted: (sha) => {
|
|
4828
|
+
for (const files of pending.values()) {
|
|
4829
|
+
const size = files.get(sha);
|
|
4830
|
+
if (size !== void 0) return size;
|
|
4831
|
+
}
|
|
4832
|
+
},
|
|
4833
|
+
uploaded(sha) {
|
|
4834
|
+
directory.write((db) => {
|
|
4835
|
+
if (db.run("INSERT OR IGNORE INTO home_file (home_id, sha256) VALUES (?, ?)", id, sha).changes > 0) db.run("INSERT INTO file_ref (sha256, homes) VALUES (?, 1) ON CONFLICT (sha256) DO UPDATE SET homes = homes + 1, unreferenced_at = NULL", sha);
|
|
4836
|
+
});
|
|
4837
|
+
for (const files of pending.values()) files.delete(sha);
|
|
4838
|
+
},
|
|
4839
|
+
pause: (artifactId, change) => interaction.pause(artifactId, change),
|
|
4840
|
+
quarantine,
|
|
4841
|
+
release(artifactId, versionId) {
|
|
4842
|
+
ledger.write((db) => db.run(versionId === void 0 ? "DELETE FROM quarantine WHERE artifact_id = ?" : "DELETE FROM quarantine WHERE artifact_id = ? AND version_id = ?", ...versionId === void 0 ? [artifactId] : [artifactId, versionId]));
|
|
4843
|
+
},
|
|
4844
|
+
revokeLinks,
|
|
4845
|
+
revokeLink: (tokenId) => capabilities.revoke(tokenId) !== "unknown",
|
|
4846
|
+
async remove(artifactId) {
|
|
4847
|
+
/** The client files a version's listing names. */
|
|
4848
|
+
const clientFilesOf = async (versionId) => {
|
|
4849
|
+
try {
|
|
4850
|
+
return JSON.parse(await readFile(join(registry.store.versionDir(versionId), "listing.json"), "utf8")).filter(([path]) => path.startsWith("client/")).map(([, , sha]) => sha);
|
|
4851
|
+
} catch {
|
|
4852
|
+
return [];
|
|
4853
|
+
}
|
|
4854
|
+
};
|
|
4855
|
+
const recorded = directory.read((db) => db.get("SELECT removing_json FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId)?.removing_json);
|
|
4856
|
+
let plan;
|
|
4857
|
+
if (recorded != null) plan = JSON.parse(recorded);
|
|
4858
|
+
else {
|
|
4859
|
+
const versions = registry.get({ artifactId }).versions.map((version) => version.id);
|
|
4860
|
+
const files = /* @__PURE__ */ new Set();
|
|
4861
|
+
for (const versionId of versions) for (const sha of await clientFilesOf(versionId)) files.add(sha);
|
|
4862
|
+
plan = {
|
|
4863
|
+
versions,
|
|
4864
|
+
going: [...files]
|
|
4865
|
+
};
|
|
4866
|
+
directory.write((db) => db.run("UPDATE artifact_route SET removing_json = ? WHERE home_id = ? AND artifact_id = ?", JSON.stringify(plan), id, artifactId));
|
|
4867
|
+
}
|
|
4868
|
+
const versions = plan.versions;
|
|
4869
|
+
const going = new Set(plan.going);
|
|
4870
|
+
if (registry.list({}).some((summary) => summary.id === artifactId)) revokeLinks(artifactId);
|
|
4871
|
+
const removed = ledger.removal((db) => purgeArtifact(db, artifactId));
|
|
4872
|
+
faults.at("remove:after-purge");
|
|
4873
|
+
const kept = /* @__PURE__ */ new Set();
|
|
4874
|
+
for (const other of registry.list({})) for (const version of registry.get({ artifactId: other.id }).versions) for (const sha of await clientFilesOf(version.id)) kept.add(sha);
|
|
4875
|
+
const route = directory.read((db) => db.get("SELECT id FROM artifact_route WHERE home_id = ? AND artifact_id = ?", id, artifactId));
|
|
4876
|
+
directory.write((db) => {
|
|
4877
|
+
for (const sha of going) {
|
|
4878
|
+
if (kept.has(sha)) continue;
|
|
4879
|
+
if (db.run("DELETE FROM home_file WHERE home_id = ? AND sha256 = ?", id, sha).changes > 0) db.run(`UPDATE file_ref SET homes = homes - 1,
|
|
4880
|
+
unreferenced_at = CASE WHEN homes - 1 = 0 THEN ? ELSE NULL END
|
|
4881
|
+
WHERE sha256 = ?`, (/* @__PURE__ */ new Date()).toISOString(), sha);
|
|
4882
|
+
}
|
|
4883
|
+
if (route) {
|
|
4884
|
+
db.run("DELETE FROM hosted_token WHERE route_id = ?", route.id);
|
|
4885
|
+
db.run("DELETE FROM artifact_route WHERE id = ?", route.id);
|
|
4886
|
+
}
|
|
4887
|
+
});
|
|
4888
|
+
for (const versionId of versions) await removeTree(registry.store.versionDir(versionId)).catch((error) => log.warn("server.remove_files_failed", {
|
|
4889
|
+
versionId,
|
|
4890
|
+
error
|
|
4891
|
+
}));
|
|
4892
|
+
const rows = Object.values(removed).reduce((sum, count) => sum + count, 0);
|
|
4893
|
+
log.info("server.artifact_removed", {
|
|
4894
|
+
home: id,
|
|
4895
|
+
artifactId,
|
|
4896
|
+
rows
|
|
4897
|
+
});
|
|
4898
|
+
return { rows };
|
|
4899
|
+
},
|
|
4900
|
+
defaultOwnerSession() {
|
|
4901
|
+
const link = directory.read((db) => db.get("SELECT id FROM instance_link WHERE home_id = ? AND is_default = 1 AND revoked_at IS NULL", id)?.id);
|
|
4902
|
+
if (link === void 0) return void 0;
|
|
4903
|
+
return protocol.registrants("relay").filter((entry) => entry.owner === link).at(-1)?.session;
|
|
4904
|
+
},
|
|
4905
|
+
busy: () => protocol.connections > 0 || bus.activeViews() > 0 || relay.busy(),
|
|
4906
|
+
serve,
|
|
4907
|
+
async stop() {
|
|
4908
|
+
feed?.stop();
|
|
4909
|
+
relay.stop();
|
|
4910
|
+
live.stop();
|
|
4911
|
+
interaction.stop();
|
|
4912
|
+
await gateway.close();
|
|
4913
|
+
await protocol.close();
|
|
4914
|
+
bus.close?.();
|
|
4915
|
+
}
|
|
4916
|
+
};
|
|
4917
|
+
}
|
|
4918
|
+
/**
|
|
4919
|
+
* What is wrong with a hosted version's stored files (FAILURE_MODEL §3): its listing must be the
|
|
4920
|
+
* one its output digest names, and every client file it lists present with its bytes. Server files
|
|
4921
|
+
* are listed but never stored (D165 item 3).
|
|
4922
|
+
*/
|
|
4923
|
+
async function hostedDamage(versionDir) {
|
|
4924
|
+
try {
|
|
4925
|
+
const manifest = JSON.parse(await readFile(join(versionDir, "manifest.json"), "utf8"));
|
|
4926
|
+
const listing = JSON.parse(await readFile(join(versionDir, "listing.json"), "utf8"));
|
|
4927
|
+
const listed = listing.map(([path, executable, sha256]) => ({
|
|
4928
|
+
path,
|
|
4929
|
+
executable,
|
|
4930
|
+
sha256
|
|
4931
|
+
}));
|
|
4932
|
+
if (listingDigest(listed) !== manifest.outputDigest) return "its listing doesn't match its digest";
|
|
4933
|
+
for (const [path, , sha256] of listing) {
|
|
4934
|
+
if (!path.startsWith("client/") && path !== "registry.json") continue;
|
|
4935
|
+
const bytes = await readFile(join(versionDir, ...path.split("/")));
|
|
4936
|
+
if (createHash("sha256").update(bytes).digest("hex") !== sha256) return `${path} was changed`;
|
|
4937
|
+
}
|
|
4938
|
+
return;
|
|
4939
|
+
} catch (error) {
|
|
4940
|
+
return `a file is missing (${error.code ?? "unreadable"})`;
|
|
4941
|
+
}
|
|
4942
|
+
}
|
|
4943
|
+
/** The SHA-256 of a text's UTF-8 bytes, lowercase hex. */
|
|
4944
|
+
function sha256Text(text) {
|
|
4945
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
4946
|
+
}
|
|
4947
|
+
//#endregion
|
|
4948
|
+
//#region src/server/mcp.ts
|
|
4949
|
+
/**
|
|
4950
|
+
* The remote MCP server (INTERFACES §18.8, MC-04, D165 items 5, 10): `@mostra/mcp`'s tools over
|
|
4951
|
+
* Streamable HTTP at `<apiOrigin>/mcp`, statelessly, behind the authorization server. Each request
|
|
4952
|
+
* is built for the account its token names:
|
|
4953
|
+
*
|
|
4954
|
+
* - **the instance** reads and writes the account's hosted home through a protocol session of its
|
|
4955
|
+
* own in this process, as any host would (invariant 11); authoring (`artifact/create`, `verify`,
|
|
4956
|
+
* `publish`) goes to the account's default owner instance through `port/relay.author`, and
|
|
4957
|
+
* answers `MOSTRA_REMOTE_NO_INSTANCE` while none is connected;
|
|
4958
|
+
* - **the workspace** is the default owner instance's own, reached the same way;
|
|
4959
|
+
* - **the docs** are the reference this build carries. There is no browser.
|
|
4960
|
+
*
|
|
4961
|
+
* Each call is counted (`mcp.calls`, with the client's `clientInfo` name, D148) and asked of the
|
|
4962
|
+
* operator's `limits` (`mcp.call`) first; a refusal answers the operator's code.
|
|
4963
|
+
*/
|
|
4964
|
+
/** How long a relayed authoring step may take: verify and publish can take minutes. */
|
|
4965
|
+
const AUTHOR_TIMEOUT_MS = 6e5;
|
|
4966
|
+
/** How long a workspace step may take. */
|
|
4967
|
+
const WORKSPACE_TIMEOUT_MS = 3e4;
|
|
4968
|
+
/** How long a relayed publish waits for its version to arrive here before answering its link. */
|
|
4969
|
+
const PUSH_WAIT_MS = 12e4;
|
|
4970
|
+
/** The largest request body read. */
|
|
4971
|
+
const MAX_BODY_BYTES = 16777216;
|
|
4972
|
+
/** The methods that run on the owner instance, never on the hosted home. */
|
|
4973
|
+
const AUTHORING = /* @__PURE__ */ new Set([
|
|
4974
|
+
"artifact/create",
|
|
4975
|
+
"artifact/verify",
|
|
4976
|
+
"artifact/publish"
|
|
4977
|
+
]);
|
|
4978
|
+
function noInstance() {
|
|
4979
|
+
return new RpcError(createDiagnostic("MOSTRA_REMOTE_NO_INSTANCE", { message: "No Mostra instance of this account is connected to the server, and building and verifying run there. Start Mostra on the linked machine (mostra daemon start), or link one with mostra login <server> --default." }));
|
|
4980
|
+
}
|
|
4981
|
+
/**
|
|
4982
|
+
* The reference this runtime carries: its build's copy (`dist/reference`, `dist/skill`), or the
|
|
4983
|
+
* repository's when it runs from source.
|
|
4984
|
+
*/
|
|
4985
|
+
function serverDocs() {
|
|
4986
|
+
const root = runtimeRoot();
|
|
4987
|
+
const built = join(root, "dist", "reference");
|
|
4988
|
+
return existsSync(built) ? fileDocs({
|
|
4989
|
+
referenceDir: built,
|
|
4990
|
+
skillDir: join(root, "dist", "skill")
|
|
4991
|
+
}) : fileDocs({
|
|
4992
|
+
referenceDir: join(root, "..", "..", "docs", "reference"),
|
|
4993
|
+
skillDir: join(root, "..", "..", "skills", "mostra")
|
|
4994
|
+
});
|
|
4995
|
+
}
|
|
4996
|
+
/** Builds the endpoint. */
|
|
4997
|
+
function createRemoteMcp(options) {
|
|
4998
|
+
const { log } = options;
|
|
4999
|
+
/** The default owner instance's session on a home: the account's chat-host authoring goes there. */
|
|
5000
|
+
const authorOn = (home) => {
|
|
5001
|
+
const call = async (method, params, timeoutMs) => {
|
|
5002
|
+
const session = home.defaultOwnerSession();
|
|
5003
|
+
if (session === void 0) throw noInstance();
|
|
5004
|
+
return await home.protocol.callSession(session, portRelayAuthorMethod.method, {
|
|
5005
|
+
method,
|
|
5006
|
+
params
|
|
5007
|
+
}, timeoutMs);
|
|
5008
|
+
};
|
|
5009
|
+
return call;
|
|
5010
|
+
};
|
|
5011
|
+
const endpoint = createAuthorizedEndpoint((authorization) => {
|
|
5012
|
+
const subject = authorization.subject;
|
|
5013
|
+
const author = authorOn(subject.home);
|
|
5014
|
+
const resolveRef = async (ref) => {
|
|
5015
|
+
if (!("path" in ref)) return ref;
|
|
5016
|
+
return { artifactId: (await author("artifact/get", { artifact: ref }, WORKSPACE_TIMEOUT_MS)).id };
|
|
5017
|
+
};
|
|
5018
|
+
return {
|
|
5019
|
+
instance: {
|
|
5020
|
+
async call(method, params) {
|
|
5021
|
+
if (method.method === "artifact/publish") {
|
|
5022
|
+
const receipt = await author("artifact/publish", params, AUTHOR_TIMEOUT_MS);
|
|
5023
|
+
const until = Date.now() + PUSH_WAIT_MS;
|
|
5024
|
+
while (!subject.home.registry.hasVersion(receipt.versionId) && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 100));
|
|
5025
|
+
const link = await subject.client.peer.call(viewDefaultMethod, { artifact: { artifactId: receipt.artifactId } });
|
|
5026
|
+
return {
|
|
5027
|
+
...receipt,
|
|
5028
|
+
url: link.url,
|
|
5029
|
+
tokenId: link.tokenId
|
|
5030
|
+
};
|
|
5031
|
+
}
|
|
5032
|
+
if (AUTHORING.has(method.method)) return await author(method.method, params, AUTHOR_TIMEOUT_MS);
|
|
5033
|
+
const value = params;
|
|
5034
|
+
const sent = value.artifact !== void 0 ? {
|
|
5035
|
+
...value,
|
|
5036
|
+
artifact: await resolveRef(value.artifact)
|
|
5037
|
+
} : params;
|
|
5038
|
+
return await subject.client.peer.call(method, sent);
|
|
5039
|
+
},
|
|
5040
|
+
onProgress: () => () => void 0
|
|
5041
|
+
},
|
|
5042
|
+
workspace: {
|
|
5043
|
+
root: subject.root,
|
|
5044
|
+
resolveDir: (dir) => dir,
|
|
5045
|
+
allocateDir: async (title) => await author("workspace/allocate", { title }, WORKSPACE_TIMEOUT_MS),
|
|
5046
|
+
async read(dir, path) {
|
|
5047
|
+
const answer = await author("workspace/read", {
|
|
5048
|
+
dir,
|
|
5049
|
+
path
|
|
5050
|
+
}, WORKSPACE_TIMEOUT_MS);
|
|
5051
|
+
return answer.content === void 0 ? void 0 : Buffer.from(answer.content, "base64");
|
|
5052
|
+
},
|
|
5053
|
+
async apply(dir, changes) {
|
|
5054
|
+
return await author("workspace/apply", {
|
|
5055
|
+
dir,
|
|
5056
|
+
write: changes.write.map((file) => ({
|
|
5057
|
+
path: file.path,
|
|
5058
|
+
content: Buffer.from(file.content).toString("base64")
|
|
5059
|
+
})),
|
|
5060
|
+
delete: changes.delete
|
|
5061
|
+
}, WORKSPACE_TIMEOUT_MS);
|
|
5062
|
+
}
|
|
5063
|
+
},
|
|
5064
|
+
docs: options.docs,
|
|
5065
|
+
version: options.version,
|
|
5066
|
+
readScreenshot: async (path) => {
|
|
5067
|
+
const answer = await author("verify/screenshot", { path }, WORKSPACE_TIMEOUT_MS);
|
|
5068
|
+
if (answer.png === void 0) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message: "That screenshot isn't one of the owner instance's verify runs." }));
|
|
5069
|
+
return Buffer.from(answer.png, "base64");
|
|
5070
|
+
},
|
|
5071
|
+
onClient: (client) => {
|
|
5072
|
+
options.meter?.add("mcp.calls", {
|
|
5073
|
+
account: subject.account,
|
|
5074
|
+
home: subject.home.id,
|
|
5075
|
+
dimensions: { client: client.name.slice(0, 64) }
|
|
5076
|
+
});
|
|
5077
|
+
}
|
|
5078
|
+
};
|
|
5079
|
+
}, { onError: (error) => log.warn("mcp.error", { message: error.message }) });
|
|
5080
|
+
return {
|
|
5081
|
+
async handle(request, response, who) {
|
|
5082
|
+
const homeId = who.homeId !== "" ? who.homeId : options.ensureHome(who.accountId);
|
|
5083
|
+
const verdict = await options.operator.limit({
|
|
5084
|
+
account: who.accountId,
|
|
5085
|
+
home: homeId,
|
|
5086
|
+
operation: "mcp.call"
|
|
5087
|
+
});
|
|
5088
|
+
if (verdict.allowed === false || verdict.allowed === "unavailable") {
|
|
5089
|
+
const diagnostic = verdict.allowed === false ? createDiagnostic("MOSTRA_REMOTE_LIMIT_REACHED", { message: verdict.message }) : createDiagnostic("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", { message: "The server's operator didn't answer in time; try again shortly." });
|
|
5090
|
+
const text = JSON.stringify({
|
|
5091
|
+
jsonrpc: "2.0",
|
|
5092
|
+
id: null,
|
|
5093
|
+
error: {
|
|
5094
|
+
code: -32e3,
|
|
5095
|
+
message: diagnostic.message,
|
|
5096
|
+
data: diagnostic
|
|
5097
|
+
}
|
|
5098
|
+
});
|
|
5099
|
+
response.writeHead(verdict.allowed === false ? 403 : 503, {
|
|
5100
|
+
"content-type": "application/json",
|
|
5101
|
+
"cache-control": "no-store",
|
|
5102
|
+
...verdict.allowed === false && verdict.retryAfterMs !== void 0 ? { "retry-after": String(Math.ceil(verdict.retryAfterMs / 1e3)) } : {}
|
|
5103
|
+
});
|
|
5104
|
+
response.end(text);
|
|
5105
|
+
return;
|
|
5106
|
+
}
|
|
5107
|
+
const chunks = [];
|
|
5108
|
+
let size = 0;
|
|
5109
|
+
for await (const chunk of request) {
|
|
5110
|
+
size += chunk.length;
|
|
5111
|
+
if (size > MAX_BODY_BYTES) {
|
|
5112
|
+
response.writeHead(413, { "content-type": "application/json" });
|
|
5113
|
+
response.end(JSON.stringify({
|
|
5114
|
+
jsonrpc: "2.0",
|
|
5115
|
+
id: null,
|
|
5116
|
+
error: {
|
|
5117
|
+
code: -32600,
|
|
5118
|
+
message: "The request is too large."
|
|
5119
|
+
}
|
|
5120
|
+
}));
|
|
5121
|
+
return;
|
|
5122
|
+
}
|
|
5123
|
+
chunks.push(chunk);
|
|
5124
|
+
}
|
|
5125
|
+
const headers = new Headers();
|
|
5126
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
5127
|
+
if (value === void 0 || name === "host" || name === "cookie") continue;
|
|
5128
|
+
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
5129
|
+
}
|
|
5130
|
+
const web = new Request(`${options.apiOrigin}${request.url ?? "/mcp"}`, {
|
|
5131
|
+
method: request.method ?? "POST",
|
|
5132
|
+
headers,
|
|
5133
|
+
...request.method === "POST" ? { body: Buffer.concat(chunks) } : {}
|
|
5134
|
+
});
|
|
5135
|
+
const home = await options.home(homeId);
|
|
5136
|
+
let root = "the workspace of this account's Mostra instance";
|
|
5137
|
+
if (home.defaultOwnerSession() !== void 0) {
|
|
5138
|
+
const found = await authorOn(home)("workspace/root", {}, WORKSPACE_TIMEOUT_MS).catch(() => void 0);
|
|
5139
|
+
if (typeof found === "string") root = found;
|
|
5140
|
+
}
|
|
5141
|
+
const { client } = await attachInProcess(home.protocol, {
|
|
5142
|
+
name: "mostra-remote-mcp",
|
|
5143
|
+
version: options.version
|
|
5144
|
+
}, {
|
|
5145
|
+
accountId: who.accountId,
|
|
5146
|
+
grantId: who.grantId,
|
|
5147
|
+
homeId,
|
|
5148
|
+
linkId: void 0
|
|
5149
|
+
});
|
|
5150
|
+
try {
|
|
5151
|
+
const answer = await endpoint.fetch(web, {
|
|
5152
|
+
token: "",
|
|
5153
|
+
clientId: who.clientId,
|
|
5154
|
+
scopes: ["mostra"],
|
|
5155
|
+
expiresAt: Math.floor(who.expiresAt / 1e3),
|
|
5156
|
+
resource: `${options.apiOrigin}/mcp`,
|
|
5157
|
+
subject: {
|
|
5158
|
+
home,
|
|
5159
|
+
client,
|
|
5160
|
+
account: who.accountId,
|
|
5161
|
+
root
|
|
5162
|
+
}
|
|
5163
|
+
});
|
|
5164
|
+
const out = {};
|
|
5165
|
+
answer.headers.forEach((value, name) => {
|
|
5166
|
+
out[name] = value;
|
|
5167
|
+
});
|
|
5168
|
+
response.writeHead(answer.status, out);
|
|
5169
|
+
if (answer.body) for await (const chunk of answer.body) response.write(chunk);
|
|
5170
|
+
response.end();
|
|
5171
|
+
} finally {
|
|
5172
|
+
client.close();
|
|
5173
|
+
}
|
|
5174
|
+
},
|
|
5175
|
+
close: () => endpoint.close()
|
|
5176
|
+
};
|
|
5177
|
+
}
|
|
5178
|
+
//#endregion
|
|
5179
|
+
//#region src/server/metering.ts
|
|
5180
|
+
/**
|
|
5181
|
+
* Metering for an operator (INTERFACES §18.6, D165 item 9): counters kept in memory for a window,
|
|
5182
|
+
* then handed to the operator's `metering.record` as one batch with a stable `batchId`, through
|
|
5183
|
+
* the durable outbound queue, so a batch is delivered at least once across restarts. With no
|
|
5184
|
+
* metering port nothing is counted.
|
|
5185
|
+
*
|
|
5186
|
+
* Views carry `viewerKey`, a monthly pseudonymous key: an HMAC of the viewer's subject under a key
|
|
5187
|
+
* the server makes for each month (`<data>/keys/metering-<YYYY-MM>`), so an operator can count
|
|
5188
|
+
* monthly viewers without learning who they are or matching them across months. The subject is
|
|
5189
|
+
* the account for a signed-in viewer, the viewer for a link minted with one, and the route's
|
|
5190
|
+
* anonymous key for anyone else (D167): no route ever learns another's key.
|
|
5191
|
+
*/
|
|
5192
|
+
/** How long one batch's window lasts. */
|
|
5193
|
+
const WINDOW_MS = 6e4;
|
|
5194
|
+
/** Creates the meter. */
|
|
5195
|
+
function createMeter(options) {
|
|
5196
|
+
const on = options.operator.has.metering;
|
|
5197
|
+
const now = options.now ?? (() => Date.now());
|
|
5198
|
+
const windowMs = options.windowMs ?? WINDOW_MS;
|
|
5199
|
+
const counters = /* @__PURE__ */ new Map();
|
|
5200
|
+
let from = now();
|
|
5201
|
+
const monthKeys = /* @__PURE__ */ new Map();
|
|
5202
|
+
const monthKey = () => {
|
|
5203
|
+
const month = new Date(now()).toISOString().slice(0, 7);
|
|
5204
|
+
let key = monthKeys.get(month);
|
|
5205
|
+
if (key) return key;
|
|
5206
|
+
const file = join(options.keysDir, `metering-${month}`);
|
|
5207
|
+
try {
|
|
5208
|
+
key = readFileSync(file);
|
|
5209
|
+
} catch {
|
|
5210
|
+
key = randomBytes(32);
|
|
5211
|
+
try {
|
|
5212
|
+
writeFileSync(file, key, {
|
|
5213
|
+
mode: 384,
|
|
5214
|
+
flag: "wx"
|
|
5215
|
+
});
|
|
5216
|
+
} catch {
|
|
5217
|
+
key = readFileSync(file);
|
|
5218
|
+
}
|
|
5219
|
+
}
|
|
5220
|
+
monthKeys.clear();
|
|
5221
|
+
monthKeys.set(month, key);
|
|
5222
|
+
return key;
|
|
5223
|
+
};
|
|
5224
|
+
const flush = () => {
|
|
5225
|
+
if (!on) return;
|
|
5226
|
+
const to = now();
|
|
5227
|
+
const seconds = Math.max(0, Math.round((to - from) / 1e3));
|
|
5228
|
+
if (seconds > 0) for (const active of options.activeHomes?.() ?? []) add("home.activeSeconds", {
|
|
5229
|
+
account: active.account,
|
|
5230
|
+
home: active.home
|
|
5231
|
+
}, seconds);
|
|
5232
|
+
if (counters.size === 0) {
|
|
5233
|
+
from = to;
|
|
5234
|
+
return;
|
|
5235
|
+
}
|
|
5236
|
+
const batch = {
|
|
5237
|
+
batchId: randomUUID(),
|
|
5238
|
+
from: new Date(from).toISOString(),
|
|
5239
|
+
to: new Date(to).toISOString(),
|
|
5240
|
+
counters: [...counters.values()].map(({ counter, value }) => ({
|
|
5241
|
+
...counter,
|
|
5242
|
+
value
|
|
5243
|
+
}))
|
|
5244
|
+
};
|
|
5245
|
+
counters.clear();
|
|
5246
|
+
from = to;
|
|
5247
|
+
options.operator.enqueue({
|
|
5248
|
+
port: "metering",
|
|
5249
|
+
batch
|
|
5250
|
+
});
|
|
5251
|
+
};
|
|
5252
|
+
const add = (name, scope, value = 1) => {
|
|
5253
|
+
if (!on || scope.account === "" || value <= 0) return;
|
|
5254
|
+
const key = JSON.stringify([
|
|
5255
|
+
name,
|
|
5256
|
+
scope.account,
|
|
5257
|
+
scope.home ?? null,
|
|
5258
|
+
scope.artifactId ?? null,
|
|
5259
|
+
scope.routeId ?? null,
|
|
5260
|
+
scope.dimensions ?? null
|
|
5261
|
+
]);
|
|
5262
|
+
const found = counters.get(key);
|
|
5263
|
+
if (found) {
|
|
5264
|
+
found.value += value;
|
|
5265
|
+
return;
|
|
5266
|
+
}
|
|
5267
|
+
counters.set(key, {
|
|
5268
|
+
counter: {
|
|
5269
|
+
name,
|
|
5270
|
+
account: scope.account,
|
|
5271
|
+
...scope.home !== void 0 ? { home: scope.home } : {},
|
|
5272
|
+
...scope.artifactId !== void 0 ? { artifactId: scope.artifactId } : {},
|
|
5273
|
+
...scope.routeId !== void 0 ? { routeId: scope.routeId } : {},
|
|
5274
|
+
value: 0,
|
|
5275
|
+
...scope.dimensions !== void 0 ? { dimensions: { ...scope.dimensions } } : {}
|
|
5276
|
+
},
|
|
5277
|
+
value
|
|
5278
|
+
});
|
|
5279
|
+
};
|
|
5280
|
+
const timer = on ? setInterval(flush, windowMs) : void 0;
|
|
5281
|
+
timer?.unref();
|
|
5282
|
+
if (on) options.log.info("meter.started", { windowMs });
|
|
5283
|
+
return {
|
|
5284
|
+
on,
|
|
5285
|
+
add,
|
|
5286
|
+
viewerKey: (subject) => createHmac("sha256", monthKey()).update(`mostra viewer ${subject}`).digest("base64url"),
|
|
5287
|
+
flush,
|
|
5288
|
+
stop() {
|
|
5289
|
+
if (timer) clearInterval(timer);
|
|
5290
|
+
flush();
|
|
5291
|
+
}
|
|
5292
|
+
};
|
|
5293
|
+
}
|
|
5294
|
+
//#endregion
|
|
5295
|
+
//#region src/server/operator.ts
|
|
5296
|
+
/**
|
|
5297
|
+
* The remote server's operator boundary at run time (ARCHITECTURE §15.10, INTERFACES §18.6, D165
|
|
5298
|
+
* items 9, 11): the operator module a configuration names, loaded in process, and every call into
|
|
5299
|
+
* it. Each call has its time limit and its answer is checked against `@mostra/protocol/operator`'s
|
|
5300
|
+
* schemas; a call that throws, times out or answers what the schema refuses counts as no answer,
|
|
5301
|
+
* and each port's caller says what no answer means (`limits`: operations that create fail closed,
|
|
5302
|
+
* viewer input proceeds; `routing`: nothing is served; `policy`: nothing is added). Outbound
|
|
5303
|
+
* deliveries (`metering`, `events`) are kept in the directory's `outbound` table and retried with
|
|
5304
|
+
* backoff until the operator takes them, at least once and idempotent by their IDs, across
|
|
5305
|
+
* restarts.
|
|
5306
|
+
*
|
|
5307
|
+
* Without an operator module every port is its no-op default, and this module does nothing but
|
|
5308
|
+
* answer "allowed".
|
|
5309
|
+
*/
|
|
5310
|
+
function configInvalid(message) {
|
|
5311
|
+
return new RpcError(createDiagnostic("MOSTRA_REMOTE_CONFIG_INVALID", { message }));
|
|
5312
|
+
}
|
|
5313
|
+
var Timeout = class extends Error {};
|
|
5314
|
+
/** Races a call against its time limit. */
|
|
5315
|
+
async function within(limitMs, call) {
|
|
5316
|
+
let timer;
|
|
5317
|
+
try {
|
|
5318
|
+
return await Promise.race([Promise.resolve().then(call), new Promise((_, reject) => {
|
|
5319
|
+
timer = setTimeout(() => reject(new Timeout(`no answer within ${limitMs} ms`)), limitMs);
|
|
5320
|
+
timer.unref();
|
|
5321
|
+
})]);
|
|
5322
|
+
} finally {
|
|
5323
|
+
if (timer) clearTimeout(timer);
|
|
5324
|
+
}
|
|
5325
|
+
}
|
|
5326
|
+
/** The longest an outbound delivery waits between attempts. */
|
|
5327
|
+
const OUTBOUND_MAX_BACKOFF_MS = 3e5;
|
|
5328
|
+
/**
|
|
5329
|
+
* Loads the operator module a configuration names and starts its outbound dispatcher. A module
|
|
5330
|
+
* that can't be loaded, or whose default export isn't a function, stops the server before it
|
|
5331
|
+
* serves anything (`MOSTRA_REMOTE_CONFIG_INVALID`, naming `operator`).
|
|
5332
|
+
*/
|
|
5333
|
+
async function loadOperator(options) {
|
|
5334
|
+
const { log, directory } = options;
|
|
5335
|
+
const now = options.now ?? (() => Date.now());
|
|
5336
|
+
let ports = {};
|
|
5337
|
+
if (options.path !== void 0) {
|
|
5338
|
+
let loaded;
|
|
5339
|
+
try {
|
|
5340
|
+
loaded = await import(pathToFileURL(options.path).href);
|
|
5341
|
+
} catch (error) {
|
|
5342
|
+
throw configInvalid(`The configuration key \`operator\` names a module that can't be loaded: ${error.message}.`);
|
|
5343
|
+
}
|
|
5344
|
+
if (typeof loaded.default !== "function") throw configInvalid("The configuration key `operator` names a module whose default export isn't a function of the server's handle.");
|
|
5345
|
+
try {
|
|
5346
|
+
ports = await loaded.default(options.handle) ?? {};
|
|
5347
|
+
} catch (error) {
|
|
5348
|
+
throw configInvalid(`The operator module's default export failed: ${error.message}.`);
|
|
5349
|
+
}
|
|
5350
|
+
if (typeof ports !== "object") throw configInvalid("The operator module's default export didn't return its ports.");
|
|
5351
|
+
log.info("operator.loaded", { ports: Object.keys(ports).filter((key) => ports[key]) });
|
|
5352
|
+
}
|
|
5353
|
+
/** One call into the module: time-limited, its answer checked; `undefined` for no answer. */
|
|
5354
|
+
const ask = async (port, limitMs, schema, call) => {
|
|
5355
|
+
try {
|
|
5356
|
+
const answer = await within(limitMs, call);
|
|
5357
|
+
const checked = schema.safeParse(answer);
|
|
5358
|
+
if (!checked.success) {
|
|
5359
|
+
log.warn("operator.answer_refused", {
|
|
5360
|
+
port,
|
|
5361
|
+
issue: checked.error.issues[0]?.message ?? "invalid"
|
|
5362
|
+
});
|
|
5363
|
+
return;
|
|
5364
|
+
}
|
|
5365
|
+
return { value: checked.data };
|
|
5366
|
+
} catch (error) {
|
|
5367
|
+
log.warn("operator.no_answer", {
|
|
5368
|
+
port,
|
|
5369
|
+
why: error instanceof Timeout ? "timeout" : "error",
|
|
5370
|
+
message: error.message
|
|
5371
|
+
});
|
|
5372
|
+
return;
|
|
5373
|
+
}
|
|
5374
|
+
};
|
|
5375
|
+
/** Answers the operator allowed to keep, by key, until their time. */
|
|
5376
|
+
const cache = /* @__PURE__ */ new Map();
|
|
5377
|
+
const cached = (key) => {
|
|
5378
|
+
const hit = cache.get(key);
|
|
5379
|
+
if (!hit) return void 0;
|
|
5380
|
+
if (hit.until <= now()) {
|
|
5381
|
+
cache.delete(key);
|
|
5382
|
+
return;
|
|
5383
|
+
}
|
|
5384
|
+
return hit.value;
|
|
5385
|
+
};
|
|
5386
|
+
const keep = (key, value, forMs) => {
|
|
5387
|
+
if (forMs === void 0 || forMs <= 0) return;
|
|
5388
|
+
if (cache.size >= 1e4) cache.delete(cache.keys().next().value);
|
|
5389
|
+
cache.set(key, {
|
|
5390
|
+
value,
|
|
5391
|
+
until: now() + forMs
|
|
5392
|
+
});
|
|
5393
|
+
};
|
|
5394
|
+
let dispatching;
|
|
5395
|
+
const deliverOne = async (row) => {
|
|
5396
|
+
const payload = JSON.parse(row.payload_json);
|
|
5397
|
+
try {
|
|
5398
|
+
await within(OPERATOR_TIME_LIMITS.outbound, () => row.port === "events" ? ports.events?.deliver(payload) : ports.metering?.record(payload));
|
|
5399
|
+
directory.write((db) => db.run("DELETE FROM outbound WHERE id = ?", row.id));
|
|
5400
|
+
} catch (error) {
|
|
5401
|
+
const delay = Math.min(OUTBOUND_MAX_BACKOFF_MS, 1e3 * 2 ** Math.min(row.attempts, 20));
|
|
5402
|
+
directory.write((db) => db.run("UPDATE outbound SET attempts = attempts + 1, next_attempt_at = ? WHERE id = ?", new Date(now() + delay).toISOString(), row.id));
|
|
5403
|
+
log.warn("operator.outbound_failed", {
|
|
5404
|
+
port: row.port,
|
|
5405
|
+
attempts: row.attempts + 1,
|
|
5406
|
+
message: error.message
|
|
5407
|
+
});
|
|
5408
|
+
}
|
|
5409
|
+
};
|
|
5410
|
+
const dispatch = () => {
|
|
5411
|
+
dispatching ??= (async () => {
|
|
5412
|
+
await Promise.resolve();
|
|
5413
|
+
try {
|
|
5414
|
+
for (;;) {
|
|
5415
|
+
const rows = directory.read((db) => ["events", "metering"].flatMap((port) => db.all("SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = ? ORDER BY rowid LIMIT 50", port)));
|
|
5416
|
+
const due = new Date(now()).toISOString();
|
|
5417
|
+
if (rows.every((row) => row.next_attempt_at > due)) return;
|
|
5418
|
+
const blocked = /* @__PURE__ */ new Set();
|
|
5419
|
+
let delivered = 0;
|
|
5420
|
+
for (const row of rows) {
|
|
5421
|
+
if (blocked.has(row.port)) continue;
|
|
5422
|
+
if (row.next_attempt_at > due) {
|
|
5423
|
+
blocked.add(row.port);
|
|
5424
|
+
continue;
|
|
5425
|
+
}
|
|
5426
|
+
const before = row.attempts;
|
|
5427
|
+
await deliverOne(row);
|
|
5428
|
+
const still = directory.read((db) => db.get("SELECT attempts FROM outbound WHERE id = ?", row.id));
|
|
5429
|
+
if (still && still.attempts > before) blocked.add(row.port);
|
|
5430
|
+
else delivered += 1;
|
|
5431
|
+
}
|
|
5432
|
+
if (delivered === 0) return;
|
|
5433
|
+
}
|
|
5434
|
+
} finally {
|
|
5435
|
+
dispatching = void 0;
|
|
5436
|
+
}
|
|
5437
|
+
})();
|
|
5438
|
+
return dispatching;
|
|
5439
|
+
};
|
|
5440
|
+
const timer = ports.events || ports.metering ? setInterval(() => void dispatch(), options.dispatchMs ?? 1e3) : void 0;
|
|
5441
|
+
timer?.unref();
|
|
5442
|
+
const has = {
|
|
5443
|
+
limits: typeof ports.limits?.check === "function",
|
|
5444
|
+
metering: typeof ports.metering?.record === "function",
|
|
5445
|
+
accounts: typeof ports.accounts?.resolve === "function",
|
|
5446
|
+
authenticate: typeof ports.accounts?.authenticate === "function",
|
|
5447
|
+
status: typeof ports.accounts?.status === "function",
|
|
5448
|
+
abuse: typeof ports.abuse?.report === "function",
|
|
5449
|
+
pushed: typeof ports.abuse?.pushed === "function",
|
|
5450
|
+
policy: typeof ports.policy?.link === "function",
|
|
5451
|
+
routing: typeof ports.routing?.resolve === "function",
|
|
5452
|
+
linkHost: typeof ports.routing?.linkHost === "function",
|
|
5453
|
+
events: typeof ports.events?.deliver === "function",
|
|
5454
|
+
identity: typeof ports.identity?.providers === "function"
|
|
5455
|
+
};
|
|
5456
|
+
return {
|
|
5457
|
+
has,
|
|
5458
|
+
async limit(q) {
|
|
5459
|
+
if (!has.limits) return { allowed: true };
|
|
5460
|
+
const key = `limits\u0000${JSON.stringify(q)}`;
|
|
5461
|
+
const hit = cached(key);
|
|
5462
|
+
if (hit) return hit;
|
|
5463
|
+
const answer = await ask("limits", OPERATOR_TIME_LIMITS.limits, LimitAnswer, () => ports.limits?.check(q));
|
|
5464
|
+
if (!answer) return { allowed: "unavailable" };
|
|
5465
|
+
const verdict = answer.value.allowed ? { allowed: true } : {
|
|
5466
|
+
allowed: false,
|
|
5467
|
+
code: answer.value.code,
|
|
5468
|
+
message: answer.value.message,
|
|
5469
|
+
...answer.value.retryAfterMs !== void 0 ? { retryAfterMs: answer.value.retryAfterMs } : {}
|
|
5470
|
+
};
|
|
5471
|
+
keep(key, verdict, answer.value.cacheForMs);
|
|
5472
|
+
return verdict;
|
|
5473
|
+
},
|
|
5474
|
+
async linkPolicy(q) {
|
|
5475
|
+
if (!has.policy) return {};
|
|
5476
|
+
const key = `policy\u0000${q.routeId}\u0000${q.tokenId ?? ""}`;
|
|
5477
|
+
const hit = cached(key);
|
|
5478
|
+
if (hit) return hit;
|
|
5479
|
+
const answer = await ask("policy", OPERATOR_TIME_LIMITS.policy, LinkPolicy, () => ports.policy?.link(q));
|
|
5480
|
+
if (!answer) return {};
|
|
5481
|
+
keep(key, answer.value, answer.value.cacheForMs);
|
|
5482
|
+
return answer.value;
|
|
5483
|
+
},
|
|
5484
|
+
async chatHost(client) {
|
|
5485
|
+
if (typeof ports.policy?.chatHost !== "function") return null;
|
|
5486
|
+
return (await ask("policy.chatHost", OPERATOR_TIME_LIMITS.policy, ChatHostPolicy.nullable(), () => ports.policy?.chatHost?.(client)))?.value ?? null;
|
|
5487
|
+
},
|
|
5488
|
+
async route(host) {
|
|
5489
|
+
if (!has.routing) return null;
|
|
5490
|
+
const key = `routing\u0000${host}`;
|
|
5491
|
+
const hit = cache.get(key);
|
|
5492
|
+
if (hit && hit.until > now()) return hit.value;
|
|
5493
|
+
const answer = await ask("routing", OPERATOR_TIME_LIMITS.routing, RoutingAnswer, () => ports.routing?.resolve(host));
|
|
5494
|
+
if (!answer) return "unavailable";
|
|
5495
|
+
keep(key, answer.value, answer.value?.cacheForMs);
|
|
5496
|
+
return answer.value;
|
|
5497
|
+
},
|
|
5498
|
+
async linkHost(q) {
|
|
5499
|
+
if (!has.linkHost) return null;
|
|
5500
|
+
return (await ask("routing.linkHost", OPERATOR_TIME_LIMITS.routing, LinkHost, () => ports.routing?.linkHost?.(q)))?.value ?? null;
|
|
5501
|
+
},
|
|
5502
|
+
async providers() {
|
|
5503
|
+
if (!has.identity) return [];
|
|
5504
|
+
try {
|
|
5505
|
+
const found = await within(OPERATOR_TIME_LIMITS.identity, () => ports.identity?.providers());
|
|
5506
|
+
return (Array.isArray(found) ? found : []).filter((provider) => typeof provider?.id === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(provider.id) && typeof provider.authorize === "function" && typeof provider.callback === "function");
|
|
5507
|
+
} catch (error) {
|
|
5508
|
+
log.warn("operator.no_answer", {
|
|
5509
|
+
port: "identity",
|
|
5510
|
+
message: error.message
|
|
5511
|
+
});
|
|
5512
|
+
return [];
|
|
5513
|
+
}
|
|
2322
5514
|
},
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
5515
|
+
async resolve(identity, steps) {
|
|
5516
|
+
if (!has.accounts) return { default: true };
|
|
5517
|
+
const answer = await ask("accounts.resolve", OPERATOR_TIME_LIMITS.accounts, AccountResolution, () => ports.accounts?.resolve(identity, { steps }));
|
|
5518
|
+
return answer ? answer.value : "unavailable";
|
|
2326
5519
|
},
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
5520
|
+
async authenticate(bearer, resource) {
|
|
5521
|
+
if (!has.authenticate) return null;
|
|
5522
|
+
return (await ask("accounts.authenticate", OPERATOR_TIME_LIMITS.authenticate, AuthenticatedCredential, () => ports.accounts?.authenticate?.(bearer, { resource })))?.value ?? null;
|
|
2330
5523
|
},
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
return {
|
|
2357
|
-
id,
|
|
2358
|
-
dir,
|
|
2359
|
-
ledger,
|
|
2360
|
-
registry,
|
|
2361
|
-
interaction,
|
|
2362
|
-
protocol,
|
|
2363
|
-
incarnation: () => incarnation,
|
|
2364
|
-
wanted: (sha) => [...pending.values()].some((files) => files.has(sha)),
|
|
2365
|
-
uploaded(sha) {
|
|
2366
|
-
directory.write((db) => {
|
|
2367
|
-
if (db.run("INSERT OR IGNORE INTO home_file (home_id, sha256) VALUES (?, ?)", id, sha).changes > 0) db.run("INSERT INTO file_ref (sha256, homes) VALUES (?, 1) ON CONFLICT (sha256) DO UPDATE SET homes = homes + 1, unreferenced_at = NULL", sha);
|
|
5524
|
+
async status(account) {
|
|
5525
|
+
if (typeof ports.accounts?.status !== "function") return void 0;
|
|
5526
|
+
try {
|
|
5527
|
+
const found = await within(OPERATOR_TIME_LIMITS.accounts, () => ports.accounts?.status?.(account));
|
|
5528
|
+
return found === "active" || found === "suspended" ? found : void 0;
|
|
5529
|
+
} catch {
|
|
5530
|
+
return;
|
|
5531
|
+
}
|
|
5532
|
+
},
|
|
5533
|
+
async report(r) {
|
|
5534
|
+
if (!has.abuse) return;
|
|
5535
|
+
try {
|
|
5536
|
+
await within(OPERATOR_TIME_LIMITS.policy * 5, () => ports.abuse?.report(r));
|
|
5537
|
+
} catch (error) {
|
|
5538
|
+
log.warn("operator.no_answer", {
|
|
5539
|
+
port: "abuse.report",
|
|
5540
|
+
message: error.message
|
|
5541
|
+
});
|
|
5542
|
+
}
|
|
5543
|
+
},
|
|
5544
|
+
pushed(v, quarantine) {
|
|
5545
|
+
if (!has.pushed) return;
|
|
5546
|
+
ask("abuse.pushed", OPERATOR_TIME_LIMITS.pushed, PushedAnswer, () => ports.abuse?.pushed?.(v)).then(async (answer) => {
|
|
5547
|
+
const reason = answer?.value?.quarantine?.reason;
|
|
5548
|
+
if (reason !== void 0) await quarantine(reason).catch((error) => log.error("operator.quarantine_failed", { error }));
|
|
2368
5549
|
});
|
|
2369
|
-
for (const files of pending.values()) files.delete(sha);
|
|
2370
5550
|
},
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
5551
|
+
enqueue(item) {
|
|
5552
|
+
if (item.port === "events" ? !has.events : !has.metering) return;
|
|
5553
|
+
const id = item.port === "events" ? item.event.eventId : item.batch.batchId;
|
|
5554
|
+
const payload = item.port === "events" ? item.event : item.batch;
|
|
5555
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO outbound (id, port, payload_json, attempts, next_attempt_at) VALUES (?, ?, ?, 0, ?)", `${item.port}:${id}`, item.port, JSON.stringify(payload), new Date(now()).toISOString()));
|
|
5556
|
+
dispatch();
|
|
5557
|
+
},
|
|
5558
|
+
flush: () => dispatch(),
|
|
5559
|
+
stop() {
|
|
5560
|
+
if (timer) clearInterval(timer);
|
|
2380
5561
|
}
|
|
2381
5562
|
};
|
|
2382
5563
|
}
|
|
5564
|
+
//#endregion
|
|
5565
|
+
//#region src/server/providers.ts
|
|
2383
5566
|
/**
|
|
2384
|
-
*
|
|
2385
|
-
*
|
|
2386
|
-
*
|
|
5567
|
+
* The remote server's identity providers (INTERFACES §18.5, D165 item 8): the sign-in port's
|
|
5568
|
+
* built-in adapters, configured in `identityProviders`, beside those an operator module supplies
|
|
5569
|
+
* (asked at every sign-in, so its set can change while the server runs, D167):
|
|
5570
|
+
*
|
|
5571
|
+
* - `oidc`: any OpenID Connect provider, by its issuer's discovery document; the authorization
|
|
5572
|
+
* code flow with PKCE (S256) and a nonce, and the ID token checked (signature, issuer, audience,
|
|
5573
|
+
* expiry, nonce) by `openid-client`.
|
|
5574
|
+
* - `github`: GitHub's OAuth web flow with PKCE, then `GET /user` for the account's stable ID, its
|
|
5575
|
+
* login and name, and its age (`facts.createdAt`) for an operator's policy.
|
|
5576
|
+
* - `development`: a page that asks for a name and trusts it, for tests and a self-hoster's first
|
|
5577
|
+
* run; its names are never shown as verified.
|
|
5578
|
+
*
|
|
5579
|
+
* A provider's client secret is read from `clientSecretFile`, never from the configuration itself,
|
|
5580
|
+
* and is never logged.
|
|
2387
5581
|
*/
|
|
2388
|
-
|
|
5582
|
+
/** How long a provider's discovery, token exchange or user lookup may take. */
|
|
5583
|
+
const PROVIDER_TIMEOUT_MS = 8e3;
|
|
5584
|
+
/** GitHub's endpoints (VERIFIED_FACTS, WP-30). */
|
|
5585
|
+
const GITHUB = {
|
|
5586
|
+
authorize: "https://github.com/login/oauth/authorize",
|
|
5587
|
+
token: "https://github.com/login/oauth/access_token",
|
|
5588
|
+
user: "https://api.github.com/user"
|
|
5589
|
+
};
|
|
5590
|
+
function invalid$1(message) {
|
|
5591
|
+
return new RpcError(createDiagnostic("MOSTRA_REMOTE_CONFIG_INVALID", { message }));
|
|
5592
|
+
}
|
|
5593
|
+
function secretOf(config) {
|
|
5594
|
+
if (config.clientSecretFile === void 0) throw invalid$1(`The identity provider \`${config.id}\` needs \`clientSecretFile\`, a file holding its client secret.`);
|
|
2389
5595
|
try {
|
|
2390
|
-
const
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
sha256
|
|
2396
|
-
}));
|
|
2397
|
-
if (listingDigest(listed) !== manifest.outputDigest) return "its listing doesn't match its digest";
|
|
2398
|
-
for (const [path, , sha256] of listing) {
|
|
2399
|
-
if (!path.startsWith("client/") && path !== "registry.json") continue;
|
|
2400
|
-
const bytes = await readFile(join(versionDir, ...path.split("/")));
|
|
2401
|
-
if (createHash("sha256").update(bytes).digest("hex") !== sha256) return `${path} was changed`;
|
|
2402
|
-
}
|
|
2403
|
-
return;
|
|
2404
|
-
} catch (error) {
|
|
2405
|
-
return `a file is missing (${error.code ?? "unreadable"})`;
|
|
5596
|
+
const secret = readFileSync(config.clientSecretFile, "utf8").trim();
|
|
5597
|
+
if (secret === "") throw new Error("empty");
|
|
5598
|
+
return secret;
|
|
5599
|
+
} catch {
|
|
5600
|
+
throw invalid$1(`The identity provider \`${config.id}\`'s \`clientSecretFile\` (${config.clientSecretFile}) can't be read, or is empty.`);
|
|
2406
5601
|
}
|
|
2407
5602
|
}
|
|
2408
|
-
/**
|
|
2409
|
-
function
|
|
2410
|
-
return
|
|
5603
|
+
/** A fetch bounded in time, for a provider's own endpoints. */
|
|
5604
|
+
async function timedFetch(url, init) {
|
|
5605
|
+
return fetch(url, {
|
|
5606
|
+
...init,
|
|
5607
|
+
signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS)
|
|
5608
|
+
});
|
|
5609
|
+
}
|
|
5610
|
+
/** The OpenID Connect adapter. Discovery happens at the first sign-in and is kept. */
|
|
5611
|
+
function oidcProvider(config, env) {
|
|
5612
|
+
if (config.issuer === void 0 || config.clientId === void 0) throw invalid$1(`The identity provider \`${config.id}\` (oidc) needs \`issuer\` and \`clientId\`.`);
|
|
5613
|
+
const secret = secretOf(config);
|
|
5614
|
+
const issuer = new URL(config.issuer);
|
|
5615
|
+
const insecure = issuer.protocol === "http:" && env["MOSTRA_TEST_OIDC_INSECURE"] === "1" && (issuer.hostname === "127.0.0.1" || issuer.hostname === "localhost");
|
|
5616
|
+
if (issuer.protocol !== "https:" && !insecure) throw invalid$1(`The identity provider \`${config.id}\`'s \`issuer\` must be an https: URL.`);
|
|
5617
|
+
let discovered;
|
|
5618
|
+
const configuration = () => {
|
|
5619
|
+
discovered ??= oidc.discovery(issuer, config.clientId, void 0, oidc.ClientSecretPost(secret), insecure ? {
|
|
5620
|
+
execute: [oidc.allowInsecureRequests],
|
|
5621
|
+
timeout: 8
|
|
5622
|
+
} : { timeout: 8 }).catch((error) => {
|
|
5623
|
+
discovered = void 0;
|
|
5624
|
+
throw error;
|
|
5625
|
+
});
|
|
5626
|
+
return discovered;
|
|
5627
|
+
};
|
|
5628
|
+
return {
|
|
5629
|
+
id: config.id,
|
|
5630
|
+
label: config.label ?? config.id,
|
|
5631
|
+
kind: "oidc",
|
|
5632
|
+
verifies: true,
|
|
5633
|
+
async authorize(state, pkce, context) {
|
|
5634
|
+
return oidc.buildAuthorizationUrl(await configuration(), {
|
|
5635
|
+
redirect_uri: context.redirectUri,
|
|
5636
|
+
scope: "openid email profile",
|
|
5637
|
+
state,
|
|
5638
|
+
nonce: context.nonce,
|
|
5639
|
+
code_challenge: pkce.challenge,
|
|
5640
|
+
code_challenge_method: "S256"
|
|
5641
|
+
}).href;
|
|
5642
|
+
},
|
|
5643
|
+
async callback(params, context) {
|
|
5644
|
+
const current = new URL(context.redirectUri);
|
|
5645
|
+
for (const [key, value] of Object.entries(params)) current.searchParams.set(key, value);
|
|
5646
|
+
const claims = (await oidc.authorizationCodeGrant(await configuration(), current, {
|
|
5647
|
+
pkceCodeVerifier: context.pkce.verifier,
|
|
5648
|
+
expectedState: context.state,
|
|
5649
|
+
expectedNonce: context.nonce,
|
|
5650
|
+
idTokenExpected: true
|
|
5651
|
+
})).claims();
|
|
5652
|
+
if (!claims) throw new Error("The provider sent no ID token.");
|
|
5653
|
+
const name = typeof claims["name"] === "string" ? claims["name"] : typeof claims["preferred_username"] === "string" ? claims["preferred_username"] : void 0;
|
|
5654
|
+
return {
|
|
5655
|
+
provider: config.id,
|
|
5656
|
+
subject: claims.sub,
|
|
5657
|
+
...typeof claims["email"] === "string" ? { email: claims["email"] } : {},
|
|
5658
|
+
...typeof claims["email_verified"] === "boolean" ? { emailVerified: claims["email_verified"] } : {},
|
|
5659
|
+
...name !== void 0 ? { name } : {}
|
|
5660
|
+
};
|
|
5661
|
+
}
|
|
5662
|
+
};
|
|
5663
|
+
}
|
|
5664
|
+
/** The GitHub adapter: an OAuth app's web flow with PKCE (VERIFIED_FACTS, WP-30). */
|
|
5665
|
+
function githubProvider(config, env) {
|
|
5666
|
+
if (config.clientId === void 0) throw invalid$1(`The identity provider \`${config.id}\` (github) needs \`clientId\`.`);
|
|
5667
|
+
const secret = secretOf(config);
|
|
5668
|
+
const base = env["MOSTRA_TEST_GITHUB_BASE"];
|
|
5669
|
+
const endpoints = base !== void 0 && /^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(base) ? {
|
|
5670
|
+
authorize: `${base}/login/oauth/authorize`,
|
|
5671
|
+
token: `${base}/login/oauth/access_token`,
|
|
5672
|
+
user: `${base}/user`
|
|
5673
|
+
} : GITHUB;
|
|
5674
|
+
return {
|
|
5675
|
+
id: config.id,
|
|
5676
|
+
label: config.label ?? "GitHub",
|
|
5677
|
+
kind: "github",
|
|
5678
|
+
verifies: true,
|
|
5679
|
+
authorize(state, pkce, context) {
|
|
5680
|
+
const url = new URL(endpoints.authorize);
|
|
5681
|
+
url.searchParams.set("client_id", config.clientId);
|
|
5682
|
+
url.searchParams.set("redirect_uri", context.redirectUri);
|
|
5683
|
+
url.searchParams.set("state", state);
|
|
5684
|
+
url.searchParams.set("scope", "");
|
|
5685
|
+
url.searchParams.set("allow_signup", "true");
|
|
5686
|
+
url.searchParams.set("code_challenge", pkce.challenge);
|
|
5687
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
5688
|
+
return url.href;
|
|
5689
|
+
},
|
|
5690
|
+
async callback(params, context) {
|
|
5691
|
+
if (params["error"] !== void 0) throw new Error(`GitHub refused the sign-in (${params["error"]}).`);
|
|
5692
|
+
const code = params["code"];
|
|
5693
|
+
if (code === void 0) throw new Error("GitHub sent no code.");
|
|
5694
|
+
const exchanged = await timedFetch(endpoints.token, {
|
|
5695
|
+
method: "POST",
|
|
5696
|
+
headers: {
|
|
5697
|
+
accept: "application/json",
|
|
5698
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
5699
|
+
},
|
|
5700
|
+
body: new URLSearchParams({
|
|
5701
|
+
client_id: config.clientId,
|
|
5702
|
+
client_secret: secret,
|
|
5703
|
+
code,
|
|
5704
|
+
redirect_uri: context.redirectUri,
|
|
5705
|
+
code_verifier: context.pkce.verifier
|
|
5706
|
+
}).toString()
|
|
5707
|
+
});
|
|
5708
|
+
const token = await exchanged.json().catch(() => ({}));
|
|
5709
|
+
if (!exchanged.ok || typeof token.access_token !== "string") throw new Error(`GitHub's code exchange failed (${token.error ?? exchanged.status}).`);
|
|
5710
|
+
const user = await timedFetch(endpoints.user, { headers: {
|
|
5711
|
+
accept: "application/vnd.github+json",
|
|
5712
|
+
authorization: `Bearer ${token.access_token}`,
|
|
5713
|
+
"user-agent": "mostra-remote-server"
|
|
5714
|
+
} });
|
|
5715
|
+
const found = await user.json().catch(() => ({}));
|
|
5716
|
+
if (!user.ok || typeof found.id !== "number") throw new Error(`GitHub's user lookup failed (${user.status}).`);
|
|
5717
|
+
return {
|
|
5718
|
+
provider: config.id,
|
|
5719
|
+
subject: String(found.id),
|
|
5720
|
+
...typeof found.email === "string" ? { email: found.email } : {},
|
|
5721
|
+
name: found.name ?? found.login ?? String(found.id),
|
|
5722
|
+
facts: {
|
|
5723
|
+
login: found.login ?? null,
|
|
5724
|
+
...found.created_at !== void 0 ? { createdAt: found.created_at } : {}
|
|
5725
|
+
}
|
|
5726
|
+
};
|
|
5727
|
+
}
|
|
5728
|
+
};
|
|
5729
|
+
}
|
|
5730
|
+
/**
|
|
5731
|
+
* The development adapter: the device page and the sign-in page ask for a name and trust it
|
|
5732
|
+
* (D166 item 4). Its `authorize` sends the person to the server's own name page.
|
|
5733
|
+
*/
|
|
5734
|
+
function developmentProvider(config, apiOrigin) {
|
|
5735
|
+
return {
|
|
5736
|
+
id: config.id,
|
|
5737
|
+
label: config.label ?? "Development sign-in",
|
|
5738
|
+
kind: "development",
|
|
5739
|
+
verifies: false,
|
|
5740
|
+
authorize(state) {
|
|
5741
|
+
const url = new URL(`${apiOrigin}/signin/${config.id}/name`);
|
|
5742
|
+
url.searchParams.set("state", state);
|
|
5743
|
+
return url.href;
|
|
5744
|
+
},
|
|
5745
|
+
async callback(params) {
|
|
5746
|
+
const name = (params["name"] ?? "").trim().slice(0, 64);
|
|
5747
|
+
if (name === "") throw new Error("No name was given.");
|
|
5748
|
+
return {
|
|
5749
|
+
provider: config.id,
|
|
5750
|
+
subject: name.toLowerCase(),
|
|
5751
|
+
name
|
|
5752
|
+
};
|
|
5753
|
+
}
|
|
5754
|
+
};
|
|
5755
|
+
}
|
|
5756
|
+
/** Builds the configured providers; a provider it can't use stops the server, naming it. */
|
|
5757
|
+
function builtInProviders(configs, options) {
|
|
5758
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5759
|
+
return configs.map((config) => {
|
|
5760
|
+
if (seen.has(config.id)) throw invalid$1(`Two identity providers are named \`${config.id}\`.`);
|
|
5761
|
+
seen.add(config.id);
|
|
5762
|
+
const provider = config.kind === "oidc" ? oidcProvider(config, options.env) : config.kind === "github" ? githubProvider(config, options.env) : developmentProvider(config, options.apiOrigin);
|
|
5763
|
+
options.log.info("signin.provider", {
|
|
5764
|
+
id: config.id,
|
|
5765
|
+
kind: config.kind
|
|
5766
|
+
});
|
|
5767
|
+
return provider;
|
|
5768
|
+
});
|
|
5769
|
+
}
|
|
5770
|
+
//#endregion
|
|
5771
|
+
//#region src/server/routing.ts
|
|
5772
|
+
/** The server's own labels: 26 lower-case Crockford base32 characters (§18.4). */
|
|
5773
|
+
const SERVER_LABEL = /^[0-9a-hjkmnp-tv-z]{26}$/;
|
|
5774
|
+
/** Builds the routing over the directory and the operator. */
|
|
5775
|
+
function createRouting(options) {
|
|
5776
|
+
const { directory, operator, log } = options;
|
|
5777
|
+
const configured = (host) => options.domains().includes(host);
|
|
5778
|
+
const configuredParent = (host) => options.domains().find((domain) => host.endsWith(`.${domain}`));
|
|
5779
|
+
const recorded = (host) => directory.read((db) => db.get("SELECT * FROM operator_host WHERE host = ?", host));
|
|
5780
|
+
const routeByLabel = (label) => directory.read((db) => db.get("SELECT id, home_id FROM artifact_route WHERE label = ? AND removing_json IS NULL", label));
|
|
5781
|
+
/** Whether an operator's answer may bind `host` at all: never the server's own names. */
|
|
5782
|
+
const bindable = (host) => {
|
|
5783
|
+
if (host === options.apiHost || configured(host)) return false;
|
|
5784
|
+
const parent = configuredParent(host);
|
|
5785
|
+
if (parent !== void 0) {
|
|
5786
|
+
const label = host.slice(0, host.length - parent.length - 1);
|
|
5787
|
+
if (label.includes(".") || SERVER_LABEL.test(label)) return false;
|
|
5788
|
+
}
|
|
5789
|
+
return true;
|
|
5790
|
+
};
|
|
5791
|
+
/** Records an operator's answer for a new host; `undefined` when it can't be bound. */
|
|
5792
|
+
const record = (host, answer) => {
|
|
5793
|
+
if (!bindable(host)) {
|
|
5794
|
+
log.warn("routing.answer_refused", {
|
|
5795
|
+
host,
|
|
5796
|
+
why: "reserved"
|
|
5797
|
+
});
|
|
5798
|
+
return;
|
|
5799
|
+
}
|
|
5800
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
5801
|
+
return directory.write((db) => {
|
|
5802
|
+
let row;
|
|
5803
|
+
if ("shell" in answer) {
|
|
5804
|
+
if (!db.get("SELECT 1 FROM home WHERE id = ?", answer.shell.home)) return void 0;
|
|
5805
|
+
if (answer.shell.domain === options.apiHost) return void 0;
|
|
5806
|
+
row = {
|
|
5807
|
+
host,
|
|
5808
|
+
home_id: answer.shell.home,
|
|
5809
|
+
route_id: null,
|
|
5810
|
+
frame_domain: answer.shell.domain
|
|
5811
|
+
};
|
|
5812
|
+
} else {
|
|
5813
|
+
if (!db.get("SELECT home_id FROM artifact_route WHERE id = ? AND home_id = ? AND removing_json IS NULL", answer.route.routeId, answer.route.home)) return void 0;
|
|
5814
|
+
row = {
|
|
5815
|
+
host,
|
|
5816
|
+
home_id: answer.route.home,
|
|
5817
|
+
route_id: answer.route.routeId,
|
|
5818
|
+
frame_domain: options.active()
|
|
5819
|
+
};
|
|
5820
|
+
}
|
|
5821
|
+
const issued = db.get("SELECT home_id FROM label_issued WHERE label = ?", host);
|
|
5822
|
+
if (issued && issued.home_id !== row.home_id) {
|
|
5823
|
+
log.warn("routing.answer_refused", {
|
|
5824
|
+
host,
|
|
5825
|
+
why: "issued-to-another-home"
|
|
5826
|
+
});
|
|
5827
|
+
return;
|
|
5828
|
+
}
|
|
5829
|
+
if (!issued) db.run("INSERT INTO label_issued (label, home_id, route_id, kind, issued_at) VALUES (?, ?, ?, 'operator', ?)", host, row.home_id, row.route_id, at);
|
|
5830
|
+
db.run("INSERT INTO operator_host (host, home_id, route_id, frame_domain, recorded_at) VALUES (?, ?, ?, ?, ?)", row.host, row.home_id, row.route_id, row.frame_domain, at);
|
|
5831
|
+
log.info("routing.host_recorded", {
|
|
5832
|
+
host,
|
|
5833
|
+
home: row.home_id
|
|
5834
|
+
});
|
|
5835
|
+
return row;
|
|
5836
|
+
});
|
|
5837
|
+
};
|
|
5838
|
+
/** Whether an operator's answer agrees with a recorded host's binding. */
|
|
5839
|
+
const agrees = (row, answer) => "shell" in answer ? answer.shell.home === row.home_id && row.route_id === null && answer.shell.domain === row.frame_domain : answer.route.home === row.home_id && answer.route.routeId === row.route_id;
|
|
5840
|
+
/** The operator's host for `host`, asked and recorded, or `undefined`. */
|
|
5841
|
+
const operatorHost = async (host) => {
|
|
5842
|
+
const row = recorded(host);
|
|
5843
|
+
if (!operator.has.routing) return void 0;
|
|
5844
|
+
const answer = await operator.route(host);
|
|
5845
|
+
if (answer === "unavailable") return row;
|
|
5846
|
+
if (answer === null) return void 0;
|
|
5847
|
+
if (row) {
|
|
5848
|
+
if (agrees(row, answer)) return row;
|
|
5849
|
+
log.warn("routing.answer_refused", {
|
|
5850
|
+
host,
|
|
5851
|
+
why: "moved"
|
|
5852
|
+
});
|
|
5853
|
+
return;
|
|
5854
|
+
}
|
|
5855
|
+
return record(host, answer);
|
|
5856
|
+
};
|
|
5857
|
+
const asShell = (row) => ({
|
|
5858
|
+
kind: "shell",
|
|
5859
|
+
host: row.host,
|
|
5860
|
+
frameDomain: row.frame_domain,
|
|
5861
|
+
homeId: row.home_id,
|
|
5862
|
+
...row.route_id !== null ? { routeId: row.route_id } : {}
|
|
5863
|
+
});
|
|
5864
|
+
/** A route's frames on `<label>.<domain>`, when the label is the route's and the domain serves it. */
|
|
5865
|
+
const frame = (host) => {
|
|
5866
|
+
const dot = host.indexOf(".");
|
|
5867
|
+
if (dot <= 0) return void 0;
|
|
5868
|
+
const label = host.slice(0, dot);
|
|
5869
|
+
const domain = host.slice(dot + 1);
|
|
5870
|
+
if (!SERVER_LABEL.test(label)) return void 0;
|
|
5871
|
+
const route = routeByLabel(label);
|
|
5872
|
+
if (!route) return void 0;
|
|
5873
|
+
if (configured(domain)) return {
|
|
5874
|
+
kind: "frame",
|
|
5875
|
+
frameDomain: domain,
|
|
5876
|
+
route: {
|
|
5877
|
+
id: route.id,
|
|
5878
|
+
homeId: route.home_id
|
|
5879
|
+
}
|
|
5880
|
+
};
|
|
5881
|
+
return directory.read((db) => db.get("SELECT 1 FROM operator_host WHERE frame_domain = ? AND home_id = ? AND (route_id IS NULL OR route_id = ?)", domain, route.home_id, route.id)) ? {
|
|
5882
|
+
kind: "frame",
|
|
5883
|
+
frameDomain: domain,
|
|
5884
|
+
route: {
|
|
5885
|
+
id: route.id,
|
|
5886
|
+
homeId: route.home_id
|
|
5887
|
+
}
|
|
5888
|
+
} : void 0;
|
|
5889
|
+
};
|
|
5890
|
+
return {
|
|
5891
|
+
async destination(host) {
|
|
5892
|
+
if (host === options.apiHost) return { kind: "api" };
|
|
5893
|
+
if (configured(host)) return {
|
|
5894
|
+
kind: "shell",
|
|
5895
|
+
host,
|
|
5896
|
+
frameDomain: host
|
|
5897
|
+
};
|
|
5898
|
+
const framed = frame(host);
|
|
5899
|
+
if (framed) return framed;
|
|
5900
|
+
const row = await operatorHost(host);
|
|
5901
|
+
return row ? asShell(row) : { kind: "none" };
|
|
5902
|
+
},
|
|
5903
|
+
async linkHost(homeId, routeId, host) {
|
|
5904
|
+
const row = await operatorHost(host.toLowerCase());
|
|
5905
|
+
if (!row || row.home_id !== homeId) return void 0;
|
|
5906
|
+
if (row.route_id !== null && row.route_id !== routeId) return void 0;
|
|
5907
|
+
return row.host;
|
|
5908
|
+
},
|
|
5909
|
+
servesShell(homeId, host) {
|
|
5910
|
+
if (configured(host)) return true;
|
|
5911
|
+
const row = recorded(host);
|
|
5912
|
+
return row !== void 0 && row.home_id === homeId;
|
|
5913
|
+
},
|
|
5914
|
+
frameDomainOf(homeId, routeId, shellHost) {
|
|
5915
|
+
if (configured(shellHost)) return shellHost;
|
|
5916
|
+
const row = recorded(shellHost);
|
|
5917
|
+
if (!row || row.home_id !== homeId) return void 0;
|
|
5918
|
+
if (row.route_id !== null && row.route_id !== routeId) return void 0;
|
|
5919
|
+
return row.frame_domain;
|
|
5920
|
+
},
|
|
5921
|
+
ancestorsOf(homeId, routeId, frameDomain) {
|
|
5922
|
+
const hosts = configured(frameDomain) ? [frameDomain] : [];
|
|
5923
|
+
for (const row of directory.read((db) => db.all("SELECT host FROM operator_host WHERE frame_domain = ? AND home_id = ? AND (route_id IS NULL OR route_id = ?) ORDER BY host", frameDomain, homeId, routeId))) hosts.push(row.host);
|
|
5924
|
+
return hosts;
|
|
5925
|
+
}
|
|
5926
|
+
};
|
|
2411
5927
|
}
|
|
2412
5928
|
//#endregion
|
|
2413
5929
|
//#region src/server/config.ts
|
|
@@ -2535,6 +6051,8 @@ function readServerConfig(file, env) {
|
|
|
2535
6051
|
const domains = [config.domains.active, ...config.domains.spares ?? []];
|
|
2536
6052
|
const api = new URL(config.apiOrigin).host;
|
|
2537
6053
|
if (domains.some((domain) => domain === api || api.endsWith(`.${domain}`))) throw invalid("The configuration key `apiOrigin` can't be on a user-content domain: sign-in and the binding live apart from tenant pages (D165 item 7).");
|
|
6054
|
+
const proxy = validProxies(config.trustedProxies ?? []);
|
|
6055
|
+
if (proxy !== void 0) throw invalid(`The configuration key \`trustedProxies\` names ${JSON.stringify(proxy)}, which is neither an address nor a CIDR block.`);
|
|
2538
6056
|
if (new Set(domains).size !== domains.length) throw invalid("The configuration key `domains` names one domain twice.");
|
|
2539
6057
|
return config;
|
|
2540
6058
|
}
|
|
@@ -2582,7 +6100,59 @@ function parseListen(listen) {
|
|
|
2582
6100
|
async function startServer(options) {
|
|
2583
6101
|
const { config, log } = options;
|
|
2584
6102
|
let auth;
|
|
6103
|
+
let operator;
|
|
6104
|
+
let meter;
|
|
6105
|
+
let routing;
|
|
6106
|
+
let authorizer;
|
|
6107
|
+
let api;
|
|
2585
6108
|
const shellDir = locateShell(options.env);
|
|
6109
|
+
const clients = clientAddresses({
|
|
6110
|
+
trustedProxies: config.trustedProxies,
|
|
6111
|
+
ipv6Prefix: config.rateLimits?.ipv6Prefix
|
|
6112
|
+
});
|
|
6113
|
+
const rates = new RateLimiter();
|
|
6114
|
+
const faults = faultsFrom(options.env);
|
|
6115
|
+
const rateOf = (rate) => rate === void 0 ? void 0 : {
|
|
6116
|
+
count: rate.count,
|
|
6117
|
+
perMs: durationMs(rate.per)
|
|
6118
|
+
};
|
|
6119
|
+
/**
|
|
6120
|
+
* `rateLimits.perIp.requests`: every request to the server, from one client address (IPv6 per
|
|
6121
|
+
* /64), API origin and hosted hosts alike, before anything else is read (D165 item 13). A
|
|
6122
|
+
* health check is never counted. Without the setting there is no limit.
|
|
6123
|
+
*/
|
|
6124
|
+
const perIpRequests = rateOf(config.rateLimits?.perIp?.requests);
|
|
6125
|
+
/** Who owns a home, as its pages' sender line names them (D161). */
|
|
6126
|
+
const ownerOf = (homeId) => {
|
|
6127
|
+
const row = data.directory.read((db) => db.get(`SELECT a.id AS account, a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id
|
|
6128
|
+
ORDER BY i.linked_at LIMIT 1) AS provider
|
|
6129
|
+
FROM home h JOIN account a ON a.id = h.owner_account_id WHERE h.id = ?`, homeId));
|
|
6130
|
+
if (!row) return { account: "" };
|
|
6131
|
+
const provider = config.identityProviders?.find((candidate) => candidate.id === row.provider);
|
|
6132
|
+
const verifiedBy = provider && provider.kind !== "development" ? provider.label ?? (provider.kind === "github" ? "GitHub" : provider.id) : void 0;
|
|
6133
|
+
return {
|
|
6134
|
+
account: row.account,
|
|
6135
|
+
...row.name !== null ? { name: row.name } : {},
|
|
6136
|
+
...verifiedBy !== void 0 ? { verifiedBy } : {}
|
|
6137
|
+
};
|
|
6138
|
+
};
|
|
6139
|
+
const services = () => ({
|
|
6140
|
+
operator,
|
|
6141
|
+
clients,
|
|
6142
|
+
rates,
|
|
6143
|
+
rateLimits: {
|
|
6144
|
+
perIpSubmissions: rateOf(config.rateLimits?.perIp?.submissions),
|
|
6145
|
+
perLinkSubmissions: rateOf(config.rateLimits?.perLink?.submissions)
|
|
6146
|
+
},
|
|
6147
|
+
owner: ownerOf,
|
|
6148
|
+
meter,
|
|
6149
|
+
routing,
|
|
6150
|
+
signin: {
|
|
6151
|
+
start: (signin, challenge) => authorizer.startViewerSignin(signin, challenge),
|
|
6152
|
+
finish: (input) => authorizer.finishViewerSignin(input)
|
|
6153
|
+
},
|
|
6154
|
+
signInOffered: () => (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false)
|
|
6155
|
+
});
|
|
2586
6156
|
const data = await openDataDirectory({
|
|
2587
6157
|
dir: options.data,
|
|
2588
6158
|
runtimeVersion: options.runtimeVersion,
|
|
@@ -2591,6 +6161,7 @@ async function startServer(options) {
|
|
|
2591
6161
|
env: options.env,
|
|
2592
6162
|
assembler: {
|
|
2593
6163
|
assemble: (home) => openHostedHome({
|
|
6164
|
+
faults,
|
|
2594
6165
|
id: home.id,
|
|
2595
6166
|
dir: home.dir,
|
|
2596
6167
|
ledger: home.ledger,
|
|
@@ -2606,6 +6177,7 @@ async function startServer(options) {
|
|
|
2606
6177
|
spares: config.domains.spares ?? []
|
|
2607
6178
|
},
|
|
2608
6179
|
shellDir,
|
|
6180
|
+
services: services(),
|
|
2609
6181
|
relay: {
|
|
2610
6182
|
waitingRunsPerArtifact: config.relay?.waitingRunsPerArtifact,
|
|
2611
6183
|
drainPerSecond: config.relay?.drainPerSecond,
|
|
@@ -2625,11 +6197,50 @@ async function startServer(options) {
|
|
|
2625
6197
|
...config.homes?.idleCloseMinutes !== void 0 ? { idleCloseMs: config.homes.idleCloseMinutes * 6e4 } : {},
|
|
2626
6198
|
...config.ledger?.walAutocheckpoint !== void 0 ? { walAutocheckpoint: config.ledger.walAutocheckpoint } : {}
|
|
2627
6199
|
});
|
|
6200
|
+
const handle = createHandle({
|
|
6201
|
+
apiOrigin: config.apiOrigin,
|
|
6202
|
+
data: () => data,
|
|
6203
|
+
directory: () => data.directory,
|
|
6204
|
+
suspended: (homeId) => api?.closeHome(homeId),
|
|
6205
|
+
log
|
|
6206
|
+
});
|
|
6207
|
+
try {
|
|
6208
|
+
operator = await loadOperator({
|
|
6209
|
+
path: config.operator,
|
|
6210
|
+
handle,
|
|
6211
|
+
directory: data.directory,
|
|
6212
|
+
log,
|
|
6213
|
+
...Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) > 0 ? { dispatchMs: Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) } : {}
|
|
6214
|
+
});
|
|
6215
|
+
} catch (error) {
|
|
6216
|
+
await data.close();
|
|
6217
|
+
throw error;
|
|
6218
|
+
}
|
|
6219
|
+
routing = createRouting({
|
|
6220
|
+
apiHost: new URL(config.apiOrigin).host,
|
|
6221
|
+
domains: () => [config.domains.active, ...config.domains.spares ?? []],
|
|
6222
|
+
active: () => config.domains.active,
|
|
6223
|
+
directory: data.directory,
|
|
6224
|
+
operator,
|
|
6225
|
+
log
|
|
6226
|
+
});
|
|
6227
|
+
meter = createMeter({
|
|
6228
|
+
operator,
|
|
6229
|
+
keysDir: join(options.data, "keys"),
|
|
6230
|
+
log,
|
|
6231
|
+
...Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) > 0 ? { windowMs: Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) } : {},
|
|
6232
|
+
activeHomes: () => data.open().map((home) => ({
|
|
6233
|
+
home,
|
|
6234
|
+
account: ownerOf(home).account
|
|
6235
|
+
}))
|
|
6236
|
+
});
|
|
2628
6237
|
auth = createAuthorization({
|
|
2629
6238
|
directory: data.directory,
|
|
2630
6239
|
config,
|
|
2631
6240
|
log,
|
|
6241
|
+
operator,
|
|
2632
6242
|
...Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) > 0 ? { accessTtlMs: Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) } : {},
|
|
6243
|
+
...Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) > 0 ? { rotationGraceMs: Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) } : {},
|
|
2633
6244
|
linked: ({ homeId, linkId, name }) => {
|
|
2634
6245
|
data.home(homeId).then((home) => home.assembled.ledger.write((db) => appendEvent(db, {
|
|
2635
6246
|
artifactId: null,
|
|
@@ -2645,30 +6256,101 @@ async function startServer(options) {
|
|
|
2645
6256
|
}));
|
|
2646
6257
|
}
|
|
2647
6258
|
});
|
|
2648
|
-
const
|
|
6259
|
+
const scheme = config.scheme ?? "https";
|
|
6260
|
+
const oauthClients = createClients({
|
|
6261
|
+
directory: data.directory,
|
|
6262
|
+
log,
|
|
6263
|
+
env: options.env,
|
|
6264
|
+
isShellOrigin: (origin) => {
|
|
6265
|
+
if (!origin.startsWith(`${scheme}://`)) return false;
|
|
6266
|
+
const host = origin.slice(scheme.length + 3);
|
|
6267
|
+
if (domains.includes(host)) return true;
|
|
6268
|
+
return data.directory.read((db) => db.get("SELECT 1 FROM operator_host WHERE host = ?", host)) !== void 0;
|
|
6269
|
+
}
|
|
6270
|
+
});
|
|
6271
|
+
let providers;
|
|
6272
|
+
try {
|
|
6273
|
+
providers = builtInProviders(config.identityProviders ?? [], {
|
|
6274
|
+
apiOrigin: config.apiOrigin,
|
|
6275
|
+
env: options.env,
|
|
6276
|
+
log
|
|
6277
|
+
});
|
|
6278
|
+
} catch (error) {
|
|
6279
|
+
operator?.stop();
|
|
6280
|
+
await data.close();
|
|
6281
|
+
throw error;
|
|
6282
|
+
}
|
|
6283
|
+
const authorize = createAuthorize({
|
|
6284
|
+
apiOrigin: config.apiOrigin,
|
|
6285
|
+
directory: data.directory,
|
|
6286
|
+
auth,
|
|
6287
|
+
clients: oauthClients,
|
|
6288
|
+
operator,
|
|
6289
|
+
providers,
|
|
6290
|
+
ownerName: (homeId) => ownerOf(homeId).name,
|
|
6291
|
+
log
|
|
6292
|
+
});
|
|
6293
|
+
authorizer = authorize;
|
|
6294
|
+
const mcp = createRemoteMcp({
|
|
6295
|
+
apiOrigin: config.apiOrigin,
|
|
6296
|
+
version: options.runtimeVersion,
|
|
6297
|
+
docs: serverDocs(),
|
|
6298
|
+
log,
|
|
6299
|
+
operator,
|
|
6300
|
+
meter,
|
|
6301
|
+
home: async (id) => (await data.home(id)).assembled,
|
|
6302
|
+
ensureHome: (accountId) => auth.ensureHome(accountId)
|
|
6303
|
+
});
|
|
6304
|
+
api = createApi({
|
|
2649
6305
|
config,
|
|
2650
6306
|
auth,
|
|
6307
|
+
mcp,
|
|
6308
|
+
authorize,
|
|
6309
|
+
clients: oauthClients,
|
|
6310
|
+
registrations: {
|
|
6311
|
+
addresses: clients,
|
|
6312
|
+
rates
|
|
6313
|
+
},
|
|
6314
|
+
operator,
|
|
2651
6315
|
log,
|
|
2652
6316
|
filesDir: join(options.data, "files"),
|
|
2653
6317
|
home: async (id) => (await data.home(id)).assembled,
|
|
2654
6318
|
touch: (id) => data.touch(id),
|
|
6319
|
+
suspended: (id) => suspendedHome(id),
|
|
6320
|
+
message: (id) => meter?.add("relay.messages", {
|
|
6321
|
+
account: ownerOf(id).account,
|
|
6322
|
+
home: id
|
|
6323
|
+
}),
|
|
6324
|
+
stored: (id, bytes) => meter?.add("bytes.stored", {
|
|
6325
|
+
account: ownerOf(id).account,
|
|
6326
|
+
home: id
|
|
6327
|
+
}, bytes),
|
|
2655
6328
|
...Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) > 0 ? { recheckMs: Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) } : {}
|
|
2656
6329
|
});
|
|
6330
|
+
const served = api;
|
|
2657
6331
|
const apiHost = new URL(config.apiOrigin).host;
|
|
2658
|
-
const domains =
|
|
6332
|
+
const domains = [config.domains.active, ...config.domains.spares ?? []];
|
|
2659
6333
|
const onRequest = (request, response) => {
|
|
2660
6334
|
const host = (request.headers.host ?? "").toLowerCase();
|
|
2661
|
-
delete request.headers.cookie;
|
|
2662
6335
|
const path = (request.url ?? "/").split("?")[0] ?? "/";
|
|
2663
|
-
if (host
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
6336
|
+
if (host !== apiHost) delete request.headers.cookie;
|
|
6337
|
+
if (host === apiHost && request.method === "GET" && path === "/health") {
|
|
6338
|
+
json(response, 200, {
|
|
6339
|
+
status: "ok",
|
|
6340
|
+
homes: data.open().length
|
|
6341
|
+
});
|
|
6342
|
+
return;
|
|
6343
|
+
}
|
|
6344
|
+
if (perIpRequests) {
|
|
6345
|
+
const taken = rates.take(`request-ip:${clients.keyOf(clients.of(request))}`, perIpRequests);
|
|
6346
|
+
if (!taken.ok) {
|
|
6347
|
+
response.setHeader("retry-after", String(taken.retryAfterS));
|
|
6348
|
+
refusal$1(response, 429, createDiagnostic("MOSTRA_REMOTE_RATE_LIMITED", { message: "Too many requests from this address; try again shortly." }));
|
|
2669
6349
|
return;
|
|
2670
6350
|
}
|
|
2671
|
-
|
|
6351
|
+
}
|
|
6352
|
+
if (host === apiHost) {
|
|
6353
|
+
served.request(request, response, path).catch((error) => {
|
|
2672
6354
|
log.error("server.api_failed", {
|
|
2673
6355
|
path,
|
|
2674
6356
|
error
|
|
@@ -2678,14 +6360,20 @@ async function startServer(options) {
|
|
|
2678
6360
|
});
|
|
2679
6361
|
return;
|
|
2680
6362
|
}
|
|
2681
|
-
const
|
|
2682
|
-
if (
|
|
2683
|
-
|
|
6363
|
+
const hostRefused = () => refusal$1(response, 421, createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", { message: "This server serves no pages at this host." }));
|
|
6364
|
+
if (!/^[a-z0-9.-]{1,253}(:\d{1,5})?$/.test(host)) {
|
|
6365
|
+
hostRefused();
|
|
2684
6366
|
return;
|
|
2685
6367
|
}
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
6368
|
+
routing.destination(host).then(async (destination) => {
|
|
6369
|
+
if (destination.kind === "none" || destination.kind === "api") {
|
|
6370
|
+
hostRefused();
|
|
6371
|
+
return;
|
|
6372
|
+
}
|
|
6373
|
+
response.setHeader("origin-agent-cluster", "?1");
|
|
6374
|
+
response.setHeader("x-robots-tag", "noindex");
|
|
6375
|
+
await hosted(request, response, destination, path);
|
|
6376
|
+
}).catch((error) => {
|
|
2689
6377
|
log.error("server.hosted_failed", { error });
|
|
2690
6378
|
if (!response.headersSent) refusal$1(response, 500, createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The server failed to answer." }));
|
|
2691
6379
|
else response.destroy();
|
|
@@ -2700,41 +6388,101 @@ async function startServer(options) {
|
|
|
2700
6388
|
"cache-control": "no-store"
|
|
2701
6389
|
}
|
|
2702
6390
|
}), { overrideGlobalObjects: false });
|
|
6391
|
+
/** Whether the operator suspended a home (`ServerHandle.suspendHome`). */
|
|
6392
|
+
const suspendedHome = (homeId) => data.directory.read((db) => db.get("SELECT suspended_at FROM home WHERE id = ?", homeId)?.suspended_at != null);
|
|
6393
|
+
/**
|
|
6394
|
+
* A home whose pages are served now: a suspended one answers 403 and one being moved 503,
|
|
6395
|
+
* each with its diagnostic, and nothing of it is opened for a page (D165 item 9).
|
|
6396
|
+
*/
|
|
6397
|
+
const pagesOf = async (homeId, response) => {
|
|
6398
|
+
if (suspendedHome(homeId)) {
|
|
6399
|
+
refusal$1(response, 403, homeUnavailable("suspended"));
|
|
6400
|
+
return;
|
|
6401
|
+
}
|
|
6402
|
+
try {
|
|
6403
|
+
const opened = await data.home(homeId);
|
|
6404
|
+
if (meter?.on) {
|
|
6405
|
+
const socket = response.socket;
|
|
6406
|
+
const before = socket?.bytesWritten ?? 0;
|
|
6407
|
+
response.once("finish", () => {
|
|
6408
|
+
const account = ownerOf(homeId).account;
|
|
6409
|
+
meter?.add("requests", {
|
|
6410
|
+
account,
|
|
6411
|
+
home: homeId
|
|
6412
|
+
});
|
|
6413
|
+
meter?.add("bytes.egress", {
|
|
6414
|
+
account,
|
|
6415
|
+
home: homeId
|
|
6416
|
+
}, Math.max(0, (socket?.bytesWritten ?? before) - before));
|
|
6417
|
+
});
|
|
6418
|
+
}
|
|
6419
|
+
return opened;
|
|
6420
|
+
} catch (error) {
|
|
6421
|
+
if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_REMOTE_HOME_MOVING") {
|
|
6422
|
+
response.setHeader("retry-after", "30");
|
|
6423
|
+
refusal$1(response, 503, error.diagnostic);
|
|
6424
|
+
return;
|
|
6425
|
+
}
|
|
6426
|
+
throw error;
|
|
6427
|
+
}
|
|
6428
|
+
};
|
|
2703
6429
|
/** A route of the directory: its home and ID, by ID or by label. */
|
|
2704
|
-
const routeBy = (column, value) => data.directory.read((db) => db.get(`SELECT id, home_id FROM artifact_route WHERE ${column} =
|
|
2705
|
-
/**
|
|
2706
|
-
|
|
2707
|
-
|
|
6430
|
+
const routeBy = (column, value) => data.directory.read((db) => db.get(`SELECT id, home_id FROM artifact_route WHERE ${column} = ? AND removing_json IS NULL`, value));
|
|
6431
|
+
/**
|
|
6432
|
+
* A hosted request (§18.4): a shell (a configured apex, or an operator's host for one home or
|
|
6433
|
+
* one route) serves only `/a/<routeId>` of the routes it may show and the shell's files; a
|
|
6434
|
+
* route's label serves that route's frames.
|
|
6435
|
+
*/
|
|
6436
|
+
const hosted = async (request, response, destination, path) => {
|
|
6437
|
+
if (destination.kind === "shell") {
|
|
2708
6438
|
if (path.startsWith("/_mostra/shell/assets/")) {
|
|
2709
6439
|
await assets(request, response);
|
|
2710
6440
|
return;
|
|
2711
6441
|
}
|
|
6442
|
+
if (path === "/_mostra/signin" && (request.method === "GET" || request.method === "HEAD")) {
|
|
6443
|
+
if (shellDir === void 0) {
|
|
6444
|
+
notServed(response);
|
|
6445
|
+
return;
|
|
6446
|
+
}
|
|
6447
|
+
const html = readFileSync(join(shellDir, "index.html"));
|
|
6448
|
+
response.writeHead(200, {
|
|
6449
|
+
...BASE_HEADERS$1,
|
|
6450
|
+
...documentHeaders({
|
|
6451
|
+
kind: "shell",
|
|
6452
|
+
origin: "",
|
|
6453
|
+
shellOrigin: ""
|
|
6454
|
+
}, "'none'"),
|
|
6455
|
+
"content-type": "text/html; charset=utf-8",
|
|
6456
|
+
"cache-control": "no-store"
|
|
6457
|
+
});
|
|
6458
|
+
response.end(request.method === "HEAD" ? void 0 : html);
|
|
6459
|
+
return;
|
|
6460
|
+
}
|
|
2712
6461
|
const match = /^\/a\/(rte_[0-9A-HJKMNP-TV-Z]{26})(?:\/|$)/.exec(path);
|
|
2713
6462
|
const route = match?.[1] !== void 0 && RouteId.is(match[1]) ? routeBy("id", match[1]) : void 0;
|
|
2714
|
-
if (!route) {
|
|
6463
|
+
if (!route || destination.homeId !== void 0 && route.home_id !== destination.homeId || destination.routeId !== void 0 && route.id !== destination.routeId) {
|
|
2715
6464
|
notServed(response);
|
|
2716
6465
|
return;
|
|
2717
6466
|
}
|
|
2718
|
-
|
|
6467
|
+
const home = await pagesOf(route.home_id, response);
|
|
6468
|
+
if (!home) return;
|
|
6469
|
+
await home.assembled.serve(request, response, {
|
|
2719
6470
|
kind: "shell",
|
|
2720
|
-
domain,
|
|
6471
|
+
domain: destination.host,
|
|
2721
6472
|
routeId: route.id
|
|
2722
6473
|
});
|
|
2723
6474
|
return;
|
|
2724
6475
|
}
|
|
2725
|
-
const
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
refusal$1(response, 421, createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", { message: "This server serves no pages at this host." }));
|
|
2729
|
-
return;
|
|
2730
|
-
}
|
|
2731
|
-
await (await data.home(route.home_id)).assembled.serve(request, response, {
|
|
6476
|
+
const home = await pagesOf(destination.route.homeId, response);
|
|
6477
|
+
if (!home) return;
|
|
6478
|
+
await home.assembled.serve(request, response, {
|
|
2732
6479
|
kind: "frame",
|
|
2733
|
-
domain,
|
|
2734
|
-
routeId: route.id
|
|
6480
|
+
domain: destination.frameDomain,
|
|
6481
|
+
routeId: destination.route.id
|
|
2735
6482
|
});
|
|
2736
6483
|
};
|
|
2737
|
-
const listener = createServer({ maxHeaderSize:
|
|
6484
|
+
const listener = createServer$1({ maxHeaderSize: 1048576 }, onRequest);
|
|
6485
|
+
const stopListener = resetOnClose(listener);
|
|
2738
6486
|
listener.keepAliveTimeout = 305e3;
|
|
2739
6487
|
listener.headersTimeout = 3e4;
|
|
2740
6488
|
listener.requestTimeout = 12e4;
|
|
@@ -2742,7 +6490,7 @@ async function startServer(options) {
|
|
|
2742
6490
|
const host = (request.headers.host ?? "").toLowerCase();
|
|
2743
6491
|
const path = (request.url ?? "/").split("?")[0] ?? "/";
|
|
2744
6492
|
if (host === apiHost) {
|
|
2745
|
-
|
|
6493
|
+
served.upgrade(request, socket, head, path);
|
|
2746
6494
|
return;
|
|
2747
6495
|
}
|
|
2748
6496
|
socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\ncontent-length: 0\r\n\r\n");
|
|
@@ -2773,11 +6521,11 @@ async function startServer(options) {
|
|
|
2773
6521
|
config,
|
|
2774
6522
|
close() {
|
|
2775
6523
|
closing ??= (async () => {
|
|
2776
|
-
|
|
2777
|
-
await
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
6524
|
+
served.close();
|
|
6525
|
+
await mcp.close().catch(() => void 0);
|
|
6526
|
+
meter?.stop();
|
|
6527
|
+
operator?.stop();
|
|
6528
|
+
await stopListener();
|
|
2781
6529
|
await data.close();
|
|
2782
6530
|
log.info("server.stopped", {});
|
|
2783
6531
|
})();
|