@codemem/server 0.47.4 → 0.48.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/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3
- import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
3
+ import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
4
4
  import { serveStatic } from "@hono/node-server/serve-static";
5
5
  import { Hono } from "hono";
6
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
6
+ import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { createMiddleware } from "hono/factory";
8
8
  import { RateLimiter } from "limiter";
9
9
  import { and, count, desc, eq, inArray, max, ne, sql } from "drizzle-orm";
@@ -11,9 +11,11 @@ import { drizzle } from "drizzle-orm/better-sqlite3";
11
11
  import { homedir, hostname, networkInterfaces } from "node:os";
12
12
  import * as z from "zod";
13
13
  import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
14
+ import { BlockList, isIP } from "node:net";
14
15
  import "better-sqlite3";
15
16
  import "sqlite-vec";
16
17
  import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
18
+ import { RELAY_LOGICAL_ORIGIN, createRelayCoordinatorClient, createRelayPeerClient, createRelayPeerReachability, readRelayClientSettings, readRelayServicePin, relayCoordinatorEndpoint, resolveRelayGroup } from "@codemem/core/internal/relay-runtime";
17
19
  //#region src/routes/account.ts
18
20
  /** Mounted only alongside the account request middleware. */
19
21
  function accountRoutes(getSession) {
@@ -225,49 +227,6 @@ function preflightHandler() {
225
227
  });
226
228
  }
227
229
  //#endregion
228
- //#region src/request-rate-limit.ts
229
- function createInMemoryRequestRateLimiter(windowMs = 6e4) {
230
- const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
231
- const buckets = /* @__PURE__ */ new Map();
232
- let checks = 0;
233
- function estimatedRetryAfterS(limit) {
234
- return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
235
- }
236
- function cleanupExpiredBuckets(currentNow) {
237
- if (buckets.size < 64 || checks % 64 !== 0) return;
238
- const staleBefore = currentNow - safeWindowMs * 10;
239
- for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
240
- }
241
- return { check(key, limit) {
242
- checks += 1;
243
- const currentNow = Date.now();
244
- cleanupExpiredBuckets(currentNow);
245
- const safeLimit = Math.max(1, Math.trunc(limit));
246
- const bucketKey = `${safeLimit}:${key}`;
247
- let bucket = buckets.get(bucketKey);
248
- if (!bucket) {
249
- bucket = {
250
- limiter: new RateLimiter({
251
- tokensPerInterval: safeLimit,
252
- interval: safeWindowMs,
253
- fireImmediately: true
254
- }),
255
- lastUsedAt: currentNow
256
- };
257
- buckets.set(bucketKey, bucket);
258
- }
259
- bucket.lastUsedAt = currentNow;
260
- if (bucket.limiter.tryRemoveTokens(1)) return {
261
- allowed: true,
262
- retryAfterS: 0
263
- };
264
- return {
265
- allowed: false,
266
- retryAfterS: estimatedRetryAfterS(safeLimit)
267
- };
268
- } };
269
- }
270
- //#endregion
271
230
  //#region src/account/link-registry.ts
272
231
  var DEADLINE_MS = 6e5;
273
232
  var RETENTION_MS = 9e5;
@@ -1624,6 +1583,49 @@ function accountStatusRoutes(options) {
1624
1583
  return app;
1625
1584
  }
1626
1585
  //#endregion
1586
+ //#region src/request-rate-limit.ts
1587
+ function createInMemoryRequestRateLimiter(windowMs = 6e4) {
1588
+ const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
1589
+ const buckets = /* @__PURE__ */ new Map();
1590
+ let checks = 0;
1591
+ function estimatedRetryAfterS(limit) {
1592
+ return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
1593
+ }
1594
+ function cleanupExpiredBuckets(currentNow) {
1595
+ if (buckets.size < 64 || checks % 64 !== 0) return;
1596
+ const staleBefore = currentNow - safeWindowMs * 10;
1597
+ for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
1598
+ }
1599
+ return { check(key, limit) {
1600
+ checks += 1;
1601
+ const currentNow = Date.now();
1602
+ cleanupExpiredBuckets(currentNow);
1603
+ const safeLimit = Math.max(1, Math.trunc(limit));
1604
+ const bucketKey = `${safeLimit}:${key}`;
1605
+ let bucket = buckets.get(bucketKey);
1606
+ if (!bucket) {
1607
+ bucket = {
1608
+ limiter: new RateLimiter({
1609
+ tokensPerInterval: safeLimit,
1610
+ interval: safeWindowMs,
1611
+ fireImmediately: true
1612
+ }),
1613
+ lastUsedAt: currentNow
1614
+ };
1615
+ buckets.set(bucketKey, bucket);
1616
+ }
1617
+ bucket.lastUsedAt = currentNow;
1618
+ if (bucket.limiter.tryRemoveTokens(1)) return {
1619
+ allowed: true,
1620
+ retryAfterS: 0
1621
+ };
1622
+ return {
1623
+ allowed: false,
1624
+ retryAfterS: estimatedRetryAfterS(safeLimit)
1625
+ };
1626
+ } };
1627
+ }
1628
+ //#endregion
1627
1629
  //#region src/routes/config.ts
1628
1630
  /**
1629
1631
  * Config routes — GET /api/config, POST /api/config.
@@ -2591,7 +2593,7 @@ var BOOLEAN_IDENTITY_TARGET_KEYS = /* @__PURE__ */ new Set([
2591
2593
  "embedding_disabled",
2592
2594
  "embedding_offline"
2593
2595
  ]);
2594
- function invalidRequest$1(message) {
2596
+ function invalidRequest$2(message) {
2595
2597
  return {
2596
2598
  ok: false,
2597
2599
  status: 400,
@@ -2611,7 +2613,7 @@ function conflict(code, message) {
2611
2613
  } }
2612
2614
  };
2613
2615
  }
2614
- function isRecord$1(value) {
2616
+ function isRecord$2(value) {
2615
2617
  return value != null && typeof value === "object" && !Array.isArray(value);
2616
2618
  }
2617
2619
  function currentIdentityTarget() {
@@ -2636,7 +2638,7 @@ function identityFieldMatches(key, requested, expected) {
2636
2638
  }
2637
2639
  function requestedIdentityMatches(value) {
2638
2640
  if (value == null) return true;
2639
- if (!isRecord$1(value)) return null;
2641
+ if (!isRecord$2(value)) return null;
2640
2642
  if (Object.keys(value).length !== IDENTITY_TARGET_KEYS.size || Object.keys(value).some((key) => !IDENTITY_TARGET_KEYS.has(key))) return "unsupported";
2641
2643
  const expected = currentIdentityTarget();
2642
2644
  for (const key of VIEWER_IDENTITY_TARGET_KEYS) {
@@ -2651,15 +2653,15 @@ function requestedIdentityMatches(value) {
2651
2653
  function validateViewerTarget(store, payload, options = {}) {
2652
2654
  if (options.requirePairedTargets) {
2653
2655
  const hasDbPath = Object.hasOwn(payload, "db_path");
2654
- if (hasDbPath !== Object.hasOwn(payload, "identity_target")) return invalidRequest$1("db_path and identity_target must be provided together");
2655
- if (hasDbPath && (payload.db_path == null || payload.identity_target == null)) return invalidRequest$1("db_path and identity_target must be valid when provided");
2656
+ if (hasDbPath !== Object.hasOwn(payload, "identity_target")) return invalidRequest$2("db_path and identity_target must be provided together");
2657
+ if (hasDbPath && (payload.db_path == null || payload.identity_target == null)) return invalidRequest$2("db_path and identity_target must be valid when provided");
2656
2658
  }
2657
2659
  const dbMatches = requestedDbMatches(store, payload.db_path);
2658
- if (dbMatches == null) return invalidRequest$1("db_path must be a non-empty string");
2660
+ if (dbMatches == null) return invalidRequest$2("db_path must be a non-empty string");
2659
2661
  if (!dbMatches) return conflict("viewer_db_mismatch", "viewer database does not match request");
2660
2662
  const identityMatches = requestedIdentityMatches(payload.identity_target);
2661
2663
  if (identityMatches === "unsupported") return conflict("viewer_contract_unsupported", "viewer request contract is incompatible");
2662
- if (identityMatches == null) return invalidRequest$1("identity_target is invalid");
2664
+ if (identityMatches == null) return invalidRequest$2("identity_target is invalid");
2663
2665
  if (!identityMatches) return conflict("viewer_identity_mismatch", "viewer identity does not match request");
2664
2666
  if ((options.requireCurrentIdentity || payload.identity_target != null) && !store.hasCurrentIdentity()) return conflict("viewer_identity_mismatch", "viewer identity does not match request");
2665
2667
  return { ok: true };
@@ -3336,6 +3338,151 @@ function forgetMemoryForViewer(store, memoryId) {
3336
3338
  if (!store.forgetForUser(memoryId)) throw new Error("memory not found");
3337
3339
  }
3338
3340
  //#endregion
3341
+ //#region src/routes/memory-tool-call.ts
3342
+ /**
3343
+ * POST /api/memory-tools/:name — run one codemem memory tool on behalf of a
3344
+ * thin host (the OpenCode plugin) in another directory.
3345
+ *
3346
+ * The viewer serves every OpenCode project on the machine from one process,
3347
+ * so the caller sends its own directory and CODEMEM_PROJECT and the tool runs
3348
+ * with those instead of the viewer's working directory and environment. The
3349
+ * tool itself is executed by an injected function: `codemem serve` supplies
3350
+ * `callCodememToolLocally` from @codemem/mcp, which this package must not
3351
+ * import. Results, input validation, and retrieval-ledger capture are
3352
+ * therefore identical to stdio MCP and to the `codemem memory-tool` fallback.
3353
+ *
3354
+ * Request body:
3355
+ * { arguments: {...},
3356
+ * caller: { directory: "/abs/path", env_project: string|null,
3357
+ * session_id?: string, request_id?: string },
3358
+ * db_path, identity_target }
3359
+ *
3360
+ * The target pair is required (not optional as on read routes) because this
3361
+ * route can write. Responses: 200 `{ok:true,result}` or `{ok:false,error,result?}`
3362
+ * when the tool ran; 400/409 when the request or target is invalid.
3363
+ */
3364
+ var MEMORY_TOOL_CALL_CAPABILITY = "memory_tool_call";
3365
+ var MEMORY_TOOL_NAME = /^memory_[a-z_]+$/;
3366
+ var MEMORY_TOOL_CALL_MAX_BODY_BYTES = 1048576;
3367
+ var MAX_ID_CHARS = 200;
3368
+ function isRecord$1(value) {
3369
+ return value != null && typeof value === "object" && !Array.isArray(value);
3370
+ }
3371
+ function invalidRequest$1(message) {
3372
+ return { error: {
3373
+ code: "invalid_request",
3374
+ message
3375
+ } };
3376
+ }
3377
+ function parseEnvProject(value) {
3378
+ if (value == null) return null;
3379
+ if (typeof value !== "string") return void 0;
3380
+ return value.trim() || null;
3381
+ }
3382
+ /** Optional short identifier: null when absent or blank, undefined when invalid. */
3383
+ function parseOptionalId(value) {
3384
+ if (value == null) return null;
3385
+ if (typeof value !== "string" || value.length > MAX_ID_CHARS) return void 0;
3386
+ return value.trim() || null;
3387
+ }
3388
+ /** Validate the body shape; caller context is mandatory so nothing defaults to the viewer's cwd. */
3389
+ function parseMemoryToolCall(body) {
3390
+ const args = body.arguments ?? {};
3391
+ if (!isRecord$1(args)) return {
3392
+ ok: false,
3393
+ message: "arguments must be an object"
3394
+ };
3395
+ const caller = body.caller;
3396
+ if (!isRecord$1(caller)) return {
3397
+ ok: false,
3398
+ message: "caller is required"
3399
+ };
3400
+ if (typeof caller.directory !== "string" || !isAbsolute(caller.directory)) return {
3401
+ ok: false,
3402
+ message: "caller.directory must be an absolute path"
3403
+ };
3404
+ const envProject = parseEnvProject(caller.env_project);
3405
+ if (envProject === void 0) return {
3406
+ ok: false,
3407
+ message: "caller.env_project must be a string"
3408
+ };
3409
+ const sessionId = parseOptionalId(caller.session_id);
3410
+ if (sessionId === void 0) return {
3411
+ ok: false,
3412
+ message: "caller.session_id is invalid"
3413
+ };
3414
+ const requestId = parseOptionalId(caller.request_id);
3415
+ if (requestId === void 0) return {
3416
+ ok: false,
3417
+ message: "caller.request_id is invalid"
3418
+ };
3419
+ if (requestId && !sessionId) return {
3420
+ ok: false,
3421
+ message: "caller.request_id requires caller.session_id"
3422
+ };
3423
+ return {
3424
+ ok: true,
3425
+ args,
3426
+ caller: {
3427
+ cwd: caller.directory,
3428
+ envProject,
3429
+ ...sessionId ? { sessionId } : {},
3430
+ ...requestId ? { requestId } : {},
3431
+ statelessLedger: true
3432
+ }
3433
+ };
3434
+ }
3435
+ /** Body shape, then target: a write-capable route must name the database it expects. */
3436
+ function checkRequest(store, body) {
3437
+ if (!Object.hasOwn(body, "db_path") || !Object.hasOwn(body, "identity_target")) return {
3438
+ ok: false,
3439
+ status: 400,
3440
+ body: invalidRequest$1("db_path and identity_target are required")
3441
+ };
3442
+ const parsed = parseMemoryToolCall(body);
3443
+ if (!parsed.ok) return {
3444
+ ok: false,
3445
+ status: 400,
3446
+ body: invalidRequest$1(parsed.message)
3447
+ };
3448
+ const target = validateViewerTarget(store, body, {
3449
+ requireCurrentIdentity: true,
3450
+ requirePairedTargets: true
3451
+ });
3452
+ if (!target.ok) return {
3453
+ ok: false,
3454
+ status: target.status,
3455
+ body: target.body
3456
+ };
3457
+ return {
3458
+ ok: true,
3459
+ parsed
3460
+ };
3461
+ }
3462
+ function memoryToolCallRoutes(getStore, call) {
3463
+ const app = new Hono();
3464
+ app.post("/api/memory-tools/:name", async (c) => {
3465
+ const name = c.req.param("name");
3466
+ if (!MEMORY_TOOL_NAME.test(name)) return c.json(invalidRequest$1(`not a memory tool: ${name}`), 400);
3467
+ const body = await parseJsonObjectBody(c, MEMORY_TOOL_CALL_MAX_BODY_BYTES);
3468
+ if (body instanceof Response) return body;
3469
+ const store = getStore();
3470
+ const check = checkRequest(store, body);
3471
+ if (!check.ok) return c.json(check.body, check.status);
3472
+ const { parsed } = check;
3473
+ try {
3474
+ return c.json(await call(store, name, parsed.args, parsed.caller));
3475
+ } catch (err) {
3476
+ const message = err instanceof Error ? err.message : String(err);
3477
+ return c.json({ error: {
3478
+ code: "tool_call_failed",
3479
+ message
3480
+ } }, 500);
3481
+ }
3482
+ });
3483
+ return app;
3484
+ }
3485
+ //#endregion
3339
3486
  //#region src/routes/memory-tools.ts
3340
3487
  /**
3341
3488
  * Memory tool-support routes — HTTP twins of MCP tools that the viewer
@@ -4255,7 +4402,7 @@ async function handleLedgerRequest(c, getStore) {
4255
4402
  } }, 500);
4256
4403
  }
4257
4404
  }
4258
- function handleProfileRequest(c, getStore) {
4405
+ function handleProfileRequest(c, getStore, capabilities) {
4259
4406
  try {
4260
4407
  const store = getStore();
4261
4408
  if (!store.hasCurrentIdentity()) return c.json(viewerIdentityMismatch(), 409);
@@ -4264,7 +4411,8 @@ function handleProfileRequest(c, getStore) {
4264
4411
  protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.protocolVersion,
4265
4412
  min_supported_protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.minSupportedProtocolVersion,
4266
4413
  db_path: resolve(store.dbPath),
4267
- identity_target: currentIdentityTarget()
4414
+ identity_target: currentIdentityTarget(),
4415
+ capabilities: [...capabilities]
4268
4416
  });
4269
4417
  } catch {
4270
4418
  return c.json({ error: {
@@ -4273,9 +4421,10 @@ function handleProfileRequest(c, getStore) {
4273
4421
  } }, 500);
4274
4422
  }
4275
4423
  }
4276
- function packTransportRoutes(getStore) {
4424
+ function packTransportRoutes(getStore, options = {}) {
4277
4425
  const app = new Hono();
4278
- app.get("/api/prompt-pack-profile", (c) => handleProfileRequest(c, getStore));
4426
+ const capabilities = options.capabilities ?? [];
4427
+ app.get("/api/prompt-pack-profile", (c) => handleProfileRequest(c, getStore, capabilities));
4279
4428
  app.post("/api/pack", async (c) => {
4280
4429
  const parsed = await c.req.json().catch(() => INVALID_JSON);
4281
4430
  if (parsed === INVALID_JSON) return c.json(invalidRequest("invalid json body"), 400);
@@ -6698,7 +6847,7 @@ function remainingCoordinatorTimeoutS(configuredTimeoutS, deadlineMs, nowMs = Da
6698
6847
  const remainingMs = deadlineMs - nowMs;
6699
6848
  return remainingMs <= 0 ? null : Math.max(.1, Math.min(configuredTimeoutS, remainingMs / 1e3));
6700
6849
  }
6701
- function configuredGroupIds(groups) {
6850
+ function configuredGroupIds$1(groups) {
6702
6851
  const unique = [...new Set(groups.map((group) => group.trim()).filter(Boolean))];
6703
6852
  if (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();
6704
6853
  return unique;
@@ -6716,7 +6865,7 @@ function normalizedCoordinatorId(value) {
6716
6865
  }
6717
6866
  }
6718
6867
  function legacyTeamCandidateGroupDescriptors(store, coordinatorUrl, groups) {
6719
- const configuredIds = configuredGroupIds(groups);
6868
+ const configuredIds = configuredGroupIds$1(groups);
6720
6869
  const configuredCoordinatorId = buildBaseUrl(coordinatorUrl);
6721
6870
  const normalizedConfiguredCoordinatorId = normalizedCoordinatorId(configuredCoordinatorId);
6722
6871
  if (!configuredCoordinatorId || !normalizedConfiguredCoordinatorId) throw safeCoordinatorError();
@@ -7606,7 +7755,7 @@ function teamSetupRoutes(options) {
7606
7755
  if (!configuredCoordinatorId) return null;
7607
7756
  let currentGroupIds;
7608
7757
  try {
7609
- currentGroupIds = new Set(configuredGroupIds(config.syncCoordinatorGroups));
7758
+ currentGroupIds = new Set(configuredGroupIds$1(config.syncCoordinatorGroups));
7610
7759
  } catch {
7611
7760
  return null;
7612
7761
  }
@@ -9888,7 +10037,7 @@ function verifyDirectPeerRequestSignature(request, body, options) {
9888
10037
  signature: directSignatureHeader,
9889
10038
  publicKey: options.publicKey
9890
10039
  });
9891
- if (hasDirectMaterial && direct.status === "absent") return {
10040
+ if ((hasDirectMaterial || options.requireDirectSignature) && direct.status === "absent") return {
9892
10041
  ok: false,
9893
10042
  reason: "invalid_direct_signature"
9894
10043
  };
@@ -9940,16 +10089,17 @@ function recordDirectPeerSignatureVersion(store, deviceId, version) {
9940
10089
  throw err;
9941
10090
  }
9942
10091
  }
9943
- function authorizeSyncRequest(store, request, body) {
9944
- const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
9945
- const signature = request.header("X-Opencode-Signature") ?? "";
9946
- const timestamp = request.header("X-Opencode-Timestamp") ?? "";
9947
- const nonce = request.header("X-Opencode-Nonce") ?? "";
9948
- if (!deviceId || !signature || !timestamp || !nonce) return {
9949
- ok: false,
9950
- reason: "missing_headers",
9951
- deviceId
9952
- };
10092
+ function matchesSyncChannelPeer(request, publicKey, readPin) {
10093
+ if (!request || request.signal.aborted) return false;
10094
+ try {
10095
+ const [algorithm, blob] = publicKey.split(/\s+/);
10096
+ const pin = readPin(request);
10097
+ return algorithm === "ssh-ed25519" && !!blob && !!pin && pin === `${algorithm} ${blob}`;
10098
+ } catch {
10099
+ return false;
10100
+ }
10101
+ }
10102
+ function checkedCurrentPeerKey(store, deviceId) {
9953
10103
  const peerRow = store.db.prepare(`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,
9954
10104
  sync_peer_signature_state.highest_observed_direct_signature_version
9955
10105
  FROM sync_peers
@@ -9972,6 +10122,30 @@ function authorizeSyncRequest(store, request, body) {
9972
10122
  reason: "fingerprint_mismatch",
9973
10123
  deviceId
9974
10124
  };
10125
+ return {
10126
+ ok: true,
10127
+ publicKey,
10128
+ highestObservedVersion: peerRow.highest_observed_direct_signature_version
10129
+ };
10130
+ }
10131
+ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
10132
+ const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
10133
+ const signature = request.header("X-Opencode-Signature") ?? "";
10134
+ const timestamp = request.header("X-Opencode-Timestamp") ?? "";
10135
+ const nonce = request.header("X-Opencode-Nonce") ?? "";
10136
+ if (!deviceId || !signature || !timestamp || !nonce) return {
10137
+ ok: false,
10138
+ reason: "missing_headers",
10139
+ deviceId
10140
+ };
10141
+ const peer = checkedCurrentPeerKey(store, deviceId);
10142
+ if (!peer.ok) return peer;
10143
+ const { publicKey } = peer;
10144
+ if (syncChannelPeerPin !== void 0 && !matchesSyncChannelPeer(request.raw, publicKey, syncChannelPeerPin)) return {
10145
+ ok: false,
10146
+ reason: "channel_binding_mismatch",
10147
+ deviceId
10148
+ };
9975
10149
  let verification;
9976
10150
  try {
9977
10151
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
@@ -9979,7 +10153,8 @@ function authorizeSyncRequest(store, request, body) {
9979
10153
  deviceId,
9980
10154
  publicKey,
9981
10155
  expectedRecipientId: localDeviceId,
9982
- highestObservedVersion: peerRow.highest_observed_direct_signature_version
10156
+ highestObservedVersion: peer.highestObservedVersion,
10157
+ requireDirectSignature: syncChannelPeerPin !== void 0
9983
10158
  });
9984
10159
  } catch {
9985
10160
  return {
@@ -11304,20 +11479,22 @@ function recordInboundScopeFailure(context) {
11304
11479
  source: "inbound"
11305
11480
  });
11306
11481
  }
11307
- function inboundScopeResetResponse(c, store, reason, context) {
11308
- recordInboundScopeFailure(context);
11309
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
11482
+ function parseInboundScopeRequest(body, context, options) {
11483
+ return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.syncChannelPeerPin), {
11484
+ ...context,
11485
+ negotiatedCapability: options.negotiated
11486
+ });
11310
11487
  }
11311
- function serveAuthorizedSnapshot(c, store, auth) {
11488
+ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
11312
11489
  const peerDeviceId = auth.deviceId;
11313
11490
  try {
11314
11491
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
11315
11492
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11316
- const scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== void 0, {
11493
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.syncChannelPeerPin), {
11317
11494
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
11318
11495
  negotiatedCapability: negotiatedSyncCapability(c)
11319
11496
  });
11320
- if (!scopeRequest.ok) return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), scopeRequest.reason, LOCAL_SYNC_CAPABILITY, null), 409);
11497
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, options.syncChannelPeerPin);
11321
11498
  const pageRequest = snapshotPageRequest((name) => c.req.query(name), localDeviceId);
11322
11499
  const result = loadMemorySnapshotPageForPeer(store.db, {
11323
11500
  ...pageRequest,
@@ -11343,9 +11520,83 @@ function serveAuthorizedSnapshot(c, store, auth) {
11343
11520
  return c.json({ error: "internal_error" }, 500);
11344
11521
  }
11345
11522
  }
11523
+ function registerSyncChannelRestriction(app, options) {
11524
+ const { syncChannelPeerPin } = options;
11525
+ if (syncChannelPeerPin !== void 0) app.use("*", async (c, next) => {
11526
+ const isOps = c.req.path === "/v1/ops" && ["GET", "POST"].includes(c.req.method);
11527
+ const isRead = c.req.method === "GET" && ["/v1/status", "/v1/snapshot"].includes(c.req.path);
11528
+ if (!isOps && !isRead) return c.json({ error: "not found" }, 404);
11529
+ if (c.req.raw.signal.aborted) return c.json(unauthorizedPayload(), 401);
11530
+ if (isRead) return serveChannelRead(c, options);
11531
+ await next();
11532
+ });
11533
+ }
11534
+ function serveChannelRead(c, options) {
11535
+ const { syncChannelPeerPin, rateLimitedResponse } = options;
11536
+ const store = options.getStore();
11537
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
11538
+ if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11539
+ if (!auth.ok) {
11540
+ logDirectPeerAuthDiagnostic(auth.reason);
11541
+ return rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);
11542
+ }
11543
+ const limited = rateLimitedResponse(c, auth.deviceId, true);
11544
+ if (limited) return limited;
11545
+ if (c.req.path === "/v1/status") return serveChannelStatus(c, store, auth, syncChannelPeerPin);
11546
+ return serveAuthorizedSnapshot(c, store, auth, { syncChannelPeerPin });
11547
+ }
11548
+ function syncScopeProvided(provided, syncChannelPeerPin) {
11549
+ return syncChannelPeerPin !== void 0 || provided;
11550
+ }
11551
+ function syncScopeResetResponse(c, store, reason, syncChannelPeerPin) {
11552
+ if (syncChannelPeerPin !== void 0) return c.json({
11553
+ error: "reset_required",
11554
+ reset_required: true,
11555
+ sync_capability: LOCAL_SYNC_CAPABILITY,
11556
+ reason,
11557
+ scope_id: null
11558
+ }, 409);
11559
+ return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
11560
+ }
11561
+ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
11562
+ try {
11563
+ const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11564
+ const authorization = syncScopeAuthorizationContext(store, auth, deviceId);
11565
+ const scopeRequest = parseSyncScopeRequest(c.req.query(SYNC_SCOPE_QUERY_PARAM), true, {
11566
+ ...authorization,
11567
+ negotiatedCapability: negotiatedSyncCapability(c)
11568
+ });
11569
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11570
+ if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
11571
+ const scopes = listAuthorizedScopesForPeer(store.db, {
11572
+ ...authorization,
11573
+ scopeId: scopeRequest.scope_id
11574
+ });
11575
+ const selectedScope = scopes[0];
11576
+ if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
11577
+ return c.json({
11578
+ device_id: deviceId,
11579
+ protocol_version: SYNC_PROTOCOL_VERSION,
11580
+ fingerprint,
11581
+ runtime_version: VERSION$1,
11582
+ sync_reset: selectedScope.sync_reset,
11583
+ sync_capability: LOCAL_SYNC_CAPABILITY,
11584
+ sync_features: LOCAL_SYNC_FEATURES,
11585
+ authorized_scopes: scopes
11586
+ });
11587
+ } catch {
11588
+ return c.json({ error: "internal_error" }, 500);
11589
+ }
11590
+ }
11346
11591
  function syncProtocolRoutes(getStore, opts = {}) {
11347
11592
  const app = new Hono();
11348
11593
  const routeRateLimit = opts.routeRateLimit ?? null;
11594
+ const syncChannelPeerPin = opts.syncChannelPeerPin;
11595
+ registerSyncChannelRestriction(app, {
11596
+ syncChannelPeerPin,
11597
+ getStore,
11598
+ rateLimitedResponse
11599
+ });
11349
11600
  function rateLimitedResponse(c, key, authenticated) {
11350
11601
  if (!routeRateLimit) return null;
11351
11602
  const isRead = c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS";
@@ -11415,7 +11666,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11415
11666
  });
11416
11667
  app.get("/v1/ops", (c) => {
11417
11668
  const store = getStore();
11418
- const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));
11669
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
11419
11670
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11420
11671
  if (!auth.ok) {
11421
11672
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -11428,11 +11679,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
11428
11679
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
11429
11680
  const negotiated = negotiatedSyncCapability(c);
11430
11681
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11431
- const scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== void 0, {
11682
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, syncChannelPeerPin), {
11432
11683
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
11433
11684
  negotiatedCapability: negotiated
11434
11685
  });
11435
- if (!scopeRequest.ok) return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), scopeRequest.reason, LOCAL_SYNC_CAPABILITY, null), 409);
11686
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11436
11687
  const since = c.req.query("since") ?? null;
11437
11688
  const rawLimit = Number.parseInt(c.req.query("limit") ?? "200", 10);
11438
11689
  const rawGeneration = c.req.query("generation");
@@ -11511,7 +11762,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11511
11762
  const store = getStore();
11512
11763
  const raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);
11513
11764
  if (raw == null) return c.json({ error: "payload_too_large" }, 413);
11514
- const auth = authorizeSyncRequest(store, c.req, raw);
11765
+ const auth = authorizeSyncRequest(store, c.req, raw, syncChannelPeerPin);
11515
11766
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11516
11767
  if (!auth.ok) {
11517
11768
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -11531,11 +11782,14 @@ function syncProtocolRoutes(getStore, opts = {}) {
11531
11782
  const negotiated = negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, normalizeSyncCapability(body.sync_capability));
11532
11783
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11533
11784
  const scopeContext = syncScopeAuthorizationContext(store, auth, localDeviceId);
11534
- const scopeRequest = parseSyncScopeRequest(body.scope_id, Object.hasOwn(body, "scope_id"), {
11535
- ...scopeContext,
11536
- negotiatedCapability: negotiated
11785
+ const scopeRequest = parseInboundScopeRequest(body, scopeContext, {
11786
+ negotiated,
11787
+ syncChannelPeerPin
11537
11788
  });
11538
- if (!scopeRequest.ok) return inboundScopeResetResponse(c, store, scopeRequest.reason, scopeContext);
11789
+ if (!scopeRequest.ok) {
11790
+ recordInboundScopeFailure(scopeContext);
11791
+ return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11792
+ }
11539
11793
  if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
11540
11794
  if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
11541
11795
  const normalizedOps = extractReplicationOps(body);
@@ -14598,6 +14852,164 @@ function updateStatusRoutes(options = {}) {
14598
14852
  return app;
14599
14853
  }
14600
14854
  //#endregion
14855
+ //#region src/shared-store.ts
14856
+ var sharedStore = null;
14857
+ var sharedStoreClosePromise = null;
14858
+ /** Share the default connection across viewer and sync listeners. */
14859
+ function getStore() {
14860
+ if (!sharedStore) sharedStore = new MemoryStore(resolveDbPath());
14861
+ return sharedStore;
14862
+ }
14863
+ /** Close a synchronous-only shared store. Async pack owners use closeStoreAsync(). */
14864
+ function closeStore() {
14865
+ sharedStore?.close();
14866
+ sharedStore = null;
14867
+ }
14868
+ /** Drain semantic work before closing SQLite and releasing the shared store. */
14869
+ function closeStoreAsync() {
14870
+ if (sharedStoreClosePromise) return sharedStoreClosePromise;
14871
+ if (!sharedStore) return Promise.resolve();
14872
+ const store = sharedStore;
14873
+ sharedStoreClosePromise = store.closeAsync().then(() => {
14874
+ if (sharedStore === store) sharedStore = null;
14875
+ sharedStoreClosePromise = null;
14876
+ });
14877
+ return sharedStoreClosePromise;
14878
+ }
14879
+ //#endregion
14880
+ //#region src/sync-app.ts
14881
+ /** Keep the network listener limited to signature-authenticated peer protocol routes. */
14882
+ function createSyncApp$1(opts) {
14883
+ const storeFactory = opts?.storeFactory ?? getStore;
14884
+ const requestRateLimit = opts?.syncRequestRateLimit ?? {};
14885
+ const rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();
14886
+ const readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));
14887
+ const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
14888
+ const app = new Hono();
14889
+ app.route("/", syncProtocolRoutes(storeFactory, {
14890
+ syncChannelPeerPin: opts?.syncChannelPeerPin,
14891
+ routeRateLimit: {
14892
+ limiter: rateLimiter,
14893
+ readLimit,
14894
+ mutationLimit,
14895
+ unauthenticatedReadLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit))),
14896
+ unauthenticatedMutationLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)))
14897
+ }
14898
+ }));
14899
+ app.all("*", (c) => c.json({ error: "not found" }, 404));
14900
+ return app;
14901
+ }
14902
+ //#endregion
14903
+ //#region src/viewer-authority.ts
14904
+ var LOOPBACK_ADDRESSES = new BlockList();
14905
+ LOOPBACK_ADDRESSES.addSubnet("127.0.0.0", 8, "ipv4");
14906
+ LOOPBACK_ADDRESSES.addAddress("::1", "ipv6");
14907
+ function listenerHostname(host) {
14908
+ if (typeof host !== "string" || !host) return null;
14909
+ if (/[\s/@\\?#%]/u.test(host)) return null;
14910
+ if ([...host].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) return null;
14911
+ const authority = isIP(host) === 6 ? `[${host}]` : host;
14912
+ if (authority.includes(":") && !/^\[[0-9a-fA-F:.]+\]$/.test(authority)) return null;
14913
+ try {
14914
+ const hostname = new URL(`http://${authority}`).hostname;
14915
+ if (hostname.startsWith("[")) return hostname.slice(1, -1);
14916
+ return hostname.replace(/\.$/, "");
14917
+ } catch {
14918
+ return null;
14919
+ }
14920
+ }
14921
+ function loopbackAliases(hostname) {
14922
+ if (hostname === "localhost") return [
14923
+ "localhost",
14924
+ "127.0.0.1",
14925
+ "[::1]"
14926
+ ];
14927
+ if (isIP(hostname) === 6) {
14928
+ if (LOOPBACK_ADDRESSES.check(hostname, "ipv6")) return [`[${hostname}]`, "localhost"];
14929
+ return null;
14930
+ }
14931
+ if (isIP(hostname) === 4 && LOOPBACK_ADDRESSES.check(hostname, "ipv4")) return [hostname, "localhost"];
14932
+ return null;
14933
+ }
14934
+ function listenerPolicy(options) {
14935
+ try {
14936
+ const address = options.getListenerAddress();
14937
+ if (!address || !Number.isInteger(address.port) || address.port < 1 || address.port > 65535) return null;
14938
+ const hostname = listenerHostname(address.host);
14939
+ if (!hostname) return null;
14940
+ if (address.address === void 0) return {
14941
+ aliases: loopbackAliases(hostname),
14942
+ port: address.port
14943
+ };
14944
+ if (typeof address.address !== "string" || !isIP(address.address)) return null;
14945
+ const boundHostname = listenerHostname(address.address);
14946
+ if (!boundHostname) return null;
14947
+ const aliases = loopbackAliases(boundHostname);
14948
+ if (!aliases) return {
14949
+ aliases: null,
14950
+ port: address.port
14951
+ };
14952
+ const configuredAlias = isIP(hostname) === 6 ? `[${hostname}]` : hostname;
14953
+ const configuredAliases = hostname === "localhost" ? loopbackAliases(hostname) : null;
14954
+ return {
14955
+ aliases: [.../* @__PURE__ */ new Set([
14956
+ ...aliases,
14957
+ configuredAlias,
14958
+ ...configuredAliases ?? []
14959
+ ])],
14960
+ port: address.port
14961
+ };
14962
+ } catch {
14963
+ return null;
14964
+ }
14965
+ }
14966
+ function parseHost(host, protocol) {
14967
+ const match = /^(\[[0-9a-fA-F:.]+\]|[a-zA-Z0-9.-]+)(?::([0-9]+))?$/.exec(host);
14968
+ if (!match?.[1]) return null;
14969
+ if (match[2] !== void 0) {
14970
+ const port = Number(match[2]);
14971
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
14972
+ }
14973
+ try {
14974
+ const parsed = new URL(`${protocol}//${host}`);
14975
+ const hostname = match[1].toLowerCase();
14976
+ if (!hostname.startsWith("[") && parsed.hostname !== hostname) return null;
14977
+ return parsed;
14978
+ } catch {
14979
+ return null;
14980
+ }
14981
+ }
14982
+ function validLoopbackAuthority(requestUrl, host, policy) {
14983
+ if (!host) return false;
14984
+ try {
14985
+ const url = new URL(requestUrl);
14986
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
14987
+ if (url.username || url.password) return false;
14988
+ const authority = parseHost(host, url.protocol);
14989
+ if (!authority || authority.host !== url.host) return false;
14990
+ return Number(authority.port || (url.protocol === "https:" ? 443 : 80)) === policy.port && policy.aliases.includes(authority.hostname);
14991
+ } catch {
14992
+ return false;
14993
+ }
14994
+ }
14995
+ /**
14996
+ * Protect every loopback viewer request before preflight and route dispatch.
14997
+ * Explicit external listeners retain their existing external-auth requirements.
14998
+ * Proxy forwarding headers never supply trusted listener or request authority.
14999
+ */
15000
+ function viewerAuthorityGuard(options) {
15001
+ return createMiddleware(async (c, next) => {
15002
+ if (!options) return next();
15003
+ const policy = listenerPolicy(options);
15004
+ if (!policy) return c.json({ error: "forbidden" }, 403);
15005
+ if (policy.aliases && !validLoopbackAuthority(c.req.url, c.req.header("Host"), {
15006
+ ...policy,
15007
+ aliases: policy.aliases
15008
+ })) return c.json({ error: "forbidden" }, 403);
15009
+ await next();
15010
+ });
15011
+ }
15012
+ //#endregion
14601
15013
  //#region src/account/context.ts
14602
15014
  function validId(value) {
14603
15015
  return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value && !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(value);
@@ -15428,6 +15840,7 @@ sqliteTable("raw_event_flush_batches", {
15428
15840
  observer_error_code: text("observer_error_code"),
15429
15841
  observer_error_message: text("observer_error_message"),
15430
15842
  attempt_count: integer("attempt_count").notNull().default(0),
15843
+ claim_generation: integer("claim_generation").notNull().default(0),
15431
15844
  created_at: text("created_at").notNull(),
15432
15845
  updated_at: text("updated_at").notNull()
15433
15846
  }, (table) => [
@@ -15522,6 +15935,10 @@ sqliteTable("sync_peers", {
15522
15935
  last_error: text("last_error"),
15523
15936
  runtime_version: text("runtime_version"),
15524
15937
  runtime_version_observed_at: text("runtime_version_observed_at"),
15938
+ sync_features_json: text("sync_features_json"),
15939
+ sync_features_observed_at: text("sync_features_observed_at"),
15940
+ relay_retry_after: text("relay_retry_after"),
15941
+ relay_rejections: integer("relay_rejections").notNull().default(0),
15525
15942
  highest_observed_direct_signature_version: integer("highest_observed_direct_signature_version"),
15526
15943
  discovered_via_coordinator_id: text("discovered_via_coordinator_id"),
15527
15944
  discovered_via_group_id: text("discovered_via_group_id"),
@@ -16104,7 +16521,8 @@ var COORDINATOR_AUTH_STYLE = `
16104
16521
  .brand{display:flex;align-items:center;gap:.6rem;margin:0 0 1.5rem;color:var(--accent);font-size:.875rem;font-weight:700;letter-spacing:.02em}.brand::before{content:"";width:.65rem;height:.65rem;border-radius:3px;background:var(--accent)}
16105
16522
  h1,h2{font-family:inherit;font-weight:600;line-height:1.25;letter-spacing:-.025em}h1{font-size:1.6rem;margin:0 0 1rem}h2{font-size:1.05rem;margin:0 0 .5rem}p{margin:.5rem 0}section{padding:1.25rem 0;border-bottom:1px solid var(--border)}.eyebrow{font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-secondary)}
16106
16523
  .profile{display:flex;align-items:center;gap:1rem}.profile-text{min-width:0;overflow-wrap:anywhere}.avatar{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 3rem;width:3rem;height:3rem;border-radius:50%;background:var(--surface-2);color:var(--accent);overflow:hidden}.initials{font-weight:700}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.note{font-size:.875rem;color:var(--text-secondary)}
16107
- dl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}
16524
+ dl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}code.command{white-space:nowrap;overflow-wrap:normal}
16525
+ label{display:block;font-weight:600;margin:1rem 0 .35rem}input[type=text]{font:inherit;font-family:var(--font-mono);font-size:1.1rem;letter-spacing:.12em;text-transform:uppercase;width:100%;min-height:44px;padding:.6rem .8rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface-2);color:var(--text-primary)}
16108
16526
  .actions{display:flex;flex-wrap:wrap;gap:.75rem;margin:1.5rem 0 0}form{margin:0}button,.link{font:inherit;font-size:.875rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:.65rem 1rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--accent);color:var(--surface-0);cursor:pointer;text-decoration:none}button.secondary{background:transparent;color:var(--accent)}a{color:var(--accent)}button:hover,.link:hover{background:var(--accent-hover);color:var(--surface-0)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}
16109
16527
  @media(prefers-color-scheme:light){:root{color-scheme:light;--surface-0:#f7faf8;--surface-1:#fff;--surface-2:#eef5f1;--text-primary:#0b1016;--text-secondary:#3f4d5c;--accent:#0f8a68;--accent-hover:#0a6f53;--border:rgba(15,138,104,.16);--border-strong:rgba(15,138,104,.3)}button,.link,button:hover,.link:hover{color:#fff}button.secondary{color:var(--accent)}button.secondary:hover{color:#fff}}
16110
16528
  @media(max-width:30rem){body{padding:1rem}.actions{flex-direction:column}.actions form,.actions button,.actions .link{width:100%}h1{font-size:1.4rem}}
@@ -17048,6 +17466,438 @@ async function resumeAccountRebind(store, paths) {
17048
17466
  return { kind: "pending" };
17049
17467
  }
17050
17468
  //#endregion
17469
+ //#region src/sync-channel-dispatch.ts
17470
+ var MAX_REQUEST_BYTES = 1048576;
17471
+ var MAX_RESPONSE_BYTES = 16777216;
17472
+ function errorResponse(status, error) {
17473
+ return {
17474
+ status,
17475
+ headers: { "content-type": "application/json" },
17476
+ bodyBytes: new TextEncoder().encode(JSON.stringify({ error }))
17477
+ };
17478
+ }
17479
+ function hasForbiddenUrlCharacters(value) {
17480
+ return Array.from(value).some((char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127 || char === "\\" || char === "#");
17481
+ }
17482
+ function validLogicalUrl(url, target) {
17483
+ if (!target.startsWith("/") || target.startsWith("//") || hasForbiddenUrlCharacters(target)) return null;
17484
+ if (hasForbiddenUrlCharacters(url) || !/^https?:\/\//.test(url)) return null;
17485
+ try {
17486
+ const parsed = new URL(url);
17487
+ if (parsed.username || parsed.password || parsed.hash) return null;
17488
+ if (parsed.pathname + parsed.search !== target) return null;
17489
+ const authorityEnd = url.indexOf("/", url.indexOf("://") + 3);
17490
+ return authorityEnd >= 0 && url.slice(authorityEnd) === target ? parsed : null;
17491
+ } catch {
17492
+ return null;
17493
+ }
17494
+ }
17495
+ function checkCancellation(signal) {
17496
+ if (signal.aborted) throw new Error("Sync channel dispatch cancelled");
17497
+ }
17498
+ function invalidGetBody(method, body) {
17499
+ return method === "GET" && body.byteLength > 0;
17500
+ }
17501
+ async function collectResponse(response, signal) {
17502
+ const reader = response.body?.getReader();
17503
+ if (!reader) {
17504
+ checkCancellation(signal);
17505
+ return /* @__PURE__ */ new Uint8Array(0);
17506
+ }
17507
+ let cancelled = false;
17508
+ const cancel = () => {
17509
+ if (cancelled) return;
17510
+ cancelled = true;
17511
+ reader.cancel().catch(() => {});
17512
+ };
17513
+ signal.addEventListener("abort", cancel, { once: true });
17514
+ try {
17515
+ const chunks = [];
17516
+ let size = 0;
17517
+ while (true) {
17518
+ checkCancellation(signal);
17519
+ const chunk = await reader.read();
17520
+ checkCancellation(signal);
17521
+ if (chunk.done) break;
17522
+ size += chunk.value.byteLength;
17523
+ if (size > MAX_RESPONSE_BYTES) throw new Error("Sync channel response too large");
17524
+ chunks.push(chunk.value.slice());
17525
+ }
17526
+ const bytes = new Uint8Array(size);
17527
+ let offset = 0;
17528
+ for (const chunk of chunks) {
17529
+ bytes.set(chunk, offset);
17530
+ offset += chunk.byteLength;
17531
+ }
17532
+ return bytes;
17533
+ } catch {
17534
+ cancel();
17535
+ throw new Error("Sync channel response collection failed");
17536
+ } finally {
17537
+ signal.removeEventListener("abort", cancel);
17538
+ reader.releaseLock();
17539
+ }
17540
+ }
17541
+ function prepareChannelRequest(input) {
17542
+ const { method, target, url, peerPin, signal } = input;
17543
+ checkCancellation(signal);
17544
+ if (method !== "GET" && method !== "POST") return errorResponse(404, "not found");
17545
+ const parsed = validLogicalUrl(url, target);
17546
+ if (!parsed) return errorResponse(400, "invalid_request");
17547
+ const isOps = parsed.pathname === "/v1/ops";
17548
+ const isRead = method === "GET" && ["/v1/status", "/v1/snapshot"].includes(parsed.pathname);
17549
+ if (!isOps && !isRead) return errorResponse(404, "not found");
17550
+ const source = input.bodyBytes;
17551
+ if (source.byteLength > MAX_REQUEST_BYTES) return errorResponse(413, "payload_too_large");
17552
+ if (invalidGetBody(method, source)) return errorResponse(400, "invalid_request");
17553
+ const body = new Uint8Array(source);
17554
+ const headers = new Headers(input.headers);
17555
+ for (const name of [
17556
+ "host",
17557
+ "content-length",
17558
+ "connection"
17559
+ ]) headers.delete(name);
17560
+ return {
17561
+ request: new Request(url, {
17562
+ method,
17563
+ headers,
17564
+ signal,
17565
+ body: method === "POST" ? body : void 0
17566
+ }),
17567
+ peerPin
17568
+ };
17569
+ }
17570
+ function createSyncChannelDispatcher(options) {
17571
+ const storeFactory = options.storeFactory.bind(options);
17572
+ const pins = /* @__PURE__ */ new WeakMap();
17573
+ const app = createSyncApp$1({
17574
+ storeFactory,
17575
+ syncChannelPeerPin: (request) => pins.get(request) ?? null
17576
+ });
17577
+ return async (input) => {
17578
+ const prepared = prepareChannelRequest(input);
17579
+ if (!("request" in prepared)) return prepared;
17580
+ const { request, peerPin } = prepared;
17581
+ const signal = request.signal;
17582
+ pins.set(request, peerPin);
17583
+ try {
17584
+ checkCancellation(signal);
17585
+ const response = await app.fetch(request);
17586
+ const bodyBytes = await collectResponse(response, signal);
17587
+ return {
17588
+ status: response.status,
17589
+ headers: Object.fromEntries(response.headers),
17590
+ bodyBytes
17591
+ };
17592
+ } finally {
17593
+ pins.delete(request);
17594
+ }
17595
+ };
17596
+ }
17597
+ //#endregion
17598
+ //#region src/relay-reachability.ts
17599
+ /** Same rule as the sync daemon: an explicit directory, then `CODEMEM_KEYS_DIR`. */
17600
+ function resolveKeysDir(keysDir) {
17601
+ return keysDir?.trim() || process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
17602
+ }
17603
+ function sameDevice(a, b) {
17604
+ return a?.deviceId === b?.deviceId && a?.publicKey === b?.publicKey;
17605
+ }
17606
+ function readLocalDevice(db) {
17607
+ const row = db.prepare("SELECT device_id, public_key FROM sync_device LIMIT 1").get();
17608
+ if (!row?.device_id || !row.public_key) return null;
17609
+ return {
17610
+ deviceId: row.device_id,
17611
+ publicKey: row.public_key.trim()
17612
+ };
17613
+ }
17614
+ /** The peer's stored key, only while it still matches the pinned fingerprint. */
17615
+ function pinnedPeerKey(db, peerDeviceId) {
17616
+ const row = db.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(peerDeviceId);
17617
+ const publicKey = row?.public_key?.trim();
17618
+ if (!publicKey || !row?.pinned_fingerprint) return null;
17619
+ return fingerprintPublicKey(publicKey) === row.pinned_fingerprint ? publicKey : null;
17620
+ }
17621
+ function clientKey(config) {
17622
+ return `${config.url}\n${config.admissionUrl}\n${config.servicePublicKey}`;
17623
+ }
17624
+ function describe(resolution) {
17625
+ if (resolution.status === "ready") return "ready";
17626
+ if (resolution.status === "paused") return "paused: the relay service key changed; approve it with `codemem sync approve-relay-key`";
17627
+ return `disabled: ${resolution.reason}`;
17628
+ }
17629
+ /**
17630
+ * A coordinator without relay is the normal case, so plain disabled states
17631
+ * stay at info until the group has relayed once. A changed key, an invalid
17632
+ * reply, or losing a group that worked are warnings.
17633
+ */
17634
+ function levelFor(resolution, everReady) {
17635
+ if (resolution.status === "ready") return "info";
17636
+ if (resolution.status === "paused" || resolution.reason === "info_invalid") return "warn";
17637
+ return everReady ? "warn" : "info";
17638
+ }
17639
+ function buildClient(deps, config) {
17640
+ const { options, device } = deps;
17641
+ const db = options.store.db;
17642
+ return createRelayPeerClient({
17643
+ enabled: true,
17644
+ url: config.url,
17645
+ allowLoopbackWs: options.allowLoopback,
17646
+ servicePublicKey: config.servicePublicKey,
17647
+ deviceId: device.deviceId,
17648
+ localIdentity: {
17649
+ key: deps.key,
17650
+ expectedPin: device.publicKey
17651
+ },
17652
+ authorityId: config.authorityId,
17653
+ groupId: config.groupId,
17654
+ relayAudienceId: config.relayAudienceId,
17655
+ externalPathname: config.externalPathname,
17656
+ coordinator: createRelayCoordinatorClient({
17657
+ url: config.admissionUrl,
17658
+ allowLoopbackHttp: options.allowLoopback
17659
+ }),
17660
+ resolvePeerPin: (peerDeviceId) => pinnedPeerKey(db, peerDeviceId),
17661
+ validateLocal: () => sameDevice(readLocalDevice(db), device),
17662
+ onInbound: (_connection, context) => context.serve({
17663
+ origin: RELAY_LOGICAL_ORIGIN,
17664
+ dispatch: deps.dispatch
17665
+ })
17666
+ });
17667
+ }
17668
+ function loadDeps(options) {
17669
+ const device = readLocalDevice(options.store.db);
17670
+ if (!device) throw new Error("device identity missing");
17671
+ const bytes = loadPrivateKey(options.keysDir, options.store.dbPath, device.deviceId);
17672
+ if (!bytes) throw new Error("device private key unavailable");
17673
+ const dispatch = createSyncChannelDispatcher({ storeFactory: () => options.store });
17674
+ return {
17675
+ options,
17676
+ device,
17677
+ key: createPrivateKey(bytes),
17678
+ dispatch
17679
+ };
17680
+ }
17681
+ function defaultResolver(options, coordinatorUrl, timeoutS) {
17682
+ const settings = readRelayClientSettings(options.config);
17683
+ return (db, groupId) => resolveRelayGroup(db, {
17684
+ coordinatorUrl,
17685
+ groupId,
17686
+ settings,
17687
+ deviceId: readLocalDevice(db)?.deviceId ?? "",
17688
+ dbPath: options.store.dbPath,
17689
+ keysDir: options.keysDir,
17690
+ timeoutS,
17691
+ signal: options.signal,
17692
+ request: options.request
17693
+ });
17694
+ }
17695
+ function relayTargets(options) {
17696
+ if (!readRelayClientSettings(options.config).enabled) return null;
17697
+ const sync = readCoordinatorSyncConfig(options.config);
17698
+ const coordinatorUrl = sync.syncCoordinatorUrl.trim();
17699
+ if (!coordinatorUrl) return null;
17700
+ return {
17701
+ coordinatorUrl,
17702
+ timeoutS: sync.syncCoordinatorTimeoutS
17703
+ };
17704
+ }
17705
+ /**
17706
+ * The groups configured right now. Joining a group updates the config while
17707
+ * the viewer runs, so this is reread on every refresh. A different coordinator
17708
+ * yields no groups, because the resolver and pins belong to the startup one.
17709
+ */
17710
+ function configuredGroupIds(options, coordinatorUrl) {
17711
+ const sync = readCoordinatorSyncConfig(options.config);
17712
+ if (sync.syncCoordinatorUrl.trim() !== coordinatorUrl) return {
17713
+ groupIds: [],
17714
+ coordinatorChanged: true
17715
+ };
17716
+ return {
17717
+ groupIds: [...new Set(sync.syncCoordinatorGroups)],
17718
+ coordinatorChanged: false
17719
+ };
17720
+ }
17721
+ /** Owns one optional relay client per configured coordinator group. */
17722
+ var RelayGroupClients = class {
17723
+ options;
17724
+ coordinatorId;
17725
+ coordinatorUrl;
17726
+ resolve;
17727
+ log;
17728
+ groups = /* @__PURE__ */ new Map();
17729
+ deps;
17730
+ closed = false;
17731
+ refreshing;
17732
+ coordinatorChangeLogged = false;
17733
+ constructor(options, coordinatorId, coordinatorUrl, resolve, log) {
17734
+ this.options = options;
17735
+ this.coordinatorId = coordinatorId;
17736
+ this.coordinatorUrl = coordinatorUrl;
17737
+ this.resolve = resolve;
17738
+ this.log = log;
17739
+ this.reconcileGroups();
17740
+ }
17741
+ clientForGroup(groupId) {
17742
+ return this.groups.get(groupId)?.client;
17743
+ }
17744
+ clients() {
17745
+ return [...this.groups.values()].flatMap((state) => state.client ? [state.client] : []);
17746
+ }
17747
+ status() {
17748
+ return new Map([...this.groups].map(([groupId, state]) => [groupId, state.status]));
17749
+ }
17750
+ refresh() {
17751
+ if (this.closed) return Promise.resolve();
17752
+ this.refreshing ??= this.runRefresh().catch((error) => this.log(`[codemem] relay refresh failed: ${String(error)}`, "warn")).finally(() => {
17753
+ this.refreshing = void 0;
17754
+ });
17755
+ return this.refreshing;
17756
+ }
17757
+ async close() {
17758
+ this.closed = true;
17759
+ await this.refreshing;
17760
+ await this.dropAll();
17761
+ }
17762
+ async runRefresh() {
17763
+ await this.checkDeviceIdentity();
17764
+ await Promise.all(this.reconcileGroups().map((state) => this.dropClient(state)));
17765
+ const ids = [...this.groups.keys()];
17766
+ const results = await Promise.all(ids.map((groupId) => this.resolveSafely(groupId)));
17767
+ for (const [index, groupId] of ids.entries()) {
17768
+ const resolution = results[index];
17769
+ if (resolution) await this.apply(groupId, resolution);
17770
+ }
17771
+ }
17772
+ /** Adds newly configured groups and removes dropped ones. Returns the removed states to close. */
17773
+ reconcileGroups() {
17774
+ let current;
17775
+ try {
17776
+ current = configuredGroupIds(this.options, this.coordinatorUrl);
17777
+ } catch (error) {
17778
+ this.log(`[codemem] relay could not read the group list: ${String(error)}`, "warn");
17779
+ return [];
17780
+ }
17781
+ if (current.coordinatorChanged && !this.coordinatorChangeLogged) {
17782
+ this.coordinatorChangeLogged = true;
17783
+ this.log("[codemem] sync coordinator changed; restart codemem serve to relay through it", "warn");
17784
+ }
17785
+ const wanted = new Set(current.groupIds);
17786
+ const removed = [];
17787
+ for (const [groupId, state] of this.groups) {
17788
+ if (wanted.has(groupId)) continue;
17789
+ this.groups.delete(groupId);
17790
+ removed.push(state);
17791
+ }
17792
+ for (const groupId of wanted) if (!this.groups.has(groupId)) this.groups.set(groupId, { status: "disabled" });
17793
+ return removed;
17794
+ }
17795
+ /** A changed local identity invalidates the cached key and every client built from it. */
17796
+ async checkDeviceIdentity() {
17797
+ if (!this.deps || sameDevice(readLocalDevice(this.options.store.db), this.deps.device)) return;
17798
+ this.deps = void 0;
17799
+ await this.dropAll();
17800
+ this.log("[codemem] device identity changed; rebuilding relay clients", "warn");
17801
+ }
17802
+ async resolveSafely(groupId) {
17803
+ try {
17804
+ return await this.resolve(this.options.store.db, groupId);
17805
+ } catch {
17806
+ return {
17807
+ status: "disabled",
17808
+ groupId,
17809
+ reason: "info_unavailable"
17810
+ };
17811
+ }
17812
+ }
17813
+ /** A transient info failure keeps a client whose key is still the stored pin. */
17814
+ keepsClient(groupId, state, resolution) {
17815
+ if (resolution.status !== "disabled" || resolution.reason !== "info_unavailable") return false;
17816
+ if (!state.client) return false;
17817
+ const pin = readRelayServicePin(this.options.store.db, this.coordinatorId, groupId);
17818
+ return pin?.state === "pinned" && pin.pinnedKey === state.servicePublicKey;
17819
+ }
17820
+ async apply(groupId, resolution) {
17821
+ const state = this.groups.get(groupId);
17822
+ if (!state || this.closed) return;
17823
+ if (this.keepsClient(groupId, state, resolution)) {
17824
+ state.client?.revalidate();
17825
+ return;
17826
+ }
17827
+ state.status = resolution.status;
17828
+ if (resolution.status !== "ready") {
17829
+ await this.dropClient(state);
17830
+ this.report(groupId, state, describe(resolution), levelFor(resolution, !!state.everReady));
17831
+ return;
17832
+ }
17833
+ if (state.client && state.clientKey === clientKey(resolution.config)) {
17834
+ state.client.revalidate();
17835
+ return;
17836
+ }
17837
+ await this.dropClient(state);
17838
+ if (!this.closed) this.startClient(groupId, state, resolution.config);
17839
+ }
17840
+ startClient(groupId, state, config) {
17841
+ try {
17842
+ this.deps ??= loadDeps(this.options);
17843
+ state.client = buildClient(this.deps, config);
17844
+ state.clientKey = clientKey(config);
17845
+ state.servicePublicKey = config.servicePublicKey;
17846
+ state.everReady = true;
17847
+ this.report(groupId, state, "ready", "info");
17848
+ } catch (error) {
17849
+ state.status = "disabled";
17850
+ const reason = error instanceof Error ? error.message : String(error);
17851
+ this.report(groupId, state, `disabled: ${reason}`, state.everReady ? "warn" : "info");
17852
+ }
17853
+ }
17854
+ async dropAll() {
17855
+ await Promise.all([...this.groups.values()].map((state) => this.dropClient(state)));
17856
+ }
17857
+ async dropClient(state) {
17858
+ const client = state.client;
17859
+ state.client = void 0;
17860
+ state.clientKey = void 0;
17861
+ state.servicePublicKey = void 0;
17862
+ await client?.close().catch(() => {});
17863
+ }
17864
+ /** Logs each group's state once per change, so a persistent failure is not repeated every refresh. */
17865
+ report(groupId, state, message, level) {
17866
+ if (state.logged === message) return;
17867
+ state.logged = message;
17868
+ this.log(`[codemem] relay for group ${groupId}: ${message}`, level);
17869
+ }
17870
+ };
17871
+ /**
17872
+ * Device relay clients for `codemem serve`, one per configured coordinator
17873
+ * group that the coordinator advertises and whose service key is pinned.
17874
+ * Returns null when relay is off or coordinator sync is not configured, so
17875
+ * callers keep plain direct sync. Failures leave only that group direct-only.
17876
+ */
17877
+ function createViewerRelayReachability(options) {
17878
+ const targets = relayTargets(options);
17879
+ setLocalSyncFeature("relay", targets !== null);
17880
+ if (!targets) return null;
17881
+ const resolved = {
17882
+ ...options,
17883
+ keysDir: resolveKeysDir(options.keysDir)
17884
+ };
17885
+ const resolve = options.resolveGroup ?? defaultResolver(resolved, targets.coordinatorUrl, targets.timeoutS);
17886
+ const coordinatorId = relayCoordinatorEndpoint(targets.coordinatorUrl)?.coordinatorId ?? targets.coordinatorUrl;
17887
+ const groups = new RelayGroupClients(resolved, coordinatorId, targets.coordinatorUrl, resolve, options.log ?? (() => {}));
17888
+ return {
17889
+ reachability: createRelayPeerReachability({
17890
+ coordinatorId,
17891
+ clientForGroup: (groupId) => groups.clientForGroup(groupId),
17892
+ clients: () => groups.clients(),
17893
+ signal: options.signal
17894
+ }),
17895
+ refresh: () => groups.refresh(),
17896
+ close: () => groups.close(),
17897
+ status: () => groups.status()
17898
+ };
17899
+ }
17900
+ //#endregion
17051
17901
  //#region src/index.ts
17052
17902
  /**
17053
17903
  * @codemem/server — HTTP server (viewer, sync, API).
@@ -17058,29 +17908,15 @@ async function resumeAccountRebind(store, paths) {
17058
17908
  *
17059
17909
  * Entry: `codemem serve`
17060
17910
  */
17061
- /** Shared store instance — SQLite WAL mode handles concurrent reads safely. */
17062
- var sharedStore = null;
17063
- var sharedStoreClosePromise = null;
17064
- /** Get (or create) the shared store instance. Exported so the sweeper can share it. */
17065
- function getStore() {
17066
- if (!sharedStore) sharedStore = new MemoryStore(resolveDbPath());
17067
- return sharedStore;
17068
- }
17069
- /** Close a synchronous-only shared store. Async pack owners use closeStoreAsync(). */
17070
- function closeStore() {
17071
- sharedStore?.close();
17072
- sharedStore = null;
17073
- }
17074
- /** Drain semantic work before closing SQLite and releasing the shared store. */
17075
- function closeStoreAsync() {
17076
- if (sharedStoreClosePromise) return sharedStoreClosePromise;
17077
- if (!sharedStore) return Promise.resolve();
17078
- const store = sharedStore;
17079
- sharedStoreClosePromise = store.closeAsync().then(() => {
17080
- if (sharedStore === store) sharedStore = null;
17081
- sharedStoreClosePromise = null;
17082
- });
17083
- return sharedStoreClosePromise;
17911
+ /**
17912
+ * Prompt-pack transport plus, when `codemem serve` supplies a handler, the
17913
+ * thin-host memory-tool route. The profile advertises the route only when it
17914
+ * is mounted, so older clients and test apps see no capability.
17915
+ */
17916
+ function registerThinHostRoutes(app, storeFactory, call) {
17917
+ if (call) app.route("/", memoryToolCallRoutes(storeFactory, call));
17918
+ const capabilities = call ? [MEMORY_TOOL_CALL_CAPABILITY] : [];
17919
+ app.route("/", packTransportRoutes(storeFactory, { capabilities }));
17084
17920
  }
17085
17921
  function registerStaticRoutes(app) {
17086
17922
  const staticRoot = process.env.CODEMEM_VIEWER_STATIC_DIR ?? join(import.meta.dirname ?? ".", "../static");
@@ -17109,10 +17945,12 @@ function registerConfigRoutes(app, opts, sweeper) {
17109
17945
  getObserverApplyStatus: opts?.getObserverApplyStatus
17110
17946
  }));
17111
17947
  }
17112
- function registerAccountRoutes(app, options) {
17113
- if (!options) return;
17114
- const account = createAccountGuard(options);
17115
- app.use("*", account.middleware);
17948
+ function registerViewerBoundary(app, opts) {
17949
+ const options = opts?.accountLink;
17950
+ const account = options ? createAccountGuard(options) : null;
17951
+ if (account) app.use("*", account.middleware);
17952
+ app.use("*", viewerAuthorityGuard(opts?.viewerAuthority ?? options));
17953
+ if (!options || !account) return;
17116
17954
  app.route("/", account.routes);
17117
17955
  if (options.ownerRecovery) app.route("/", accountOwnerRecoveryRoutes(options.ownerRecovery));
17118
17956
  if (options.readContext) app.route("/", accountStatusRoutes({
@@ -17132,7 +17970,7 @@ function createApp(opts) {
17132
17970
  const getSyncRuntimeStatus = opts?.getSyncRuntimeStatus ?? (() => null);
17133
17971
  let invalidateTeamSetupSummary = () => {};
17134
17972
  const app = new Hono();
17135
- registerAccountRoutes(app, opts?.accountLink);
17973
+ registerViewerBoundary(app, opts);
17136
17974
  app.use("*", preflightHandler());
17137
17975
  app.use("*", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));
17138
17976
  const viewerTargetGuard = viewerTargetQueryGuard(storeFactory);
@@ -17144,7 +17982,7 @@ function createApp(opts) {
17144
17982
  app.route("/", statsRoutes(storeFactory));
17145
17983
  app.route("/", memoryRoutes(storeFactory));
17146
17984
  app.route("/", memoryToolRoutes(storeFactory));
17147
- app.route("/", packTransportRoutes(storeFactory));
17985
+ registerThinHostRoutes(app, storeFactory, opts?.memoryToolCall);
17148
17986
  app.route("/", fileContextRoutes(storeFactory));
17149
17987
  app.route("/", observerStatusRoutes({
17150
17988
  getStore: storeFactory,
@@ -17172,34 +18010,11 @@ function createApp(opts) {
17172
18010
  registerStaticRoutes(app);
17173
18011
  return app;
17174
18012
  }
17175
- /**
17176
- * Create the Hono app for peer-to-peer sync protocol routes only.
17177
- *
17178
- * This app is bound to a separate network-accessible listener
17179
- * (default 0.0.0.0:7337) so remote peers can reach the sync
17180
- * endpoints without exposing the viewer UI or local API routes.
17181
- *
17182
- * No CORS/origin guard is applied — sync requests are authenticated
17183
- * via cryptographic signature verification instead.
17184
- */
18013
+ /** Preserve the public server options while transport adapters use the narrower factory. */
17185
18014
  function createSyncApp(opts) {
17186
- const storeFactory = opts?.storeFactory ?? getStore;
17187
- const requestRateLimit = opts?.syncRequestRateLimit ?? {};
17188
- const rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();
17189
- const readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));
17190
- const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
17191
- const app = new Hono();
17192
- app.route("/", syncProtocolRoutes(storeFactory, { routeRateLimit: {
17193
- limiter: rateLimiter,
17194
- readLimit,
17195
- mutationLimit,
17196
- unauthenticatedReadLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit))),
17197
- unauthenticatedMutationLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)))
17198
- } }));
17199
- app.all("*", (c) => c.json({ error: "not found" }, 404));
17200
- return app;
18015
+ return createSyncApp$1(opts);
17201
18016
  }
17202
18017
  //#endregion
17203
- export { FileRawEventInbox, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, getStore, listRecipientPolicyReconciliationStatus, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
18018
+ export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
17204
18019
 
17205
18020
  //# sourceMappingURL=index.js.map