@opendatalabs/personal-server-ts-lite 0.0.1-canary.052d47e → 0.0.1-canary.05cdd81

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.
Files changed (148) hide show
  1. package/dist/account-mode-store.d.ts +11 -0
  2. package/dist/account-mode-store.d.ts.map +1 -0
  3. package/dist/account-mode-store.js +68 -0
  4. package/dist/account-mode-store.js.map +1 -0
  5. package/dist/additions-crypto.d.ts +3 -0
  6. package/dist/additions-crypto.d.ts.map +1 -0
  7. package/dist/additions-crypto.js +42 -0
  8. package/dist/additions-crypto.js.map +1 -0
  9. package/dist/additions-protocol.d.ts +56 -0
  10. package/dist/additions-protocol.d.ts.map +1 -0
  11. package/dist/additions-protocol.js +17 -0
  12. package/dist/additions-protocol.js.map +1 -0
  13. package/dist/additions-session.d.ts +20 -0
  14. package/dist/additions-session.d.ts.map +1 -0
  15. package/dist/additions-session.js +215 -0
  16. package/dist/additions-session.js.map +1 -0
  17. package/dist/additions-transport.d.ts +72 -0
  18. package/dist/additions-transport.d.ts.map +1 -0
  19. package/dist/additions-transport.js +428 -0
  20. package/dist/additions-transport.js.map +1 -0
  21. package/dist/additions-worker.bundle.js +31252 -0
  22. package/dist/additions-worker.d.ts +2 -0
  23. package/dist/additions-worker.d.ts.map +1 -0
  24. package/dist/additions-worker.js +308 -0
  25. package/dist/additions-worker.js.map +1 -0
  26. package/dist/bridge.d.ts +3 -0
  27. package/dist/bridge.d.ts.map +1 -1
  28. package/dist/bridge.js +4 -0
  29. package/dist/bridge.js.map +1 -1
  30. package/dist/browser-runtime.d.ts +111 -1
  31. package/dist/browser-runtime.d.ts.map +1 -1
  32. package/dist/browser-runtime.js +176 -11
  33. package/dist/browser-runtime.js.map +1 -1
  34. package/dist/canonical-persistence.d.ts +53 -0
  35. package/dist/canonical-persistence.d.ts.map +1 -0
  36. package/dist/canonical-persistence.js +13 -0
  37. package/dist/canonical-persistence.js.map +1 -0
  38. package/dist/canonical-store.d.ts +395 -0
  39. package/dist/canonical-store.d.ts.map +1 -0
  40. package/dist/canonical-store.js +1807 -0
  41. package/dist/canonical-store.js.map +1 -0
  42. package/dist/client.d.ts +24 -1
  43. package/dist/client.d.ts.map +1 -1
  44. package/dist/client.js +214 -1
  45. package/dist/client.js.map +1 -1
  46. package/dist/derivatives.d.ts.map +1 -1
  47. package/dist/derivatives.js +4 -2
  48. package/dist/derivatives.js.map +1 -1
  49. package/dist/diagnostics.d.ts +3 -0
  50. package/dist/diagnostics.d.ts.map +1 -1
  51. package/dist/diagnostics.js +9 -1
  52. package/dist/diagnostics.js.map +1 -1
  53. package/dist/history-probe-worker.bundle.js +31274 -0
  54. package/dist/history-probe.worker.d.ts +35 -0
  55. package/dist/history-probe.worker.d.ts.map +1 -0
  56. package/dist/history-probe.worker.js +161 -0
  57. package/dist/history-probe.worker.js.map +1 -0
  58. package/dist/index.d.ts +17 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +12 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/localdb-port.d.ts +28 -0
  63. package/dist/localdb-port.d.ts.map +1 -0
  64. package/dist/localdb-port.js +30 -0
  65. package/dist/localdb-port.js.map +1 -0
  66. package/dist/mcp-store.d.ts +1 -1
  67. package/dist/mcp-store.d.ts.map +1 -1
  68. package/dist/mcp-store.js +144 -15
  69. package/dist/mcp-store.js.map +1 -1
  70. package/dist/oura-import.d.ts +2 -0
  71. package/dist/oura-import.d.ts.map +1 -0
  72. package/dist/oura-import.js +3 -0
  73. package/dist/oura-import.js.map +1 -0
  74. package/dist/owner-binding.d.ts +5 -0
  75. package/dist/owner-binding.d.ts.map +1 -1
  76. package/dist/owner-binding.js +4 -8
  77. package/dist/owner-binding.js.map +1 -1
  78. package/dist/persistence.d.ts +1 -1
  79. package/dist/persistence.d.ts.map +1 -1
  80. package/dist/persistence.js +2 -2
  81. package/dist/persistence.js.map +1 -1
  82. package/dist/pull-signals.d.ts +38 -0
  83. package/dist/pull-signals.d.ts.map +1 -0
  84. package/dist/pull-signals.js +73 -0
  85. package/dist/pull-signals.js.map +1 -0
  86. package/dist/relay-tls.d.ts.map +1 -1
  87. package/dist/relay-tls.js +10 -0
  88. package/dist/relay-tls.js.map +1 -1
  89. package/dist/relay.d.ts +91 -3
  90. package/dist/relay.d.ts.map +1 -1
  91. package/dist/relay.js +522 -75
  92. package/dist/relay.js.map +1 -1
  93. package/dist/replication-coordinator-state.d.ts +19 -0
  94. package/dist/replication-coordinator-state.d.ts.map +1 -0
  95. package/dist/replication-coordinator-state.js +20 -0
  96. package/dist/replication-coordinator-state.js.map +1 -0
  97. package/dist/replication-door.d.ts +17 -0
  98. package/dist/replication-door.d.ts.map +1 -0
  99. package/dist/replication-door.js +23 -0
  100. package/dist/replication-door.js.map +1 -0
  101. package/dist/replication-engine.d.ts +49 -0
  102. package/dist/replication-engine.d.ts.map +1 -0
  103. package/dist/replication-engine.js +589 -0
  104. package/dist/replication-engine.js.map +1 -0
  105. package/dist/replication-host.d.ts +92 -0
  106. package/dist/replication-host.d.ts.map +1 -0
  107. package/dist/replication-host.js +135 -0
  108. package/dist/replication-host.js.map +1 -0
  109. package/dist/replication-ports.d.ts +194 -0
  110. package/dist/replication-ports.d.ts.map +1 -0
  111. package/dist/replication-ports.js +58 -0
  112. package/dist/replication-ports.js.map +1 -0
  113. package/dist/replication-runtime.d.ts +64 -0
  114. package/dist/replication-runtime.d.ts.map +1 -0
  115. package/dist/replication-runtime.js +79 -0
  116. package/dist/replication-runtime.js.map +1 -0
  117. package/dist/replication-storage.d.ts +42 -0
  118. package/dist/replication-storage.d.ts.map +1 -0
  119. package/dist/replication-storage.js +173 -0
  120. package/dist/replication-storage.js.map +1 -0
  121. package/dist/runtime.d.ts +85 -6
  122. package/dist/runtime.d.ts.map +1 -1
  123. package/dist/runtime.js +561 -37
  124. package/dist/runtime.js.map +1 -1
  125. package/dist/seed-staging.d.ts +8 -0
  126. package/dist/seed-staging.d.ts.map +1 -0
  127. package/dist/seed-staging.js +106 -0
  128. package/dist/seed-staging.js.map +1 -0
  129. package/dist/state.d.ts +16 -1
  130. package/dist/state.d.ts.map +1 -1
  131. package/dist/state.js +93 -23
  132. package/dist/state.js.map +1 -1
  133. package/dist/storage-utils.d.ts.map +1 -1
  134. package/dist/storage-utils.js +11 -3
  135. package/dist/storage-utils.js.map +1 -1
  136. package/dist/storage.d.ts +59 -1
  137. package/dist/storage.d.ts.map +1 -1
  138. package/dist/storage.js +601 -150
  139. package/dist/storage.js.map +1 -1
  140. package/dist/stream-sync-budget.d.ts +3 -0
  141. package/dist/stream-sync-budget.d.ts.map +1 -0
  142. package/dist/stream-sync-budget.js +3 -0
  143. package/dist/stream-sync-budget.js.map +1 -0
  144. package/dist/sync.d.ts +104 -3
  145. package/dist/sync.d.ts.map +1 -1
  146. package/dist/sync.js +377 -62
  147. package/dist/sync.js.map +1 -1
  148. package/package.json +12 -5
package/dist/runtime.js CHANGED
@@ -1,11 +1,17 @@
1
- import { GrantRequiredError, InvalidSignatureError, MissingAuthError, NotOwnerError, ProtocolError, PsUnavailableError, UnregisteredBuilderError, } from "@opendatalabs/personal-server-ts-core/errors";
1
+ import { liveStreamCounts } from "@opendatalabs/personal-server-ts-core/stream-sync-read";
2
+ import { RunIntakeError } from "@opendatalabs/personal-server-ts-core/stream-sync";
3
+ import { importOuraBrowserRecords } from "./oura-import.js";
4
+ import { withLegacyProjection, } from "@opendatalabs/personal-server-ts-core/storage/legacy-projection";
5
+ import { GrantRequiredError, InvalidSignatureError, MissingAuthError, NotOwnerError, ProtocolError, PsUnavailableError, } from "@opendatalabs/personal-server-ts-core/errors";
2
6
  import { authenticateRequest, } from "@opendatalabs/personal-server-ts-core/auth";
3
7
  import { approveDeviceSessionContract, createMemoryDeviceSessionStore, initiateDeviceSessionContract, pollDeviceSessionContract, provisionDeviceTokenContract, revokeDeviceTokenContract, } from "@opendatalabs/personal-server-ts-core/contracts";
4
- import { handlePersonalServerAccessLogsRequest, handlePersonalServerConfigRequest, handlePersonalServerDataRequest, handlePersonalServerGrantsRequest, handlePersonalServerOauthTokenRequest, handlePersonalServerSyncRequest, } from "@opendatalabs/personal-server-ts-core/api";
8
+ import { accountStorageModeOf, decisionBody, normalizeOwner, parseEvidenceBody, } from "@opendatalabs/personal-server-ts-core/sync/account-mode";
9
+ import { handleOwnerConnectorDelete, handlePersonalServerAccessLogsRequest, handlePersonalServerConfigRequest, handlePersonalServerDataRequest, handlePersonalServerScopeUploadAppend, refuseLegacyWrite, LegacyWriteRefusedError, accountStorageModeFor, createScopeUploadRegistry, handleOuraCollectionRequirementsRequest, handlePersonalServerGrantsRequest, handlePersonalServerOauthTokenRequest, handlePersonalServerSyncRequest, } from "@opendatalabs/personal-server-ts-core/api";
5
10
  import { handlePersonalServerDerivativesRequest, } from "@opendatalabs/personal-server-ts-core/derivatives";
6
- import { verifyDataReadPolicy, } from "@opendatalabs/personal-server-ts-core/policy";
11
+ import { resolveDataListGrantScopes, verifyDataReadPolicy, } from "@opendatalabs/personal-server-ts-core/policy";
7
12
  import { createInMemoryWriteProofReplayStore, createWriteSessionAuthorization, handleWriteSessionRequest, } from "@opendatalabs/personal-server-ts-core/write";
8
- import { approveMcpOAuthAuthorization, approveMcpOAuthAuthorizationWithScopes, approveMcpConnection, buildMcpProtectedResourceMetadataUrl, buildStableMcpUrl, createInMemoryMcpOAuthAuthorizationStore, createMcpConnection, createMcpOAuthAuthorization, createMcpDataReadClient, handleMcpStreamableHttpRequest, hashConnectionToken, listMcpConnectionViews, loadMcpGranteeAccount, McpConnectionNotFoundError, McpConnectionStateError, McpOAuthAuthorizationError, redeemMcpOAuthAuthorizationCode, toMcpOAuthAuthorizationView, revokeMcpConnection, toMcpConnectionView, McpActivityRecorder, } from "@opendatalabs/personal-server-ts-core/mcp";
13
+ import { approveMcpOAuthAuthorization, approveMcpOAuthAuthorizationWithScopes, approveMcpConnection, approveMcpScopeAccessRequest, liveMcpGrants, buildMcpProtectedResourceMetadataUrl, buildStableMcpUrl, createInMemoryMcpOAuthAuthorizationStore, createMcpConnection, createMcpOAuthAuthorization, createMcpDataReadClient, McpDataWriteError, denyMcpScopeAccessRequest, handleMcpStreamableHttpRequest, hashConnectionToken, listMcpConnectionViews, loadMcpGranteeAccount, MCP_CONNECTION_NOT_FOUND, MCP_SCOPE_REQUEST_NOT_FOUND, MCP_SCOPE_REQUEST_TOKEN_HEADER, McpInvalidScopeError, readMcpScopeRequestWithToken, getMcpConnectionView, McpConnectionNotFoundError, McpConnectionStateError, McpOAuthAuthorizationError, isAllowedOAuthRedirectUri, McpScopeRequestError, redeemMcpOAuthAuthorizationCode, refreshMcpOAuthToken, requestMcpScopeAccess, toMcpOAuthAuthorizationView, revokeMcpConnection, toMcpConnectionView, McpActivityRecorder, } from "@opendatalabs/personal-server-ts-core/mcp";
14
+ import { startPullSignals, startVisibilityPause } from "./pull-signals.js";
9
15
  import { createDefaultPsLiteAccessLogStore, createDefaultPsLiteSaveConfig, createDefaultPsLiteTokenStore, } from "./state.js";
10
16
  import { collectDiagnosticsWithTimeout, DiagnosticsRecorder, } from "./diagnostics.js";
11
17
  function jsonResponse(body, init) {
@@ -13,6 +19,73 @@ function jsonResponse(body, init) {
13
19
  headers.set("Content-Type", "application/json");
14
20
  return new Response(JSON.stringify(body), { ...init, headers });
15
21
  }
22
+ /**
23
+ * A mode answer: the decision body, with a refusal's own HTTP status. A 503 is
24
+ * retryable and says when to ask again.
25
+ */
26
+ function decisionResponse(decision) {
27
+ const refused = decision.kind === "refuse";
28
+ return jsonResponse(decisionBody(decision), {
29
+ status: refused ? decision.status : 200,
30
+ ...(refused && decision.status === 503
31
+ ? { headers: { "Retry-After": MODE_RETRY_AFTER_SECONDS } }
32
+ : {}),
33
+ });
34
+ }
35
+ // The mode routes take small bodies, as on the Node server: at most 16 KiB
36
+ // (413 above it, sized or chunked), a flat object of at most 8 plain values,
37
+ // and an owner of at most 100 characters (400 otherwise).
38
+ const MODE_BODY_MAX_BYTES = 16 * 1024;
39
+ const MODE_BODY_MAX_KEYS = 8;
40
+ const MODE_OWNER_MAX_LENGTH = 100;
41
+ const MODE_RETRY_AFTER_SECONDS = "5";
42
+ const BODY_TOO_LARGE = Symbol("body too large");
43
+ /** The request's flat JSON object, null when it is not one, or too large. */
44
+ async function readModeBody(request) {
45
+ if (Number(request.headers.get("content-length")) > MODE_BODY_MAX_BYTES) {
46
+ return BODY_TOO_LARGE;
47
+ }
48
+ const reader = request.body?.getReader();
49
+ const decoder = new TextDecoder();
50
+ let text = "";
51
+ let size = 0;
52
+ while (reader) {
53
+ const { done, value } = await reader.read();
54
+ if (done)
55
+ break;
56
+ size += value.byteLength;
57
+ if (size > MODE_BODY_MAX_BYTES) {
58
+ await reader.cancel().catch(() => undefined);
59
+ return BODY_TOO_LARGE;
60
+ }
61
+ text += decoder.decode(value, { stream: true });
62
+ }
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(text + decoder.decode());
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
71
+ return null;
72
+ }
73
+ const values = Object.values(parsed);
74
+ if (values.length > MODE_BODY_MAX_KEYS)
75
+ return null;
76
+ if (values.some((v) => v !== null && typeof v === "object"))
77
+ return null;
78
+ return parsed;
79
+ }
80
+ function modeBodyRefusal(body, code, shape) {
81
+ if (body === BODY_TOO_LARGE) {
82
+ return jsonResponse({
83
+ error: "CONTENT_TOO_LARGE",
84
+ message: `Request body exceeds maximum size of ${MODE_BODY_MAX_BYTES} bytes`,
85
+ }, { status: 413 });
86
+ }
87
+ return body ? null : errorResponse(400, code, shape);
88
+ }
16
89
  function protocolErrorResponse(err) {
17
90
  return jsonResponse(err.toJSON(), { status: err.code });
18
91
  }
@@ -39,6 +112,16 @@ function mcpUnauthorized(origin, message = "MCP authorization required") {
39
112
  },
40
113
  });
41
114
  }
115
+ /** Grant types this OAuth server implements — advertised and enforced here. */
116
+ const AUTHORIZATION_CODE_GRANT = "authorization_code";
117
+ const REFRESH_TOKEN_GRANT = "refresh_token";
118
+ const SUPPORTED_GRANT_TYPES = [
119
+ AUTHORIZATION_CODE_GRANT,
120
+ REFRESH_TOKEN_GRANT,
121
+ ];
122
+ function isSupportedGrantType(value) {
123
+ return SUPPORTED_GRANT_TYPES.includes(value);
124
+ }
42
125
  function authorizationServerMetadata(origin) {
43
126
  return {
44
127
  issuer: origin,
@@ -46,7 +129,7 @@ function authorizationServerMetadata(origin) {
46
129
  token_endpoint: `${origin}/mcp/oauth/token`,
47
130
  registration_endpoint: `${origin}/mcp/oauth/register`,
48
131
  response_types_supported: ["code"],
49
- grant_types_supported: ["authorization_code"],
132
+ grant_types_supported: [...SUPPORTED_GRANT_TYPES],
50
133
  token_endpoint_auth_methods_supported: ["none"],
51
134
  code_challenge_methods_supported: ["S256"],
52
135
  scopes_supported: ["vana:read"],
@@ -67,7 +150,8 @@ function resolveMcpApprovalUrl(value) {
67
150
  return typeof value === "function" ? value() : value;
68
151
  }
69
152
  function redirectWithOAuthError(redirectUri, error, description, state) {
70
- try {
153
+ // RFC 6749 4.1.2.1: never redirect to an invalid or unvalidated URI.
154
+ if (isAllowedOAuthRedirectUri(redirectUri)) {
71
155
  const url = new URL(redirectUri);
72
156
  url.searchParams.set("error", error);
73
157
  url.searchParams.set("error_description", description);
@@ -75,13 +159,11 @@ function redirectWithOAuthError(redirectUri, error, description, state) {
75
159
  url.searchParams.set("state", state);
76
160
  return Response.redirect(url.toString(), 302);
77
161
  }
78
- catch {
79
- return jsonResponse({
80
- error,
81
- error_description: description,
82
- ...(state ? { state } : {}),
83
- }, { status: 400 });
84
- }
162
+ return jsonResponse({
163
+ error,
164
+ error_description: description,
165
+ ...(state ? { state } : {}),
166
+ }, { status: 400 });
85
167
  }
86
168
  async function parseFormBody(request) {
87
169
  return new URLSearchParams(await request.text());
@@ -154,6 +236,7 @@ export function createBearerTokenPsLiteAuth(options) {
154
236
  assertBearerToken(request, options.ownerToken, true);
155
237
  };
156
238
  return {
239
+ supportsScopeUploadCommitments: true,
157
240
  authorizeOwner,
158
241
  ...(options.writeSessions
159
242
  ? writeSessionAuthMethods(options.writeSessions, authorizeOwner)
@@ -161,6 +244,7 @@ export function createBearerTokenPsLiteAuth(options) {
161
244
  async authorizeBuilderList(request) {
162
245
  if (parseBearerToken(request) === options.ownerToken)
163
246
  return;
247
+ // Owner-equivalent listing by design; see `builderToken`.
164
248
  assertBearerToken(request, options.builderToken);
165
249
  },
166
250
  async authorizeBuilderRead(input) {
@@ -215,6 +299,7 @@ export function createWeb3SignedPsLiteAuth(options) {
215
299
  }
216
300
  };
217
301
  return {
302
+ supportsScopeUploadCommitments: true,
218
303
  authorizeOwner,
219
304
  ...(options.writeSessions
220
305
  ? writeSessionAuthMethods({
@@ -223,7 +308,7 @@ export function createWeb3SignedPsLiteAuth(options) {
223
308
  serverOwner: options.ownerAddress,
224
309
  }, authorizeOwner)
225
310
  : {}),
226
- async authorizeBuilderList(request) {
311
+ async authorizeBuilderList(request, listOptions) {
227
312
  const auth = await authenticatePsLiteRequest(request, options);
228
313
  if (auth.isPolicyBypass || isOwnerSigner(auth, options.ownerAddress)) {
229
314
  return;
@@ -231,10 +316,13 @@ export function createWeb3SignedPsLiteAuth(options) {
231
316
  if (!options.dataReadPolicyPorts) {
232
317
  throw dataReadPolicyPortsRequired();
233
318
  }
234
- const builder = await options.dataReadPolicyPorts.authSessionVerifier.getBuilder(auth.auth.signer);
235
- if (!builder) {
236
- throw new UnregisteredBuilderError();
237
- }
319
+ // A builder lists only what its grants from this PS's owner cover.
320
+ const grantedScopes = await resolveDataListGrantScopes({
321
+ signer: auth.auth.signer,
322
+ grantId: auth.auth.payload.grantId ?? listOptions?.grantId,
323
+ serverOwner: options.ownerAddress,
324
+ }, options.dataReadPolicyPorts);
325
+ return { grantedScopes };
238
326
  },
239
327
  async authorizeBuilderRead(input) {
240
328
  const auth = await authenticatePsLiteRequest(input.request, options);
@@ -316,11 +404,27 @@ function resolveX402Settings(config, gateway = config?.gateway) {
316
404
  : undefined,
317
405
  };
318
406
  }
407
+ function warnLegacyProjectionIssue(issue) {
408
+ console.warn(issue.kind === "projection_failed"
409
+ ? "[legacy-projection] served read refused"
410
+ : "[legacy-projection] projection left rows out", issue);
411
+ }
319
412
  export function createPsLiteRuntime(options) {
320
413
  let active = options.active ?? false;
414
+ // Page signals start a pull while the runtime is active (D4-SYNC-TRIGGERS).
415
+ let stopPullSignals;
321
416
  const now = options.now ?? (() => new Date());
322
417
  const auth = options.auth ?? createMissingAuthAdapter();
323
- const dataStorage = toDataStoragePort(options.storage);
418
+ // Readers get legacy bodies projected from stored PDPP records; writes and
419
+ // listings pass through. Sync is built outside with the raw port.
420
+ const dataStorage = withLegacyProjection(toDataStoragePort(options.storage), {
421
+ onIssue: options.onLegacyProjectionIssue ?? warnLegacyProjectionIssue,
422
+ });
423
+ // Streamed scope writes need a file store that can append to an unindexed
424
+ // file; without one the upload routes answer 501.
425
+ const scopeUploads = dataStorage.openVersionWriter
426
+ ? createScopeUploadRegistry()
427
+ : undefined;
324
428
  // Wire diagnostics by default so GET /v1/diagnostics is always available.
325
429
  const diagnostics = options.diagnostics ?? new DiagnosticsRecorder();
326
430
  options = { ...options, diagnostics };
@@ -372,6 +476,12 @@ export function createPsLiteRuntime(options) {
372
476
  if (err instanceof ProtocolError) {
373
477
  return protocolErrorResponse(err);
374
478
  }
479
+ options.logger?.error?.({
480
+ errorCode: "INTERNAL_ERROR",
481
+ err: err instanceof Error
482
+ ? { name: err.name, message: err.message, stack: err.stack }
483
+ : { message: String(err) },
484
+ }, "Unhandled error in PS Lite runtime");
375
485
  return errorResponse(500, "INTERNAL_ERROR", "Internal server error");
376
486
  }
377
487
  }
@@ -381,6 +491,40 @@ export function createPsLiteRuntime(options) {
381
491
  function ownerAddress() {
382
492
  return options.serverOwner ?? options.identity?.address;
383
493
  }
494
+ // The owner the account mode is bound to: the person's owner only, as on the
495
+ // Node server. The server identity is never a substitute.
496
+ function modeOwner() {
497
+ return options.serverOwner;
498
+ }
499
+ function modeMethodNotAllowed() {
500
+ return jsonResponse({
501
+ error: {
502
+ code: 405,
503
+ errorCode: "METHOD_NOT_ALLOWED",
504
+ message: "Method not allowed",
505
+ },
506
+ }, { status: 405, headers: { Allow: "POST" } });
507
+ }
508
+ /** A refusal unless the body's owner is the runtime's mode owner. */
509
+ function modeOwnerRefusal(owner) {
510
+ if (typeof owner !== "string" || owner.length > MODE_OWNER_MAX_LENGTH) {
511
+ return errorResponse(400, "INVALID_ACCOUNT_MODE_OWNER", "Body owner must be a string of at most 100 characters");
512
+ }
513
+ const bound = modeOwner();
514
+ if (bound === undefined ||
515
+ normalizeOwner(owner) !== normalizeOwner(bound)) {
516
+ return errorResponse(403, "ACCOUNT_MODE_OWNER_MISMATCH", "This server only takes account mode for its own owner");
517
+ }
518
+ return null;
519
+ }
520
+ // The host's mode, bound once to this runtime's owner. Every consumer below
521
+ // (scope-upload append, the data handler, Oura, every MCP engine) receives
522
+ // this bound view, which cannot be asked about another account. The mode
523
+ // answers `unknown` when it is bound to a different owner or this runtime
524
+ // has none.
525
+ const accountStorageMode = accountStorageModeFor(options.accountModeAuthority
526
+ ? accountStorageModeOf(options.accountModeAuthority)
527
+ : { read: () => "unknown" }, modeOwner());
384
528
  async function handleAuthDevice(request, url) {
385
529
  if (url.pathname === "/auth/device") {
386
530
  if (request.method !== "POST") {
@@ -484,20 +628,55 @@ export function createPsLiteRuntime(options) {
484
628
  }
485
629
  return {
486
630
  kind: "ps-lite",
631
+ streamSyncSeed: options.streamSyncSeed ?? null,
487
632
  storage: options.storage,
488
633
  activate() {
489
634
  active = true;
490
635
  options.syncManager?.start?.();
636
+ stopPullSignals?.();
637
+ const manager = options.syncManager;
638
+ // Hides pause the manager; shows resume it, then the pull below probes.
639
+ const stopVisibility = manager
640
+ ? startVisibilityPause(manager)
641
+ : undefined;
642
+ const stopPulls = manager?.requestPull
643
+ ? startPullSignals(() => {
644
+ manager.requestPull?.().catch(() => undefined);
645
+ })
646
+ : undefined;
647
+ stopPullSignals = () => {
648
+ stopVisibility?.();
649
+ stopPulls?.();
650
+ };
491
651
  options.derivatives?.scheduler.start();
652
+ options.replication?.resume();
492
653
  },
493
654
  deactivate() {
494
655
  active = false;
656
+ stopPullSignals?.();
657
+ stopPullSignals = undefined;
495
658
  void options.syncManager?.stop?.();
496
659
  options.derivatives?.scheduler.stop();
660
+ void options.replication?.pause();
497
661
  },
498
662
  isAvailable() {
499
663
  return active;
500
664
  },
665
+ ...(auth.supportsScopeUploadCommitments
666
+ ? {
667
+ async appendScopeUpload(request, batch) {
668
+ if (!active)
669
+ return unavailableResponse();
670
+ return handlePersonalServerScopeUploadAppend(request, {
671
+ storage: dataStorage,
672
+ auth,
673
+ accessLogWriter,
674
+ scopeUploads,
675
+ accountStorageMode,
676
+ }, batch);
677
+ },
678
+ }
679
+ : {}),
501
680
  async fetch(request) {
502
681
  return withProtocolErrors(async () => {
503
682
  const url = new URL(request.url);
@@ -578,20 +757,136 @@ export function createPsLiteRuntime(options) {
578
757
  });
579
758
  return jsonResponse(snapshot);
580
759
  }
760
+ if (url.pathname === "/v1/replication/status") {
761
+ if (request.method !== "GET")
762
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
763
+ await auth.authorizeOwner(request);
764
+ return jsonResponse(options.replication?.status() ?? { state: "off" });
765
+ }
766
+ // Account-mode answers do not wait for activation: a host submits the
767
+ // first Off or On, and only then starts the workers that depend on it.
768
+ if (url.pathname === "/v1/account-mode/evidence" &&
769
+ options.accountModeAuthority) {
770
+ if (request.method !== "POST")
771
+ return modeMethodNotAllowed();
772
+ await auth.authorizeOwner(request);
773
+ const raw = await readModeBody(request);
774
+ const bad = modeBodyRefusal(raw, "INVALID_ACCOUNT_MODE_BODY", "Body must be a flat JSON object");
775
+ if (bad)
776
+ return bad;
777
+ const mismatch = modeOwnerRefusal(raw.owner);
778
+ if (mismatch)
779
+ return mismatch;
780
+ const body = parseEvidenceBody(raw);
781
+ if (!body) {
782
+ return errorResponse(400, "INVALID_ACCOUNT_MODE_EVIDENCE", "Body must be {owner, state, generation?}");
783
+ }
784
+ // authorizeOwner succeeded, so the caller is this runtime's owner,
785
+ // and so is the body's.
786
+ return decisionResponse(await options.accountModeAuthority.submitEvidence(body));
787
+ }
581
788
  if (!active) {
582
789
  return unavailableResponse();
583
790
  }
791
+ const connectorPath = /^\/v1\/owner\/connectors\/([^/]+)$/.exec(url.pathname);
792
+ if (connectorPath) {
793
+ if (request.method !== "DELETE") {
794
+ // Owner first: a caller who is not the owner learns nothing of the route.
795
+ await auth.authorizeOwner(request);
796
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
797
+ }
798
+ let connectorId;
799
+ try {
800
+ connectorId = decodeURIComponent(connectorPath[1]);
801
+ }
802
+ catch {
803
+ // A malformed percent-escape is a bad id (400 after authorization).
804
+ connectorId = null;
805
+ }
806
+ return handleOwnerConnectorDelete(request, connectorId, {
807
+ authorizeOwner: (req) => auth.authorizeOwner(req),
808
+ mode: accountStorageMode,
809
+ connectionDelete: options.streamSyncConnectionDelete,
810
+ });
811
+ }
812
+ if (url.pathname === "/v1/replication/sync") {
813
+ if (request.method !== "POST")
814
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
815
+ await auth.authorizeOwner(request);
816
+ const status = options.replication?.status() ?? { state: "off" };
817
+ if (status.state !== "on")
818
+ return jsonResponse({
819
+ error: {
820
+ code: 409,
821
+ errorCode: "REPLICATION_NOT_RUNNING",
822
+ message: "Replication is not running",
823
+ },
824
+ status,
825
+ }, { status: 409 });
826
+ // "Sync now" starts a step and answers at once; the step may run
827
+ // up to its deadline. Its outcome shows in the status.
828
+ void options.replication.trigger("sync_now");
829
+ return jsonResponse({ accepted: true, status }, { status: 202 });
830
+ }
831
+ if (url.pathname === "/v1/import/oura-browser/requirements") {
832
+ return handleOuraCollectionRequirementsRequest(request, {
833
+ auth,
834
+ storage: toDataStoragePort(options.storage),
835
+ });
836
+ }
837
+ if (url.pathname === "/v1/import/oura-browser") {
838
+ await auth.authorizeOwner(request);
839
+ if (request.method !== "POST")
840
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
841
+ // An Oura browser import is a legacy write: a switched account refuses
842
+ // it. This is the early refusal; each stream the import stores is a
843
+ // storage write that passes the storage's seal on its own, so an
844
+ // account that switches mid-batch stops at the next stream.
845
+ const refusal = refuseLegacyWrite(accountStorageMode);
846
+ if (refusal)
847
+ return refusal;
848
+ let body;
849
+ try {
850
+ body = await request.json();
851
+ }
852
+ catch {
853
+ return errorResponse(400, "INVALID_BODY", "Body must be JSON");
854
+ }
855
+ try {
856
+ const result = await importOuraBrowserRecords(toDataStoragePort(options.storage), body, {
857
+ accountStorageMode,
858
+ additions: options.additions,
859
+ scopeDeletions: options.scopeDeletions,
860
+ syncManager: options.syncManager ?? null,
861
+ onDataWritten: options.derivatives
862
+ ? (event) => options.derivatives?.scheduler.markSourceChanged(event.scope, { lineageSources: event.lineageSources })
863
+ : undefined,
864
+ });
865
+ return jsonResponse(result, { status: result.ok ? 200 : 409 });
866
+ }
867
+ catch (error) {
868
+ if (error instanceof LegacyWriteRefusedError)
869
+ return error.response;
870
+ throw error;
871
+ }
872
+ }
584
873
  const dataPrefix = "/v1/data";
585
874
  if (url.pathname === dataPrefix ||
586
875
  url.pathname.startsWith(`${dataPrefix}/`)) {
587
876
  const x402 = resolveX402Settings(options.config, boundGatewayConfig);
588
877
  return handlePersonalServerDataRequest(request, {
589
878
  storage: dataStorage,
879
+ accountStorageMode,
590
880
  auth,
881
+ logger: options.logger,
591
882
  accessLogWriter,
592
883
  readFulfillmentReporter: options.readFulfillmentReporter,
884
+ additions: options.additions,
593
885
  syncManager: options.syncManager ?? null,
594
886
  scopeDeletions: options.scopeDeletions,
887
+ streamSyncRead: options.streamSyncRead,
888
+ history: options.history,
889
+ scopeUploads,
595
890
  now,
596
891
  createLogId,
597
892
  // x402 payment enforcement for builder reads. Only engages with a
@@ -613,11 +908,15 @@ export function createPsLiteRuntime(options) {
613
908
  serverOwner: options.serverOwner,
614
909
  serverSigner: x402ServerSigner,
615
910
  lineageGateway: options.lineageGateway,
616
- // Recompute on refresh: a new local version marks every
617
- // question that reads the scope stale.
911
+ // A new local version marks every question that reads the
912
+ // scope stale; the recompute waits for a reader.
618
913
  onDataWritten: options.derivatives
619
914
  ? (event) => options.derivatives?.scheduler.markSourceChanged(event.scope, { lineageSources: event.lineageSources })
620
915
  : undefined,
916
+ // And an authorized read of a derived scope is that reader.
917
+ onDataRead: options.derivatives
918
+ ? (event) => options.derivatives?.scheduler.markDemand(event.scope)
919
+ : undefined,
621
920
  }, { basePath: dataPrefix });
622
921
  }
623
922
  // Write API handshake. Mounted only when a session store is wired,
@@ -699,7 +998,51 @@ export function createPsLiteRuntime(options) {
699
998
  url.pathname === `${accessLogsPrefix}/`) {
700
999
  return handlePersonalServerAccessLogsRequest(request, { auth, accessLogReader }, { basePath: accessLogsPrefix });
701
1000
  }
1001
+ if (url.pathname === "/v1/stream-sync/read-status" &&
1002
+ options.localSync) {
1003
+ await auth.authorizeOwner(request);
1004
+ if (request.method !== "GET")
1005
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1006
+ const local = await options.localSync();
1007
+ const status = await local.listing.status();
1008
+ return jsonResponse({
1009
+ listed: status.listed,
1010
+ streams: liveStreamCounts(status),
1011
+ issues: status.issues.length,
1012
+ olderVersionReads: local.olderVersions.counts(),
1013
+ });
1014
+ }
1015
+ // Whether a run is saved: `GET /v1/stream-sync/runs/:runId/publication`.
1016
+ // `superseded` alone does not mean saved; a consumer must check `reason`.
1017
+ const runPublication = /^\/v1\/stream-sync\/runs\/([A-Za-z0-9._-]{1,128})\/publication$/.exec(url.pathname);
1018
+ if (runPublication && options.localSync) {
1019
+ await auth.authorizeOwner(request);
1020
+ if (request.method !== "GET")
1021
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1022
+ // Bind to the runtime's owner: a run written under another owner
1023
+ // answers 404, the same as an unknown run, so it is not revealed.
1024
+ const owner = ownerAddress();
1025
+ if (!owner)
1026
+ return errorResponse(404, "RUN_NOT_FOUND", "Run not found");
1027
+ try {
1028
+ return jsonResponse(await (await options.localSync()).intake.publicationStatus(runPublication[1], { owner }));
1029
+ }
1030
+ catch (err) {
1031
+ if (err instanceof RunIntakeError &&
1032
+ (err.code === "gone" || err.code === "owner_mismatch"))
1033
+ return errorResponse(404, "RUN_NOT_FOUND", "Run not found");
1034
+ throw err;
1035
+ }
1036
+ }
702
1037
  const syncPrefix = "/v1/sync";
1038
+ if (url.pathname === `${syncPrefix}/status` &&
1039
+ options.localSync &&
1040
+ accountStorageMode.read() !== "unswitched") {
1041
+ await auth.authorizeOwner(request);
1042
+ if (request.method !== "GET")
1043
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1044
+ return jsonResponse(await (await options.localSync()).listing.status());
1045
+ }
703
1046
  if (url.pathname === `${syncPrefix}/trigger` ||
704
1047
  url.pathname === `${syncPrefix}/status` ||
705
1048
  url.pathname.startsWith(`${syncPrefix}/file/`)) {
@@ -736,8 +1079,13 @@ export function createPsLiteRuntime(options) {
736
1079
  store: options.mcpConnectionStore,
737
1080
  authorizationStore: mcpOAuthAuthorizationStore,
738
1081
  approvalUrl: options.mcpOAuthApprovalUrl,
1082
+ scopeRequestApprovalUrl: options.mcpScopeRequestApprovalUrl,
1083
+ exposeUnsharedScopes: options.mcpExposeUnsharedScopes,
1084
+ scopeRequestGuidance: options.mcpScopeRequestGuidance,
739
1085
  auth,
740
1086
  dataStorage,
1087
+ streamSyncRead: options.streamSyncRead,
1088
+ accountStorageMode,
741
1089
  accessLogWriter,
742
1090
  readFulfillmentReporter: options.readFulfillmentReporter,
743
1091
  now,
@@ -749,6 +1097,7 @@ export function createPsLiteRuntime(options) {
749
1097
  gatewayConfig: boundGatewayConfig,
750
1098
  serverOwner: options.serverOwner ?? options.identity?.address,
751
1099
  serverSigner: options.serverSigner,
1100
+ grantTtlSeconds: options.mcpGrantTtlSeconds,
752
1101
  activityRecorder,
753
1102
  });
754
1103
  if (mcpResponse)
@@ -798,6 +1147,13 @@ async function handleMcpRoute(input) {
798
1147
  catch {
799
1148
  body = {};
800
1149
  }
1150
+ if (Array.isArray(body.redirect_uris) &&
1151
+ !body.redirect_uris.every(isAllowedOAuthRedirectUri)) {
1152
+ return jsonResponse({
1153
+ error: "invalid_redirect_uri",
1154
+ error_description: "One or more redirect_uris are not allowed",
1155
+ }, { status: 400 });
1156
+ }
801
1157
  return jsonResponse({
802
1158
  client_id: `mcp-client-${crypto.randomUUID()}`,
803
1159
  client_name: body.client_name ?? "Claude",
@@ -805,7 +1161,7 @@ async function handleMcpRoute(input) {
805
1161
  ? body.redirect_uris
806
1162
  : [],
807
1163
  token_endpoint_auth_method: "none",
808
- grant_types: ["authorization_code"],
1164
+ grant_types: [...SUPPORTED_GRANT_TYPES],
809
1165
  response_types: ["code"],
810
1166
  }, { status: 201 });
811
1167
  }
@@ -864,26 +1220,32 @@ async function handleMcpRoute(input) {
864
1220
  return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
865
1221
  }
866
1222
  const body = await parseFormBody(input.request);
867
- if (body.get("grant_type") !== "authorization_code") {
1223
+ const grantType = body.get("grant_type") ?? "";
1224
+ if (!isSupportedGrantType(grantType)) {
868
1225
  return jsonResponse({
869
1226
  error: "unsupported_grant_type",
870
- error_description: "Only authorization_code is supported",
1227
+ error_description: `Supported grant types: ${SUPPORTED_GRANT_TYPES.join(", ")}`,
871
1228
  }, { status: 400 });
872
1229
  }
1230
+ const clientId = body.get("client_id") ?? "";
873
1231
  try {
874
- const token = await redeemMcpOAuthAuthorizationCode({
875
- authorizationCode: body.get("code") ?? "",
876
- codeVerifier: body.get("code_verifier") ?? "",
877
- clientId: body.get("client_id") ?? "",
878
- redirectUri: body.get("redirect_uri") ?? "",
879
- }, {
880
- authorizationStore: input.authorizationStore,
881
- connectionStore: input.store,
882
- now: input.now,
883
- });
1232
+ const token = grantType === REFRESH_TOKEN_GRANT
1233
+ ? await refreshMcpOAuthToken({ refreshToken: body.get("refresh_token") ?? "", clientId }, { connectionStore: input.store, now: input.now })
1234
+ : await redeemMcpOAuthAuthorizationCode({
1235
+ authorizationCode: body.get("code") ?? "",
1236
+ codeVerifier: body.get("code_verifier") ?? "",
1237
+ clientId,
1238
+ redirectUri: body.get("redirect_uri") ?? "",
1239
+ }, {
1240
+ authorizationStore: input.authorizationStore,
1241
+ connectionStore: input.store,
1242
+ now: input.now,
1243
+ });
884
1244
  return jsonResponse({
885
1245
  access_token: token.accessToken,
886
1246
  token_type: "Bearer",
1247
+ expires_in: token.expiresIn,
1248
+ refresh_token: token.refreshToken,
887
1249
  ...(token.scope ? { scope: token.scope } : {}),
888
1250
  });
889
1251
  }
@@ -951,6 +1313,7 @@ async function handleMcpRoute(input) {
951
1313
  serverOwner: input.serverOwner,
952
1314
  serverSigner: input.serverSigner,
953
1315
  now: input.now,
1316
+ grantTtlSeconds: input.grantTtlSeconds,
954
1317
  });
955
1318
  return jsonResponse({ redirectTo: approved.redirectTo });
956
1319
  }
@@ -981,6 +1344,30 @@ async function handleMcpRoute(input) {
981
1344
  }
982
1345
  return errorResponse(404, "NOT_FOUND", "Not found");
983
1346
  }
1347
+ // GET /v1/mcp/connections/:id/scope-request: the pending request, read
1348
+ // with the token from its approval link instead of an owner signature, so
1349
+ // the owner signs only to answer. Every failure is the same 404, so the
1350
+ // route does not reveal which requests exist.
1351
+ const scopeRequestRead = /^\/v1\/mcp\/connections\/([^/]+)\/scope-request$/u.exec(pathname);
1352
+ if (scopeRequestRead && input.request.method === "GET") {
1353
+ let connectionId = "";
1354
+ try {
1355
+ connectionId = decodeURIComponent(scopeRequestRead[1] ?? "");
1356
+ }
1357
+ catch {
1358
+ connectionId = "";
1359
+ }
1360
+ const view = await readMcpScopeRequestWithToken({
1361
+ connectionId,
1362
+ token: input.request.headers.get(MCP_SCOPE_REQUEST_TOKEN_HEADER),
1363
+ }, { store: input.store, gateway: input.gateway, now: input.now });
1364
+ if (!view) {
1365
+ const notFound = errorResponse(404, MCP_SCOPE_REQUEST_NOT_FOUND, "Scope request not found");
1366
+ notFound.headers.set("Cache-Control", "no-store");
1367
+ return notFound;
1368
+ }
1369
+ return jsonResponse(view, { headers: { "Cache-Control": "no-store" } });
1370
+ }
984
1371
  // Owner management endpoints
985
1372
  if (pathname === ownerPrefix || pathname.startsWith(`${ownerPrefix}/`)) {
986
1373
  try {
@@ -1015,12 +1402,23 @@ async function handleMcpRoute(input) {
1015
1402
  }
1016
1403
  return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1017
1404
  }
1018
- // /v1/mcp/connections/:id[/approve]
1405
+ // /v1/mcp/connections/:id[/approve | /scope-request/(approve|deny)]
1406
+ // GET /:id reads one connection; DELETE /:id revokes it.
1019
1407
  const tail = pathname.slice(ownerPrefix.length + 1);
1020
- const [id, action] = tail.split("/");
1408
+ const [id, action, subAction, ...rest] = tail.split("/");
1021
1409
  if (!id) {
1022
1410
  return errorResponse(404, "NOT_FOUND", "Not found");
1023
1411
  }
1412
+ if (action === "scope-request") {
1413
+ if (rest.length > 0 ||
1414
+ (subAction !== "approve" && subAction !== "deny")) {
1415
+ return errorResponse(404, "NOT_FOUND", "Not found");
1416
+ }
1417
+ if (input.request.method !== "POST") {
1418
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1419
+ }
1420
+ return handleScopeRequestAnswer(id, subAction);
1421
+ }
1024
1422
  if (action === "approve") {
1025
1423
  if (input.request.method !== "POST") {
1026
1424
  return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
@@ -1046,10 +1444,24 @@ async function handleMcpRoute(input) {
1046
1444
  if (err instanceof McpConnectionStateError) {
1047
1445
  return errorResponse(409, "INVALID_STATE", err.message);
1048
1446
  }
1447
+ if (err instanceof McpInvalidScopeError) {
1448
+ return errorResponse(400, err.code, err.message);
1449
+ }
1049
1450
  throw err;
1050
1451
  }
1051
1452
  }
1052
1453
  if (!action) {
1454
+ if (input.request.method === "GET") {
1455
+ try {
1456
+ return jsonResponse(await getMcpConnectionView(id, input.store));
1457
+ }
1458
+ catch (err) {
1459
+ if (err instanceof McpConnectionNotFoundError) {
1460
+ return errorResponse(404, MCP_CONNECTION_NOT_FOUND, err.message);
1461
+ }
1462
+ throw err;
1463
+ }
1464
+ }
1053
1465
  if (input.request.method === "DELETE") {
1054
1466
  try {
1055
1467
  const updated = await revokeMcpConnection(id, {
@@ -1069,6 +1481,76 @@ async function handleMcpRoute(input) {
1069
1481
  }
1070
1482
  return errorResponse(404, "NOT_FOUND", "Not found");
1071
1483
  }
1484
+ async function handleScopeRequestAnswer(id, answer) {
1485
+ let scopes;
1486
+ if (answer === "approve") {
1487
+ try {
1488
+ scopes = (await input.request.json()).scopes;
1489
+ }
1490
+ catch {
1491
+ return errorResponse(400, "INVALID_BODY", "Body must be JSON");
1492
+ }
1493
+ }
1494
+ const gateway = input.gateway;
1495
+ if (answer === "approve" && !gateway) {
1496
+ return errorResponse(500, "SERVER_NOT_CONFIGURED", "Gateway is not configured");
1497
+ }
1498
+ const activityId = input.activityRecorder?.start({
1499
+ tool: `owner.scope_request.${answer}`,
1500
+ ...(Array.isArray(scopes)
1501
+ ? {
1502
+ scopes: scopes.filter((scope) => typeof scope === "string"),
1503
+ }
1504
+ : {}),
1505
+ });
1506
+ const finish = (status, errorCode) => {
1507
+ if (activityId) {
1508
+ input.activityRecorder?.finish(activityId, {
1509
+ status,
1510
+ ...(errorCode ? { errorCode } : {}),
1511
+ });
1512
+ }
1513
+ };
1514
+ try {
1515
+ if (answer === "deny" || !gateway) {
1516
+ const denied = await denyMcpScopeAccessRequest({ connectionId: id }, { store: input.store, now: input.now });
1517
+ finish("succeeded");
1518
+ return jsonResponse({ connection: toMcpConnectionView(denied) });
1519
+ }
1520
+ const approved = await approveMcpScopeAccessRequest({ connectionId: id, scopes }, {
1521
+ store: input.store,
1522
+ gateway,
1523
+ serverOwner: input.serverOwner,
1524
+ serverSigner: input.serverSigner,
1525
+ now: input.now,
1526
+ grantTtlSeconds: input.grantTtlSeconds,
1527
+ });
1528
+ finish("succeeded");
1529
+ return jsonResponse({
1530
+ connection: toMcpConnectionView(approved.connection),
1531
+ grantId: approved.grantId,
1532
+ grantedScopes: approved.grantedScopes,
1533
+ approvedScopes: approved.approvedScopes,
1534
+ deniedScopes: approved.deniedScopes,
1535
+ });
1536
+ }
1537
+ catch (err) {
1538
+ if (err instanceof McpConnectionNotFoundError) {
1539
+ finish("failed", MCP_CONNECTION_NOT_FOUND);
1540
+ return errorResponse(404, MCP_CONNECTION_NOT_FOUND, err.message);
1541
+ }
1542
+ if (err instanceof McpConnectionStateError) {
1543
+ finish("failed", "INVALID_STATE");
1544
+ return errorResponse(409, "INVALID_STATE", err.message);
1545
+ }
1546
+ if (err instanceof McpScopeRequestError) {
1547
+ finish("failed", err.code);
1548
+ return errorResponse(err.status, err.code, err.message);
1549
+ }
1550
+ finish("failed", "INTERNAL");
1551
+ throw err;
1552
+ }
1553
+ }
1072
1554
  async function handleMcpToken(rawToken, options) {
1073
1555
  if (!rawToken) {
1074
1556
  if (!options.oauthChallenge) {
@@ -1089,11 +1571,26 @@ async function handleMcpRoute(input) {
1089
1571
  publicKey: record.granteePublicKey,
1090
1572
  encryptedPrivateKey: record.encryptedGranteePrivateKey,
1091
1573
  });
1574
+ const mode = input.accountStorageMode?.read() ?? "unknown";
1575
+ const storage = mode === "unswitched"
1576
+ ? input.dataStorage
1577
+ : new Proxy({}, {
1578
+ get() {
1579
+ return () => {
1580
+ throw new ProtocolError(503, "STREAM_SYNC_LEGACY_STORAGE", "Legacy storage is sealed for this account mode");
1581
+ };
1582
+ },
1583
+ });
1092
1584
  const readClient = createMcpDataReadClient({
1093
1585
  serverOrigin: input.serverOrigin,
1094
1586
  granteeAccount,
1095
1587
  dataApiDeps: {
1096
- storage: input.dataStorage,
1588
+ storage,
1589
+ streamSyncRead: mode === "switched" ? input.streamSyncRead : undefined,
1590
+ accountStorageMode: {
1591
+ owner: input.accountStorageMode?.owner ?? input.serverOwner ?? "",
1592
+ read: () => mode,
1593
+ },
1097
1594
  auth: input.auth,
1098
1595
  accessLogWriter: input.accessLogWriter,
1099
1596
  readFulfillmentReporter: input.readFulfillmentReporter,
@@ -1105,7 +1602,28 @@ async function handleMcpRoute(input) {
1105
1602
  const response = await handleMcpStreamableHttpRequest(input.request, {
1106
1603
  connection: record,
1107
1604
  readClient,
1605
+ writeClient: mode === "switched"
1606
+ ? {
1607
+ async updateScope() {
1608
+ throw new McpDataWriteError(409, {
1609
+ error: {
1610
+ code: 409,
1611
+ errorCode: "STREAM_SYNC_WRITE_UNAVAILABLE",
1612
+ message: "Memory writes are not available through stream sync",
1613
+ },
1614
+ });
1615
+ },
1616
+ }
1617
+ : undefined,
1108
1618
  activityRecorder: input.activityRecorder,
1619
+ requestScopeAccess: async (request) => {
1620
+ return requestMcpScopeAccess({ connectionId: record.id, ...request }, { store: input.store, now: input.now });
1621
+ },
1622
+ scopeRequestApprovalUrl: input.scopeRequestApprovalUrl,
1623
+ exposeUnsharedScopes: input.exposeUnsharedScopes,
1624
+ verifyGrantsLive: () => liveMcpGrants(record, input.gateway, input.now),
1625
+ scopeRequestGuidance: input.scopeRequestGuidance,
1626
+ serverOrigin: input.serverOrigin,
1109
1627
  });
1110
1628
  void input.store
1111
1629
  .update(record.id, {
@@ -1141,6 +1659,12 @@ async function handleMcpRoute(input) {
1141
1659
  oauthChallenge: Boolean(resolveMcpApprovalUrl(input.approvalUrl)),
1142
1660
  });
1143
1661
  }
1662
+ // The self-signing app handshake (Node server only). Without this it falls
1663
+ // into the legacy /mcp/:token route below, which reads "session" as a
1664
+ // connection token and answers "Unknown or revoked MCP connection".
1665
+ if (pathname === "/mcp/session") {
1666
+ return errorResponse(501, "MCP_SESSION_NOT_SUPPORTED", "Third-party MCP sessions are not available on this Personal Server. The user needs Vana Desktop.");
1667
+ }
1144
1668
  // Legacy Claude-facing endpoint: /mcp/:token
1145
1669
  const mcpPrefix = "/mcp/";
1146
1670
  if (pathname.startsWith(mcpPrefix)) {