@codemem/server 0.50.0-beta.3 → 0.50.0-beta.5
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/application/background-refresh.d.ts +36 -0
- package/dist/application/background-refresh.d.ts.map +1 -0
- package/dist/application/sync-status.d.ts.map +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2628 -671
- package/dist/index.js.map +1 -1
- package/dist/request-rate-limit.d.ts +17 -1
- package/dist/request-rate-limit.d.ts.map +1 -1
- package/dist/response-byte-budget.d.ts +18 -0
- package/dist/response-byte-budget.d.ts.map +1 -0
- package/dist/routes/config.d.ts +2 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/device-removal-local.d.ts.map +1 -1
- package/dist/routes/device-removal-lookup.d.ts.map +1 -1
- package/dist/routes/health.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +31 -5
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/team-create.d.ts.map +1 -1
- package/dist/routes/team-member-removal.d.ts +10 -0
- package/dist/routes/team-member-removal.d.ts.map +1 -0
- package/dist/routes/team-recovery.d.ts +12 -0
- package/dist/routes/team-recovery.d.ts.map +1 -0
- package/dist/routes/team-setup-reconciliation.d.ts +79 -0
- package/dist/routes/team-setup-reconciliation.d.ts.map +1 -0
- package/dist/routes/team-setup-test-fixtures.d.ts +17 -0
- package/dist/routes/team-setup-test-fixtures.d.ts.map +1 -0
- package/dist/routes/team-setup-view.d.ts +9 -0
- package/dist/routes/team-setup-view.d.ts.map +1 -1
- package/dist/routes/team-setup.d.ts +49 -3
- package/dist/routes/team-setup.d.ts.map +1 -1
- package/dist/sync-app.d.ts +3 -1
- package/dist/sync-app.d.ts.map +1 -1
- package/dist/sync-channel-dispatch.d.ts +9 -0
- package/dist/sync-channel-dispatch.d.ts.map +1 -1
- package/dist/sync-channel-pass-test-fixtures.d.ts +3 -2
- package/dist/sync-channel-pass-test-fixtures.d.ts.map +1 -1
- package/dist/sync-listener-guard.d.ts +67 -0
- package/dist/sync-listener-guard.d.ts.map +1 -0
- package/dist/sync-noise-gate.d.ts +37 -0
- package/dist/sync-noise-gate.d.ts.map +1 -0
- package/dist/sync-server-mode.d.ts +58 -0
- package/dist/sync-server-mode.d.ts.map +1 -0
- package/package.json +2 -2
- package/static/app.js +63 -63
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +88 -43
- package/dist/routes/device-retire.d.ts +0 -206
- package/dist/routes/device-retire.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, 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, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, 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, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
|
|
3
|
+
import { ACCESS_CLEANUP_OP_TYPE, CHANNEL_MAX_ENTRY_BYTES, COORDINATOR_FREE_BINDING_UNVERIFIED, COORDINATOR_FREE_WITNESS_UNAVAILABLE, COORDINATOR_JOIN_CONFIRMATION_REQUIRED, 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, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, 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, SyncEntryTooLargeError, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, applyTeamMemberRemovals, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPairingPayload, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitTeamMemberRemoval, commitTeamRecovery, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, completeMaintenanceJob, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnabled, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorReadTeamGroupBindingsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusCacheIdentity, coordinatorStatusSnapshot, coordinatorTeamRecoveryEvidenceActions, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, entriesWithinLimit, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, isStrictRecipientPolicyId, isTeamRecoveryEvidenceStale, isTeamRecoveryHoldAbandoned, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, 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, localRemovedDeviceIds, lookupCoordinatorPeers, markCoordinatorManaged, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, normalizedCoordinatorId, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, peerTransportExecutor, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, previewTeamMemberRemoval, previewTeamRecovery, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readPeerTransportPolicy, readRepositoryIdentitySnapshot, readTeamRecoveryEvidence, readUnpairedPeerPin, readViewerPidFile, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordDeviceCoordinatorHistory, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPairingTransportEvidence, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, revokePendingTeamInvitations, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, startMaintenanceJob, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, teamCoordinatorLinkConflicts, teamIdsForBindingRead, teamInvitationGroup, teamRecoveryTarget, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, 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
6
|
import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
@@ -13,12 +13,15 @@ import { Buffer as Buffer$1 } from "node:buffer";
|
|
|
13
13
|
import { homedir, hostname, networkInterfaces } from "node:os";
|
|
14
14
|
import * as z from "zod";
|
|
15
15
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
16
|
+
import { DIRECT_NOISE_ACTIVE, DIRECT_NOISE_LOGICAL_ORIGIN, DIRECT_NOISE_TRANSPORT_LABEL, DIRECT_NOISE_UPGRADE_PROTOCOL, PEER_HTTP_LIMITS, RELAY_LOGICAL_ORIGIN, RELAY_NOISE_LIMITS, acceptRelayNoiseResponder, createRelayCoordinatorClient, createRelayPeerClient, createRelayPeerReachability, parseDirectNoiseUpgradeTarget, readRelayClientSettings, readRelayServicePin, relayCoordinatorEndpoint, resolveRelayGroup, servePeerHttpConnection } from "@codemem/core/internal/relay-runtime";
|
|
16
17
|
import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
|
|
17
18
|
import { BlockList, isIP } from "node:net";
|
|
18
|
-
import "better-sqlite3";
|
|
19
19
|
import "sqlite-vec";
|
|
20
|
+
import "better-sqlite3";
|
|
20
21
|
import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
21
|
-
import {
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { performance as performance$1 } from "node:perf_hooks";
|
|
24
|
+
import { finished } from "node:stream/promises";
|
|
22
25
|
//#region src/routes/account.ts
|
|
23
26
|
/** Mounted only alongside the account request middleware. */
|
|
24
27
|
function accountRoutes(getSession) {
|
|
@@ -1640,48 +1643,81 @@ function accountStatusRoutes(options) {
|
|
|
1640
1643
|
});
|
|
1641
1644
|
return app;
|
|
1642
1645
|
}
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
+
/**
|
|
1647
|
+
* A token bucket per key, at most maxBuckets of them.
|
|
1648
|
+
*
|
|
1649
|
+
* A full map never evicts a bucket that may still be depleted, because a key
|
|
1650
|
+
* could then refill its budget by churning other keys through the map. Only a
|
|
1651
|
+
* bucket unused for a whole window, which has refilled anyway, can make room.
|
|
1652
|
+
* When none can, a new key draws from one overflow budget per limit that
|
|
1653
|
+
* every such key shares, so churn spends that budget instead of minting fresh
|
|
1654
|
+
* ones.
|
|
1655
|
+
*/
|
|
1656
|
+
function createInMemoryRequestRateLimiter(windowMs = 6e4, options = {}) {
|
|
1646
1657
|
const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
|
|
1658
|
+
const maxBuckets = Math.max(1, Math.trunc(options.maxBuckets ?? 1e4));
|
|
1647
1659
|
const buckets = /* @__PURE__ */ new Map();
|
|
1660
|
+
const overflow = /* @__PURE__ */ new Map();
|
|
1648
1661
|
let checks = 0;
|
|
1662
|
+
const newBucket = (limit, now) => ({
|
|
1663
|
+
limiter: new RateLimiter({
|
|
1664
|
+
tokensPerInterval: limit,
|
|
1665
|
+
interval: safeWindowMs,
|
|
1666
|
+
fireImmediately: true
|
|
1667
|
+
}),
|
|
1668
|
+
lastUsedAt: now
|
|
1669
|
+
});
|
|
1649
1670
|
function estimatedRetryAfterS(limit) {
|
|
1650
1671
|
return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
|
|
1651
1672
|
}
|
|
1652
|
-
function cleanupExpiredBuckets(
|
|
1673
|
+
function cleanupExpiredBuckets(now) {
|
|
1653
1674
|
if (buckets.size < 64 || checks % 64 !== 0) return;
|
|
1654
|
-
const staleBefore =
|
|
1675
|
+
const staleBefore = now - safeWindowMs * 10;
|
|
1655
1676
|
for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
|
|
1656
1677
|
}
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
lastUsedAt: currentNow
|
|
1672
|
-
};
|
|
1673
|
-
buckets.set(bucketKey, bucket);
|
|
1678
|
+
/** Frees the stalest slot only if that bucket sat unused for a full window. */
|
|
1679
|
+
function makeRoom(now) {
|
|
1680
|
+
if (buckets.size < maxBuckets) return true;
|
|
1681
|
+
const [stalestKey, stalest] = buckets.entries().next().value ?? [];
|
|
1682
|
+
if (stalestKey === void 0 || !stalest || now - stalest.lastUsedAt < safeWindowMs) return false;
|
|
1683
|
+
buckets.delete(stalestKey);
|
|
1684
|
+
return true;
|
|
1685
|
+
}
|
|
1686
|
+
function bucketFor(bucketKey, limit, now) {
|
|
1687
|
+
const existing = buckets.get(bucketKey);
|
|
1688
|
+
if (existing) {
|
|
1689
|
+
buckets.delete(bucketKey);
|
|
1690
|
+
buckets.set(bucketKey, existing);
|
|
1691
|
+
return existing;
|
|
1674
1692
|
}
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1693
|
+
if (makeRoom(now)) {
|
|
1694
|
+
const created = newBucket(limit, now);
|
|
1695
|
+
buckets.set(bucketKey, created);
|
|
1696
|
+
return created;
|
|
1697
|
+
}
|
|
1698
|
+
const shared = overflow.get(limit) ?? newBucket(limit, now);
|
|
1699
|
+
overflow.set(limit, shared);
|
|
1700
|
+
return shared;
|
|
1701
|
+
}
|
|
1702
|
+
return {
|
|
1703
|
+
check(key, limit) {
|
|
1704
|
+
checks += 1;
|
|
1705
|
+
const now = performance.now();
|
|
1706
|
+
cleanupExpiredBuckets(now);
|
|
1707
|
+
const safeLimit = Math.max(1, Math.trunc(limit));
|
|
1708
|
+
const bucket = bucketFor(`${safeLimit}:${key}`, safeLimit, now);
|
|
1709
|
+
bucket.lastUsedAt = now;
|
|
1710
|
+
if (bucket.limiter.tryRemoveTokens(1)) return {
|
|
1711
|
+
allowed: true,
|
|
1712
|
+
retryAfterS: 0
|
|
1713
|
+
};
|
|
1714
|
+
return {
|
|
1715
|
+
allowed: false,
|
|
1716
|
+
retryAfterS: estimatedRetryAfterS(safeLimit)
|
|
1717
|
+
};
|
|
1718
|
+
},
|
|
1719
|
+
bucketCount: () => buckets.size
|
|
1720
|
+
};
|
|
1685
1721
|
}
|
|
1686
1722
|
//#endregion
|
|
1687
1723
|
//#region src/routes/config.ts
|
|
@@ -1741,13 +1777,17 @@ var PROTECTED_WRITE_KEYS = /* @__PURE__ */ new Set([
|
|
|
1741
1777
|
"observer_auth_file",
|
|
1742
1778
|
"observer_auth_command",
|
|
1743
1779
|
"observer_headers",
|
|
1744
|
-
"sync_coordinator_url"
|
|
1780
|
+
"sync_coordinator_url",
|
|
1781
|
+
"sync_coordinator_invite_token_key",
|
|
1782
|
+
"sync_coordinator_invite_token_key_previous"
|
|
1745
1783
|
]);
|
|
1746
1784
|
var SECRET_CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
1747
1785
|
"observer_auth_file",
|
|
1748
1786
|
"observer_auth_command",
|
|
1749
1787
|
"observer_headers",
|
|
1750
|
-
"sync_coordinator_admin_secret"
|
|
1788
|
+
"sync_coordinator_admin_secret",
|
|
1789
|
+
"sync_coordinator_invite_token_key",
|
|
1790
|
+
"sync_coordinator_invite_token_key_previous"
|
|
1751
1791
|
]);
|
|
1752
1792
|
var REMOVED_CONFIG_KEYS = /* @__PURE__ */ new Set(["observer_rich_openai_use_responses"]);
|
|
1753
1793
|
var ALLOWED_KEYS = [
|
|
@@ -2030,6 +2070,7 @@ function applyRuntimeEffects(changedKeys, opts) {
|
|
|
2030
2070
|
opts.getSweeper?.()?.notifyConfigChanged();
|
|
2031
2071
|
applied.push("raw_events_sweeper_interval_s");
|
|
2032
2072
|
}
|
|
2073
|
+
if (changedKeys.some((key) => key.startsWith("sync_coordinator_"))) opts.onCoordinatorConfigChanged?.();
|
|
2033
2074
|
return applied;
|
|
2034
2075
|
}
|
|
2035
2076
|
var ConfigUpdateError = class extends Error {
|
|
@@ -2454,6 +2495,24 @@ async function commitViewerDeviceBlock(confirmed, deps) {
|
|
|
2454
2495
|
}
|
|
2455
2496
|
//#endregion
|
|
2456
2497
|
//#region src/routes/device-removal-lookup.ts
|
|
2498
|
+
/**
|
|
2499
|
+
* The pairing's pin, or the last verified pin kept when this device unpaired the device. The
|
|
2500
|
+
* coordinator is asked about the key either way, so a key-only revocation filed under another
|
|
2501
|
+
* device ID is found. The kept pin never authorizes sync.
|
|
2502
|
+
*/
|
|
2503
|
+
function readPin$1(store, deviceId) {
|
|
2504
|
+
const live = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
|
|
2505
|
+
if (live) return live;
|
|
2506
|
+
const kept = readUnpairedPeerPin(store.db, {
|
|
2507
|
+
localDeviceId: store.deviceId,
|
|
2508
|
+
peerDeviceId: deviceId
|
|
2509
|
+
});
|
|
2510
|
+
return kept ? {
|
|
2511
|
+
public_key: kept.publicKey,
|
|
2512
|
+
pinned_fingerprint: kept.pinnedFingerprint,
|
|
2513
|
+
created_at: kept.recordedAt
|
|
2514
|
+
} : void 0;
|
|
2515
|
+
}
|
|
2457
2516
|
function readSubject(store, deviceId) {
|
|
2458
2517
|
const configKey = verifiedLocalKeyId(store.db, store.deviceId);
|
|
2459
2518
|
if (deviceId === store.deviceId) return {
|
|
@@ -2464,7 +2523,7 @@ function readSubject(store, deviceId) {
|
|
|
2464
2523
|
error: "local_identity_unverified",
|
|
2465
2524
|
status: 409
|
|
2466
2525
|
};
|
|
2467
|
-
const pin = store
|
|
2526
|
+
const pin = readPin$1(store, deviceId);
|
|
2468
2527
|
const key = pin?.public_key;
|
|
2469
2528
|
if (key && canonicalKeyId(key) === configKey) return {
|
|
2470
2529
|
error: "cannot_remove_this_device",
|
|
@@ -2560,6 +2619,24 @@ function hasNoRemovalCoordinator(readConfig) {
|
|
|
2560
2619
|
if (url !== void 0 && typeof url !== "string") return false;
|
|
2561
2620
|
return !readCoordinatorSyncConfig(data).syncCoordinatorUrl;
|
|
2562
2621
|
}
|
|
2622
|
+
/**
|
|
2623
|
+
* The pairing's pin, or the last verified pin kept when this device unpaired the device, so
|
|
2624
|
+
* Remove still works after Unpair. The kept pin only identifies the key to remove. It never
|
|
2625
|
+
* authorizes sync.
|
|
2626
|
+
*/
|
|
2627
|
+
function readPin(store, deviceId) {
|
|
2628
|
+
const live = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
|
|
2629
|
+
if (live) return live;
|
|
2630
|
+
const kept = readUnpairedPeerPin(store.db, {
|
|
2631
|
+
localDeviceId: store.deviceId,
|
|
2632
|
+
peerDeviceId: deviceId
|
|
2633
|
+
});
|
|
2634
|
+
return kept ? {
|
|
2635
|
+
public_key: kept.publicKey,
|
|
2636
|
+
pinned_fingerprint: kept.pinnedFingerprint,
|
|
2637
|
+
created_at: kept.recordedAt
|
|
2638
|
+
} : void 0;
|
|
2639
|
+
}
|
|
2563
2640
|
function readLocalRemoval(store, deviceId) {
|
|
2564
2641
|
if (deviceId === store.deviceId) return {
|
|
2565
2642
|
error: "cannot_remove_this_device",
|
|
@@ -2570,7 +2647,7 @@ function readLocalRemoval(store, deviceId) {
|
|
|
2570
2647
|
error: "local_identity_unverified",
|
|
2571
2648
|
status: 409
|
|
2572
2649
|
};
|
|
2573
|
-
const pin = store
|
|
2650
|
+
const pin = readPin(store, deviceId);
|
|
2574
2651
|
if (!pin) return {
|
|
2575
2652
|
error: "removal_target_not_enrolled",
|
|
2576
2653
|
status: 404
|
|
@@ -3067,7 +3144,7 @@ function removedDeviceBlockRoutes(options) {
|
|
|
3067
3144
|
//#endregion
|
|
3068
3145
|
//#region src/routes/device-rejoin-events.ts
|
|
3069
3146
|
var PATH = "/api/sync/devices/rejoin-events";
|
|
3070
|
-
var HASH
|
|
3147
|
+
var HASH = /^[a-f0-9]{64}$/u;
|
|
3071
3148
|
function captureTarget(options) {
|
|
3072
3149
|
const config = (options.readConfig ?? readCoordinatorSyncConfig)();
|
|
3073
3150
|
const origin = normalizeCoordinatorAccountLinkOrigin(config.syncCoordinatorUrl);
|
|
@@ -3100,7 +3177,7 @@ function isCurrentTarget(options, target) {
|
|
|
3100
3177
|
function input(query) {
|
|
3101
3178
|
const [scope] = query.getAll("scope");
|
|
3102
3179
|
const [after] = query.getAll("after");
|
|
3103
|
-
if ([...query.keys()].some((key) => key !== "scope" && key !== "after") || query.getAll("scope").length > 1 || query.getAll("after").length > 1 || scope !== void 0 && !HASH
|
|
3180
|
+
if ([...query.keys()].some((key) => key !== "scope" && key !== "after") || query.getAll("scope").length > 1 || query.getAll("after").length > 1 || scope !== void 0 && !HASH.test(scope) || after !== void 0 && (!scope || !after.trim() || after.length > 256)) return null;
|
|
3104
3181
|
return {
|
|
3105
3182
|
scope,
|
|
3106
3183
|
after
|
|
@@ -3150,7 +3227,7 @@ function deviceRejoinEventRoutes(options) {
|
|
|
3150
3227
|
}
|
|
3151
3228
|
//#endregion
|
|
3152
3229
|
//#region src/routes/device-removal-commit.ts
|
|
3153
|
-
var REFUSAL_STATUS = {
|
|
3230
|
+
var REFUSAL_STATUS$1 = {
|
|
3154
3231
|
invalid_input: 400,
|
|
3155
3232
|
cannot_remove_this_device: 400,
|
|
3156
3233
|
coordinator_admin_required: 409,
|
|
@@ -3196,7 +3273,7 @@ async function commitRemove(c, options) {
|
|
|
3196
3273
|
},
|
|
3197
3274
|
...options.createDeviceRemovalRefreshHooks()
|
|
3198
3275
|
});
|
|
3199
|
-
if (result.kind === "rejected") return c.json({ error: result.error }, REFUSAL_STATUS[result.error]);
|
|
3276
|
+
if (result.kind === "rejected") return c.json({ error: result.error }, REFUSAL_STATUS$1[result.error]);
|
|
3200
3277
|
if (result.kind === "unknown") return c.json({ error: result.error }, 502);
|
|
3201
3278
|
return c.json({
|
|
3202
3279
|
state: "removed",
|
|
@@ -3789,10 +3866,14 @@ function fileContextRoutes(getStore) {
|
|
|
3789
3866
|
}
|
|
3790
3867
|
//#endregion
|
|
3791
3868
|
//#region src/routes/health.ts
|
|
3869
|
+
/**
|
|
3870
|
+
* Whether this process holds an open database connection. Answered from the connection
|
|
3871
|
+
* object in memory: no statement runs, so a busy or locked database, or other work on the
|
|
3872
|
+
* same connection, can never delay the health answer or turn it into a false failure.
|
|
3873
|
+
*/
|
|
3792
3874
|
function databaseReachable(getStore) {
|
|
3793
3875
|
try {
|
|
3794
|
-
getStore().db.
|
|
3795
|
-
return true;
|
|
3876
|
+
return getStore().db.open === true;
|
|
3796
3877
|
} catch {
|
|
3797
3878
|
return false;
|
|
3798
3879
|
}
|
|
@@ -6514,6 +6595,45 @@ function overallSyncHealth(peers, options) {
|
|
|
6514
6595
|
};
|
|
6515
6596
|
}
|
|
6516
6597
|
//#endregion
|
|
6598
|
+
//#region src/application/background-refresh.ts
|
|
6599
|
+
var entries = /* @__PURE__ */ new Map();
|
|
6600
|
+
function maxAge(setting, value, refreshedAtMs) {
|
|
6601
|
+
return typeof setting === "number" ? setting : setting(value, refreshedAtMs);
|
|
6602
|
+
}
|
|
6603
|
+
/**
|
|
6604
|
+
* The current value for `key`, starting a single background refresh when it is
|
|
6605
|
+
* missing, older than `maxAgeMs`, or loaded for another version.
|
|
6606
|
+
*/
|
|
6607
|
+
function readInBackground(options) {
|
|
6608
|
+
const now = options.now ?? Date.now;
|
|
6609
|
+
const version = options.version ?? "";
|
|
6610
|
+
const entry = entries.get(options.key) ?? {
|
|
6611
|
+
value: null,
|
|
6612
|
+
refreshedAtMs: null,
|
|
6613
|
+
version,
|
|
6614
|
+
inFlight: null,
|
|
6615
|
+
error: null
|
|
6616
|
+
};
|
|
6617
|
+
entries.set(options.key, entry);
|
|
6618
|
+
if ((entry.refreshedAtMs == null || entry.version !== version || now() - entry.refreshedAtMs >= maxAge(options.maxAgeMs, entry.value, entry.refreshedAtMs)) && !entry.inFlight) entry.inFlight = options.load().then((value) => {
|
|
6619
|
+
entry.value = value;
|
|
6620
|
+
entry.version = version;
|
|
6621
|
+
entry.error = null;
|
|
6622
|
+
entry.refreshedAtMs = now();
|
|
6623
|
+
}).catch((error) => {
|
|
6624
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
6625
|
+
}).finally(() => {
|
|
6626
|
+
entry.inFlight = null;
|
|
6627
|
+
});
|
|
6628
|
+
return {
|
|
6629
|
+
value: entry.value,
|
|
6630
|
+
refreshedAt: entry.refreshedAtMs == null ? null : new Date(entry.refreshedAtMs).toISOString(),
|
|
6631
|
+
ageMs: entry.refreshedAtMs == null ? null : Math.max(0, now() - entry.refreshedAtMs),
|
|
6632
|
+
refreshing: entry.inFlight !== null,
|
|
6633
|
+
error: entry.error
|
|
6634
|
+
};
|
|
6635
|
+
}
|
|
6636
|
+
//#endregion
|
|
6517
6637
|
//#region src/application/sync-status.ts
|
|
6518
6638
|
var SAFE_RUNTIME_DETAILS = {
|
|
6519
6639
|
starting: "Running initial sync in background",
|
|
@@ -6763,13 +6883,107 @@ function applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlo
|
|
|
6763
6883
|
base.statusPayload.daemon_state = state;
|
|
6764
6884
|
statusBlock.daemon_state = state;
|
|
6765
6885
|
}
|
|
6766
|
-
|
|
6767
|
-
|
|
6768
|
-
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
|
|
6886
|
+
/** How long a coordinator answer is served before a background refresh starts. */
|
|
6887
|
+
var COORDINATOR_STATUS_MAX_AGE_MS = 3e4;
|
|
6888
|
+
function discoveredDevices(snapshot) {
|
|
6889
|
+
return Array.isArray(snapshot.discovered_devices) ? snapshot.discovered_devices : [];
|
|
6890
|
+
}
|
|
6891
|
+
function expiresAtMs(device) {
|
|
6892
|
+
const parsed = Date.parse(String(device.expires_at ?? ""));
|
|
6893
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
6894
|
+
}
|
|
6895
|
+
/**
|
|
6896
|
+
* How long one coordinator answer is served, matching the coordinator runtime's own
|
|
6897
|
+
* cache. Answers that need another try are refreshed on the next read: an unenrolled
|
|
6898
|
+
* device, or a failed peer or approval lookup. Others are refreshed after 30 seconds,
|
|
6899
|
+
* or sooner when a fresh peer's presence expires.
|
|
6900
|
+
*/
|
|
6901
|
+
function coordinatorStatusMaxAgeMs(snapshot, refreshedAtMs) {
|
|
6902
|
+
if (snapshot.presence_status === "not_enrolled" || Boolean(snapshot.lookup_error) || Boolean(snapshot.reciprocal_approval_error)) return 0;
|
|
6903
|
+
let deadline = refreshedAtMs + COORDINATOR_STATUS_MAX_AGE_MS;
|
|
6904
|
+
for (const device of discoveredDevices(snapshot)) {
|
|
6905
|
+
const expiry = device.stale ? null : expiresAtMs(device);
|
|
6906
|
+
if (expiry !== null) deadline = Math.min(deadline, expiry);
|
|
6772
6907
|
}
|
|
6908
|
+
return Math.max(0, deadline - refreshedAtMs);
|
|
6909
|
+
}
|
|
6910
|
+
/**
|
|
6911
|
+
* Marks peers whose presence expired since the answer was fetched as stale, so a read
|
|
6912
|
+
* served while the refresh runs never shows an expired peer as fresh.
|
|
6913
|
+
*/
|
|
6914
|
+
function withExpiredPeersStale(snapshot, nowMs) {
|
|
6915
|
+
const devices = discoveredDevices(snapshot);
|
|
6916
|
+
const expired = (device) => {
|
|
6917
|
+
const expiry = expiresAtMs(device);
|
|
6918
|
+
return !device.stale && expiry !== null && expiry <= nowMs;
|
|
6919
|
+
};
|
|
6920
|
+
if (!devices.some(expired)) return snapshot;
|
|
6921
|
+
const served = devices.map((device) => expired(device) ? {
|
|
6922
|
+
...device,
|
|
6923
|
+
stale: true
|
|
6924
|
+
} : device);
|
|
6925
|
+
const stale = served.filter((device) => device.stale).length;
|
|
6926
|
+
return {
|
|
6927
|
+
...snapshot,
|
|
6928
|
+
discovered_devices: served,
|
|
6929
|
+
fresh_peer_count: served.length - stale,
|
|
6930
|
+
stale_peer_count: stale
|
|
6931
|
+
};
|
|
6932
|
+
}
|
|
6933
|
+
/** The coordinator fields known without asking it, shown until the first answer arrives. */
|
|
6934
|
+
function localCoordinatorSnapshot(config) {
|
|
6935
|
+
return {
|
|
6936
|
+
enabled: true,
|
|
6937
|
+
configured: true,
|
|
6938
|
+
sync_enabled: config.syncEnabled,
|
|
6939
|
+
coordinator_url: config.syncCoordinatorUrl,
|
|
6940
|
+
groups: config.syncCoordinatorGroups,
|
|
6941
|
+
presence_status: "unknown",
|
|
6942
|
+
presence_error: null,
|
|
6943
|
+
advertised_addresses: [],
|
|
6944
|
+
fresh_peer_count: 0,
|
|
6945
|
+
stale_peer_count: 0,
|
|
6946
|
+
discovered_peer_count: 0,
|
|
6947
|
+
discovered_devices: []
|
|
6948
|
+
};
|
|
6949
|
+
}
|
|
6950
|
+
/** When the served answer was fetched, so readers can tell how current it is. */
|
|
6951
|
+
function refreshFields(value) {
|
|
6952
|
+
return {
|
|
6953
|
+
status_refreshed_at: value.refreshedAt,
|
|
6954
|
+
status_age_ms: value.ageMs,
|
|
6955
|
+
status_refreshing: value.refreshing,
|
|
6956
|
+
status_refresh_error: value.error
|
|
6957
|
+
};
|
|
6958
|
+
}
|
|
6959
|
+
/**
|
|
6960
|
+
* The coordinator status, from memory. Asking the coordinator takes several network
|
|
6961
|
+
* round trips and a write transaction, so a background task refreshes the answer and
|
|
6962
|
+
* this read never waits for it.
|
|
6963
|
+
*/
|
|
6964
|
+
async function readCoordinatorStatus(input, base) {
|
|
6965
|
+
const { config } = base;
|
|
6966
|
+
if (!coordinatorEnabled(config)) return coordinatorStatusSnapshot(input.store, config);
|
|
6967
|
+
const identity = coordinatorStatusCacheIdentity(input.store, config);
|
|
6968
|
+
const cached = readInBackground({
|
|
6969
|
+
key: `coordinator-status|${identity.key}`,
|
|
6970
|
+
version: String(identity.generation),
|
|
6971
|
+
maxAgeMs: (snapshot, refreshedAtMs) => Math.min(coordinatorStatusMaxAgeMs(snapshot, refreshedAtMs), identity.presenceRenewalMs),
|
|
6972
|
+
load: () => coordinatorStatusSnapshot(input.store, config)
|
|
6973
|
+
});
|
|
6974
|
+
return {
|
|
6975
|
+
...cached.value ? withExpiredPeersStale(cached.value, Date.now()) : localCoordinatorSnapshot(config),
|
|
6976
|
+
paired_peer_count: Number(base.statusPayload.peer_count ?? 0),
|
|
6977
|
+
...refreshFields(cached)
|
|
6978
|
+
};
|
|
6979
|
+
}
|
|
6980
|
+
function readJoinRequests(input, config) {
|
|
6981
|
+
if (!input.includeJoinRequests || !input.showDiagnostics || !config.syncCoordinatorAdminSecret) return [];
|
|
6982
|
+
return readInBackground({
|
|
6983
|
+
key: `coordinator-join-requests|${input.store.dbPath}|${config.syncCoordinatorUrl}|${config.syncCoordinatorGroups.join(",")}`,
|
|
6984
|
+
maxAgeMs: COORDINATOR_STATUS_MAX_AGE_MS,
|
|
6985
|
+
load: () => listCoordinatorJoinRequests(config)
|
|
6986
|
+
}).value ?? [];
|
|
6773
6987
|
}
|
|
6774
6988
|
function addSyncHealth(base, peers, status) {
|
|
6775
6989
|
const health = overallSyncHealth(peers.items, {
|
|
@@ -6787,7 +7001,7 @@ function markPeerFailures(peers, failedPeerIds) {
|
|
|
6787
7001
|
}
|
|
6788
7002
|
async function buildSyncStatusResponse(input) {
|
|
6789
7003
|
const base = readBaseStatus(input);
|
|
6790
|
-
const coordinatorSnapshot = await
|
|
7004
|
+
const coordinatorSnapshot = await readCoordinatorStatus(input, base);
|
|
6791
7005
|
const coordinator = traceSync("coordinator", () => input.operations.redactCoordinatorStatus(coordinatorSnapshot, input.showDiagnostics));
|
|
6792
7006
|
const peers = readPeerStatus(input, base.localDeviceId);
|
|
6793
7007
|
const attempts = readAttemptStatus(input);
|
|
@@ -6806,7 +7020,7 @@ async function buildSyncStatusResponse(input) {
|
|
|
6806
7020
|
const legacyReview = traceSync("legacySharedReview", () => input.operations.legacySharedReviewSummary(input.store));
|
|
6807
7021
|
const sharingReview = traceSync("sharingReview", () => input.store.sharingReviewSummary(input.project));
|
|
6808
7022
|
const recipientPolicyReconciliation = traceSync("recipientPolicyReconciliation", () => input.operations.listRecipientPolicyReconciliationStatus(input.store));
|
|
6809
|
-
const joinRequests =
|
|
7023
|
+
const joinRequests = readJoinRequests(input, base.config);
|
|
6810
7024
|
applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlock);
|
|
6811
7025
|
const syncHealth = addSyncHealth(base, peers, statusBlock);
|
|
6812
7026
|
const response = {
|
|
@@ -6872,6 +7086,60 @@ function snapshotPageRequest(query, localDeviceId) {
|
|
|
6872
7086
|
};
|
|
6873
7087
|
}
|
|
6874
7088
|
//#endregion
|
|
7089
|
+
//#region src/sync-server-mode.ts
|
|
7090
|
+
var PLAIN_DIRECT_MODE = Object.freeze({ kind: "plain-direct" });
|
|
7091
|
+
function canonicalPin(publicKey) {
|
|
7092
|
+
const [algorithm, blob] = publicKey.split(/\s+/);
|
|
7093
|
+
return algorithm === "ssh-ed25519" && blob ? `${algorithm} ${blob}` : null;
|
|
7094
|
+
}
|
|
7095
|
+
function bindsKey(pin, publicKey) {
|
|
7096
|
+
const expected = canonicalPin(publicKey);
|
|
7097
|
+
return !!pin && !!expected && pin === expected;
|
|
7098
|
+
}
|
|
7099
|
+
function channelBinding(mode) {
|
|
7100
|
+
if (mode.kind === "plain-direct") return void 0;
|
|
7101
|
+
return (request, deviceId, publicKey) => {
|
|
7102
|
+
if (!request || request.signal.aborted) return false;
|
|
7103
|
+
try {
|
|
7104
|
+
if (mode.kind === "relay") return bindsKey(mode.peerPin(request), publicKey);
|
|
7105
|
+
const peer = mode.peer(request);
|
|
7106
|
+
return !!peer && peer.deviceId === deviceId && bindsKey(peer.pin, publicKey);
|
|
7107
|
+
} catch {
|
|
7108
|
+
return false;
|
|
7109
|
+
}
|
|
7110
|
+
};
|
|
7111
|
+
}
|
|
7112
|
+
/** Relay requests must name a scope. The default stream is never served there. */
|
|
7113
|
+
function requiresScope(mode) {
|
|
7114
|
+
return mode.kind === "relay";
|
|
7115
|
+
}
|
|
7116
|
+
/**
|
|
7117
|
+
* Largest single pull entry a channel response can carry. Undefined for the
|
|
7118
|
+
* plain listener, which has no response ceiling and keeps sending any size.
|
|
7119
|
+
*/
|
|
7120
|
+
function entryByteLimit(mode) {
|
|
7121
|
+
if (mode.kind === "plain-direct") return void 0;
|
|
7122
|
+
return mode.maxEntryBytes ?? CHANNEL_MAX_ENTRY_BYTES;
|
|
7123
|
+
}
|
|
7124
|
+
var CHANNEL_ROUTES = /* @__PURE__ */ new Set([
|
|
7125
|
+
"GET /v1/status",
|
|
7126
|
+
"GET /v1/snapshot",
|
|
7127
|
+
"GET /v1/ops",
|
|
7128
|
+
"POST /v1/ops"
|
|
7129
|
+
]);
|
|
7130
|
+
/** Channels serve the peer protocol only. The plain listener keeps its own 404 for the rest. */
|
|
7131
|
+
function channelRouteAllowed(mode, method, path) {
|
|
7132
|
+
return mode.kind === "plain-direct" || CHANNEL_ROUTES.has(`${method} ${path}`);
|
|
7133
|
+
}
|
|
7134
|
+
/**
|
|
7135
|
+
* Whether the plain listener runs with direct Noise on. Then a bootstrap grant
|
|
7136
|
+
* authorizes only status, and an unmarked grant status from a worker known to
|
|
7137
|
+
* speak Noise is refused. Channels never accept grants at all.
|
|
7138
|
+
*/
|
|
7139
|
+
function noiseActive(mode) {
|
|
7140
|
+
return mode.kind === "plain-direct" && (mode.noiseActive ?? DIRECT_NOISE_ACTIVE);
|
|
7141
|
+
}
|
|
7142
|
+
//#endregion
|
|
6875
7143
|
//#region src/routes/device-rejoin-evidence.ts
|
|
6876
7144
|
function localPins(store) {
|
|
6877
7145
|
const rows = store.db.prepare(`SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers
|
|
@@ -6927,211 +7195,126 @@ async function readInventoryWithRejoinEvidence(store, input, readConfig = readCo
|
|
|
6927
7195
|
return inventory();
|
|
6928
7196
|
}
|
|
6929
7197
|
}
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
|
|
6934
|
-
const remoteUrl = config.syncCoordinatorUrl.trim();
|
|
6935
|
-
const adminSecret = config.syncCoordinatorAdminSecret.trim();
|
|
6936
|
-
return remoteUrl && adminSecret ? {
|
|
6937
|
-
remoteUrl,
|
|
6938
|
-
adminSecret
|
|
6939
|
-
} : null;
|
|
6940
|
-
}
|
|
6941
|
-
/** Maps revocation client failures to messages Devices can act on. */
|
|
6942
|
-
function revocationFailure(error) {
|
|
6943
|
-
let code = error instanceof Error ? error.message : "";
|
|
6944
|
-
if (error instanceof RemoteCoordinatorRequestError) code = error.code;
|
|
6945
|
-
if (code === "revocation_preview_stale") return {
|
|
6946
|
-
error: "retire_preview_stale",
|
|
6947
|
-
status: 409
|
|
6948
|
-
};
|
|
6949
|
-
if (code === "revocation_target_unavailable") return {
|
|
6950
|
-
error: "retire_target_unavailable",
|
|
6951
|
-
status: 409
|
|
6952
|
-
};
|
|
6953
|
-
if (code === "revocation_outcome_unknown") return {
|
|
6954
|
-
error: "retire_outcome_unknown",
|
|
6955
|
-
status: 502
|
|
6956
|
-
};
|
|
6957
|
-
return {
|
|
6958
|
-
error: "retire_unavailable",
|
|
6959
|
-
status: 503
|
|
6960
|
-
};
|
|
6961
|
-
}
|
|
6962
|
-
function fail(c, failure) {
|
|
6963
|
-
return c.json({ error: failure.error }, failure.status);
|
|
6964
|
-
}
|
|
6965
|
-
var TARGET_FAILURES = {
|
|
6966
|
-
device_not_enrolled: {
|
|
6967
|
-
error: "device_not_enrolled",
|
|
6968
|
-
status: 404
|
|
6969
|
-
},
|
|
6970
|
-
cannot_retire_this_device: {
|
|
6971
|
-
error: "cannot_retire_this_device",
|
|
6972
|
-
status: 400
|
|
6973
|
-
},
|
|
6974
|
-
device_already_retired: {
|
|
6975
|
-
error: "device_already_retired",
|
|
6976
|
-
status: 409
|
|
6977
|
-
},
|
|
6978
|
-
device_enrollment_conflict: {
|
|
6979
|
-
error: "device_enrollment_conflict",
|
|
6980
|
-
status: 409
|
|
6981
|
-
},
|
|
6982
|
-
device_evidence_incomplete: {
|
|
6983
|
-
error: "coordinator_evidence_too_large",
|
|
6984
|
-
status: 503
|
|
6985
|
-
},
|
|
6986
|
-
device_key_unrecognized: {
|
|
6987
|
-
error: "device_key_unrecognized",
|
|
6988
|
-
status: 409
|
|
6989
|
-
},
|
|
6990
|
-
local_identity_unverified: {
|
|
6991
|
-
error: "local_identity_unverified",
|
|
6992
|
-
status: 409
|
|
6993
|
-
}
|
|
7198
|
+
var NOTHING_FAILED = {
|
|
7199
|
+
failedGroups: 0,
|
|
7200
|
+
skippedGroups: 0,
|
|
7201
|
+
errorCode: null
|
|
6994
7202
|
};
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
7005
|
-
|
|
7203
|
+
var BackgroundTeamSetupReconciliation = class {
|
|
7204
|
+
options;
|
|
7205
|
+
now;
|
|
7206
|
+
refreshAfterMs;
|
|
7207
|
+
staleAfterMs;
|
|
7208
|
+
lastGood = null;
|
|
7209
|
+
lastAttemptAtMs = null;
|
|
7210
|
+
lastErrorCode = null;
|
|
7211
|
+
lastAssessment = NOTHING_FAILED;
|
|
7212
|
+
retryTimer = null;
|
|
7213
|
+
inFlight = null;
|
|
7214
|
+
rerun = false;
|
|
7215
|
+
timer = null;
|
|
7216
|
+
constructor(options) {
|
|
7217
|
+
this.options = options;
|
|
7218
|
+
this.now = options.now ?? Date.now;
|
|
7219
|
+
this.refreshAfterMs = options.refreshAfterMs ?? 3e4;
|
|
7220
|
+
this.staleAfterMs = options.staleAfterMs ?? 3e5;
|
|
7221
|
+
}
|
|
7222
|
+
read() {
|
|
7223
|
+
const due = this.lastAttemptAtMs === null || this.now() - this.lastAttemptAtMs >= this.refreshAfterMs;
|
|
7224
|
+
if (!this.inFlight && due) this.refresh();
|
|
7006
7225
|
return {
|
|
7007
|
-
|
|
7008
|
-
status:
|
|
7226
|
+
result: this.lastGood?.result ?? null,
|
|
7227
|
+
status: this.status()
|
|
7009
7228
|
};
|
|
7010
7229
|
}
|
|
7011
|
-
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
function retireTarget(c) {
|
|
7019
|
-
const deviceId = String(c.req.param("device_id") ?? "").trim();
|
|
7020
|
-
if (!deviceId) return {
|
|
7021
|
-
error: "device_id_required",
|
|
7022
|
-
status: 400
|
|
7023
|
-
};
|
|
7024
|
-
return deviceId;
|
|
7025
|
-
}
|
|
7026
|
-
async function previewRetire(c, store) {
|
|
7027
|
-
const deviceId = retireTarget(c);
|
|
7028
|
-
if (typeof deviceId !== "string") return fail(c, deviceId);
|
|
7029
|
-
const config = readCoordinatorSyncConfig();
|
|
7030
|
-
const credentials = coordinatorCredentials(config);
|
|
7031
|
-
if (!credentials) return fail(c, {
|
|
7032
|
-
error: "coordinator_admin_required",
|
|
7033
|
-
status: 409
|
|
7034
|
-
});
|
|
7035
|
-
const target = await resolveTarget(config, store, deviceId);
|
|
7036
|
-
if ("error" in target) return fail(c, target);
|
|
7037
|
-
try {
|
|
7038
|
-
const preview = await coordinatorRevokeDeviceAction({
|
|
7039
|
-
...credentials,
|
|
7040
|
-
groupId: target.groupId,
|
|
7041
|
-
deviceId: target.enrollmentDeviceId
|
|
7042
|
-
});
|
|
7043
|
-
if (preview.state !== "ready") return fail(c, {
|
|
7044
|
-
error: "retire_unavailable",
|
|
7045
|
-
status: 503
|
|
7046
|
-
});
|
|
7047
|
-
if (preview.key_id !== target.keyId) return fail(c, {
|
|
7048
|
-
error: "device_enrollment_conflict",
|
|
7049
|
-
status: 409
|
|
7050
|
-
});
|
|
7051
|
-
return c.json({
|
|
7052
|
-
device_id: deviceId,
|
|
7053
|
-
display_name: target.displayName,
|
|
7054
|
-
enrollment_device_id: target.enrollmentDeviceId,
|
|
7055
|
-
alias_device_ids: target.aliasDeviceIds,
|
|
7056
|
-
group_id: target.groupId,
|
|
7057
|
-
coordinator_id: preview.coordinator_id,
|
|
7058
|
-
key_id: preview.key_id,
|
|
7059
|
-
expected_digest: preview.expected_digest
|
|
7230
|
+
refresh() {
|
|
7231
|
+
if (this.inFlight) {
|
|
7232
|
+
this.rerun = true;
|
|
7233
|
+
return this.inFlight;
|
|
7234
|
+
}
|
|
7235
|
+
this.inFlight = this.runPasses().finally(() => {
|
|
7236
|
+
this.inFlight = null;
|
|
7060
7237
|
});
|
|
7061
|
-
|
|
7062
|
-
return fail(c, revocationFailure(error));
|
|
7238
|
+
return this.inFlight;
|
|
7063
7239
|
}
|
|
7064
|
-
|
|
7065
|
-
|
|
7066
|
-
|
|
7067
|
-
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7072
|
-
|
|
7073
|
-
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7077
|
-
|
|
7078
|
-
|
|
7079
|
-
|
|
7080
|
-
|
|
7240
|
+
startPeriodic(intervalMs) {
|
|
7241
|
+
if (this.timer) return;
|
|
7242
|
+
this.refresh();
|
|
7243
|
+
this.timer = setInterval(() => void this.refresh(), intervalMs);
|
|
7244
|
+
this.timer.unref?.();
|
|
7245
|
+
}
|
|
7246
|
+
stop() {
|
|
7247
|
+
if (this.timer) clearInterval(this.timer);
|
|
7248
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
7249
|
+
this.timer = null;
|
|
7250
|
+
this.retryTimer = null;
|
|
7251
|
+
}
|
|
7252
|
+
async settle() {
|
|
7253
|
+
while (this.inFlight) await this.inFlight;
|
|
7254
|
+
}
|
|
7255
|
+
async runPasses() {
|
|
7256
|
+
do {
|
|
7257
|
+
this.rerun = false;
|
|
7258
|
+
await this.pass();
|
|
7259
|
+
} while (this.rerun);
|
|
7260
|
+
}
|
|
7261
|
+
async pass() {
|
|
7262
|
+
try {
|
|
7263
|
+
const result = await this.options.run(this.lastGood?.result ?? null);
|
|
7264
|
+
this.lastGood = {
|
|
7265
|
+
result,
|
|
7266
|
+
checkedAtMs: this.now()
|
|
7267
|
+
};
|
|
7268
|
+
this.lastAssessment = this.options.assess?.(result) ?? NOTHING_FAILED;
|
|
7269
|
+
this.lastErrorCode = this.lastAssessment.errorCode;
|
|
7270
|
+
if (this.lastAssessment.skippedGroups > 0) this.retrySkippedSoon();
|
|
7271
|
+
} catch (error) {
|
|
7272
|
+
this.lastErrorCode = this.options.errorCode(error);
|
|
7273
|
+
} finally {
|
|
7274
|
+
this.lastAttemptAtMs = this.now();
|
|
7081
7275
|
}
|
|
7082
|
-
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
7086
|
-
|
|
7087
|
-
|
|
7088
|
-
|
|
7089
|
-
if (!confirmed) return fail(c, {
|
|
7090
|
-
error: "retire_preview_required",
|
|
7091
|
-
status: 400
|
|
7092
|
-
});
|
|
7093
|
-
const config = readCoordinatorSyncConfig();
|
|
7094
|
-
const credentials = coordinatorCredentials(config);
|
|
7095
|
-
if (!credentials) return fail(c, {
|
|
7096
|
-
error: "coordinator_admin_required",
|
|
7097
|
-
status: 409
|
|
7098
|
-
});
|
|
7099
|
-
const target = await resolveTarget(config, store, deviceId);
|
|
7100
|
-
if ("error" in target) return fail(c, target);
|
|
7101
|
-
if (target.groupId !== confirmed.revocation.groupId || target.enrollmentDeviceId !== confirmed.enrollmentDeviceId || target.keyId !== confirmed.revocation.expectedContext.keyId) return fail(c, {
|
|
7102
|
-
error: "retire_preview_stale",
|
|
7103
|
-
status: 409
|
|
7104
|
-
});
|
|
7105
|
-
try {
|
|
7106
|
-
if ((await coordinatorRevokeDeviceAction({
|
|
7107
|
-
...credentials,
|
|
7108
|
-
...confirmed.revocation,
|
|
7109
|
-
deviceId: target.enrollmentDeviceId
|
|
7110
|
-
})).state !== "revoked") return fail(c, {
|
|
7111
|
-
error: "retire_outcome_unknown",
|
|
7112
|
-
status: 502
|
|
7113
|
-
});
|
|
7114
|
-
} catch (error) {
|
|
7115
|
-
return fail(c, revocationFailure(error));
|
|
7276
|
+
try {
|
|
7277
|
+
this.options.record?.({
|
|
7278
|
+
ok: this.lastErrorCode === null,
|
|
7279
|
+
checkedAtMs: this.lastGood?.checkedAtMs ?? null,
|
|
7280
|
+
errorCode: this.lastErrorCode
|
|
7281
|
+
});
|
|
7282
|
+
} catch {}
|
|
7116
7283
|
}
|
|
7117
|
-
|
|
7118
|
-
|
|
7119
|
-
|
|
7120
|
-
|
|
7121
|
-
|
|
7122
|
-
|
|
7123
|
-
}
|
|
7124
|
-
|
|
7125
|
-
|
|
7126
|
-
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
|
|
7130
|
-
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7284
|
+
/** One delayed pass for groups skipped because a route held them. */
|
|
7285
|
+
retrySkippedSoon() {
|
|
7286
|
+
if (this.retryTimer) return;
|
|
7287
|
+
this.retryTimer = setTimeout(() => {
|
|
7288
|
+
this.retryTimer = null;
|
|
7289
|
+
this.refresh();
|
|
7290
|
+
}, this.options.retryDelayMs ?? 5e3);
|
|
7291
|
+
this.retryTimer.unref?.();
|
|
7292
|
+
}
|
|
7293
|
+
status() {
|
|
7294
|
+
const lastGood = this.lastGood;
|
|
7295
|
+
if (!lastGood) return {
|
|
7296
|
+
state: "never",
|
|
7297
|
+
refreshing: this.inFlight !== null,
|
|
7298
|
+
checked_at: null,
|
|
7299
|
+
age_ms: null,
|
|
7300
|
+
error_code: this.lastErrorCode,
|
|
7301
|
+
failed_groups: 0,
|
|
7302
|
+
skipped_groups: 0
|
|
7303
|
+
};
|
|
7304
|
+
const ageMs = Math.max(0, this.now() - lastGood.checkedAtMs);
|
|
7305
|
+
return {
|
|
7306
|
+
state: this.lastErrorCode !== null || ageMs >= this.staleAfterMs ? "stale" : "current",
|
|
7307
|
+
refreshing: this.inFlight !== null,
|
|
7308
|
+
checked_at: new Date(lastGood.checkedAtMs).toISOString(),
|
|
7309
|
+
age_ms: ageMs,
|
|
7310
|
+
error_code: this.lastErrorCode,
|
|
7311
|
+
failed_groups: this.lastAssessment.failedGroups,
|
|
7312
|
+
skipped_groups: this.lastAssessment.skippedGroups
|
|
7313
|
+
};
|
|
7314
|
+
}
|
|
7315
|
+
};
|
|
7316
|
+
function createTeamSetupReconciliation(options) {
|
|
7317
|
+
return new BackgroundTeamSetupReconciliation(options);
|
|
7135
7318
|
}
|
|
7136
7319
|
//#endregion
|
|
7137
7320
|
//#region src/routes/team-setup-view.ts
|
|
@@ -7276,6 +7459,25 @@ var FINISH_DIGEST_PATTERN = /^legacy-team-activation-finish-v1:[0-9a-f]{64}$/u;
|
|
|
7276
7459
|
var ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-access-delta:[0-9a-f]{64}$/u;
|
|
7277
7460
|
var VIEWER_ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-viewer-access-delta-v1:[0-9a-f]{64}$/u;
|
|
7278
7461
|
var activeCandidateMutations = /* @__PURE__ */ new WeakMap();
|
|
7462
|
+
/**
|
|
7463
|
+
* How many operations on each candidate have finished and released its claim. A
|
|
7464
|
+
* background pass compares it with the count it began with, to tell whether
|
|
7465
|
+
* another operation ran on the candidate since.
|
|
7466
|
+
*/
|
|
7467
|
+
var candidateMutationRevisions = /* @__PURE__ */ new WeakMap();
|
|
7468
|
+
function candidateMutationRevision(db, candidateRef) {
|
|
7469
|
+
return candidateMutationRevisions.get(db)?.get(candidateRef) ?? 0;
|
|
7470
|
+
}
|
|
7471
|
+
function advanceCandidateMutationRevision(db, candidateRef) {
|
|
7472
|
+
const revisions = candidateMutationRevisions.get(db) ?? /* @__PURE__ */ new Map();
|
|
7473
|
+
candidateMutationRevisions.set(db, revisions);
|
|
7474
|
+
revisions.set(candidateRef, (revisions.get(candidateRef) ?? 0) + 1);
|
|
7475
|
+
}
|
|
7476
|
+
/**
|
|
7477
|
+
* Claims the candidate for one access-changing operation, or returns null when
|
|
7478
|
+
* another holds it. Draft and finish routes, Team recovery and each background
|
|
7479
|
+
* reconciliation pass take it, so none of them runs across another.
|
|
7480
|
+
*/
|
|
7279
7481
|
function claimCandidateMutation(db, candidateRef) {
|
|
7280
7482
|
let active = activeCandidateMutations.get(db);
|
|
7281
7483
|
if (!active) {
|
|
@@ -7293,6 +7495,7 @@ function claimCandidateMutation(db, candidateRef) {
|
|
|
7293
7495
|
if (released) return;
|
|
7294
7496
|
released = true;
|
|
7295
7497
|
active?.delete(candidateRef);
|
|
7498
|
+
advanceCandidateMutationRevision(db, candidateRef);
|
|
7296
7499
|
settle();
|
|
7297
7500
|
};
|
|
7298
7501
|
}
|
|
@@ -7300,9 +7503,44 @@ function claimCandidateMutation(db, candidateRef) {
|
|
|
7300
7503
|
function candidateMutationSettled(db, candidateRef) {
|
|
7301
7504
|
return activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();
|
|
7302
7505
|
}
|
|
7303
|
-
|
|
7506
|
+
var candidatePass = new AsyncLocalStorage();
|
|
7507
|
+
function beginCandidatePass(db) {
|
|
7508
|
+
return {
|
|
7509
|
+
skipped: /* @__PURE__ */ new Set(),
|
|
7510
|
+
revisions: new Map(candidateMutationRevisions.get(db))
|
|
7511
|
+
};
|
|
7512
|
+
}
|
|
7513
|
+
/** Whether no other operation holds the candidate or has run on it since the pass began. */
|
|
7514
|
+
function isUntouchedSince(db, pass, candidateRef) {
|
|
7515
|
+
return !activeCandidateMutations.get(db)?.has(candidateRef) && candidateMutationRevision(db, candidateRef) === (pass.revisions.get(candidateRef) ?? 0);
|
|
7516
|
+
}
|
|
7517
|
+
/**
|
|
7518
|
+
* Claims the candidate for a write of a background pass, or returns null when
|
|
7519
|
+
* another operation holds it or has run on it since the pass began. What the
|
|
7520
|
+
* pass read from the coordinator may be older than that operation, for example
|
|
7521
|
+
* a list of completions taken while a setup was finishing, so the pass must not
|
|
7522
|
+
* act on it once the setup lets go.
|
|
7523
|
+
*/
|
|
7524
|
+
function claimForCandidatePass(db, pass, candidateRef) {
|
|
7525
|
+
const untouched = isUntouchedSince(db, pass, candidateRef);
|
|
7304
7526
|
const release = claimCandidateMutation(db, candidateRef);
|
|
7305
|
-
if (!release) return
|
|
7527
|
+
if (!release) return null;
|
|
7528
|
+
if (!untouched) {
|
|
7529
|
+
release();
|
|
7530
|
+
return null;
|
|
7531
|
+
}
|
|
7532
|
+
return () => {
|
|
7533
|
+
release();
|
|
7534
|
+
pass.revisions.set(candidateRef, candidateMutationRevision(db, candidateRef));
|
|
7535
|
+
};
|
|
7536
|
+
}
|
|
7537
|
+
async function runCandidateMutation(db, candidateRef, operation) {
|
|
7538
|
+
const pass = candidatePass.getStore();
|
|
7539
|
+
const release = pass ? claimForCandidatePass(db, pass, candidateRef) : claimCandidateMutation(db, candidateRef);
|
|
7540
|
+
if (!release) {
|
|
7541
|
+
pass?.skipped.add(candidateRef);
|
|
7542
|
+
return false;
|
|
7543
|
+
}
|
|
7306
7544
|
try {
|
|
7307
7545
|
await operation();
|
|
7308
7546
|
return true;
|
|
@@ -7326,8 +7564,19 @@ function completionFailureHandlers(options) {
|
|
|
7326
7564
|
reportFailure
|
|
7327
7565
|
};
|
|
7328
7566
|
}
|
|
7567
|
+
/**
|
|
7568
|
+
* The group's Team member removals could not be read, so a completion is not
|
|
7569
|
+
* applied in this pass: it might make a removed person a member again on a
|
|
7570
|
+
* machine that has not recorded the removal. Nothing diverged.
|
|
7571
|
+
*/
|
|
7572
|
+
var TeamMemberRemovalsUnavailableError = class extends Error {
|
|
7573
|
+
constructor(cause) {
|
|
7574
|
+
super("team_member_removals_unavailable", cause === void 0 ? void 0 : { cause });
|
|
7575
|
+
this.name = "TeamMemberRemovalsUnavailableError";
|
|
7576
|
+
}
|
|
7577
|
+
};
|
|
7329
7578
|
function isNonDivergentApplyFailure(error) {
|
|
7330
|
-
return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError;
|
|
7579
|
+
return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError || error instanceof TeamMemberRemovalsUnavailableError;
|
|
7331
7580
|
}
|
|
7332
7581
|
function completionConflictError(cause) {
|
|
7333
7582
|
return new Error("team_setup_completion_conflict", { cause });
|
|
@@ -7348,7 +7597,9 @@ function groupCompletionFailureHandler(groups, handleFailure) {
|
|
|
7348
7597
|
}
|
|
7349
7598
|
/** The safe cause behind a retryable completion failure, when one is known. */
|
|
7350
7599
|
function completionFailureReason(error) {
|
|
7351
|
-
|
|
7600
|
+
const chain = errorChain(error);
|
|
7601
|
+
if (chain.some((item) => item instanceof LegacyTeamSetupDeviceRemovalsUnavailableError)) return "device_removals_unavailable";
|
|
7602
|
+
if (chain.some((item) => item instanceof TeamMemberRemovalsUnavailableError)) return "team_member_removals_unavailable";
|
|
7352
7603
|
}
|
|
7353
7604
|
function completionBlocker(error) {
|
|
7354
7605
|
const code = apiErrorCode(new Error(completionApiError(error)));
|
|
@@ -7378,19 +7629,53 @@ function summaryReconciliationOptions(blockingErrors) {
|
|
|
7378
7629
|
}
|
|
7379
7630
|
};
|
|
7380
7631
|
}
|
|
7381
|
-
|
|
7632
|
+
/**
|
|
7633
|
+
* The daemon's signed lookup, asked with this device's existing identity. A
|
|
7634
|
+
* reconciliation never creates or repairs signing keys: with no usable identity
|
|
7635
|
+
* the lookup is reported unavailable, which keeps every pairing.
|
|
7636
|
+
*/
|
|
7637
|
+
async function lookupPeerRemovalsAsDaemon(store, config) {
|
|
7638
|
+
const identity = daemonSigningIdentity(store);
|
|
7639
|
+
if (!identity) return unavailablePeerRemovalLookup();
|
|
7640
|
+
return fetchPeerRemovalLookup(store, config, identity);
|
|
7641
|
+
}
|
|
7642
|
+
/**
|
|
7643
|
+
* The identity the sync daemon signs coordinator requests with: this store's
|
|
7644
|
+
* one device, and its keys in the directory `CODEMEM_KEYS_DIR` names or the
|
|
7645
|
+
* default one. Null when the store has no single device or its key is not
|
|
7646
|
+
* usable. Nothing here creates or repairs a key.
|
|
7647
|
+
*/
|
|
7648
|
+
function daemonSigningIdentity(store) {
|
|
7382
7649
|
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
7383
|
-
const
|
|
7384
|
-
|
|
7650
|
+
const rows = store.db.prepare("SELECT device_id FROM sync_device LIMIT 2").pluck().all();
|
|
7651
|
+
const localDeviceId = rows.length === 1 && typeof rows[0] === "string" ? rows[0] : null;
|
|
7652
|
+
if (!localDeviceId) return null;
|
|
7653
|
+
if (!loadRuntimeSigningPublicKey(store.db, {
|
|
7654
|
+
deviceId: localDeviceId,
|
|
7655
|
+
keysDir
|
|
7656
|
+
})) return null;
|
|
7657
|
+
return {
|
|
7385
7658
|
localDeviceId,
|
|
7386
7659
|
keysDir
|
|
7387
|
-
}
|
|
7660
|
+
};
|
|
7661
|
+
}
|
|
7662
|
+
function unavailablePeerRemovalLookup() {
|
|
7663
|
+
return {
|
|
7664
|
+
status: "failed",
|
|
7665
|
+
revoked: [],
|
|
7666
|
+
removed: [],
|
|
7667
|
+
enrolled: [],
|
|
7668
|
+
removalSeq: null,
|
|
7669
|
+
generation: null,
|
|
7670
|
+
removedFromGroups: []
|
|
7671
|
+
};
|
|
7388
7672
|
}
|
|
7389
7673
|
var defaultCompletionDependencies = {
|
|
7390
7674
|
create: coordinatorCreateLegacyTeamCompletionAction,
|
|
7391
7675
|
get: coordinatorGetLegacyTeamCompletionAction,
|
|
7392
7676
|
list: coordinatorListLegacyTeamCompletionsAction,
|
|
7393
7677
|
listRemovals: coordinatorListRemovedDevicesAction,
|
|
7678
|
+
listTeamMemberRemovals: coordinatorListTeamMemberRemovalsAction,
|
|
7394
7679
|
lookupPeerRemovals: lookupPeerRemovalsAsDaemon
|
|
7395
7680
|
};
|
|
7396
7681
|
var defaultSnapshotLoaderDependencies = {
|
|
@@ -7519,18 +7804,6 @@ function configuredGroupIds$1(groups) {
|
|
|
7519
7804
|
if (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();
|
|
7520
7805
|
return unique;
|
|
7521
7806
|
}
|
|
7522
|
-
function normalizedCoordinatorId(value) {
|
|
7523
|
-
try {
|
|
7524
|
-
const normalized = buildBaseUrl(value);
|
|
7525
|
-
if (!normalized) return null;
|
|
7526
|
-
const parsed = new URL(normalized);
|
|
7527
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.host || parsed.username || parsed.password) return null;
|
|
7528
|
-
const path = parsed.pathname === "/" ? "" : parsed.pathname;
|
|
7529
|
-
return `${parsed.protocol}//${parsed.host}${path}${parsed.search}`;
|
|
7530
|
-
} catch {
|
|
7531
|
-
return null;
|
|
7532
|
-
}
|
|
7533
|
-
}
|
|
7534
7807
|
function legacyTeamCandidateGroupDescriptors(store, coordinatorUrl, groups) {
|
|
7535
7808
|
const configuredIds = configuredGroupIds$1(groups);
|
|
7536
7809
|
const configuredCoordinatorId = buildBaseUrl(coordinatorUrl);
|
|
@@ -7761,43 +8034,332 @@ function blockedCandidateSummary(store, group, blocker) {
|
|
|
7761
8034
|
unresolvedProjectCount: 0
|
|
7762
8035
|
};
|
|
7763
8036
|
}
|
|
7764
|
-
|
|
7765
|
-
|
|
7766
|
-
|
|
7767
|
-
|
|
7768
|
-
|
|
8037
|
+
var TEAM_SETUP_RECONCILIATION_JOB = "team_setup_reconciliation";
|
|
8038
|
+
/**
|
|
8039
|
+
* One background pass, on fresh evidence only: it loads the roster from the
|
|
8040
|
+
* coordinator, creates drafts for groups that have no local setup at all, then
|
|
8041
|
+
* reads completions and removals. Only after that, for each group that neither
|
|
8042
|
+
* failed nor was skipped, it rediscovers groups with a local completion, the
|
|
8043
|
+
* step that can restore setup-owned Project recipients. Every discovery runs
|
|
8044
|
+
* under the candidate claim, and none runs on a cached roster or after a failed
|
|
8045
|
+
* removal read.
|
|
8046
|
+
*/
|
|
8047
|
+
function runSummaryReconciliation(store, dependencies, previous) {
|
|
8048
|
+
const pass = beginCandidatePass(store.db);
|
|
8049
|
+
return candidatePass.run(pass, () => reconcileSummaryGroups(store, dependencies, previous, pass));
|
|
8050
|
+
}
|
|
8051
|
+
async function reconcileSummaryGroups(store, dependencies, previous, pass) {
|
|
8052
|
+
const { skipped } = pass;
|
|
8053
|
+
dependencies.loadSnapshots.invalidate();
|
|
8054
|
+
const configured = await dependencies.loadSnapshots();
|
|
8055
|
+
requireBoundedSnapshots(configured);
|
|
8056
|
+
const groups = openSummaryGroups(store, configured, pass);
|
|
8057
|
+
const blockers = /* @__PURE__ */ new Map();
|
|
8058
|
+
const views = /* @__PURE__ */ new Map();
|
|
8059
|
+
for (const group of groups) {
|
|
8060
|
+
if (!hasNoLocalSetup(store, summaryCandidateRef(group))) continue;
|
|
8061
|
+
await discoverAfterReconciliation(store, group, dependencies, {
|
|
8062
|
+
views,
|
|
8063
|
+
skipped
|
|
8064
|
+
});
|
|
8065
|
+
}
|
|
8066
|
+
await dependencies.reconcile(store, groups, summaryReconciliationOptions(blockers));
|
|
8067
|
+
for (const group of groups) {
|
|
8068
|
+
const candidateRef = summaryCandidateRef(group);
|
|
8069
|
+
if (blockers.has(candidateRef) || skipped.has(candidateRef) || views.has(candidateRef)) continue;
|
|
8070
|
+
let removals = null;
|
|
8071
|
+
if (hasRepairableSetupTeam(store, candidateRef)) {
|
|
8072
|
+
const evidence = await dependencies.readRemovalsForRepair(group);
|
|
8073
|
+
if (evidence.status === "failed") blockers.set(candidateRef, evidence.blocker);
|
|
8074
|
+
if (evidence.status !== "read") continue;
|
|
8075
|
+
removals = evidence;
|
|
8076
|
+
}
|
|
8077
|
+
await discoverAfterReconciliation(store, group, dependencies, {
|
|
8078
|
+
views,
|
|
8079
|
+
skipped
|
|
8080
|
+
}, () => removals ? applyRemovalsBeforeRepair(store, group, removals) : true);
|
|
8081
|
+
}
|
|
8082
|
+
return carrySkippedGroups({
|
|
8083
|
+
groups: configured,
|
|
8084
|
+
views,
|
|
8085
|
+
blockers,
|
|
8086
|
+
skipped
|
|
8087
|
+
}, previous);
|
|
8088
|
+
}
|
|
8089
|
+
/** The groups a pass goes on with. One another operation holds or ran on is marked skipped. */
|
|
8090
|
+
function openSummaryGroups(store, groups, pass) {
|
|
8091
|
+
return groups.filter((group) => {
|
|
8092
|
+
const candidateRef = summaryCandidateRef(group);
|
|
8093
|
+
if (isUntouchedSince(store.db, pass, candidateRef)) return true;
|
|
8094
|
+
pass.skipped.add(candidateRef);
|
|
8095
|
+
return false;
|
|
7769
8096
|
});
|
|
7770
|
-
|
|
7771
|
-
|
|
7772
|
-
|
|
8097
|
+
}
|
|
8098
|
+
/**
|
|
8099
|
+
* Whether rediscovering this candidate can restore setup recipients: core repairs
|
|
8100
|
+
* them only for the setup's Team while it is active, so this is the same check.
|
|
8101
|
+
*/
|
|
8102
|
+
function hasRepairableSetupTeam(store, candidateRef) {
|
|
8103
|
+
return Boolean(store.db.prepare("SELECT 1 FROM policy_teams WHERE team_id = ? AND status = 'active' LIMIT 1").pluck().get(deterministicPolicyTeamId(candidateRef)));
|
|
8104
|
+
}
|
|
8105
|
+
var DEVICE_REMOVALS_UNREAD = {
|
|
8106
|
+
code: "team_setup_completion_unavailable",
|
|
8107
|
+
reason: "device_removals_unavailable"
|
|
8108
|
+
};
|
|
8109
|
+
var TEAM_MEMBER_REMOVALS_UNREAD = {
|
|
8110
|
+
code: "team_setup_completion_unavailable",
|
|
8111
|
+
reason: "team_member_removals_unavailable"
|
|
8112
|
+
};
|
|
8113
|
+
/** Fresh removal evidence for one group, read before any recipient repair. */
|
|
8114
|
+
async function readRemovalsForRepair(options, store, group) {
|
|
8115
|
+
const dependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
|
|
8116
|
+
const authorization = readCompletionAuthorization(options);
|
|
8117
|
+
if (!(dependencies?.listRemovals && dependencies.listTeamMemberRemovals) || !authorization || !authorizesGroup(authorization, group)) return { status: "unavailable" };
|
|
8118
|
+
const timeoutS = Math.max(1, authorization.config.syncCoordinatorTimeoutS);
|
|
8119
|
+
const deadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;
|
|
8120
|
+
const { removalReads } = completionReadActions(dependencies, {
|
|
8121
|
+
authorization,
|
|
8122
|
+
store
|
|
8123
|
+
}, timeoutS, deadlineMs);
|
|
8124
|
+
const devices = await removalReads.listRemovals();
|
|
8125
|
+
if (devices?.status !== "read") return {
|
|
8126
|
+
status: "failed",
|
|
8127
|
+
blocker: DEVICE_REMOVALS_UNREAD
|
|
8128
|
+
};
|
|
8129
|
+
let teamMemberRemovals;
|
|
8130
|
+
try {
|
|
8131
|
+
teamMemberRemovals = await removalReads.listTeamMemberRemovals(group.groupId);
|
|
8132
|
+
} catch {
|
|
8133
|
+
return {
|
|
8134
|
+
status: "failed",
|
|
8135
|
+
blocker: TEAM_MEMBER_REMOVALS_UNREAD
|
|
8136
|
+
};
|
|
8137
|
+
}
|
|
8138
|
+
if (!teamMemberRemovals) return { status: "unavailable" };
|
|
8139
|
+
return {
|
|
8140
|
+
status: "read",
|
|
8141
|
+
deviceRemovals: devices.removals,
|
|
8142
|
+
teamMemberRemovals
|
|
8143
|
+
};
|
|
8144
|
+
}
|
|
8145
|
+
/**
|
|
8146
|
+
* Applies the removals a check read, before rediscovery can restore recipients,
|
|
8147
|
+
* and returns whether the repair may run.
|
|
8148
|
+
*
|
|
8149
|
+
* Team member removals are recorded with their enforcements, as the enrollment
|
|
8150
|
+
* check does. They commit in their own transaction before rediscovery, under the
|
|
8151
|
+
* same candidate claim, so any recipient the repair restores is refused to a
|
|
8152
|
+
* removed person's devices.
|
|
8153
|
+
*
|
|
8154
|
+
* A device removal covers one group, and the device may still be enrolled in
|
|
8155
|
+
* another, so this check does not end device-wide access: the sync daemon's
|
|
8156
|
+
* removal check does that once the device is removed everywhere, and the Team
|
|
8157
|
+
* then goes back to review. While this machine still pins or binds a device
|
|
8158
|
+
* this group removed, under the removed key, the repair waits.
|
|
8159
|
+
*/
|
|
8160
|
+
function applyRemovalsBeforeRepair(store, group, evidence) {
|
|
8161
|
+
applyTeamMemberRemovals(store.db, {
|
|
8162
|
+
coordinatorId: group.coordinatorId,
|
|
8163
|
+
groupId: group.groupId,
|
|
8164
|
+
removals: evidence.teamMemberRemovals,
|
|
8165
|
+
now: (/* @__PURE__ */ new Date()).toISOString()
|
|
7773
8166
|
});
|
|
8167
|
+
const removed = evidence.deviceRemovals.filter((removal) => removal.group_id === group.groupId);
|
|
8168
|
+
if (removed.length === 0) return true;
|
|
8169
|
+
const localDeviceId = store.db.prepare("SELECT device_id FROM sync_device LIMIT 1").pluck().get() ?? "";
|
|
8170
|
+
const removedLocally = localRemovedDeviceIds(store.db, {
|
|
8171
|
+
enrollments: removed.map(({ device_id, fingerprint }) => ({
|
|
8172
|
+
device_id,
|
|
8173
|
+
fingerprint
|
|
8174
|
+
})),
|
|
8175
|
+
keyId: null
|
|
8176
|
+
}, localDeviceId);
|
|
8177
|
+
const stillServed = store.db.prepare(`SELECT 1 FROM identity_devices WHERE device_id = ? AND status = 'active'
|
|
8178
|
+
UNION ALL SELECT 1 FROM sync_peers WHERE peer_device_id = ? LIMIT 1`);
|
|
8179
|
+
return removedLocally.every((deviceId) => !stillServed.get(deviceId, deviceId));
|
|
8180
|
+
}
|
|
8181
|
+
/** No draft of any state and no completed Team: discovery here only creates a draft. */
|
|
8182
|
+
function hasNoLocalSetup(store, candidateRef) {
|
|
8183
|
+
return getLegacyTeamSetupDraft(store.db, candidateRef) === null && !hasCompletedLegacyTeamSetup(store, candidateRef);
|
|
8184
|
+
}
|
|
8185
|
+
function summaryCandidateRef(group) {
|
|
8186
|
+
return legacyTeamCandidateId(group.coordinatorId, group.groupId);
|
|
8187
|
+
}
|
|
8188
|
+
/** Discovery for one group under its claim; a taken claim marks the group skipped. */
|
|
8189
|
+
async function discoverAfterReconciliation(store, group, dependencies, found, mayRepair = () => true) {
|
|
8190
|
+
const candidateRef = summaryCandidateRef(group);
|
|
8191
|
+
if (!await runCandidateMutation(store.db, candidateRef, async () => {
|
|
8192
|
+
if (!mayRepair()) return;
|
|
8193
|
+
const view = discoveredSummaryView(store, group, dependencies.mayRediscover);
|
|
8194
|
+
if (view) found.views.set(candidateRef, view);
|
|
8195
|
+
})) found.skipped.add(candidateRef);
|
|
8196
|
+
}
|
|
8197
|
+
/** The candidate view the summary lists for one group, discovering it when needed. */
|
|
8198
|
+
function discoveredSummaryView(store, group, mayRediscover) {
|
|
8199
|
+
const candidateRef = summaryCandidateRef(group);
|
|
8200
|
+
const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
|
|
8201
|
+
if (hasCompletedLegacyTeamSetup(store, candidateRef)) {
|
|
8202
|
+
if (!isLegacyTeamCandidateSelectable(store.db, candidateRef)) return null;
|
|
8203
|
+
} else if (draft && draft.state !== "completed") return candidateFromDraft(draft);
|
|
8204
|
+
const [view] = completedTeamDiscoveryAuthority.run(mayRediscover, () => discoverCandidates(store, [group]));
|
|
8205
|
+
return view ?? null;
|
|
8206
|
+
}
|
|
8207
|
+
/** A skipped group keeps what the previous pass found, so a busy route never clears it. */
|
|
8208
|
+
function carrySkippedGroups(result, previous) {
|
|
8209
|
+
for (const candidateRef of result.skipped) {
|
|
8210
|
+
result.blockers.delete(candidateRef);
|
|
8211
|
+
const blocker = previous?.blockers.get(candidateRef);
|
|
8212
|
+
if (blocker) result.blockers.set(candidateRef, blocker);
|
|
8213
|
+
const view = previous?.views.get(candidateRef);
|
|
8214
|
+
if (view) result.views.set(candidateRef, view);
|
|
8215
|
+
}
|
|
8216
|
+
return {
|
|
8217
|
+
...result,
|
|
8218
|
+
failed: new Set(result.blockers.keys())
|
|
8219
|
+
};
|
|
7774
8220
|
}
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
|
|
7778
|
-
|
|
8221
|
+
/** Candidates with an unfinished local draft, listed before the coordinator was ever checked. */
|
|
8222
|
+
function localDraftCandidateSummaries(store) {
|
|
8223
|
+
return store.db.prepare(`SELECT DISTINCT candidate_id FROM legacy_team_setup_drafts
|
|
8224
|
+
WHERE state <> 'completed' AND superseded_at IS NULL ORDER BY candidate_id`).pluck().all().flatMap((candidateRef) => {
|
|
8225
|
+
const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
|
|
8226
|
+
if (!draft || draft.state === "completed" || hasCompletedLegacyTeamSetup(store, candidateRef)) return [];
|
|
8227
|
+
const summary = candidateSummary(candidateFromDraft(draft));
|
|
8228
|
+
return summary.status === "ready" ? [] : [summary];
|
|
8229
|
+
});
|
|
8230
|
+
}
|
|
8231
|
+
/**
|
|
8232
|
+
* The summary from the last reconciliation pass, read from local state only. With
|
|
8233
|
+
* nothing checked yet and the latest check failed, the answer is that failure, as
|
|
8234
|
+
* when the summary checked inline.
|
|
8235
|
+
*/
|
|
8236
|
+
function summaryResponse(store, read) {
|
|
8237
|
+
if (!read.result && read.status.error_code) return { error: read.status.error_code };
|
|
7779
8238
|
return {
|
|
7780
8239
|
version: TEAM_SETUP_VERSION,
|
|
7781
|
-
candidates:
|
|
8240
|
+
candidates: read.result ? checkedCandidateSummaries(store, read.result) : localDraftCandidateSummaries(store),
|
|
8241
|
+
reconciliation: read.status
|
|
7782
8242
|
};
|
|
7783
8243
|
}
|
|
7784
|
-
|
|
7785
|
-
|
|
7786
|
-
const
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
|
|
7795
|
-
|
|
7796
|
-
|
|
7797
|
-
}
|
|
7798
|
-
existing.push(candidateFromDraft(draft));
|
|
8244
|
+
/** The summary, with what only an admin device is told. */
|
|
8245
|
+
function summaryForDevice(options, read) {
|
|
8246
|
+
const store = options.getStore();
|
|
8247
|
+
const summary = summaryResponse(store, read);
|
|
8248
|
+
if ("error" in summary) return summary;
|
|
8249
|
+
return withRecoverableTeams(store, summary, currentCompletionAuthorization(options));
|
|
8250
|
+
}
|
|
8251
|
+
/** What this device's configuration lets it read as a coordinator admin now, or null for nothing. */
|
|
8252
|
+
function currentCompletionAuthorization(options) {
|
|
8253
|
+
try {
|
|
8254
|
+
return readCompletionAuthorization(options);
|
|
8255
|
+
} catch {
|
|
8256
|
+
return null;
|
|
7799
8257
|
}
|
|
7800
|
-
|
|
8258
|
+
}
|
|
8259
|
+
/**
|
|
8260
|
+
* Names, for an admin device, the Team each candidate's recovery would restore:
|
|
8261
|
+
* the Team its setup completed, while that Team is disabled or a recovery of it
|
|
8262
|
+
* was saved and never confirmed, and only while the setup's coordinator and
|
|
8263
|
+
* group are the configured ones. Local reads only.
|
|
8264
|
+
*/
|
|
8265
|
+
function withRecoverableTeams(store, summary, authorization) {
|
|
8266
|
+
if (!authorization) return summary;
|
|
8267
|
+
const disabled = store.db.prepare(`SELECT 1 FROM policy_teams WHERE team_id = ? AND status = 'inactive'
|
|
8268
|
+
AND migration_state = 'needs_setup' AND provenance = 'reviewed_team_candidate'`).pluck();
|
|
8269
|
+
const candidates = summary.candidates.map((candidate) => {
|
|
8270
|
+
const teamId = deterministicPolicyTeamId(candidate.candidateRef);
|
|
8271
|
+
const target = disabled.get(teamId) || isRecoveryUnconfirmed(store, candidate.candidateRef) ? teamRecoveryTarget(store.db, teamId) : null;
|
|
8272
|
+
return target !== null && authorizesGroup(authorization, target) ? {
|
|
8273
|
+
...candidate,
|
|
8274
|
+
recoverableTeamId: teamId
|
|
8275
|
+
} : candidate;
|
|
8276
|
+
});
|
|
8277
|
+
return {
|
|
8278
|
+
...summary,
|
|
8279
|
+
candidates
|
|
8280
|
+
};
|
|
8281
|
+
}
|
|
8282
|
+
var RECOVERY_UNCONFIRMED = {
|
|
8283
|
+
code: "team_setup_completion_unavailable",
|
|
8284
|
+
reason: "team_recovery_unconfirmed"
|
|
8285
|
+
};
|
|
8286
|
+
/**
|
|
8287
|
+
* Whether the candidate's Team is active with a recovery that was saved and
|
|
8288
|
+
* never confirmed. Such a Team is on hold and shares nothing until another
|
|
8289
|
+
* recovery is confirmed. A recovery this process is still confirming does not count.
|
|
8290
|
+
*/
|
|
8291
|
+
function isRecoveryUnconfirmed(store, candidateRef) {
|
|
8292
|
+
const teamId = deterministicPolicyTeamId(candidateRef);
|
|
8293
|
+
return hasCompletedLegacyTeamSetup(store, candidateRef) && isTeamRecoveryHoldAbandoned(store.db, teamId, Date.now());
|
|
8294
|
+
}
|
|
8295
|
+
/**
|
|
8296
|
+
* The candidates the last pass found, with local drafts read again so edits show
|
|
8297
|
+
* at once. Reads only: discovery, which can write drafts and access, runs in the pass.
|
|
8298
|
+
*/
|
|
8299
|
+
function checkedCandidateSummaries(store, result) {
|
|
8300
|
+
return result.groups.flatMap((group) => {
|
|
8301
|
+
const candidateRef = summaryCandidateRef(group);
|
|
8302
|
+
const blocker = result.blockers.get(candidateRef);
|
|
8303
|
+
if (blocker) return [blockedCandidateSummary(store, group, blocker)];
|
|
8304
|
+
if (isRecoveryUnconfirmed(store, candidateRef)) return [blockedCandidateSummary(store, group, RECOVERY_UNCONFIRMED)];
|
|
8305
|
+
if (hasCompletedLegacyTeamSetup(store, candidateRef)) return [];
|
|
8306
|
+
const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
|
|
8307
|
+
const view = draft && draft.state !== "completed" ? candidateFromDraft(draft) : result.views.get(candidateRef);
|
|
8308
|
+
if (!view || view.status === "ready") return [];
|
|
8309
|
+
return [candidateSummary(view)];
|
|
8310
|
+
}).toSorted((left, right) => compareCandidateRefs(left.candidateRef, right.candidateRef));
|
|
8311
|
+
}
|
|
8312
|
+
function compareCandidateRefs(left, right) {
|
|
8313
|
+
if (left < right) return -1;
|
|
8314
|
+
return left > right ? 1 : 0;
|
|
8315
|
+
}
|
|
8316
|
+
/** The background check behind the summary, refreshed again when coordinator settings change. */
|
|
8317
|
+
function createSummaryReconciliation(options, loadSnapshots, reconcile) {
|
|
8318
|
+
const mayRediscover = (group) => {
|
|
8319
|
+
const authorization = readCompletionAuthorization(options);
|
|
8320
|
+
return Boolean(authorization && authorizesGroup(authorization, group));
|
|
8321
|
+
};
|
|
8322
|
+
const dependencies = {
|
|
8323
|
+
loadSnapshots,
|
|
8324
|
+
reconcile,
|
|
8325
|
+
mayRediscover,
|
|
8326
|
+
readRemovalsForRepair: (group) => readRemovalsForRepair(options, options.getStore(), group)
|
|
8327
|
+
};
|
|
8328
|
+
const reconciliation = createTeamSetupReconciliation({
|
|
8329
|
+
run: (previous) => runSummaryReconciliation(options.getStore(), dependencies, previous),
|
|
8330
|
+
assess: (result) => ({
|
|
8331
|
+
failedGroups: result.failed.size,
|
|
8332
|
+
skippedGroups: result.skipped.size,
|
|
8333
|
+
errorCode: result.blockers.values().next().value?.code ?? null
|
|
8334
|
+
}),
|
|
8335
|
+
retryDelayMs: options.reconciliationRetryDelayMs,
|
|
8336
|
+
errorCode: (error) => teamSetupFailure(error, "background GET /api/sync/team-setup/v1").code,
|
|
8337
|
+
record: (outcome) => recordReconciliationOutcome(options.getStore(), outcome)
|
|
8338
|
+
});
|
|
8339
|
+
options.registerReconciliation?.(reconciliation);
|
|
8340
|
+
options.registerSummaryInvalidator?.(() => {
|
|
8341
|
+
loadSnapshots.invalidate();
|
|
8342
|
+
reconciliation.refresh();
|
|
8343
|
+
});
|
|
8344
|
+
return reconciliation;
|
|
8345
|
+
}
|
|
8346
|
+
/** Shows each pass on the Health tab; a coordinator outage is not a failed job. */
|
|
8347
|
+
function recordReconciliationOutcome(store, outcome) {
|
|
8348
|
+
const checkedAt = outcome.checkedAtMs === null ? null : new Date(outcome.checkedAtMs).toISOString();
|
|
8349
|
+
const message = outcome.ok ? "Checked Team setup with the coordinator" : `Could not check Team setup with the coordinator (${outcome.errorCode}); showing the last check`;
|
|
8350
|
+
store.db.transaction(() => {
|
|
8351
|
+
startMaintenanceJob(store.db, {
|
|
8352
|
+
kind: TEAM_SETUP_RECONCILIATION_JOB,
|
|
8353
|
+
title: "Team setup check",
|
|
8354
|
+
status: "pending",
|
|
8355
|
+
message,
|
|
8356
|
+
metadata: {
|
|
8357
|
+
last_checked_at: checkedAt,
|
|
8358
|
+
last_error_code: outcome.errorCode
|
|
8359
|
+
}
|
|
8360
|
+
});
|
|
8361
|
+
completeMaintenanceJob(store.db, TEAM_SETUP_RECONCILIATION_JOB, { message });
|
|
8362
|
+
})();
|
|
7801
8363
|
}
|
|
7802
8364
|
function hasCompletedLegacyTeamSetup(store, candidateRef) {
|
|
7803
8365
|
return Boolean(store.db.prepare(`SELECT 1 FROM policy_teams
|
|
@@ -8223,6 +8785,36 @@ var TeamSetupFinishError = class extends Error {
|
|
|
8223
8785
|
}
|
|
8224
8786
|
};
|
|
8225
8787
|
/**
|
|
8788
|
+
* Records the group's Team member removals, then applies the coordinator's
|
|
8789
|
+
* winning completion, whether this request published it or recovered it after
|
|
8790
|
+
* a lost response. A removal recorded on another admin device must be known
|
|
8791
|
+
* before the completion runs. When the removals cannot be read, nothing is
|
|
8792
|
+
* applied here; reconciliation applies the published winner later.
|
|
8793
|
+
*/
|
|
8794
|
+
async function applyFinishWinnerAfterRemovals({ store, dependencies, config }, input) {
|
|
8795
|
+
const list = dependencies.listTeamMemberRemovals;
|
|
8796
|
+
if (list) {
|
|
8797
|
+
let removals;
|
|
8798
|
+
try {
|
|
8799
|
+
removals = await list({
|
|
8800
|
+
groupId: input.groupId,
|
|
8801
|
+
remoteUrl: buildBaseUrl(config.syncCoordinatorUrl),
|
|
8802
|
+
adminSecret: config.syncCoordinatorAdminSecret,
|
|
8803
|
+
timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
|
|
8804
|
+
});
|
|
8805
|
+
} catch (error) {
|
|
8806
|
+
throw new TeamSetupFinishError("team_setup_completion_unavailable", "team_member_removals_unavailable", false, error);
|
|
8807
|
+
}
|
|
8808
|
+
applyTeamMemberRemovals(store.db, {
|
|
8809
|
+
coordinatorId: input.coordinatorId,
|
|
8810
|
+
groupId: input.groupId,
|
|
8811
|
+
removals,
|
|
8812
|
+
now: (/* @__PURE__ */ new Date()).toISOString()
|
|
8813
|
+
});
|
|
8814
|
+
}
|
|
8815
|
+
return applyLegacyTeamSetupCompletionManifestAndReturnActivation(store.db, input);
|
|
8816
|
+
}
|
|
8817
|
+
/**
|
|
8226
8818
|
* The generic `legacy_team_setup_roster_too_large` string is thrown by ten
|
|
8227
8819
|
* sites for unrelated limits (coordinator roster size, draft device count,
|
|
8228
8820
|
* local project choices). Only the local project-candidate scan is a
|
|
@@ -8593,10 +9185,47 @@ function completionReadActions(dependencies, { authorization, store }, timeoutS,
|
|
|
8593
9185
|
listCompletionRecords,
|
|
8594
9186
|
removalReads: {
|
|
8595
9187
|
listRemovals,
|
|
8596
|
-
lookupPeerRemovals: peerRemovalReader(dependencies, store, config)
|
|
9188
|
+
lookupPeerRemovals: peerRemovalReader(dependencies, store, config),
|
|
9189
|
+
listTeamMemberRemovals: async (groupId) => {
|
|
9190
|
+
const read = dependencies.listTeamMemberRemovals;
|
|
9191
|
+
if (!read) return void 0;
|
|
9192
|
+
try {
|
|
9193
|
+
return await read({
|
|
9194
|
+
groupId,
|
|
9195
|
+
remoteUrl,
|
|
9196
|
+
adminSecret,
|
|
9197
|
+
timeoutS
|
|
9198
|
+
});
|
|
9199
|
+
} catch (error) {
|
|
9200
|
+
throw new TeamMemberRemovalsUnavailableError(error);
|
|
9201
|
+
}
|
|
9202
|
+
}
|
|
8597
9203
|
}
|
|
8598
9204
|
};
|
|
8599
9205
|
}
|
|
9206
|
+
/**
|
|
9207
|
+
* What applying a completion needs from the coordinator: device removal
|
|
9208
|
+
* evidence when an included device is missing, and always the group's Team
|
|
9209
|
+
* member removals. A removal recorded on another admin device must be known
|
|
9210
|
+
* before the completion runs, or applying it could make that person a member
|
|
9211
|
+
* again. A failed removal read throws, so nothing is applied.
|
|
9212
|
+
*/
|
|
9213
|
+
async function readCompletionEvidence(reads, groupId, includedDeviceMissing) {
|
|
9214
|
+
return {
|
|
9215
|
+
removalEvidence: includedDeviceMissing ? await readRemovalEvidence(reads) : {},
|
|
9216
|
+
teamMemberRemovals: await reads.listTeamMemberRemovals(groupId)
|
|
9217
|
+
};
|
|
9218
|
+
}
|
|
9219
|
+
/** Records the group's Team member removals, then applies the completion. */
|
|
9220
|
+
async function applyCompletionAfterTeamMemberRemovals(store, teamMemberRemovals, input) {
|
|
9221
|
+
if (teamMemberRemovals) applyTeamMemberRemovals(store.db, {
|
|
9222
|
+
coordinatorId: input.coordinatorId,
|
|
9223
|
+
groupId: input.groupId,
|
|
9224
|
+
removals: teamMemberRemovals,
|
|
9225
|
+
now: (/* @__PURE__ */ new Date()).toISOString()
|
|
9226
|
+
});
|
|
9227
|
+
await applyLegacyTeamSetupCompletionManifest(store.db, input);
|
|
9228
|
+
}
|
|
8600
9229
|
async function readRemovalEvidence(reads) {
|
|
8601
9230
|
return {
|
|
8602
9231
|
deviceRemovals: await reads.listRemovals(),
|
|
@@ -8655,7 +9284,7 @@ function teamSetupRoutes(options) {
|
|
|
8655
9284
|
}
|
|
8656
9285
|
}
|
|
8657
9286
|
const loadedSummarySnapshots = createLoadedSummarySnapshotCache(loadedSnapshots, options);
|
|
8658
|
-
options
|
|
9287
|
+
const reconciliation = createSummaryReconciliation(options, loadedSummarySnapshots, reconcileCompletions);
|
|
8659
9288
|
const completionDependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
|
|
8660
9289
|
const currentCompletionAuthorization = () => readCompletionAuthorization(options);
|
|
8661
9290
|
function hasDraftEditAuthority(store, candidateRef) {
|
|
@@ -8717,16 +9346,17 @@ function teamSetupRoutes(options) {
|
|
|
8717
9346
|
*/
|
|
8718
9347
|
async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster, reads) {
|
|
8719
9348
|
const freshIds = new Set(freshRoster.map((device) => device.deviceId));
|
|
8720
|
-
const
|
|
9349
|
+
const missing = manifest.device_decisions.some((device) => device.decision === "included" && !freshIds.has(device.device_id));
|
|
9350
|
+
const evidence = await readCompletionEvidence(reads, group.groupId, missing);
|
|
8721
9351
|
let outcome = "unauthorized";
|
|
8722
9352
|
return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
|
|
8723
9353
|
if (!stillAuthorizesGroup(authorization, group)) return;
|
|
8724
|
-
await
|
|
9354
|
+
await applyCompletionAfterTeamMemberRemovals(store, evidence.teamMemberRemovals, {
|
|
8725
9355
|
coordinatorId: group.coordinatorId,
|
|
8726
9356
|
groupId: group.groupId,
|
|
8727
9357
|
manifest,
|
|
8728
9358
|
freshRoster,
|
|
8729
|
-
...removalEvidence,
|
|
9359
|
+
...evidence.removalEvidence,
|
|
8730
9360
|
recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
|
|
8731
9361
|
});
|
|
8732
9362
|
outcome = "applied";
|
|
@@ -8986,17 +9616,10 @@ function teamSetupRoutes(options) {
|
|
|
8986
9616
|
groupId: row.group_id
|
|
8987
9617
|
};
|
|
8988
9618
|
}
|
|
8989
|
-
app.get("/api/sync/team-setup/v1",
|
|
8990
|
-
let groups;
|
|
9619
|
+
app.get("/api/sync/team-setup/v1", (c) => {
|
|
8991
9620
|
try {
|
|
8992
|
-
|
|
8993
|
-
|
|
8994
|
-
const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
|
|
8995
|
-
return c.json({ error: failure.code }, failure.status);
|
|
8996
|
-
}
|
|
8997
|
-
try {
|
|
8998
|
-
const response = await reconcileSummaryCandidates(options.getStore(), groups, reconcileCompletions);
|
|
8999
|
-
return c.json(response);
|
|
9621
|
+
const summary = summaryForDevice(options, reconciliation.read());
|
|
9622
|
+
return "error" in summary ? c.json(summary, errorStatus$1(summary.error)) : c.json(summary);
|
|
9000
9623
|
} catch (error) {
|
|
9001
9624
|
const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
|
|
9002
9625
|
return c.json({ error: failure.code }, failure.status);
|
|
@@ -9378,7 +10001,11 @@ function teamSetupRoutes(options) {
|
|
|
9378
10001
|
throw error;
|
|
9379
10002
|
}
|
|
9380
10003
|
if (!postPublicationGroup) throw new TeamSetupFinishError("team_setup_roster_unavailable", "coordinator_roster_unavailable", false, /* @__PURE__ */ new Error("coordinator roster unavailable"));
|
|
9381
|
-
const result = await
|
|
10004
|
+
const result = await applyFinishWinnerAfterRemovals({
|
|
10005
|
+
store,
|
|
10006
|
+
dependencies: completionDependencies,
|
|
10007
|
+
config
|
|
10008
|
+
}, {
|
|
9382
10009
|
coordinatorId: group.coordinatorId,
|
|
9383
10010
|
groupId: group.groupId,
|
|
9384
10011
|
freshRoster: postPublicationGroup.devices,
|
|
@@ -9557,7 +10184,31 @@ function tryParsePairingPayload(value) {
|
|
|
9557
10184
|
device_id: deviceId,
|
|
9558
10185
|
fingerprint,
|
|
9559
10186
|
public_key: publicKey,
|
|
9560
|
-
addresses
|
|
10187
|
+
addresses,
|
|
10188
|
+
payload: parsed
|
|
10189
|
+
};
|
|
10190
|
+
}
|
|
10191
|
+
/** Pins the payload's key and records what the payload says about Noise, together. */
|
|
10192
|
+
function savePairingPayload(store, pairing) {
|
|
10193
|
+
store.db.transaction(() => {
|
|
10194
|
+
updatePeerAddresses(store.db, pairing.device_id, pairing.addresses, {
|
|
10195
|
+
pinnedFingerprint: pairing.fingerprint,
|
|
10196
|
+
publicKey: pairing.public_key,
|
|
10197
|
+
replaceTrust: true
|
|
10198
|
+
});
|
|
10199
|
+
recordPairingTransportEvidence(store.db, pairing.device_id, pairing.payload);
|
|
10200
|
+
})();
|
|
10201
|
+
}
|
|
10202
|
+
/** The shared pairing payload plus the viewer's filter hint. */
|
|
10203
|
+
function pairingPayloadBody(input) {
|
|
10204
|
+
return {
|
|
10205
|
+
...buildPairingPayload({
|
|
10206
|
+
deviceId: input.deviceId,
|
|
10207
|
+
fingerprint: input.fingerprint,
|
|
10208
|
+
publicKey: input.publicKey ?? "",
|
|
10209
|
+
addresses: pairingAdvertiseAddresses(input.config)
|
|
10210
|
+
}),
|
|
10211
|
+
pairing_filter_hint: PAIRING_FILTER_HINT
|
|
9561
10212
|
};
|
|
9562
10213
|
}
|
|
9563
10214
|
async function inspectPairingInvite(c, next) {
|
|
@@ -10107,15 +10758,30 @@ function recipientPolicyCapabilityFromStatus(payload) {
|
|
|
10107
10758
|
if (!isScopedSyncCapability(normalizeSyncCapability(payload.sync_capability))) return "unsupported";
|
|
10108
10759
|
return supportsSyncFeature(payload.sync_features, "reassign_scope") ? "supported" : "unsupported";
|
|
10109
10760
|
}
|
|
10761
|
+
/** The probe reaches the peer through the shared transport policy, like a sync pass. */
|
|
10762
|
+
function peerStatusExecutor(store, peerDeviceId, localDeviceId) {
|
|
10763
|
+
const execute = peerTransportExecutor({
|
|
10764
|
+
db: store.db,
|
|
10765
|
+
peerDeviceId,
|
|
10766
|
+
localDeviceId,
|
|
10767
|
+
dbPath: store.dbPath,
|
|
10768
|
+
keysDir: syncKeysDir()
|
|
10769
|
+
});
|
|
10770
|
+
return (url, headers) => execute("GET", url, {
|
|
10771
|
+
operation: "status",
|
|
10772
|
+
headers,
|
|
10773
|
+
timeoutS: 5
|
|
10774
|
+
});
|
|
10775
|
+
}
|
|
10110
10776
|
async function peerSupportsSyncRequirements(store, deviceId, requirements) {
|
|
10111
10777
|
const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
10112
10778
|
if (deviceId === localDeviceId) return "supported";
|
|
10113
10779
|
const row = store.db.prepare("SELECT addresses_json, pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
|
|
10114
10780
|
const expectedFingerprint = String(row?.pinned_fingerprint ?? "").trim() || (row?.public_key ? fingerprintPublicKey(row.public_key) : "");
|
|
10115
|
-
const
|
|
10116
|
-
for (const address of
|
|
10781
|
+
const execute = peerStatusExecutor(store, deviceId, localDeviceId);
|
|
10782
|
+
for (const address of safeJsonList(row?.addresses_json ?? null)) try {
|
|
10117
10783
|
const url = `${buildBaseUrl(address)}/v1/status`;
|
|
10118
|
-
const
|
|
10784
|
+
const [status, payload] = await execute(url, {
|
|
10119
10785
|
...buildDirectPeerAuthHeaders({
|
|
10120
10786
|
deviceId: localDeviceId,
|
|
10121
10787
|
recipientId: deviceId,
|
|
@@ -10127,10 +10793,6 @@ async function peerSupportsSyncRequirements(store, deviceId, requirements) {
|
|
|
10127
10793
|
}),
|
|
10128
10794
|
[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,
|
|
10129
10795
|
[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(",")
|
|
10130
|
-
};
|
|
10131
|
-
const [status, payload] = await requestJson("GET", url, {
|
|
10132
|
-
headers,
|
|
10133
|
-
timeoutS: 5
|
|
10134
10796
|
});
|
|
10135
10797
|
if (status < 200 || status >= 300) continue;
|
|
10136
10798
|
if (String(payload?.device_id ?? "").trim() !== deviceId) continue;
|
|
@@ -10656,12 +11318,42 @@ async function completeCoordinatorEnrollment(context, initial, completeDeviceSet
|
|
|
10656
11318
|
if (!hasCanonicalOwnEnrollment(context, enrollments)) throw new Error(setup.kind === "unknown" ? "completion_outcome_unknown" : "device_setup_enrollment_incomplete");
|
|
10657
11319
|
return enrollments;
|
|
10658
11320
|
}
|
|
11321
|
+
/**
|
|
11322
|
+
* The group's Team member removals and the coordinator's binding of each Team
|
|
11323
|
+
* this check handles, each undefined when its read fails. Read after the
|
|
11324
|
+
* invitations: a removal recorded between the reads is still applied, so no
|
|
11325
|
+
* invitation in this snapshot restores that member. A failed read still
|
|
11326
|
+
* reconciles devices, but grants no Team access from an invitation, and
|
|
11327
|
+
* reconciliation reports each invitation it held back. Each Team's group comes
|
|
11328
|
+
* from its coordinator, never from its invitations.
|
|
11329
|
+
*/
|
|
11330
|
+
async function readTeamEvidence(store, options, input) {
|
|
11331
|
+
const { groupId, remoteUrl, adminSecret } = input;
|
|
11332
|
+
const listRemovals = options.listTeamMemberRemovals ?? coordinatorListTeamMemberRemovalsAction;
|
|
11333
|
+
const readBindings = options.readTeamGroupBindings ?? coordinatorReadTeamGroupBindingsAction;
|
|
11334
|
+
const teamMemberRemovals = await listRemovals({
|
|
11335
|
+
groupId,
|
|
11336
|
+
remoteUrl,
|
|
11337
|
+
adminSecret
|
|
11338
|
+
}).catch(() => void 0);
|
|
11339
|
+
const teamIds = teamIdsForBindingRead(store.db, {
|
|
11340
|
+
coordinatorId: buildBaseUrl(remoteUrl),
|
|
11341
|
+
invitedTeamIds: input.invites.filter((invite) => invite.group_id === groupId).map((invite) => invite.policy_team_id)
|
|
11342
|
+
});
|
|
11343
|
+
return {
|
|
11344
|
+
teamMemberRemovals,
|
|
11345
|
+
teamGroupBindings: teamIds.length === 0 ? [] : await readBindings({
|
|
11346
|
+
remoteUrl,
|
|
11347
|
+
adminSecret,
|
|
11348
|
+
teamIds
|
|
11349
|
+
}).catch(() => void 0)
|
|
11350
|
+
};
|
|
11351
|
+
}
|
|
10659
11352
|
async function reconcileConfiguredCoordinatorGroup(store, groupId, config, options) {
|
|
10660
11353
|
const remoteUrl = config.syncCoordinatorUrl.trim();
|
|
10661
11354
|
const adminSecret = config.syncCoordinatorAdminSecret.trim();
|
|
10662
11355
|
const listDevices = options.listDevices ?? coordinatorListDevicesAction;
|
|
10663
11356
|
const listInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
|
|
10664
|
-
const listRemovals = options.listTeamMemberRemovals ?? coordinatorListTeamMemberRemovalsAction;
|
|
10665
11357
|
const reconcile = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
|
|
10666
11358
|
let stage = "complete_device_setup";
|
|
10667
11359
|
try {
|
|
@@ -10689,11 +11381,12 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
|
|
|
10689
11381
|
remoteUrl,
|
|
10690
11382
|
adminSecret
|
|
10691
11383
|
});
|
|
10692
|
-
const teamMemberRemovals = await
|
|
11384
|
+
const { teamMemberRemovals, teamGroupBindings } = await readTeamEvidence(store, options, {
|
|
10693
11385
|
groupId,
|
|
10694
11386
|
remoteUrl,
|
|
10695
|
-
adminSecret
|
|
10696
|
-
|
|
11387
|
+
adminSecret,
|
|
11388
|
+
invites
|
|
11389
|
+
});
|
|
10697
11390
|
stage = "complete_device_setup";
|
|
10698
11391
|
context.assertCurrent();
|
|
10699
11392
|
stage = "reconcile_snapshot";
|
|
@@ -10703,6 +11396,7 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
|
|
|
10703
11396
|
enrollments,
|
|
10704
11397
|
consumedTeamInvites: invites,
|
|
10705
11398
|
teamMemberRemovals,
|
|
11399
|
+
teamGroupBindings,
|
|
10706
11400
|
localDeviceId: store.deviceId
|
|
10707
11401
|
}) };
|
|
10708
11402
|
} catch (error) {
|
|
@@ -10734,6 +11428,22 @@ async function loadAllGroupsDeviceIdentityCoordinatorEvidence(options = {}) {
|
|
|
10734
11428
|
return unavailable("coordinator_unavailable");
|
|
10735
11429
|
}
|
|
10736
11430
|
}
|
|
11431
|
+
/** Group IDs may hold any text, so lists are compared entry by entry. */
|
|
11432
|
+
function sameGroups(current, fetched) {
|
|
11433
|
+
return current.length === fetched.length && current.every((group, i) => group === fetched[i]);
|
|
11434
|
+
}
|
|
11435
|
+
/**
|
|
11436
|
+
* Whether the coordinator, groups and admin secret are still the ones the evidence
|
|
11437
|
+
* was fetched with. The fetch can outlast a change, so the write checks this.
|
|
11438
|
+
*/
|
|
11439
|
+
function sameCoordinatorAuthority(readConfig, fetchedWith) {
|
|
11440
|
+
try {
|
|
11441
|
+
const current = readConfig();
|
|
11442
|
+
return current.syncCoordinatorUrl === fetchedWith.syncCoordinatorUrl && current.syncCoordinatorAdminSecret === fetchedWith.syncCoordinatorAdminSecret && sameGroups(current.syncCoordinatorGroups, fetchedWith.syncCoordinatorGroups);
|
|
11443
|
+
} catch {
|
|
11444
|
+
return false;
|
|
11445
|
+
}
|
|
11446
|
+
}
|
|
10737
11447
|
/**
|
|
10738
11448
|
* Runs the one-time conversion of the person assigned on pairings into Identity
|
|
10739
11449
|
* bindings. It runs after enrollment reconciliation, so a binding the coordinator
|
|
@@ -10746,13 +11456,17 @@ async function convertLegacyPairingAssignmentsOperation(store, options = {}) {
|
|
|
10746
11456
|
status: "already_converted",
|
|
10747
11457
|
waitingReason: null
|
|
10748
11458
|
};
|
|
10749
|
-
const
|
|
11459
|
+
const readConfig = options.readConfig ?? readCoordinatorSyncConfig;
|
|
11460
|
+
const load = options.loadCoordinatorEvidence ?? ((config) => loadAllGroupsDeviceIdentityCoordinatorEvidence({ config }));
|
|
11461
|
+
const fetchedWith = readConfig();
|
|
11462
|
+
const coordinator = await load(fetchedWith);
|
|
10750
11463
|
try {
|
|
10751
11464
|
const { status, waitingReason } = convertLegacyPairingAssignments(store.db, {
|
|
10752
11465
|
localActorId: store.actorId,
|
|
10753
11466
|
localDeviceId: store.deviceId,
|
|
10754
11467
|
coordinator,
|
|
10755
|
-
ensureLocalIdentity: () => ensureLocalActorRecord(store)
|
|
11468
|
+
ensureLocalIdentity: () => ensureLocalActorRecord(store),
|
|
11469
|
+
authorityStillHolds: () => sameCoordinatorAuthority(readConfig, fetchedWith)
|
|
10756
11470
|
});
|
|
10757
11471
|
return {
|
|
10758
11472
|
status,
|
|
@@ -11123,7 +11837,12 @@ function summarizeMaintenanceJobs(jobs, showDiagnostics) {
|
|
|
11123
11837
|
}
|
|
11124
11838
|
function redactSemanticIndexDiagnostics(diagnostics, showDiagnostics) {
|
|
11125
11839
|
if (showDiagnostics || !diagnostics.maintenance_job) return diagnostics;
|
|
11126
|
-
const
|
|
11840
|
+
const job = diagnostics.maintenance_job;
|
|
11841
|
+
const summary = {
|
|
11842
|
+
failed: "Semantic-index catch-up failed",
|
|
11843
|
+
degraded: "Semantic index is running in degraded mode",
|
|
11844
|
+
...job.status === "pending" || job.status === "running" ? { pending: "Semantic-index catch-up is pending" } : {}
|
|
11845
|
+
}[diagnostics.state] ?? diagnostics.summary;
|
|
11127
11846
|
return {
|
|
11128
11847
|
...diagnostics,
|
|
11129
11848
|
summary,
|
|
@@ -11301,16 +12020,6 @@ function recordDirectPeerSignatureVersion(store, deviceId, version) {
|
|
|
11301
12020
|
throw err;
|
|
11302
12021
|
}
|
|
11303
12022
|
}
|
|
11304
|
-
function matchesSyncChannelPeer(request, publicKey, readPin) {
|
|
11305
|
-
if (!request || request.signal.aborted) return false;
|
|
11306
|
-
try {
|
|
11307
|
-
const [algorithm, blob] = publicKey.split(/\s+/);
|
|
11308
|
-
const pin = readPin(request);
|
|
11309
|
-
return algorithm === "ssh-ed25519" && !!blob && !!pin && pin === `${algorithm} ${blob}`;
|
|
11310
|
-
} catch {
|
|
11311
|
-
return false;
|
|
11312
|
-
}
|
|
11313
|
-
}
|
|
11314
12023
|
function checkedCurrentPeerKey(store, deviceId) {
|
|
11315
12024
|
const peerRow = store.db.prepare(`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,
|
|
11316
12025
|
sync_peer_signature_state.highest_observed_direct_signature_version
|
|
@@ -11340,7 +12049,19 @@ function checkedCurrentPeerKey(store, deviceId) {
|
|
|
11340
12049
|
highestObservedVersion: peerRow.highest_observed_direct_signature_version
|
|
11341
12050
|
};
|
|
11342
12051
|
}
|
|
11343
|
-
function
|
|
12052
|
+
function plaintextTransportGate(mode) {
|
|
12053
|
+
if (!noiseActive(mode)) return void 0;
|
|
12054
|
+
return (store, deviceId, request) => !marksNoiseStatusTarget(request) && readPeerTransportPolicy(store.db, deviceId) === "noise_required";
|
|
12055
|
+
}
|
|
12056
|
+
/**
|
|
12057
|
+
* A status request marked transport=noise1 inside its signed target. A grant
|
|
12058
|
+
* worker needs this one plaintext answer, the pin only, before Noise can admit it.
|
|
12059
|
+
*/
|
|
12060
|
+
function marksNoiseStatusTarget(request) {
|
|
12061
|
+
const url = new URL(request.url, "http://sync.invalid");
|
|
12062
|
+
return request.method === "GET" && url.pathname === "/v1/status" && url.searchParams.get("transport") === "noise1";
|
|
12063
|
+
}
|
|
12064
|
+
function authorizeSyncRequest(store, request, body, binding, transportGate) {
|
|
11344
12065
|
const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
|
|
11345
12066
|
const signature = request.header("X-Opencode-Signature") ?? "";
|
|
11346
12067
|
const timestamp = request.header("X-Opencode-Timestamp") ?? "";
|
|
@@ -11353,7 +12074,7 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
|
|
|
11353
12074
|
const peer = checkedCurrentPeerKey(store, deviceId);
|
|
11354
12075
|
if (!peer.ok) return peer;
|
|
11355
12076
|
const { publicKey } = peer;
|
|
11356
|
-
if (
|
|
12077
|
+
if (binding !== void 0 && !binding(request.raw, deviceId, publicKey)) return {
|
|
11357
12078
|
ok: false,
|
|
11358
12079
|
reason: "channel_binding_mismatch",
|
|
11359
12080
|
deviceId
|
|
@@ -11366,7 +12087,7 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
|
|
|
11366
12087
|
publicKey,
|
|
11367
12088
|
expectedRecipientId: localDeviceId,
|
|
11368
12089
|
highestObservedVersion: peer.highestObservedVersion,
|
|
11369
|
-
requireDirectSignature:
|
|
12090
|
+
requireDirectSignature: binding !== void 0
|
|
11370
12091
|
});
|
|
11371
12092
|
} catch {
|
|
11372
12093
|
return {
|
|
@@ -11380,14 +12101,48 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
|
|
|
11380
12101
|
reason: verification.reason,
|
|
11381
12102
|
deviceId
|
|
11382
12103
|
};
|
|
12104
|
+
if (transportGate?.(store, deviceId, request)) return {
|
|
12105
|
+
ok: false,
|
|
12106
|
+
reason: "transport_downgrade_refused",
|
|
12107
|
+
deviceId
|
|
12108
|
+
};
|
|
11383
12109
|
const nonceResult = recordSyncAuthNonce(store, deviceId, nonce, (/* @__PURE__ */ new Date()).toISOString());
|
|
11384
12110
|
if (nonceResult) return nonceResult;
|
|
11385
|
-
|
|
11386
|
-
|
|
11387
|
-
if (versionResult) return versionResult;
|
|
11388
|
-
}
|
|
12111
|
+
const versionResult = recordAdoptedSignatureVersion(store, deviceId, verification, binding);
|
|
12112
|
+
if (versionResult) return versionResult;
|
|
11389
12113
|
return authenticatedSyncPeer(deviceId, publicKey);
|
|
11390
12114
|
}
|
|
12115
|
+
/** Records that the peer now signs with v3, unless the binding defers that to later traffic. */
|
|
12116
|
+
function recordAdoptedSignatureVersion(store, deviceId, verification, binding) {
|
|
12117
|
+
if (verification.version !== DIRECT_PEER_SIGNATURE_VERSION_NUMBER) return null;
|
|
12118
|
+
if (binding?.deferSignatureAdoption) return null;
|
|
12119
|
+
return recordDirectPeerSignatureVersion(store, deviceId, verification.version);
|
|
12120
|
+
}
|
|
12121
|
+
/**
|
|
12122
|
+
* No channel exists before the upgrade, so the only binding demanded is the v3
|
|
12123
|
+
* signature. Its adoption is recorded later, by the authenticated inner traffic.
|
|
12124
|
+
*/
|
|
12125
|
+
var REQUIRE_DIRECT_SIGNATURE = Object.assign(() => true, { deferSignatureAdoption: true });
|
|
12126
|
+
/**
|
|
12127
|
+
* Authorizes a direct Noise upgrade before any Noise byte is sent: a pinned
|
|
12128
|
+
* device, its current key, a fresh nonce, and a recipient-bound v3 signature
|
|
12129
|
+
* over the exact target. Bootstrap grants are never accepted here.
|
|
12130
|
+
*/
|
|
12131
|
+
function authorizeDirectNoiseUpgrade(store, request) {
|
|
12132
|
+
const auth = authorizeSyncRequest(store, request, Buffer.alloc(0), REQUIRE_DIRECT_SIGNATURE);
|
|
12133
|
+
if (!auth.ok) {
|
|
12134
|
+
logDirectPeerAuthDiagnostic(auth.reason);
|
|
12135
|
+
return {
|
|
12136
|
+
ok: false,
|
|
12137
|
+
busy: isSyncAuthStoreBusy(auth)
|
|
12138
|
+
};
|
|
12139
|
+
}
|
|
12140
|
+
return {
|
|
12141
|
+
ok: true,
|
|
12142
|
+
deviceId: auth.deviceId,
|
|
12143
|
+
publicKey: auth.authenticatedPeerSigningKey
|
|
12144
|
+
};
|
|
12145
|
+
}
|
|
11391
12146
|
function bootstrapPayloadRecord(value) {
|
|
11392
12147
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
11393
12148
|
}
|
|
@@ -11445,6 +12200,34 @@ function bootstrapGrantFailureReason(store, verification, request) {
|
|
|
11445
12200
|
if (scopeId !== void 0 && !isBootstrapGrantGroupScope(store, scopeId, grant, request.config.syncCoordinatorUrl)) return "bootstrap_grant_scope_outside_group";
|
|
11446
12201
|
return null;
|
|
11447
12202
|
}
|
|
12203
|
+
/** The coordinator's record of a bootstrap grant, or null when no lookup succeeds. */
|
|
12204
|
+
async function lookupBootstrapGrant(store, config, grantId, localDeviceId) {
|
|
12205
|
+
const base = buildBaseUrl(config.syncCoordinatorUrl);
|
|
12206
|
+
const timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);
|
|
12207
|
+
if (config.syncCoordinatorAdminSecret) {
|
|
12208
|
+
const [status, adminPayload] = await requestJson("GET", `${base}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`, {
|
|
12209
|
+
headers: { "X-Codemem-Coordinator-Admin": config.syncCoordinatorAdminSecret },
|
|
12210
|
+
timeoutS
|
|
12211
|
+
});
|
|
12212
|
+
return status === 200 ? adminPayload : null;
|
|
12213
|
+
}
|
|
12214
|
+
for (const groupId of config.syncCoordinatorGroups) {
|
|
12215
|
+
const lookupUrl = `${base}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;
|
|
12216
|
+
const [status, signedPayload] = await requestJson("GET", lookupUrl, {
|
|
12217
|
+
headers: buildAuthHeaders({
|
|
12218
|
+
deviceId: localDeviceId,
|
|
12219
|
+
dbPath: store.dbPath,
|
|
12220
|
+
method: "GET",
|
|
12221
|
+
url: lookupUrl,
|
|
12222
|
+
bodyBytes: Buffer.alloc(0),
|
|
12223
|
+
keysDir: syncKeysDir()
|
|
12224
|
+
}),
|
|
12225
|
+
timeoutS
|
|
12226
|
+
});
|
|
12227
|
+
if (status === 200) return signedPayload;
|
|
12228
|
+
}
|
|
12229
|
+
return null;
|
|
12230
|
+
}
|
|
11448
12231
|
async function authorizeBootstrapGrantRequest(store, request, body, options = {}) {
|
|
11449
12232
|
const grantId = (request.header("X-Codemem-Bootstrap-Grant") ?? "").trim();
|
|
11450
12233
|
const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
|
|
@@ -11466,31 +12249,7 @@ async function authorizeBootstrapGrantRequest(store, request, body, options = {}
|
|
|
11466
12249
|
let verification;
|
|
11467
12250
|
try {
|
|
11468
12251
|
[localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
11469
|
-
|
|
11470
|
-
if (config.syncCoordinatorAdminSecret) {
|
|
11471
|
-
const [status, adminPayload] = await requestJson("GET", `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`, {
|
|
11472
|
-
headers: { "X-Codemem-Coordinator-Admin": config.syncCoordinatorAdminSecret },
|
|
11473
|
-
timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
|
|
11474
|
-
});
|
|
11475
|
-
if (status === 200) payload = adminPayload;
|
|
11476
|
-
} else for (const groupId of config.syncCoordinatorGroups) {
|
|
11477
|
-
const lookupUrl = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;
|
|
11478
|
-
const [status, signedPayload] = await requestJson("GET", lookupUrl, {
|
|
11479
|
-
headers: buildAuthHeaders({
|
|
11480
|
-
deviceId: localDeviceId,
|
|
11481
|
-
dbPath: store.dbPath,
|
|
11482
|
-
method: "GET",
|
|
11483
|
-
url: lookupUrl,
|
|
11484
|
-
bodyBytes: Buffer.alloc(0),
|
|
11485
|
-
keysDir: syncKeysDir()
|
|
11486
|
-
}),
|
|
11487
|
-
timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
|
|
11488
|
-
});
|
|
11489
|
-
if (status === 200) {
|
|
11490
|
-
payload = signedPayload;
|
|
11491
|
-
break;
|
|
11492
|
-
}
|
|
11493
|
-
}
|
|
12252
|
+
const payload = await lookupBootstrapGrant(store, config, grantId, localDeviceId);
|
|
11494
12253
|
if (!payload) return {
|
|
11495
12254
|
ok: false,
|
|
11496
12255
|
reason: "bootstrap_grant_lookup_failed",
|
|
@@ -11550,20 +12309,84 @@ async function authorizeBootstrapGrantRequest(store, request, body, options = {}
|
|
|
11550
12309
|
reason: "bootstrap_grant_peer_trust_conflict",
|
|
11551
12310
|
deviceId
|
|
11552
12311
|
};
|
|
12312
|
+
if (options.transportGate?.(store, deviceId, request)) return {
|
|
12313
|
+
ok: false,
|
|
12314
|
+
reason: "transport_downgrade_refused",
|
|
12315
|
+
deviceId
|
|
12316
|
+
};
|
|
11553
12317
|
const nonceResult = recordSyncAuthNonce(store, deviceId, nonce, (/* @__PURE__ */ new Date()).toISOString());
|
|
11554
12318
|
if (nonceResult) return nonceResult;
|
|
11555
|
-
|
|
11556
|
-
name: workerEnrollment.display_name?.trim() || void 0,
|
|
11557
|
-
pinnedFingerprint: workerFingerprint,
|
|
11558
|
-
publicKey: workerPublicKey,
|
|
11559
|
-
replaceTrust: true
|
|
11560
|
-
});
|
|
12319
|
+
pinBootstrapGrantPeer(store.db, deviceId, workerEnrollment);
|
|
11561
12320
|
if (signatureVerification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {
|
|
11562
12321
|
const versionResult = recordDirectPeerSignatureVersion(store, deviceId, signatureVerification.version);
|
|
11563
12322
|
if (versionResult) return versionResult;
|
|
11564
12323
|
}
|
|
11565
12324
|
return authenticatedSyncPeer(deviceId, workerPublicKey);
|
|
11566
12325
|
}
|
|
12326
|
+
/**
|
|
12327
|
+
* The pin names no group, so the coordinator history alone records that a coordinator
|
|
12328
|
+
* vouched for this device. Both are written together, or neither is.
|
|
12329
|
+
*/
|
|
12330
|
+
var COORDINATOR_JOIN_CONFIRMATION = {
|
|
12331
|
+
error: COORDINATOR_JOIN_CONFIRMATION_REQUIRED,
|
|
12332
|
+
detail: "Joining a coordinator permanently turns off syncing without a coordinator for this device's key, including other codemem profiles that use the same key."
|
|
12333
|
+
};
|
|
12334
|
+
var COORDINATOR_RECORD_UNVERIFIED = {
|
|
12335
|
+
error: COORDINATOR_FREE_BINDING_UNVERIFIED,
|
|
12336
|
+
detail: "codemem couldn't check this device's coordinator record because a file in the codemem keys folder is missing or damaged. Restore the keys folder that belongs with this database, then try again."
|
|
12337
|
+
};
|
|
12338
|
+
var COORDINATOR_RECORD_UNAVAILABLE = {
|
|
12339
|
+
error: COORDINATOR_FREE_WITNESS_UNAVAILABLE,
|
|
12340
|
+
detail: "codemem couldn't save this device's coordinator record. Unlock or repair the keychain, or make the codemem keys folder writable, then try again."
|
|
12341
|
+
};
|
|
12342
|
+
/** The status and body for a failed invitation import. */
|
|
12343
|
+
function inviteImportFailureResponse(error, invite) {
|
|
12344
|
+
const code = error instanceof Error ? error.message : String(error);
|
|
12345
|
+
if (code === COORDINATOR_JOIN_CONFIRMATION_REQUIRED) return {
|
|
12346
|
+
status: 409,
|
|
12347
|
+
body: COORDINATOR_JOIN_CONFIRMATION
|
|
12348
|
+
};
|
|
12349
|
+
if (code === COORDINATOR_FREE_WITNESS_UNAVAILABLE) return {
|
|
12350
|
+
status: 503,
|
|
12351
|
+
body: COORDINATOR_RECORD_UNAVAILABLE
|
|
12352
|
+
};
|
|
12353
|
+
if (code === COORDINATOR_FREE_BINDING_UNVERIFIED) return {
|
|
12354
|
+
status: 503,
|
|
12355
|
+
body: COORDINATOR_RECORD_UNVERIFIED
|
|
12356
|
+
};
|
|
12357
|
+
if (invite.projectInvite) return {
|
|
12358
|
+
status: 400,
|
|
12359
|
+
body: projectInviteAcceptanceFailure(error)
|
|
12360
|
+
};
|
|
12361
|
+
if (invite.recipientInvite) return {
|
|
12362
|
+
status: 400,
|
|
12363
|
+
body: { error: safeRecipientInviteError(error) }
|
|
12364
|
+
};
|
|
12365
|
+
return {
|
|
12366
|
+
status: 400,
|
|
12367
|
+
body: { error: code }
|
|
12368
|
+
};
|
|
12369
|
+
}
|
|
12370
|
+
function inviteImportFailure(c, error, invite) {
|
|
12371
|
+
const { status, body } = inviteImportFailureResponse(error, invite);
|
|
12372
|
+
return c.json(body, status);
|
|
12373
|
+
}
|
|
12374
|
+
function pinBootstrapGrantPeer(db, deviceId, enrollment) {
|
|
12375
|
+
markCoordinatorManaged(db, { keysDir: syncKeysDir() });
|
|
12376
|
+
db.transaction(() => {
|
|
12377
|
+
recordDeviceCoordinatorHistory(db, {
|
|
12378
|
+
deviceId,
|
|
12379
|
+
fingerprint: enrollment.fingerprint,
|
|
12380
|
+
source: "bootstrap_grant"
|
|
12381
|
+
});
|
|
12382
|
+
updatePeerAddresses(db, deviceId, [], {
|
|
12383
|
+
name: enrollment.display_name?.trim() || void 0,
|
|
12384
|
+
pinnedFingerprint: enrollment.fingerprint,
|
|
12385
|
+
publicKey: enrollment.public_key,
|
|
12386
|
+
replaceTrust: true
|
|
12387
|
+
});
|
|
12388
|
+
})();
|
|
12389
|
+
}
|
|
11567
12390
|
function parseJsonList(value) {
|
|
11568
12391
|
if (value == null) return [];
|
|
11569
12392
|
if (typeof value === "string") try {
|
|
@@ -11640,16 +12463,30 @@ function peerAuthorizedScopes(store, peerDeviceId) {
|
|
|
11640
12463
|
function isPendingCaptureActorConflict(error) {
|
|
11641
12464
|
return error instanceof Error && error.constructor === Error && error.message === "device_adoption_actor_conflict";
|
|
11642
12465
|
}
|
|
12466
|
+
/**
|
|
12467
|
+
* Whether this device's identity may claim its actor row. Throws when another
|
|
12468
|
+
* process retired the identity; false preserves a pending capture conflict.
|
|
12469
|
+
*/
|
|
12470
|
+
function localIdentityMayClaimActor(store) {
|
|
12471
|
+
store.assertLocalIdentityCurrent();
|
|
12472
|
+
try {
|
|
12473
|
+
store.assertPendingLocalCaptureAdoptionActors();
|
|
12474
|
+
} catch (error) {
|
|
12475
|
+
if (isPendingCaptureActorConflict(error)) return false;
|
|
12476
|
+
throw error;
|
|
12477
|
+
}
|
|
12478
|
+
return true;
|
|
12479
|
+
}
|
|
12480
|
+
/** Exactly one local actor row, and it is this device's actor: the state the repair writes. */
|
|
12481
|
+
function localActorRecordCurrent(store) {
|
|
12482
|
+
const rows = store.db.prepare("SELECT actor_id, is_local FROM actors WHERE is_local = 1 OR actor_id = ?").all(store.actorId);
|
|
12483
|
+
return rows.length === 1 && rows[0]?.actor_id === store.actorId && rows[0]?.is_local === 1;
|
|
12484
|
+
}
|
|
11643
12485
|
/** False leaves the conflict untouched; callers must check before claiming or merging identity. */
|
|
11644
12486
|
function ensureLocalActorRecord(store) {
|
|
12487
|
+
if (!store.hasPendingLocalCapture() && localActorRecordCurrent(store)) return localIdentityMayClaimActor(store);
|
|
11645
12488
|
return store.db.transaction(() => {
|
|
11646
|
-
store
|
|
11647
|
-
try {
|
|
11648
|
-
store.assertPendingLocalCaptureAdoptionActors();
|
|
11649
|
-
} catch (error) {
|
|
11650
|
-
if (isPendingCaptureActorConflict(error)) return false;
|
|
11651
|
-
throw error;
|
|
11652
|
-
}
|
|
12489
|
+
if (!localIdentityMayClaimActor(store)) return false;
|
|
11653
12490
|
persistLocalActorRecord(store);
|
|
11654
12491
|
return true;
|
|
11655
12492
|
}).immediate();
|
|
@@ -11696,6 +12533,41 @@ function ensureStableStoreIdentityForRead(store) {
|
|
|
11696
12533
|
ensureLocalActorRecord(store);
|
|
11697
12534
|
return deviceId;
|
|
11698
12535
|
}
|
|
12536
|
+
var DEVICE_IDENTITY_UNAVAILABLE = {
|
|
12537
|
+
device_identity_missing: "This device's sync identity isn't set up yet. Nothing changed. Open Devices once to finish setting it up, then try again.",
|
|
12538
|
+
device_identity_ambiguous: "This database has more than one device identity, so codemem can't tell which device the change is for. Nothing changed. Report this as a codemem issue."
|
|
12539
|
+
};
|
|
12540
|
+
var DeviceIdentityUnavailableError = class extends Error {
|
|
12541
|
+
code;
|
|
12542
|
+
constructor(code) {
|
|
12543
|
+
super(code);
|
|
12544
|
+
this.code = code;
|
|
12545
|
+
}
|
|
12546
|
+
};
|
|
12547
|
+
/**
|
|
12548
|
+
* The one device identity this store already has and runs as. Mapping changes
|
|
12549
|
+
* analyze and write for the same device, so they never create or adopt an
|
|
12550
|
+
* identity or pick one of several: each would change which device the confirmed
|
|
12551
|
+
* guardrails were for. A store that still runs as the placeholder device has not
|
|
12552
|
+
* adopted its identity yet; loading Devices does that.
|
|
12553
|
+
*/
|
|
12554
|
+
function requireExistingDeviceIdentity(store) {
|
|
12555
|
+
const rows = store.db.prepare("SELECT device_id FROM sync_device LIMIT 2").pluck().all();
|
|
12556
|
+
if (rows.length === 0 || store.deviceId === "local") throw new DeviceIdentityUnavailableError("device_identity_missing");
|
|
12557
|
+
const [only] = rows;
|
|
12558
|
+
if (rows.length > 1 || only !== store.deviceId) throw new DeviceIdentityUnavailableError("device_identity_ambiguous");
|
|
12559
|
+
return store.deviceId;
|
|
12560
|
+
}
|
|
12561
|
+
/** Thrown inside a mapping write when the guardrails no longer match what was confirmed. */
|
|
12562
|
+
var MappingGuardrailsChangedError = class extends Error {
|
|
12563
|
+
warnings;
|
|
12564
|
+
missing;
|
|
12565
|
+
constructor(warnings, missing) {
|
|
12566
|
+
super("guardrail_confirmation_required");
|
|
12567
|
+
this.warnings = warnings;
|
|
12568
|
+
this.missing = missing;
|
|
12569
|
+
}
|
|
12570
|
+
};
|
|
11699
12571
|
function ensureStableStoreDeviceIdentity(store) {
|
|
11700
12572
|
const [deviceId] = ensureStableStoreDeviceIdentityWithFingerprint(store);
|
|
11701
12573
|
return deviceId;
|
|
@@ -12448,8 +13320,9 @@ function legacySharedReviewReassignmentPreview(store, input) {
|
|
|
12448
13320
|
workspace_identity: input.workspaceIdentity
|
|
12449
13321
|
};
|
|
12450
13322
|
}
|
|
12451
|
-
function reassignLegacySharedReviewGroup(store, input) {
|
|
13323
|
+
function reassignLegacySharedReviewGroup(store, input, stillAllowed) {
|
|
12452
13324
|
return store.db.transaction(() => {
|
|
13325
|
+
if (!stillAllowed()) throw new Error("access_change_needs_admin_device");
|
|
12453
13326
|
const preview = legacySharedReviewReassignmentPreview(store, input);
|
|
12454
13327
|
if (input.confirmationToken !== preview.confirmation_token) throw new Error("legacy shared review group changed before reassignment; refresh and try again");
|
|
12455
13328
|
const rows = reassignableLegacySharedReviewRows(store, legacySharedReviewRowsForWorkspace(store, input.workspaceIdentity));
|
|
@@ -12535,7 +13408,8 @@ function attemptStatus(attempt) {
|
|
|
12535
13408
|
}
|
|
12536
13409
|
function readViewerBinding(dbPath) {
|
|
12537
13410
|
try {
|
|
12538
|
-
const raw =
|
|
13411
|
+
const raw = readViewerPidFile(dbPath);
|
|
13412
|
+
if (raw === null) return null;
|
|
12539
13413
|
const parsed = JSON.parse(raw);
|
|
12540
13414
|
if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
|
|
12541
13415
|
host: parsed.host,
|
|
@@ -12699,7 +13573,17 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
|
|
|
12699
13573
|
const reason = peerFacingScopeResetReason(failure.reason);
|
|
12700
13574
|
const scopeId = (/* @__PURE__ */ new Set([options.scopeId, ...ops.map(cleanOpScopeId)])).has(failure.scopeId) ? failure.scopeId : options.scopeId;
|
|
12701
13575
|
if (reason !== failure.reason || scopeId !== failure.scopeId) logWithheldScopeDenial(failure.reason, failure.scopeId);
|
|
12702
|
-
return c.json(
|
|
13576
|
+
return c.json(peerFacingScopeReset(reason, scopeId), 409);
|
|
13577
|
+
}
|
|
13578
|
+
/** A scope refusal that tells the peer nothing about this device's default stream. */
|
|
13579
|
+
function peerFacingScopeReset(reason, scopeId) {
|
|
13580
|
+
return {
|
|
13581
|
+
error: "reset_required",
|
|
13582
|
+
reset_required: true,
|
|
13583
|
+
sync_capability: LOCAL_SYNC_CAPABILITY,
|
|
13584
|
+
reason,
|
|
13585
|
+
scope_id: scopeId
|
|
13586
|
+
};
|
|
12703
13587
|
}
|
|
12704
13588
|
/** Records locally what a scope denial withheld from the peer's answer. */
|
|
12705
13589
|
function logWithheldScopeDenial(reason, scopeId) {
|
|
@@ -12724,7 +13608,7 @@ function recordInboundScopeFailure(context) {
|
|
|
12724
13608
|
});
|
|
12725
13609
|
}
|
|
12726
13610
|
function parseInboundScopeRequest(body, context, options) {
|
|
12727
|
-
return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.
|
|
13611
|
+
return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.requireScope), {
|
|
12728
13612
|
...context,
|
|
12729
13613
|
negotiatedCapability: options.negotiated
|
|
12730
13614
|
});
|
|
@@ -12738,14 +13622,15 @@ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
|
|
|
12738
13622
|
try {
|
|
12739
13623
|
const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
|
|
12740
13624
|
const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
12741
|
-
const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.
|
|
13625
|
+
const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.requireScope), {
|
|
12742
13626
|
...syncScopeAuthorizationContext(store, auth, localDeviceId),
|
|
12743
13627
|
negotiatedCapability: negotiatedSyncCapability(c)
|
|
12744
13628
|
});
|
|
12745
|
-
if (!scopeRequest.ok) return syncScopeResetResponse(c,
|
|
13629
|
+
if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
|
|
12746
13630
|
const pageRequest = snapshotPageRequest((name) => c.req.query(name), localDeviceId);
|
|
12747
13631
|
const result = loadMemorySnapshotPageForPeer(store.db, {
|
|
12748
13632
|
...pageRequest,
|
|
13633
|
+
maxEntryBytes: options.maxEntryBytes,
|
|
12749
13634
|
peerDeviceId,
|
|
12750
13635
|
scopeId: scopeRequest.mode === "scoped" ? scopeRequest.scope_id : void 0
|
|
12751
13636
|
});
|
|
@@ -12762,27 +13647,39 @@ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
|
|
|
12762
13647
|
has_more: result.hasMore
|
|
12763
13648
|
});
|
|
12764
13649
|
} catch (err) {
|
|
13650
|
+
if (err instanceof SyncEntryTooLargeError) return c.json(err.toResponseBody(), 409);
|
|
12765
13651
|
const message = err instanceof Error ? err.message : "";
|
|
12766
13652
|
const status = snapshotErrorStatus(message);
|
|
12767
13653
|
if (status) return c.json({ error: message }, status);
|
|
12768
13654
|
return c.json({ error: "internal_error" }, 500);
|
|
12769
13655
|
}
|
|
12770
13656
|
}
|
|
13657
|
+
/** Ops a channel can carry, or a typed refusal naming the one it cannot. */
|
|
13658
|
+
function opsWithinLimit(ops, limit) {
|
|
13659
|
+
return entriesWithinLimit("op", ops, (op) => op.op_id, limit);
|
|
13660
|
+
}
|
|
13661
|
+
/** A named 409 for an entry too large for the channel. Other read failures stay generic. */
|
|
13662
|
+
function syncReadFailureResponse(c, err) {
|
|
13663
|
+
if (err instanceof SyncEntryTooLargeError) return c.json(err.toResponseBody(), 409);
|
|
13664
|
+
return c.json({ error: "internal_error" }, 500);
|
|
13665
|
+
}
|
|
13666
|
+
/**
|
|
13667
|
+
* Channel requests never reach the bootstrap-grant fallback in the plain read
|
|
13668
|
+
* handlers: their reads are answered here, after the channel binding check.
|
|
13669
|
+
*/
|
|
12771
13670
|
function registerSyncChannelRestriction(app, options) {
|
|
12772
|
-
|
|
12773
|
-
|
|
12774
|
-
|
|
12775
|
-
const isRead = c.req.method === "GET" && ["/v1/status", "/v1/snapshot"].includes(c.req.path);
|
|
12776
|
-
if (!isOps && !isRead) return c.json({ error: "not found" }, 404);
|
|
13671
|
+
if (options.mode.kind === "plain-direct") return;
|
|
13672
|
+
app.use("*", async (c, next) => {
|
|
13673
|
+
if (!channelRouteAllowed(options.mode, c.req.method, c.req.path)) return c.json({ error: "not found" }, 404);
|
|
12777
13674
|
if (c.req.raw.signal.aborted) return c.json(unauthorizedPayload(), 401);
|
|
12778
|
-
if (
|
|
13675
|
+
if (c.req.method === "GET" && c.req.path !== "/v1/ops") return serveChannelRead(c, options);
|
|
12779
13676
|
await next();
|
|
12780
13677
|
});
|
|
12781
13678
|
}
|
|
12782
|
-
function serveChannelRead(c, options) {
|
|
12783
|
-
const {
|
|
13679
|
+
async function serveChannelRead(c, options) {
|
|
13680
|
+
const { mode, binding, rateLimitedResponse } = options;
|
|
12784
13681
|
const store = options.getStore();
|
|
12785
|
-
const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0),
|
|
13682
|
+
const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), binding);
|
|
12786
13683
|
if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
|
|
12787
13684
|
if (!auth.ok) {
|
|
12788
13685
|
logDirectPeerAuthDiagnostic(auth.reason);
|
|
@@ -12790,25 +13687,33 @@ function serveChannelRead(c, options) {
|
|
|
12790
13687
|
}
|
|
12791
13688
|
const limited = rateLimitedResponse(c, auth.deviceId, true);
|
|
12792
13689
|
if (limited) return limited;
|
|
12793
|
-
|
|
12794
|
-
|
|
13690
|
+
const requireScope = requiresScope(mode);
|
|
13691
|
+
const maxEntryBytes = entryByteLimit(mode);
|
|
13692
|
+
if (c.req.path !== "/v1/status") return serveAuthorizedSnapshot(c, store, auth, {
|
|
13693
|
+
requireScope,
|
|
13694
|
+
maxEntryBytes
|
|
13695
|
+
});
|
|
13696
|
+
if (requireScope) return serveScopedStatus(c, store, auth);
|
|
13697
|
+
return serveAuthenticatedStatus(c, store, auth);
|
|
12795
13698
|
}
|
|
12796
|
-
function syncScopeProvided(provided,
|
|
12797
|
-
return
|
|
13699
|
+
function syncScopeProvided(provided, requireScope) {
|
|
13700
|
+
return requireScope === true || provided;
|
|
12798
13701
|
}
|
|
12799
|
-
|
|
13702
|
+
/**
|
|
13703
|
+
* Refuses a request whose scope this peer may not use. The answer names no
|
|
13704
|
+
* boundary: the default stream's is not the peer's to see, and a refused scope has
|
|
13705
|
+
* none it may use. Resets after authorization carry their own scope's boundary.
|
|
13706
|
+
*/
|
|
13707
|
+
function syncScopeResetResponse(c, preciseReason) {
|
|
12800
13708
|
const reason = peerFacingScopeResetReason(preciseReason);
|
|
12801
13709
|
if (reason !== preciseReason) logWithheldScopeDenial(preciseReason, c.req.query(SYNC_SCOPE_QUERY_PARAM) ?? null);
|
|
12802
|
-
|
|
12803
|
-
error: "reset_required",
|
|
12804
|
-
reset_required: true,
|
|
12805
|
-
sync_capability: LOCAL_SYNC_CAPABILITY,
|
|
12806
|
-
reason,
|
|
12807
|
-
scope_id: null
|
|
12808
|
-
}, 409);
|
|
12809
|
-
return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
|
|
13710
|
+
return c.json(peerFacingScopeReset(reason, null), 409);
|
|
12810
13711
|
}
|
|
12811
|
-
|
|
13712
|
+
/**
|
|
13713
|
+
* Status for one named scope, from the channel or from a direct request that
|
|
13714
|
+
* names a scope. A scope the peer may not use gets the minimal refusal.
|
|
13715
|
+
*/
|
|
13716
|
+
function serveScopedStatus(c, store, auth) {
|
|
12812
13717
|
try {
|
|
12813
13718
|
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
12814
13719
|
const authorization = syncScopeAuthorizationContext(store, auth, deviceId);
|
|
@@ -12816,14 +13721,14 @@ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
|
|
|
12816
13721
|
...authorization,
|
|
12817
13722
|
negotiatedCapability: negotiatedSyncCapability(c)
|
|
12818
13723
|
});
|
|
12819
|
-
if (!scopeRequest.ok) return syncScopeResetResponse(c,
|
|
12820
|
-
if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c,
|
|
13724
|
+
if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
|
|
13725
|
+
if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c, "missing_scope");
|
|
12821
13726
|
const scopes = listAuthorizedScopesForPeer(store.db, {
|
|
12822
13727
|
...authorization,
|
|
12823
13728
|
scopeId: scopeRequest.scope_id
|
|
12824
13729
|
});
|
|
12825
13730
|
const selectedScope = scopes[0];
|
|
12826
|
-
if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c,
|
|
13731
|
+
if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c, "missing_scope");
|
|
12827
13732
|
return c.json({
|
|
12828
13733
|
device_id: deviceId,
|
|
12829
13734
|
protocol_version: SYNC_PROTOCOL_VERSION,
|
|
@@ -12838,12 +13743,96 @@ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
|
|
|
12838
13743
|
return c.json({ error: "internal_error" }, 500);
|
|
12839
13744
|
}
|
|
12840
13745
|
}
|
|
13746
|
+
/** Status for an authenticated direct request, with or without a named scope. */
|
|
13747
|
+
async function serveAuthenticatedStatus(c, store, auth) {
|
|
13748
|
+
try {
|
|
13749
|
+
if (c.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === "1" && supportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), "reassign_scope")) await refreshConfiguredScopeMembershipCache(store.db, void 0, {
|
|
13750
|
+
keysDir: syncKeysDir(),
|
|
13751
|
+
dbPath: store.dbPath
|
|
13752
|
+
});
|
|
13753
|
+
if (c.req.query(SYNC_SCOPE_QUERY_PARAM) !== void 0) return serveScopedStatus(c, store, auth);
|
|
13754
|
+
return serveDefaultStatus(c, store, auth);
|
|
13755
|
+
} catch {
|
|
13756
|
+
return c.json({ error: "internal_error" }, 500);
|
|
13757
|
+
}
|
|
13758
|
+
}
|
|
13759
|
+
/** Status for a direct request that names no scope: the default stream and every authorized scope. */
|
|
13760
|
+
function serveDefaultStatus(c, store, auth) {
|
|
13761
|
+
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
13762
|
+
const syncReset = getSyncResetState(store.db);
|
|
13763
|
+
const negotiated = negotiatedSyncCapability(c);
|
|
13764
|
+
const authorizedScopes = isScopedSyncCapability(negotiated) ? listAuthorizedScopesForPeer(store.db, { ...syncScopeAuthorizationContext(store, auth, deviceId) }) : null;
|
|
13765
|
+
const response = {
|
|
13766
|
+
device_id: deviceId,
|
|
13767
|
+
protocol_version: SYNC_PROTOCOL_VERSION,
|
|
13768
|
+
fingerprint,
|
|
13769
|
+
runtime_version: VERSION$1,
|
|
13770
|
+
sync_reset: addSyncScopeToBoundary(syncReset, null),
|
|
13771
|
+
sync_capability: LOCAL_SYNC_CAPABILITY,
|
|
13772
|
+
sync_features: LOCAL_SYNC_FEATURES
|
|
13773
|
+
};
|
|
13774
|
+
if (authorizedScopes !== null) response.authorized_scopes = authorizedScopes;
|
|
13775
|
+
return c.json(response);
|
|
13776
|
+
}
|
|
13777
|
+
/**
|
|
13778
|
+
* Device authentication for the plain status and snapshot reads, with the
|
|
13779
|
+
* bootstrap-grant fallback when allowed. Returns the response to send when
|
|
13780
|
+
* the request is refused or rate limited.
|
|
13781
|
+
*/
|
|
13782
|
+
async function authorizePeerRead(c, store, rateLimitedResponse, options) {
|
|
13783
|
+
const { transportGate } = options;
|
|
13784
|
+
const device = authorizeSyncRequest(store, c.req, Buffer.alloc(0), void 0, transportGate);
|
|
13785
|
+
if (isSyncAuthStoreBusy(device)) return syncAuthStoreBusyResponse(c);
|
|
13786
|
+
if (device.ok) return admittedPeerRead(c, rateLimitedResponse, device, false);
|
|
13787
|
+
const limited = rateLimitedResponse(c, c.req.path, false);
|
|
13788
|
+
if (limited) return limited;
|
|
13789
|
+
if (!options.allowGrant) return refusedPeerRead(c, device.reason, device, false);
|
|
13790
|
+
const scope = options.scope ? scopeOf(c) : {};
|
|
13791
|
+
const grant = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), {
|
|
13792
|
+
...scope,
|
|
13793
|
+
transportGate
|
|
13794
|
+
});
|
|
13795
|
+
if (isSyncAuthStoreBusy(grant)) return syncAuthStoreBusyResponse(c);
|
|
13796
|
+
if (!grant.ok) return refusedPeerRead(c, device.reason, grant, true);
|
|
13797
|
+
return admittedPeerRead(c, rateLimitedResponse, grant, true);
|
|
13798
|
+
}
|
|
13799
|
+
function admittedPeerRead(c, rateLimitedResponse, auth, viaGrant) {
|
|
13800
|
+
return rateLimitedResponse(c, auth.deviceId, true) ?? {
|
|
13801
|
+
auth,
|
|
13802
|
+
viaGrant
|
|
13803
|
+
};
|
|
13804
|
+
}
|
|
13805
|
+
/** Specific reasons stay server-side; wire responses remain generic. */
|
|
13806
|
+
function refusedPeerRead(c, deviceAuthReason, auth, bootstrapAttempted) {
|
|
13807
|
+
const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
|
|
13808
|
+
if (bootstrapAttempted && (grantPresent || deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
|
|
13809
|
+
else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
|
|
13810
|
+
return c.json(unauthorizedPayload(), 401);
|
|
13811
|
+
}
|
|
13812
|
+
/**
|
|
13813
|
+
* The pin-only answer to a marked status, or null to serve the full status.
|
|
13814
|
+
* Only while direct Noise is on, and for either auth path: a worker that the
|
|
13815
|
+
* grant already pinned still gets only the pin when it retries. The rest of
|
|
13816
|
+
* the status, with its reset metadata, comes over Noise.
|
|
13817
|
+
*/
|
|
13818
|
+
function grantStatusAnswer(c, store, mode) {
|
|
13819
|
+
if (!noiseActive(mode) || !marksNoiseStatusTarget(c.req)) return null;
|
|
13820
|
+
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
13821
|
+
return c.json({
|
|
13822
|
+
device_id: deviceId,
|
|
13823
|
+
fingerprint,
|
|
13824
|
+
transport: "noise1"
|
|
13825
|
+
});
|
|
13826
|
+
}
|
|
12841
13827
|
function syncProtocolRoutes(getStore, opts = {}) {
|
|
12842
13828
|
const app = new Hono();
|
|
12843
13829
|
const routeRateLimit = opts.routeRateLimit ?? null;
|
|
12844
|
-
const
|
|
13830
|
+
const mode = opts.mode ?? PLAIN_DIRECT_MODE;
|
|
13831
|
+
const binding = channelBinding(mode);
|
|
13832
|
+
const transportGate = plaintextTransportGate(mode);
|
|
12845
13833
|
registerSyncChannelRestriction(app, {
|
|
12846
|
-
|
|
13834
|
+
mode,
|
|
13835
|
+
binding,
|
|
12847
13836
|
getStore,
|
|
12848
13837
|
rateLimitedResponse
|
|
12849
13838
|
});
|
|
@@ -12861,62 +13850,17 @@ function syncProtocolRoutes(getStore, opts = {}) {
|
|
|
12861
13850
|
app.get("/v1/status", (c) => {
|
|
12862
13851
|
const store = getStore();
|
|
12863
13852
|
return (async () => {
|
|
12864
|
-
|
|
12865
|
-
|
|
12866
|
-
|
|
12867
|
-
|
|
12868
|
-
|
|
12869
|
-
|
|
12870
|
-
if ((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim()) {
|
|
12871
|
-
preauthChecked = true;
|
|
12872
|
-
const bootstrapLimited = rateLimitedResponse(c, c.req.path, false);
|
|
12873
|
-
if (bootstrapLimited) return bootstrapLimited;
|
|
12874
|
-
} else {
|
|
12875
|
-
preauthChecked = true;
|
|
12876
|
-
const unauthLimited = rateLimitedResponse(c, c.req.path, false);
|
|
12877
|
-
if (unauthLimited) return unauthLimited;
|
|
12878
|
-
}
|
|
12879
|
-
deviceAuthReason = auth.reason;
|
|
12880
|
-
auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));
|
|
12881
|
-
bootstrapAttempted = true;
|
|
12882
|
-
}
|
|
12883
|
-
if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
|
|
12884
|
-
if (!auth.ok) {
|
|
12885
|
-
const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
|
|
12886
|
-
if (bootstrapAttempted && (grantPresent || deviceAuthReason != null && deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? "none"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
|
|
12887
|
-
else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
|
|
12888
|
-
return (preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ?? c.json(unauthorizedPayload(), 401);
|
|
12889
|
-
}
|
|
12890
|
-
const limited = rateLimitedResponse(c, auth.deviceId, true);
|
|
12891
|
-
if (limited) return limited;
|
|
12892
|
-
try {
|
|
12893
|
-
if (c.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === "1" && supportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), "reassign_scope")) await refreshConfiguredScopeMembershipCache(store.db, void 0, {
|
|
12894
|
-
keysDir: syncKeysDir(),
|
|
12895
|
-
dbPath: store.dbPath
|
|
12896
|
-
});
|
|
12897
|
-
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
12898
|
-
const syncReset = getSyncResetState(store.db);
|
|
12899
|
-
const negotiated = negotiatedSyncCapability(c);
|
|
12900
|
-
const authorizedScopes = isScopedSyncCapability(negotiated) ? listAuthorizedScopesForPeer(store.db, { ...syncScopeAuthorizationContext(store, auth, deviceId) }) : null;
|
|
12901
|
-
const response = {
|
|
12902
|
-
device_id: deviceId,
|
|
12903
|
-
protocol_version: SYNC_PROTOCOL_VERSION,
|
|
12904
|
-
fingerprint,
|
|
12905
|
-
runtime_version: VERSION$1,
|
|
12906
|
-
sync_reset: addSyncScopeToBoundary(syncReset, null),
|
|
12907
|
-
sync_capability: LOCAL_SYNC_CAPABILITY,
|
|
12908
|
-
sync_features: LOCAL_SYNC_FEATURES
|
|
12909
|
-
};
|
|
12910
|
-
if (authorizedScopes !== null) response.authorized_scopes = authorizedScopes;
|
|
12911
|
-
return c.json(response);
|
|
12912
|
-
} catch {
|
|
12913
|
-
return c.json({ error: "internal_error" }, 500);
|
|
12914
|
-
}
|
|
13853
|
+
const read = await authorizePeerRead(c, store, rateLimitedResponse, {
|
|
13854
|
+
allowGrant: true,
|
|
13855
|
+
transportGate
|
|
13856
|
+
});
|
|
13857
|
+
if (read instanceof Response) return read;
|
|
13858
|
+
return grantStatusAnswer(c, store, mode) ?? serveAuthenticatedStatus(c, store, read.auth);
|
|
12915
13859
|
})();
|
|
12916
13860
|
});
|
|
12917
13861
|
app.get("/v1/ops", (c) => {
|
|
12918
13862
|
const store = getStore();
|
|
12919
|
-
const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0),
|
|
13863
|
+
const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), binding, transportGate);
|
|
12920
13864
|
if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
|
|
12921
13865
|
if (!auth.ok) {
|
|
12922
13866
|
logDirectPeerAuthDiagnostic(auth.reason);
|
|
@@ -12929,11 +13873,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
|
|
|
12929
13873
|
const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
|
|
12930
13874
|
const negotiated = negotiatedSyncCapability(c);
|
|
12931
13875
|
const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
12932
|
-
const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0,
|
|
13876
|
+
const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, requiresScope(mode)), {
|
|
12933
13877
|
...syncScopeAuthorizationContext(store, auth, localDeviceId),
|
|
12934
13878
|
negotiatedCapability: negotiated
|
|
12935
13879
|
});
|
|
12936
|
-
if (!scopeRequest.ok) return syncScopeResetResponse(c,
|
|
13880
|
+
if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
|
|
12937
13881
|
const since = c.req.query("since") ?? null;
|
|
12938
13882
|
const rawLimit = Number.parseInt(c.req.query("limit") ?? "200", 10);
|
|
12939
13883
|
const rawGeneration = c.req.query("generation");
|
|
@@ -12965,54 +13909,33 @@ function syncProtocolRoutes(getStore, opts = {}) {
|
|
|
12965
13909
|
snapshot_id: boundary.snapshot_id,
|
|
12966
13910
|
baseline_cursor: boundary.baseline_cursor,
|
|
12967
13911
|
retained_floor_cursor: boundary.retained_floor_cursor,
|
|
12968
|
-
ops: filtered.allowed,
|
|
13912
|
+
ops: opsWithinLimit(filtered.allowed, entryByteLimit(mode)),
|
|
12969
13913
|
next_cursor: nextCursor,
|
|
12970
13914
|
skipped: filtered.skipped,
|
|
12971
13915
|
skipped_detail: filtered.skippedDetail
|
|
12972
13916
|
});
|
|
12973
|
-
} catch {
|
|
12974
|
-
return c
|
|
13917
|
+
} catch (err) {
|
|
13918
|
+
return syncReadFailureResponse(c, err);
|
|
12975
13919
|
}
|
|
12976
13920
|
});
|
|
12977
13921
|
app.get("/v1/snapshot", (c) => {
|
|
12978
13922
|
const store = getStore();
|
|
12979
13923
|
return (async () => {
|
|
12980
|
-
|
|
12981
|
-
|
|
12982
|
-
|
|
12983
|
-
|
|
12984
|
-
|
|
12985
|
-
|
|
12986
|
-
|
|
12987
|
-
|
|
12988
|
-
const bootstrapLimited = rateLimitedResponse(c, c.req.path, false);
|
|
12989
|
-
if (bootstrapLimited) return bootstrapLimited;
|
|
12990
|
-
} else {
|
|
12991
|
-
preauthChecked = true;
|
|
12992
|
-
const unauthLimited = rateLimitedResponse(c, c.req.path, false);
|
|
12993
|
-
if (unauthLimited) return unauthLimited;
|
|
12994
|
-
}
|
|
12995
|
-
deviceAuthReason = auth.reason;
|
|
12996
|
-
auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), scopeOf(c));
|
|
12997
|
-
bootstrapAttempted = true;
|
|
12998
|
-
}
|
|
12999
|
-
if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
|
|
13000
|
-
if (!auth.ok) {
|
|
13001
|
-
const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
|
|
13002
|
-
if (bootstrapAttempted && (grantPresent || deviceAuthReason != null && deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? "none"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
|
|
13003
|
-
else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
|
|
13004
|
-
return (preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ?? c.json(unauthorizedPayload(), 401);
|
|
13005
|
-
}
|
|
13006
|
-
const limited = rateLimitedResponse(c, auth.deviceId, true);
|
|
13007
|
-
if (limited) return limited;
|
|
13008
|
-
return serveAuthorizedSnapshot(c, store, auth);
|
|
13924
|
+
const allowGrant = !noiseActive(mode);
|
|
13925
|
+
const read = await authorizePeerRead(c, store, rateLimitedResponse, {
|
|
13926
|
+
allowGrant,
|
|
13927
|
+
scope: true,
|
|
13928
|
+
transportGate
|
|
13929
|
+
});
|
|
13930
|
+
if (read instanceof Response) return read;
|
|
13931
|
+
return serveAuthorizedSnapshot(c, store, read.auth);
|
|
13009
13932
|
})();
|
|
13010
13933
|
});
|
|
13011
13934
|
app.post("/v1/ops", async (c) => {
|
|
13012
13935
|
const store = getStore();
|
|
13013
13936
|
const raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);
|
|
13014
13937
|
if (raw == null) return c.json({ error: "payload_too_large" }, 413);
|
|
13015
|
-
const auth = authorizeSyncRequest(store, c.req, raw,
|
|
13938
|
+
const auth = authorizeSyncRequest(store, c.req, raw, binding, transportGate);
|
|
13016
13939
|
if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
|
|
13017
13940
|
if (!auth.ok) {
|
|
13018
13941
|
logDirectPeerAuthDiagnostic(auth.reason);
|
|
@@ -13034,11 +13957,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
|
|
|
13034
13957
|
const scopeContext = syncScopeAuthorizationContext(store, auth, localDeviceId);
|
|
13035
13958
|
const scopeRequest = parseInboundScopeRequest(body, scopeContext, {
|
|
13036
13959
|
negotiated,
|
|
13037
|
-
|
|
13960
|
+
requireScope: requiresScope(mode)
|
|
13038
13961
|
});
|
|
13039
13962
|
if (!scopeRequest.ok) {
|
|
13040
13963
|
recordInboundScopeFailure(scopeContext);
|
|
13041
|
-
return syncScopeResetResponse(c,
|
|
13964
|
+
return syncScopeResetResponse(c, scopeRequest.reason);
|
|
13042
13965
|
}
|
|
13043
13966
|
if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
|
|
13044
13967
|
if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
|
|
@@ -13191,7 +14114,7 @@ async function deleteProjectScopeMappingRoute(c, store) {
|
|
|
13191
14114
|
if (!body) return c.json({ error: "invalid json" }, 400);
|
|
13192
14115
|
const confirmedGuardrailTokens = optionalViewerStringList(body, "confirmed_guardrail_tokens");
|
|
13193
14116
|
releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
|
|
13194
|
-
const
|
|
14117
|
+
const deviceId = requireExistingDeviceIdentity(store);
|
|
13195
14118
|
const warnings = analyzeProjectScopeMappingDeletionGuardrails(store.db, id, deviceId);
|
|
13196
14119
|
const missing = missingGuardrailConfirmations(warnings, confirmedGuardrailTokens);
|
|
13197
14120
|
if (missing.length > 0) return c.json({
|
|
@@ -13200,13 +14123,13 @@ async function deleteProjectScopeMappingRoute(c, store) {
|
|
|
13200
14123
|
required_guardrail_tokens: missing.map((warning) => warning.confirmation_token),
|
|
13201
14124
|
guardrail_warnings: warnings
|
|
13202
14125
|
}, 409);
|
|
13203
|
-
const deleted = deleteProjectMappingAndWakePolicies(store,
|
|
14126
|
+
const deleted = deleteProjectMappingAndWakePolicies(store, deviceId, id, confirmedGuardrailTokens);
|
|
13204
14127
|
return c.json({
|
|
13205
14128
|
ok: true,
|
|
13206
14129
|
deleted
|
|
13207
14130
|
});
|
|
13208
14131
|
} catch (error) {
|
|
13209
|
-
return c
|
|
14132
|
+
return mappingChangeError(c, error);
|
|
13210
14133
|
} finally {
|
|
13211
14134
|
releasePublicationMutation?.();
|
|
13212
14135
|
}
|
|
@@ -13290,10 +14213,22 @@ function mappedProjectsInScopes(mappings, scopeIds) {
|
|
|
13290
14213
|
function wakeRecipientPolicyProjects(store, projectIdentities, now) {
|
|
13291
14214
|
wakeRecipientPoliciesForProjectIdentities(store.db, [...new Set(projectIdentities)], now);
|
|
13292
14215
|
}
|
|
13293
|
-
|
|
13294
|
-
|
|
14216
|
+
/**
|
|
14217
|
+
* The guardrails, computed again inside the write for the device it writes for,
|
|
14218
|
+
* must need no confirmation beyond the ones the request carries.
|
|
14219
|
+
*/
|
|
14220
|
+
function requireConfirmedGuardrails(store, deviceId, mappingInputs, confirmedGuardrailTokens) {
|
|
14221
|
+
const warnings = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
|
|
14222
|
+
...input,
|
|
14223
|
+
deviceId
|
|
14224
|
+
}))).flatMap((analysis) => analysis.warnings);
|
|
14225
|
+
const missing = missingGuardrailConfirmations(warnings, confirmedGuardrailTokens);
|
|
14226
|
+
if (missing.length > 0) throw new MappingGuardrailsChangedError(warnings, missing);
|
|
14227
|
+
}
|
|
14228
|
+
function saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs, confirmedGuardrailTokens) {
|
|
13295
14229
|
return store.db.transaction(() => {
|
|
13296
14230
|
requireNarrowingWhenGated(store, mappingInputs);
|
|
14231
|
+
requireConfirmedGuardrails(store, deviceId, mappingInputs, confirmedGuardrailTokens);
|
|
13297
14232
|
const before = policyWakeMappings(store);
|
|
13298
14233
|
const previousMappings = existingRequestedMappings(before, mappingInputs);
|
|
13299
14234
|
const writableScopeIds = new Set(resolveVisibleScopeIds(store.db, store.deviceId, store.scopeResolutionDeviceContext()));
|
|
@@ -13307,9 +14242,9 @@ function saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs) {
|
|
|
13307
14242
|
return mappings;
|
|
13308
14243
|
}).immediate();
|
|
13309
14244
|
}
|
|
13310
|
-
function deleteProjectMappingAndWakePolicies(store,
|
|
13311
|
-
store.adoptEnsuredDeviceIdentity(deviceId);
|
|
14245
|
+
function deleteProjectMappingAndWakePolicies(store, deviceId, mappingId, confirmedGuardrailTokens) {
|
|
13312
14246
|
return store.db.transaction(() => {
|
|
14247
|
+
requireAdminWhenGated();
|
|
13313
14248
|
const before = policyWakeMappings(store);
|
|
13314
14249
|
const removed = before.find((mapping) => mapping.id === mappingId);
|
|
13315
14250
|
const deleted = deleteProjectScopeSettingsMapping(store.db, mappingId, {
|
|
@@ -13441,6 +14376,117 @@ function persistPeerIdentityMutation(store, body) {
|
|
|
13441
14376
|
}).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).run();
|
|
13442
14377
|
return assignment;
|
|
13443
14378
|
}
|
|
14379
|
+
/**
|
|
14380
|
+
* Assigns a paired device to a person through the older route. The gate checked on
|
|
14381
|
+
* entry, but reading the body can outlast that, so the write checks again.
|
|
14382
|
+
*/
|
|
14383
|
+
function persistPeerIdentityIfAllowed(store, body, readConfig) {
|
|
14384
|
+
return runViewerActorMutation(store, () => canChangeRecipientAccess(readConfig) ? persistPeerIdentityMutation(store, body) : {
|
|
14385
|
+
...ACCESS_CHANGE_REFUSAL,
|
|
14386
|
+
status: 403
|
|
14387
|
+
});
|
|
14388
|
+
}
|
|
14389
|
+
var BINDING_COMMIT_HTTP_STATUS = {
|
|
14390
|
+
invalid: 400,
|
|
14391
|
+
not_found: 404,
|
|
14392
|
+
stale: 409,
|
|
14393
|
+
conflict: 409
|
|
14394
|
+
};
|
|
14395
|
+
/**
|
|
14396
|
+
* Commits reviewed device bindings, or returns null when this device may no longer
|
|
14397
|
+
* change access. The gate checked on entry, but the publication lock and the
|
|
14398
|
+
* inventory read can outlast that, so the write transaction checks again.
|
|
14399
|
+
*/
|
|
14400
|
+
function commitBindingsIfAllowed(store, inventory, request, readConfig) {
|
|
14401
|
+
return store.db.transaction(() => canChangeRecipientAccess(readConfig) ? commitDeviceIdentityBindings(store.db, {
|
|
14402
|
+
localActorId: store.actorId,
|
|
14403
|
+
localDeviceId: store.deviceId
|
|
14404
|
+
}, inventory, request) : null).immediate();
|
|
14405
|
+
}
|
|
14406
|
+
/** Adds a person. People belong to coordinator setups, so this needs the admin device. */
|
|
14407
|
+
async function createActorRoute(c, store, readConfig) {
|
|
14408
|
+
ensureLocalActorRecord(store);
|
|
14409
|
+
let body;
|
|
14410
|
+
try {
|
|
14411
|
+
body = await c.req.json();
|
|
14412
|
+
} catch {
|
|
14413
|
+
return c.json({ error: "invalid json" }, 400);
|
|
14414
|
+
}
|
|
14415
|
+
const rawDisplayName = String(body.display_name ?? "");
|
|
14416
|
+
if (!rawDisplayName.trim()) return c.json({ error: "display_name required" }, 400);
|
|
14417
|
+
let displayName;
|
|
14418
|
+
try {
|
|
14419
|
+
displayName = normalizeHumanPresentationName(rawDisplayName, "display_name");
|
|
14420
|
+
} catch (error) {
|
|
14421
|
+
return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
|
|
14422
|
+
}
|
|
14423
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
14424
|
+
const actor = {
|
|
14425
|
+
actor_id: randomUUID(),
|
|
14426
|
+
display_name: displayName,
|
|
14427
|
+
is_local: 0,
|
|
14428
|
+
status: "active",
|
|
14429
|
+
merged_into_actor_id: null,
|
|
14430
|
+
created_at: now,
|
|
14431
|
+
updated_at: now
|
|
14432
|
+
};
|
|
14433
|
+
return store.db.transaction(() => {
|
|
14434
|
+
if (!canChangeRecipientAccess(readConfig)) return false;
|
|
14435
|
+
drizzle(store.db, { schema }).insert(schema.actors).values(actor).run();
|
|
14436
|
+
return true;
|
|
14437
|
+
}).immediate() ? c.json(actor) : c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14438
|
+
}
|
|
14439
|
+
/** Renames a person, which needs the admin device like other changes to people. */
|
|
14440
|
+
async function renameActorRoute(c, store, readConfig) {
|
|
14441
|
+
ensureLocalActorRecord(store);
|
|
14442
|
+
let body;
|
|
14443
|
+
try {
|
|
14444
|
+
body = await c.req.json();
|
|
14445
|
+
} catch {
|
|
14446
|
+
return c.json({ error: "invalid json" }, 400);
|
|
14447
|
+
}
|
|
14448
|
+
const actorId = String(body.actor_id ?? "").trim();
|
|
14449
|
+
if (!actorId) return c.json({ error: "actor_id required" }, 400);
|
|
14450
|
+
let displayName;
|
|
14451
|
+
try {
|
|
14452
|
+
displayName = normalizeHumanPresentationName(String(body.display_name ?? ""), "display_name");
|
|
14453
|
+
} catch (error) {
|
|
14454
|
+
return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
|
|
14455
|
+
}
|
|
14456
|
+
const d = drizzle(store.db, { schema });
|
|
14457
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
14458
|
+
const result = store.db.transaction(() => {
|
|
14459
|
+
if (!canChangeRecipientAccess(readConfig)) return "refused";
|
|
14460
|
+
const actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();
|
|
14461
|
+
if (!actor) return null;
|
|
14462
|
+
d.update(schema.actors).set({
|
|
14463
|
+
display_name: displayName,
|
|
14464
|
+
updated_at: updatedAt
|
|
14465
|
+
}).where(eq(schema.actors.actor_id, actorId)).run();
|
|
14466
|
+
return actor;
|
|
14467
|
+
}).immediate();
|
|
14468
|
+
if (result === "refused") return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14469
|
+
if (!result) return c.json({ error: "actor not found" }, 404);
|
|
14470
|
+
return c.json({
|
|
14471
|
+
...result,
|
|
14472
|
+
display_name: displayName,
|
|
14473
|
+
updated_at: updatedAt
|
|
14474
|
+
});
|
|
14475
|
+
}
|
|
14476
|
+
/**
|
|
14477
|
+
* Runs the recipient-policy migration, or returns null when this device may no
|
|
14478
|
+
* longer change access. A dry run writes nothing, so any device may run one. The
|
|
14479
|
+
* gate checked on entry, but reading the body can outlast that, so a migration
|
|
14480
|
+
* that writes checks again inside its transaction.
|
|
14481
|
+
*/
|
|
14482
|
+
function migrateIfAllowed(store, dryRun, readConfig) {
|
|
14483
|
+
const migrate = () => migrateRecipientPolicyIntent(store.db, {
|
|
14484
|
+
localActorId: store.actorId,
|
|
14485
|
+
localDeviceId: store.deviceId
|
|
14486
|
+
}, { dryRun });
|
|
14487
|
+
if (dryRun) return migrate();
|
|
14488
|
+
return store.db.transaction(() => canChangeRecipientAccess(readConfig) ? migrate() : null).immediate();
|
|
14489
|
+
}
|
|
13444
14490
|
function createActorMutationPreflightRoutes(getStore) {
|
|
13445
14491
|
const app = new Hono();
|
|
13446
14492
|
const preflight = async (c, next) => {
|
|
@@ -13540,6 +14586,54 @@ async function projectScopeInventoryRoute(c, store) {
|
|
|
13540
14586
|
* other devices must not save those changes.
|
|
13541
14587
|
*/
|
|
13542
14588
|
var ACCESS_CHANGE_REFUSAL = { error: "access_change_needs_admin_device" };
|
|
14589
|
+
function resolveReviewIfAllowed(store, readConfig, request) {
|
|
14590
|
+
const context = {
|
|
14591
|
+
localActorId: store.actorId,
|
|
14592
|
+
localDeviceId: store.deviceId,
|
|
14593
|
+
beforeResolve: () => {
|
|
14594
|
+
if (!canChangeRecipientAccess(readConfig)) throw new Error(ACCESS_CHANGE_REFUSAL.error);
|
|
14595
|
+
requireLocalActorRecord(store);
|
|
14596
|
+
}
|
|
14597
|
+
};
|
|
14598
|
+
try {
|
|
14599
|
+
return Array.isArray(request) ? resolveRecipientPolicyReviewBulk(store.db, context, request) : resolveRecipientPolicyReview(store.db, context, request);
|
|
14600
|
+
} catch (error) {
|
|
14601
|
+
if (error instanceof Error && error.message === ACCESS_CHANGE_REFUSAL.error) return null;
|
|
14602
|
+
throw error;
|
|
14603
|
+
}
|
|
14604
|
+
}
|
|
14605
|
+
/**
|
|
14606
|
+
* Commits recipient edges, refusing inside the write transaction when this device
|
|
14607
|
+
* may no longer change access. The gate checked on entry; the body and the Team
|
|
14608
|
+
* queues can outlast that.
|
|
14609
|
+
*/
|
|
14610
|
+
function commitEdgesIfAllowed(store, request, readConfig) {
|
|
14611
|
+
return commitRecipientPolicyEdges(store.db, request, { stillAllowed: () => canChangeRecipientAccess(readConfig) });
|
|
14612
|
+
}
|
|
14613
|
+
var EDGE_COMMIT_HTTP_STATUS = {
|
|
14614
|
+
invalid: 400,
|
|
14615
|
+
not_found: 404,
|
|
14616
|
+
stale: 409,
|
|
14617
|
+
conflict: 409
|
|
14618
|
+
};
|
|
14619
|
+
function edgeCommitResponse(c, result) {
|
|
14620
|
+
if (result.errorCode === ACCESS_CHANGE_REFUSAL.error) return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14621
|
+
return c.json(result, EDGE_COMMIT_HTTP_STATUS[result.status] ?? 200);
|
|
14622
|
+
}
|
|
14623
|
+
/** A write that found this device no longer the admin device answers like the gate. */
|
|
14624
|
+
function accessRefusalOr(c, message, status) {
|
|
14625
|
+
if (message === ACCESS_CHANGE_REFUSAL.error) return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14626
|
+
return c.json({ error: message }, status);
|
|
14627
|
+
}
|
|
14628
|
+
/** A mapping change refused for this device's identity, its guardrails, or its authority. */
|
|
14629
|
+
function mappingChangeError(c, error) {
|
|
14630
|
+
if (error instanceof DeviceIdentityUnavailableError) return c.json({
|
|
14631
|
+
error: error.code,
|
|
14632
|
+
message: DEVICE_IDENTITY_UNAVAILABLE[error.code]
|
|
14633
|
+
}, 409);
|
|
14634
|
+
if (error instanceof MappingGuardrailsChangedError) return c.json(mappingGuardrailChallenge(error.warnings, error.missing), 409);
|
|
14635
|
+
return accessRefusalOr(c, error instanceof Error ? error.message : String(error), 400);
|
|
14636
|
+
}
|
|
13543
14637
|
function canChangeRecipientAccess(readConfig) {
|
|
13544
14638
|
try {
|
|
13545
14639
|
return isCoordinatorAdminDevice(readConfig());
|
|
@@ -13775,15 +14869,22 @@ function peerEnrollmentHandler(getStore) {
|
|
|
13775
14869
|
};
|
|
13776
14870
|
}
|
|
13777
14871
|
/**
|
|
13778
|
-
*
|
|
13779
|
-
* handled.
|
|
13780
|
-
*
|
|
14872
|
+
* The gate's config reader, set while a mapping save or delete that passed the
|
|
14873
|
+
* gate is handled. The body, the publication lock and another save can all land
|
|
14874
|
+
* between the gate and the write, so the write checks again inside its
|
|
14875
|
+
* transaction: a device that is no longer the admin device may still only narrow.
|
|
13781
14876
|
*/
|
|
13782
|
-
var
|
|
14877
|
+
var mappingWriteAuthority = new AsyncLocalStorage();
|
|
13783
14878
|
function requireNarrowingWhenGated(store, inputs) {
|
|
13784
|
-
|
|
14879
|
+
const readConfig = mappingWriteAuthority.getStore();
|
|
14880
|
+
if (!readConfig || canChangeRecipientAccess(readConfig)) return;
|
|
13785
14881
|
if (!projectScopeMappingSavesOnlyNarrow(store.db, inputs)) throw new Error("access_change_needs_admin_device");
|
|
13786
14882
|
}
|
|
14883
|
+
/** Removing a mapping can expose a broader one, so only the admin device may. */
|
|
14884
|
+
function requireAdminWhenGated() {
|
|
14885
|
+
const readConfig = mappingWriteAuthority.getStore();
|
|
14886
|
+
if (readConfig && !canChangeRecipientAccess(readConfig)) throw new Error("access_change_needs_admin_device");
|
|
14887
|
+
}
|
|
13787
14888
|
async function isDryRunMigration(c) {
|
|
13788
14889
|
return (await parseViewerJsonBody(c, { allowEmpty: true }))?.dryRun === true;
|
|
13789
14890
|
}
|
|
@@ -13814,6 +14915,10 @@ function installRecipientAccessChangeGate(app, getStore, readConfig = readCoordi
|
|
|
13814
14915
|
const allowed = () => canChangeRecipientAccess(readConfig);
|
|
13815
14916
|
for (const path of [
|
|
13816
14917
|
"/api/sync/recipient-policy/v1/edges/commit",
|
|
14918
|
+
"/api/sync/recipient-policy/v1/device-bindings/commit",
|
|
14919
|
+
"/api/sync/peers/identity",
|
|
14920
|
+
"/api/sync/actors",
|
|
14921
|
+
"/api/sync/actors/rename",
|
|
13817
14922
|
"/api/sync/actors/merge",
|
|
13818
14923
|
"/api/sync/actors/deactivate",
|
|
13819
14924
|
"/api/sync/recipient-policy/v1/review/resolve",
|
|
@@ -13823,33 +14928,31 @@ function installRecipientAccessChangeGate(app, getStore, readConfig = readCoordi
|
|
|
13823
14928
|
app.post("/api/sync/recipient-policy/v1/migrate", async (c, next) => allowed() || await isDryRunMigration(c) ? next() : refuse(c));
|
|
13824
14929
|
const mappingRoutes = [["/api/sync/sharing-domains/project-mappings", (body) => [parseViewerProjectMappingInput(body)]], ["/api/sync/sharing-domains/project-mappings/bulk", parseViewerProjectMappingInputs]];
|
|
13825
14930
|
for (const [path, parse] of mappingRoutes) app.put(path, async (c, next) => {
|
|
13826
|
-
if (allowed()) return
|
|
13827
|
-
|
|
13828
|
-
return mappingSaveMustOnlyNarrow.run(true, () => next());
|
|
14931
|
+
if (!allowed() && !await mappingSaveOnlyNarrows(c, getStore(), parse)) return refuse(c);
|
|
14932
|
+
return mappingWriteAuthority.run(readConfig, () => next());
|
|
13829
14933
|
});
|
|
13830
|
-
app.delete("/api/sync/sharing-domains/project-mappings/:id", async (c, next) => allowed() ? next() : refuse(c));
|
|
14934
|
+
app.delete("/api/sync/sharing-domains/project-mappings/:id", async (c, next) => allowed() ? mappingWriteAuthority.run(readConfig, () => next()) : refuse(c));
|
|
13831
14935
|
}
|
|
13832
|
-
|
|
14936
|
+
/** With a coordinator, codemem can pair the devices again. Without one, nothing does. */
|
|
14937
|
+
function unpairNotice(coordinatorConfigured) {
|
|
14938
|
+
if (!coordinatorConfigured) return "Only this device's pairing was removed.";
|
|
14939
|
+
return "Only this device's pairing was removed. If both devices share a Team Project, codemem can pair them again automatically. To stop syncing on all your devices, use Remove device.";
|
|
14940
|
+
}
|
|
14941
|
+
function removeLocalPeerRoute(c, getStore, options) {
|
|
13833
14942
|
const store = getStore();
|
|
13834
14943
|
const d = drizzle(store.db, { schema });
|
|
13835
14944
|
const peerDeviceId = c.req.param("peer_device_id")?.trim();
|
|
13836
14945
|
if (!peerDeviceId) return c.json({ error: "peer_device_id required" }, 400);
|
|
13837
14946
|
if (!d.select({ peer_device_id: schema.syncPeers.peer_device_id }).from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get()) return c.json({ error: "peer not found" }, 404);
|
|
13838
|
-
const { binding } =
|
|
14947
|
+
const { binding } = removePeerFromThisDevice(store.db, {
|
|
13839
14948
|
localDeviceId: store.deviceId,
|
|
13840
|
-
peerDeviceId
|
|
13841
|
-
readConfig: options.readCoordinatorConfig,
|
|
13842
|
-
lookupCoordinatorAnswer: options.lookupCoordinatorDeviceAnswer
|
|
13843
|
-
});
|
|
13844
|
-
if (binding === "ended") return c.json({
|
|
13845
|
-
ok: true,
|
|
13846
|
-
binding
|
|
14949
|
+
peerDeviceId
|
|
13847
14950
|
});
|
|
13848
14951
|
return c.json({
|
|
13849
14952
|
ok: true,
|
|
13850
14953
|
binding,
|
|
13851
14954
|
remove_from_projects: "needs_admin_device",
|
|
13852
|
-
notice:
|
|
14955
|
+
notice: unpairNotice(Boolean((options.readCoordinatorConfig ?? readCoordinatorSyncConfig)().syncCoordinatorUrl.trim()))
|
|
13853
14956
|
});
|
|
13854
14957
|
}
|
|
13855
14958
|
function recipientInvitationTarget(store, body, kind) {
|
|
@@ -13882,12 +14985,32 @@ function previewRecipientInvitation(store, body) {
|
|
|
13882
14985
|
};
|
|
13883
14986
|
}
|
|
13884
14987
|
}
|
|
14988
|
+
/**
|
|
14989
|
+
* The group a recipient invitation goes through. A Team's first invitation
|
|
14990
|
+
* binds it on the coordinator, so a Team whose group is known goes only through
|
|
14991
|
+
* that group; anything else uses the requested or configured group.
|
|
14992
|
+
*/
|
|
14993
|
+
function recipientInvitationGroup(store, input) {
|
|
14994
|
+
const requestedGroupId = optionalViewerString(input.body, "group_id");
|
|
14995
|
+
return (input.kind === "team_member" ? teamInvitationGroup(store.db, {
|
|
14996
|
+
teamId: input.targetId,
|
|
14997
|
+
coordinatorId: input.config.syncCoordinatorUrl,
|
|
14998
|
+
configuredGroupIds: input.config.syncCoordinatorGroups,
|
|
14999
|
+
requestedGroupId
|
|
15000
|
+
}) : null) ?? resolveCoordinatorAdminGroup(requestedGroupId, input.status);
|
|
15001
|
+
}
|
|
13885
15002
|
async function issueRecipientInvitation(store, body, kind, targetId, preview) {
|
|
13886
15003
|
const config = readCoordinatorSyncConfig();
|
|
13887
15004
|
const status = coordinatorAdminStatusPayload(config);
|
|
13888
15005
|
const reviewedIntent = recipientInviteReviewedIntent(store, kind, targetId, preview);
|
|
13889
15006
|
const reviewedPreviewDigest = await recipientReviewedIntentDigest(reviewedIntent);
|
|
13890
|
-
const groupId =
|
|
15007
|
+
const groupId = recipientInvitationGroup(store, {
|
|
15008
|
+
body,
|
|
15009
|
+
kind,
|
|
15010
|
+
targetId,
|
|
15011
|
+
config,
|
|
15012
|
+
status
|
|
15013
|
+
});
|
|
13891
15014
|
const ttlHours = parseInviteTtlHours(body.ttl_hours);
|
|
13892
15015
|
if (!groupId) throw new Error("group_id_required");
|
|
13893
15016
|
if (ttlHours == null) throw new Error("ttl_hours_invalid");
|
|
@@ -13947,6 +15070,11 @@ async function createRecipientInvitation(store, body) {
|
|
|
13947
15070
|
}
|
|
13948
15071
|
};
|
|
13949
15072
|
} catch (error) {
|
|
15073
|
+
const code = error instanceof Error ? error.message : "";
|
|
15074
|
+
if (code === "team_group_mismatch" || code === "team_link_conflict") return {
|
|
15075
|
+
httpStatus: 409,
|
|
15076
|
+
body: { error: code }
|
|
15077
|
+
};
|
|
13950
15078
|
return {
|
|
13951
15079
|
httpStatus: 400,
|
|
13952
15080
|
body: { error: error instanceof Error ? error.message : "recipient_invite_failed" }
|
|
@@ -14110,14 +15238,9 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14110
15238
|
try {
|
|
14111
15239
|
releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
|
|
14112
15240
|
ensureStableStoreIdentity(store);
|
|
14113
|
-
const result =
|
|
14114
|
-
|
|
14115
|
-
|
|
14116
|
-
}, await localInventoryInput(store), body);
|
|
14117
|
-
if (result.status === "invalid") return c.json(result, 400);
|
|
14118
|
-
if (result.status === "not_found") return c.json(result, 404);
|
|
14119
|
-
if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
|
|
14120
|
-
return c.json(result);
|
|
15241
|
+
const result = commitBindingsIfAllowed(store, await localInventoryInput(store), body, readCoordinatorConfig);
|
|
15242
|
+
if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
15243
|
+
return c.json(result, BINDING_COMMIT_HTTP_STATUS[result.status] ?? 200);
|
|
14121
15244
|
} catch (error) {
|
|
14122
15245
|
if (isSqliteBusy(error)) {
|
|
14123
15246
|
c.header("Retry-After", "1");
|
|
@@ -14249,13 +15372,12 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14249
15372
|
return c.json({ error: "device identity unavailable" }, 500);
|
|
14250
15373
|
}
|
|
14251
15374
|
if (!deviceId || !fingerprint) return c.json({ error: "public key missing" }, 500);
|
|
14252
|
-
return c.json({
|
|
14253
|
-
|
|
15375
|
+
return c.json(pairingPayloadBody({
|
|
15376
|
+
deviceId,
|
|
14254
15377
|
fingerprint,
|
|
14255
|
-
|
|
14256
|
-
|
|
14257
|
-
|
|
14258
|
-
});
|
|
15378
|
+
publicKey,
|
|
15379
|
+
config
|
|
15380
|
+
}));
|
|
14259
15381
|
}
|
|
14260
15382
|
});
|
|
14261
15383
|
app.post("/api/sync/peers/rename", async (c) => {
|
|
@@ -14310,7 +15432,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14310
15432
|
localDeviceId: store.deviceId
|
|
14311
15433
|
}));
|
|
14312
15434
|
});
|
|
14313
|
-
app.route("/",
|
|
15435
|
+
app.route("/", deviceRenameRoutes(getStore)).get("/api/sync/recipient-policy/v1/intent", (c) => {
|
|
14314
15436
|
const store = getStore();
|
|
14315
15437
|
return c.json(listRecipientPolicyIntent(store.db));
|
|
14316
15438
|
});
|
|
@@ -14342,14 +15464,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14342
15464
|
const teamIds = request ? [...new Set(request.changes.flatMap((change) => change.recipient.recipientKind === "team" ? [change.recipient.teamId] : []))].toSorted() : [];
|
|
14343
15465
|
const commit = async (index) => {
|
|
14344
15466
|
const teamId = teamIds[index];
|
|
14345
|
-
if (!teamId) return
|
|
15467
|
+
if (!teamId) return commitEdgesIfAllowed(store, request ?? body, readCoordinatorConfig);
|
|
14346
15468
|
return serializeRecipientPolicyTeamMutation(store.db, teamId, () => commit(index + 1));
|
|
14347
15469
|
};
|
|
14348
|
-
|
|
14349
|
-
if (result.status === "invalid") return c.json(result, 400);
|
|
14350
|
-
if (result.status === "not_found") return c.json(result, 404);
|
|
14351
|
-
if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
|
|
14352
|
-
return c.json(result);
|
|
15470
|
+
return edgeCommitResponse(c, await commit(0));
|
|
14353
15471
|
} catch (error) {
|
|
14354
15472
|
if (isSqliteBusy(error)) {
|
|
14355
15473
|
c.header("Retry-After", "1");
|
|
@@ -14385,10 +15503,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14385
15503
|
const body = value;
|
|
14386
15504
|
if (Object.keys(body).some((key) => key !== "dryRun") || Object.hasOwn(body, "dryRun") && typeof body.dryRun !== "boolean") return c.json({ error: "request_invalid" }, 400);
|
|
14387
15505
|
try {
|
|
14388
|
-
|
|
14389
|
-
|
|
14390
|
-
localDeviceId: store.deviceId
|
|
14391
|
-
}, { dryRun: body.dryRun === true }));
|
|
15506
|
+
const result = migrateIfAllowed(store, body.dryRun === true, readCoordinatorConfig);
|
|
15507
|
+
return result ? c.json(result) : c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14392
15508
|
} catch (error) {
|
|
14393
15509
|
if (isSqliteBusy(error)) {
|
|
14394
15510
|
c.header("Retry-After", "1");
|
|
@@ -14419,11 +15535,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14419
15535
|
const body = await parseViewerJsonBody(c);
|
|
14420
15536
|
const request = parseReviewRequest(body);
|
|
14421
15537
|
if (!request) return c.json({ error: "request_invalid" }, 400);
|
|
14422
|
-
|
|
14423
|
-
|
|
14424
|
-
localActorId: store.actorId,
|
|
14425
|
-
localDeviceId: store.deviceId
|
|
14426
|
-
}, request);
|
|
15538
|
+
const result = resolveReviewIfAllowed(store, readCoordinatorConfig, request);
|
|
15539
|
+
if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14427
15540
|
if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
|
|
14428
15541
|
if (result.status === "not_found") return c.json(result, 404);
|
|
14429
15542
|
if (result.status === "invalid") return c.json(result, 400);
|
|
@@ -14435,11 +15548,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14435
15548
|
if (!body || !Array.isArray(body.requests) || body.requests.length === 0 || body.requests.length > 100) return c.json({ error: "request_invalid" }, 400);
|
|
14436
15549
|
const requests = body.requests.map(parseReviewRequest);
|
|
14437
15550
|
if (requests.some((request) => request == null)) return c.json({ error: "request_invalid" }, 400);
|
|
14438
|
-
|
|
14439
|
-
|
|
14440
|
-
localActorId: store.actorId,
|
|
14441
|
-
localDeviceId: store.deviceId
|
|
14442
|
-
}, requests);
|
|
15551
|
+
const result = resolveReviewIfAllowed(store, readCoordinatorConfig, requests);
|
|
15552
|
+
if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
|
|
14443
15553
|
return c.json(result, result.results.some((item) => item.status !== "applied") ? 207 : 200);
|
|
14444
15554
|
});
|
|
14445
15555
|
app.get("/api/sync/projects", (c) => projectScopeInventoryRoute(c, getStore()));
|
|
@@ -14662,10 +15772,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14662
15772
|
confirmationToken,
|
|
14663
15773
|
scopeId,
|
|
14664
15774
|
workspaceIdentity
|
|
14665
|
-
}));
|
|
15775
|
+
}, () => canChangeRecipientAccess(readCoordinatorConfig)));
|
|
14666
15776
|
} catch (error) {
|
|
14667
15777
|
const message = error instanceof Error ? error.message : String(error);
|
|
14668
|
-
return c
|
|
15778
|
+
return accessRefusalOr(c, message, message.includes("not found") ? 404 : 400);
|
|
14669
15779
|
}
|
|
14670
15780
|
});
|
|
14671
15781
|
app.put("/api/sync/sharing-domains/project-mappings", async (c) => {
|
|
@@ -14677,7 +15787,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14677
15787
|
const confirmedGuardrailTokens = optionalViewerStringList(body, "confirmed_guardrail_tokens");
|
|
14678
15788
|
const mappingInput = parseViewerProjectMappingInput(body);
|
|
14679
15789
|
releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
|
|
14680
|
-
const
|
|
15790
|
+
const deviceId = requireExistingDeviceIdentity(store);
|
|
14681
15791
|
const analysis = analyzeProjectScopeMappingChangeGuardrails(store.db, {
|
|
14682
15792
|
...mappingInput,
|
|
14683
15793
|
deviceId
|
|
@@ -14689,14 +15799,14 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14689
15799
|
}, 400);
|
|
14690
15800
|
const missingConfirmations = missingGuardrailConfirmations(analysis.warnings, confirmedGuardrailTokens);
|
|
14691
15801
|
if (missingConfirmations.length > 0) return c.json(mappingGuardrailChallenge(analysis.warnings, missingConfirmations), 409);
|
|
14692
|
-
const [mapping] = saveProjectMappingsAndWakePolicies(store, deviceId, [mappingInput]);
|
|
15802
|
+
const [mapping] = saveProjectMappingsAndWakePolicies(store, deviceId, [mappingInput], confirmedGuardrailTokens);
|
|
14693
15803
|
return c.json({
|
|
14694
15804
|
ok: true,
|
|
14695
15805
|
mapping,
|
|
14696
15806
|
guardrail_warnings: analysis.warnings
|
|
14697
15807
|
});
|
|
14698
15808
|
} catch (error) {
|
|
14699
|
-
return c
|
|
15809
|
+
return mappingChangeError(c, error);
|
|
14700
15810
|
} finally {
|
|
14701
15811
|
releasePublicationMutation?.();
|
|
14702
15812
|
}
|
|
@@ -14709,16 +15819,16 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14709
15819
|
try {
|
|
14710
15820
|
const mappingInputs = parseViewerProjectMappingInputs(body);
|
|
14711
15821
|
releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
|
|
14712
|
-
const
|
|
15822
|
+
const deviceId = requireExistingDeviceIdentity(store);
|
|
14713
15823
|
const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
|
|
14714
15824
|
if (verdict.refusal) return c.json(verdict.refusal.body, verdict.refusal.status);
|
|
14715
15825
|
return c.json({
|
|
14716
15826
|
ok: true,
|
|
14717
|
-
mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs),
|
|
15827
|
+
mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs, []),
|
|
14718
15828
|
guardrail_warnings: verdict.warnings
|
|
14719
15829
|
});
|
|
14720
15830
|
} catch (error) {
|
|
14721
|
-
return c
|
|
15831
|
+
return mappingChangeError(c, error);
|
|
14722
15832
|
} finally {
|
|
14723
15833
|
releasePublicationMutation?.();
|
|
14724
15834
|
}
|
|
@@ -14728,9 +15838,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14728
15838
|
const body = await parseViewerJsonBody(c);
|
|
14729
15839
|
if (!body) return c.json({ error: "invalid json" }, 400);
|
|
14730
15840
|
try {
|
|
14731
|
-
const
|
|
14732
|
-
const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
|
|
14733
|
-
const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
|
|
15841
|
+
const verdict = bulkProjectMappingVerdict(store, parseViewerProjectMappingInputs(body), requireExistingDeviceIdentity(store));
|
|
14734
15842
|
return c.json({
|
|
14735
15843
|
ok: true,
|
|
14736
15844
|
accepted: verdict.refusal === null,
|
|
@@ -14738,7 +15846,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14738
15846
|
guardrail_warnings: verdict.warnings
|
|
14739
15847
|
});
|
|
14740
15848
|
} catch (error) {
|
|
14741
|
-
return c
|
|
15849
|
+
return mappingChangeError(c, error);
|
|
14742
15850
|
}
|
|
14743
15851
|
});
|
|
14744
15852
|
app.delete("/api/sync/sharing-domains/project-mappings/:id", (c) => deleteProjectScopeMappingRoute(c, getStore()));
|
|
@@ -14750,75 +15858,15 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
14750
15858
|
} catch {
|
|
14751
15859
|
return c.json({ error: "invalid json" }, 400);
|
|
14752
15860
|
}
|
|
14753
|
-
const result =
|
|
14754
|
-
if ("error" in result) return c.json({ error: result.error }, result.status);
|
|
14755
|
-
return c.json({
|
|
14756
|
-
ok: true,
|
|
14757
|
-
...result
|
|
14758
|
-
});
|
|
14759
|
-
});
|
|
14760
|
-
app.post("/api/sync/actors", async (c) => {
|
|
14761
|
-
const store = getStore();
|
|
14762
|
-
ensureLocalActorRecord(store);
|
|
14763
|
-
let body;
|
|
14764
|
-
try {
|
|
14765
|
-
body = await c.req.json();
|
|
14766
|
-
} catch {
|
|
14767
|
-
return c.json({ error: "invalid json" }, 400);
|
|
14768
|
-
}
|
|
14769
|
-
const rawDisplayName = String(body.display_name ?? "");
|
|
14770
|
-
if (!rawDisplayName.trim()) return c.json({ error: "display_name required" }, 400);
|
|
14771
|
-
let displayName;
|
|
14772
|
-
try {
|
|
14773
|
-
displayName = normalizeHumanPresentationName(rawDisplayName, "display_name");
|
|
14774
|
-
} catch (error) {
|
|
14775
|
-
return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
|
|
14776
|
-
}
|
|
14777
|
-
const d = drizzle(store.db, { schema });
|
|
14778
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
14779
|
-
const actor = {
|
|
14780
|
-
actor_id: randomUUID(),
|
|
14781
|
-
display_name: displayName,
|
|
14782
|
-
is_local: 0,
|
|
14783
|
-
status: "active",
|
|
14784
|
-
merged_into_actor_id: null,
|
|
14785
|
-
created_at: now,
|
|
14786
|
-
updated_at: now
|
|
14787
|
-
};
|
|
14788
|
-
d.insert(schema.actors).values(actor).run();
|
|
14789
|
-
return c.json(actor);
|
|
14790
|
-
});
|
|
14791
|
-
app.post("/api/sync/actors/rename", async (c) => {
|
|
14792
|
-
const store = getStore();
|
|
14793
|
-
ensureLocalActorRecord(store);
|
|
14794
|
-
let body;
|
|
14795
|
-
try {
|
|
14796
|
-
body = await c.req.json();
|
|
14797
|
-
} catch {
|
|
14798
|
-
return c.json({ error: "invalid json" }, 400);
|
|
14799
|
-
}
|
|
14800
|
-
const actorId = String(body.actor_id ?? "").trim();
|
|
14801
|
-
if (!actorId) return c.json({ error: "actor_id required" }, 400);
|
|
14802
|
-
let displayName;
|
|
14803
|
-
try {
|
|
14804
|
-
displayName = normalizeHumanPresentationName(String(body.display_name ?? ""), "display_name");
|
|
14805
|
-
} catch (error) {
|
|
14806
|
-
return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
|
|
14807
|
-
}
|
|
14808
|
-
const d = drizzle(store.db, { schema });
|
|
14809
|
-
const actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();
|
|
14810
|
-
if (!actor) return c.json({ error: "actor not found" }, 404);
|
|
14811
|
-
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
14812
|
-
d.update(schema.actors).set({
|
|
14813
|
-
display_name: displayName,
|
|
14814
|
-
updated_at: updatedAt
|
|
14815
|
-
}).where(eq(schema.actors.actor_id, actorId)).run();
|
|
15861
|
+
const result = persistPeerIdentityIfAllowed(store, body, readCoordinatorConfig);
|
|
15862
|
+
if ("error" in result) return c.json({ error: result.error }, result.status);
|
|
14816
15863
|
return c.json({
|
|
14817
|
-
|
|
14818
|
-
|
|
14819
|
-
updated_at: updatedAt
|
|
15864
|
+
ok: true,
|
|
15865
|
+
...result
|
|
14820
15866
|
});
|
|
14821
15867
|
});
|
|
15868
|
+
app.post("/api/sync/actors", (c) => createActorRoute(c, getStore(), readCoordinatorConfig));
|
|
15869
|
+
app.post("/api/sync/actors/rename", (c) => renameActorRoute(c, getStore(), readCoordinatorConfig));
|
|
14822
15870
|
app.post("/api/sync/actors/merge", async (c) => {
|
|
14823
15871
|
const store = getStore();
|
|
14824
15872
|
let body;
|
|
@@ -15128,11 +16176,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
15128
16176
|
error: "peer_conflict",
|
|
15129
16177
|
detail: "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload."
|
|
15130
16178
|
}, 409);
|
|
15131
|
-
|
|
15132
|
-
pinnedFingerprint: pairingResult.fingerprint,
|
|
15133
|
-
publicKey: pairingResult.public_key,
|
|
15134
|
-
replaceTrust: true
|
|
15135
|
-
});
|
|
16179
|
+
savePairingPayload(store, pairingResult);
|
|
15136
16180
|
return c.json({
|
|
15137
16181
|
ok: true,
|
|
15138
16182
|
type: "pair",
|
|
@@ -15157,7 +16201,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
15157
16201
|
recipientActorId: recipientInvite ? null : store.actorId,
|
|
15158
16202
|
recipientDisplayName: decoded.kind === "add_device" ? null : typeof body.recipient_name === "string" ? body.recipient_name : store.actorDisplayName,
|
|
15159
16203
|
deviceDisplayName: typeof body.device_name === "string" ? body.device_name : null,
|
|
15160
|
-
reviewedOnboardingDigest: reviewedOnboardingDigest || null
|
|
16204
|
+
reviewedOnboardingDigest: reviewedOnboardingDigest || null,
|
|
16205
|
+
confirmCoordinatorJoin: body.confirm_coordinator_join === true
|
|
15161
16206
|
});
|
|
15162
16207
|
const type = recipientInvite ? "recipient_onboarding" : projectInvite ? "project_share" : "team_join";
|
|
15163
16208
|
if (recipientInvite) {
|
|
@@ -15182,9 +16227,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
15182
16227
|
type
|
|
15183
16228
|
});
|
|
15184
16229
|
} catch (error) {
|
|
15185
|
-
|
|
15186
|
-
|
|
15187
|
-
|
|
16230
|
+
return inviteImportFailure(c, error, {
|
|
16231
|
+
projectInvite,
|
|
16232
|
+
recipientInvite
|
|
16233
|
+
});
|
|
15188
16234
|
}
|
|
15189
16235
|
});
|
|
15190
16236
|
app.get("/api/coordinator/admin/status", async (c) => {
|
|
@@ -17485,8 +18531,18 @@ function teamCreationUnavailable(status) {
|
|
|
17485
18531
|
function isCreateTeamBody(body) {
|
|
17486
18532
|
return Boolean(body) && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.displayName === "string";
|
|
17487
18533
|
}
|
|
18534
|
+
/** The one configured group the Team's invitations will go through, if there is exactly one. */
|
|
18535
|
+
function invitationGroup(config) {
|
|
18536
|
+
const groups = config.syncCoordinatorGroups;
|
|
18537
|
+
const coordinatorId = buildBaseUrl(config.syncCoordinatorUrl);
|
|
18538
|
+
return groups.length === 1 && groups[0] && coordinatorId ? {
|
|
18539
|
+
coordinatorId,
|
|
18540
|
+
groupId: groups[0]
|
|
18541
|
+
} : void 0;
|
|
18542
|
+
}
|
|
17488
18543
|
async function createTeam(c, getStore, readConfig) {
|
|
17489
|
-
const
|
|
18544
|
+
const config = readConfig();
|
|
18545
|
+
const unavailable = teamCreationUnavailable(coordinatorAdminStatusPayload(config));
|
|
17490
18546
|
if (unavailable) return c.json({ error: unavailable.code }, unavailable.httpStatus);
|
|
17491
18547
|
const body = await parseViewerJsonBody(c);
|
|
17492
18548
|
if (!isCreateTeamBody(body)) return c.json({ error: "team_name_invalid" }, 400);
|
|
@@ -17496,7 +18552,8 @@ async function createTeam(c, getStore, readConfig) {
|
|
|
17496
18552
|
const team = createRecipientPolicyTeam(store.db, {
|
|
17497
18553
|
displayName: body.displayName,
|
|
17498
18554
|
creatorIdentityId: store.actorId,
|
|
17499
|
-
now: (/* @__PURE__ */ new Date()).toISOString()
|
|
18555
|
+
now: (/* @__PURE__ */ new Date()).toISOString(),
|
|
18556
|
+
coordinatorGroup: invitationGroup(config)
|
|
17500
18557
|
});
|
|
17501
18558
|
return c.json(team, 201);
|
|
17502
18559
|
} catch (error) {
|
|
@@ -17510,6 +18567,295 @@ function teamCreateRoutes(getStore, readCoordinatorConfig = readCoordinatorSyncC
|
|
|
17510
18567
|
return app;
|
|
17511
18568
|
}
|
|
17512
18569
|
//#endregion
|
|
18570
|
+
//#region src/routes/team-member-removal.ts
|
|
18571
|
+
var BASE$1 = "/api/sync/recipient-policy/v1/teams/:teamId/member-removals";
|
|
18572
|
+
var STATUS = {
|
|
18573
|
+
invalid_input: 400,
|
|
18574
|
+
team_not_found: 404,
|
|
18575
|
+
member_not_found: 404,
|
|
18576
|
+
team_not_linked: 409,
|
|
18577
|
+
team_link_conflict: 409,
|
|
18578
|
+
team_coordinator_not_configured: 409,
|
|
18579
|
+
member_already_removed: 409,
|
|
18580
|
+
cannot_remove_yourself: 409,
|
|
18581
|
+
removal_preview_stale: 409,
|
|
18582
|
+
invitations_unavailable: 503,
|
|
18583
|
+
coordinator_unavailable: 503
|
|
18584
|
+
};
|
|
18585
|
+
/** The identifier format the policy layer and the coordinator accept. */
|
|
18586
|
+
function isId(value) {
|
|
18587
|
+
return isStrictRecipientPolicyId(value);
|
|
18588
|
+
}
|
|
18589
|
+
function previewBody(body) {
|
|
18590
|
+
const data = body;
|
|
18591
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return null;
|
|
18592
|
+
if (Object.keys(data).length !== 1 || !isId(data.identityId)) return null;
|
|
18593
|
+
return { identityId: data.identityId };
|
|
18594
|
+
}
|
|
18595
|
+
function commitBody$1(body) {
|
|
18596
|
+
const data = body;
|
|
18597
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return null;
|
|
18598
|
+
if (Object.keys(data).toSorted().join(",") !== "expectedDigest,identityId,revokeInvitationIds") return null;
|
|
18599
|
+
const { identityId, expectedDigest, revokeInvitationIds } = data;
|
|
18600
|
+
if (!isId(identityId) || typeof expectedDigest !== "string" || expectedDigest.length > 256) return null;
|
|
18601
|
+
if (!Array.isArray(revokeInvitationIds) || revokeInvitationIds.length > 200) return null;
|
|
18602
|
+
if (!revokeInvitationIds.every(isId)) return null;
|
|
18603
|
+
return {
|
|
18604
|
+
identityId,
|
|
18605
|
+
expectedDigest,
|
|
18606
|
+
revokeInvitationIds
|
|
18607
|
+
};
|
|
18608
|
+
}
|
|
18609
|
+
function revokeBody(body) {
|
|
18610
|
+
const data = body;
|
|
18611
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return null;
|
|
18612
|
+
if (Object.keys(data).length !== 1 || !Array.isArray(data.inviteIds)) return null;
|
|
18613
|
+
const ids = data.inviteIds;
|
|
18614
|
+
return ids.length > 0 && ids.length <= 200 && ids.every(isId) ? ids : null;
|
|
18615
|
+
}
|
|
18616
|
+
/** The removal context, or null when this device cannot change other people's access. */
|
|
18617
|
+
function removalContext(getStore, options) {
|
|
18618
|
+
const config = (options.readCoordinatorConfig ?? readCoordinatorSyncConfig)();
|
|
18619
|
+
if (!isCoordinatorAdminDevice(config)) return null;
|
|
18620
|
+
const store = getStore();
|
|
18621
|
+
return {
|
|
18622
|
+
coordinator: {
|
|
18623
|
+
remoteUrl: buildBaseUrl(config.syncCoordinatorUrl),
|
|
18624
|
+
adminSecret: config.syncCoordinatorAdminSecret,
|
|
18625
|
+
groupIds: config.syncCoordinatorGroups,
|
|
18626
|
+
timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
|
|
18627
|
+
},
|
|
18628
|
+
localIdentityId: store.actorId ?? null,
|
|
18629
|
+
localDeviceId: store.deviceId ?? null,
|
|
18630
|
+
actions: options.actions
|
|
18631
|
+
};
|
|
18632
|
+
}
|
|
18633
|
+
function teamMemberRemovalRoutes(getStore, options = {}) {
|
|
18634
|
+
const app = new Hono();
|
|
18635
|
+
const context = () => removalContext(getStore, options);
|
|
18636
|
+
const handle = async (c, run) => {
|
|
18637
|
+
const ctx = context();
|
|
18638
|
+
if (!ctx) return c.json({ error: "coordinator_admin_required" }, 403);
|
|
18639
|
+
const teamId = c.req.param("teamId");
|
|
18640
|
+
if (!isId(teamId)) return c.json({ error: "invalid_input" }, 400);
|
|
18641
|
+
const result = await run(teamId, await parseViewerJsonBody(c), ctx);
|
|
18642
|
+
if (result.state === "rejected" && "error" in result) return c.json({ error: result.error }, STATUS[result.error]);
|
|
18643
|
+
return c.json(result);
|
|
18644
|
+
};
|
|
18645
|
+
app.get("/api/sync/recipient-policy/v1/team-coordinator-link-conflicts", (c) => c.json({ teamIds: teamCoordinatorLinkConflicts(getStore().db) }));
|
|
18646
|
+
app.post(`${BASE$1}/preview`, (c) => handle(c, async (teamId, body, ctx) => {
|
|
18647
|
+
const input = previewBody(body);
|
|
18648
|
+
if (!input) return {
|
|
18649
|
+
state: "rejected",
|
|
18650
|
+
error: "invalid_input"
|
|
18651
|
+
};
|
|
18652
|
+
return previewTeamMemberRemoval(getStore().db, {
|
|
18653
|
+
teamId,
|
|
18654
|
+
...input
|
|
18655
|
+
}, ctx);
|
|
18656
|
+
}));
|
|
18657
|
+
app.post(`${BASE$1}/commit`, (c) => handle(c, async (teamId, body, ctx) => {
|
|
18658
|
+
const input = commitBody$1(body);
|
|
18659
|
+
if (!input) return {
|
|
18660
|
+
state: "rejected",
|
|
18661
|
+
error: "invalid_input"
|
|
18662
|
+
};
|
|
18663
|
+
return commitTeamMemberRemoval(getStore().db, {
|
|
18664
|
+
teamId,
|
|
18665
|
+
...input
|
|
18666
|
+
}, ctx);
|
|
18667
|
+
}));
|
|
18668
|
+
app.post("/api/sync/recipient-policy/v1/teams/:teamId/invitations/revoke", (c) => handle(c, async (teamId, body, ctx) => {
|
|
18669
|
+
const inviteIds = revokeBody(body);
|
|
18670
|
+
if (!inviteIds) return {
|
|
18671
|
+
state: "rejected",
|
|
18672
|
+
error: "invalid_input"
|
|
18673
|
+
};
|
|
18674
|
+
return revokePendingTeamInvitations(getStore().db, {
|
|
18675
|
+
teamId,
|
|
18676
|
+
inviteIds
|
|
18677
|
+
}, ctx);
|
|
18678
|
+
}));
|
|
18679
|
+
return app;
|
|
18680
|
+
}
|
|
18681
|
+
//#endregion
|
|
18682
|
+
//#region src/routes/team-recovery.ts
|
|
18683
|
+
var BASE = "/api/sync/recipient-policy/v1/teams/:teamId/recovery";
|
|
18684
|
+
var REFUSAL_STATUS = {
|
|
18685
|
+
invalid_input: 400,
|
|
18686
|
+
team_not_found: 404,
|
|
18687
|
+
team_not_quarantined: 409,
|
|
18688
|
+
setup_record_missing: 409,
|
|
18689
|
+
roster_unavailable: 503,
|
|
18690
|
+
device_removals_unavailable: 503,
|
|
18691
|
+
device_blocks_unavailable: 503,
|
|
18692
|
+
completion_unavailable: 503,
|
|
18693
|
+
member_removals_unavailable: 503,
|
|
18694
|
+
team_group_unavailable: 503,
|
|
18695
|
+
completion_missing: 409,
|
|
18696
|
+
completion_invalid: 409,
|
|
18697
|
+
setup_differs_from_completion: 409,
|
|
18698
|
+
team_group_conflict: 409,
|
|
18699
|
+
team_group_mismatch: 409,
|
|
18700
|
+
team_policy_blocked: 409,
|
|
18701
|
+
device_blocked: 409,
|
|
18702
|
+
device_evidence_contradictory: 409,
|
|
18703
|
+
device_key_unverified: 409,
|
|
18704
|
+
device_key_changed: 409,
|
|
18705
|
+
device_disabled: 409,
|
|
18706
|
+
device_block_unchecked: 503,
|
|
18707
|
+
device_missing_without_removal: 409,
|
|
18708
|
+
device_decision_changed: 409,
|
|
18709
|
+
evidence_stale: 503,
|
|
18710
|
+
admin_authority_changed: 403,
|
|
18711
|
+
recovery_preview_stale: 409,
|
|
18712
|
+
recovery_state_changed: 409
|
|
18713
|
+
};
|
|
18714
|
+
/** Whether the configuration is for the setup's coordinator and one of its groups. */
|
|
18715
|
+
function configuredFor(config, target) {
|
|
18716
|
+
const configured = normalizedCoordinatorId(config.syncCoordinatorUrl);
|
|
18717
|
+
return configured !== null && configured === normalizedCoordinatorId(target.coordinatorId) && config.syncCoordinatorGroups.includes(target.groupId);
|
|
18718
|
+
}
|
|
18719
|
+
/**
|
|
18720
|
+
* The coordinator reads for this device. The block check is signed with the
|
|
18721
|
+
* identity the sync daemon signs with, keys directory included. Without a
|
|
18722
|
+
* usable one the check fails, and the recovery reads it as unavailable.
|
|
18723
|
+
*/
|
|
18724
|
+
function evidenceActions(store, config) {
|
|
18725
|
+
const identity = daemonSigningIdentity(store);
|
|
18726
|
+
const actions = coordinatorTeamRecoveryEvidenceActions(store, config, identity ?? { localDeviceId: "" });
|
|
18727
|
+
if (identity) return actions;
|
|
18728
|
+
const unsigned = () => Promise.reject(/* @__PURE__ */ new Error("signing_identity_unavailable"));
|
|
18729
|
+
return {
|
|
18730
|
+
...actions,
|
|
18731
|
+
deviceBlocksAndRemovals: unsigned
|
|
18732
|
+
};
|
|
18733
|
+
}
|
|
18734
|
+
/**
|
|
18735
|
+
* What a request acts on, or why it cannot: the device is no admin, the Team
|
|
18736
|
+
* has no completed setup here, or its setup belongs to a coordinator or group
|
|
18737
|
+
* this device is not configured for.
|
|
18738
|
+
*/
|
|
18739
|
+
function recoveryRequest(teamId, getStore, options) {
|
|
18740
|
+
const readConfig = options.readCoordinatorConfig ?? readCoordinatorSyncConfig;
|
|
18741
|
+
const config = readConfig();
|
|
18742
|
+
if (!isCoordinatorAdminDevice(config)) return {
|
|
18743
|
+
error: "coordinator_admin_required",
|
|
18744
|
+
status: 403
|
|
18745
|
+
};
|
|
18746
|
+
if (!isStrictRecipientPolicyId(teamId)) return {
|
|
18747
|
+
error: "invalid_input",
|
|
18748
|
+
status: 400
|
|
18749
|
+
};
|
|
18750
|
+
const store = getStore();
|
|
18751
|
+
const target = teamRecoveryTarget(store.db, teamId);
|
|
18752
|
+
if (!target) return {
|
|
18753
|
+
error: "team_not_found",
|
|
18754
|
+
status: 404
|
|
18755
|
+
};
|
|
18756
|
+
if (!configuredFor(config, target)) return {
|
|
18757
|
+
error: "team_coordinator_not_configured",
|
|
18758
|
+
status: 409
|
|
18759
|
+
};
|
|
18760
|
+
const stillAuthorized = () => {
|
|
18761
|
+
const current = readConfig();
|
|
18762
|
+
return isCoordinatorAdminDevice(current) && configuredFor(current, target) && current.syncCoordinatorAdminSecret === config.syncCoordinatorAdminSecret;
|
|
18763
|
+
};
|
|
18764
|
+
const actions = options.actions ?? evidenceActions(store, config);
|
|
18765
|
+
return {
|
|
18766
|
+
db: store.db,
|
|
18767
|
+
target,
|
|
18768
|
+
actions,
|
|
18769
|
+
stillAuthorized
|
|
18770
|
+
};
|
|
18771
|
+
}
|
|
18772
|
+
/** The response for a commit that did not leave the Team recovered. */
|
|
18773
|
+
function commitFailure(result) {
|
|
18774
|
+
if (result.state === "refused") {
|
|
18775
|
+
const { reason, deviceIds } = result;
|
|
18776
|
+
return {
|
|
18777
|
+
body: deviceIds ? {
|
|
18778
|
+
error: reason,
|
|
18779
|
+
deviceIds
|
|
18780
|
+
} : { error: reason },
|
|
18781
|
+
status: REFUSAL_STATUS[reason]
|
|
18782
|
+
};
|
|
18783
|
+
}
|
|
18784
|
+
if (result.state === "superseded") return {
|
|
18785
|
+
body: { error: "recovery_superseded" },
|
|
18786
|
+
status: 409
|
|
18787
|
+
};
|
|
18788
|
+
if (result.state === "unverified") {
|
|
18789
|
+
const status = result.reason === "admin_authority_changed" ? 403 : 503;
|
|
18790
|
+
return {
|
|
18791
|
+
body: {
|
|
18792
|
+
error: "recovery_unverified",
|
|
18793
|
+
reason: result.reason
|
|
18794
|
+
},
|
|
18795
|
+
status
|
|
18796
|
+
};
|
|
18797
|
+
}
|
|
18798
|
+
return {
|
|
18799
|
+
body: {
|
|
18800
|
+
error: "recovery_quarantined_again",
|
|
18801
|
+
reason: result.reason
|
|
18802
|
+
},
|
|
18803
|
+
status: result.reason === "evidence_unavailable" ? 503 : 409
|
|
18804
|
+
};
|
|
18805
|
+
}
|
|
18806
|
+
function isEmptyObject(body) {
|
|
18807
|
+
return Boolean(body) && typeof body === "object" && Object.keys(body).length === 0;
|
|
18808
|
+
}
|
|
18809
|
+
function commitBody(body) {
|
|
18810
|
+
const data = body;
|
|
18811
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return null;
|
|
18812
|
+
if (Object.keys(data).length !== 1) return null;
|
|
18813
|
+
const { expectedDigest } = data;
|
|
18814
|
+
if (typeof expectedDigest !== "string" || !expectedDigest || expectedDigest.length > 256) return null;
|
|
18815
|
+
return { expectedDigest };
|
|
18816
|
+
}
|
|
18817
|
+
function teamRecoveryRoutes(getStore, options = {}) {
|
|
18818
|
+
const app = new Hono();
|
|
18819
|
+
const read = (request) => readTeamRecoveryEvidence(request.target, request.actions, options.nowMs);
|
|
18820
|
+
app.post(`${BASE}/preview`, async (c) => {
|
|
18821
|
+
const request = recoveryRequest(c.req.param("teamId") ?? "", getStore, options);
|
|
18822
|
+
if ("error" in request) return c.json({ error: request.error }, request.status);
|
|
18823
|
+
if (!isEmptyObject(await parseViewerJsonBody(c, { allowEmpty: true }))) return c.json({ error: "invalid_input" }, 400);
|
|
18824
|
+
const { evidence, startedAtMs } = await read(request);
|
|
18825
|
+
if (!request.stillAuthorized()) return c.json({ error: "coordinator_admin_required" }, 403);
|
|
18826
|
+
const nowMs = (options.nowMs ?? Date.now)();
|
|
18827
|
+
if (isTeamRecoveryEvidenceStale(startedAtMs, nowMs)) return c.json({ error: "evidence_stale" }, REFUSAL_STATUS.evidence_stale);
|
|
18828
|
+
const preview = previewTeamRecovery(request.db, request.target, evidence, { nowMs });
|
|
18829
|
+
if (preview.state === "ready") return c.json(preview);
|
|
18830
|
+
const failure = commitFailure(preview);
|
|
18831
|
+
return c.json(failure.body, failure.status);
|
|
18832
|
+
});
|
|
18833
|
+
app.post(`${BASE}/commit`, async (c) => {
|
|
18834
|
+
const request = recoveryRequest(c.req.param("teamId") ?? "", getStore, options);
|
|
18835
|
+
if ("error" in request) return c.json({ error: request.error }, request.status);
|
|
18836
|
+
const input = commitBody(await parseViewerJsonBody(c));
|
|
18837
|
+
if (!input) return c.json({ error: "invalid_input" }, 400);
|
|
18838
|
+
const release = claimCandidateMutation(request.db, request.target.candidateRef);
|
|
18839
|
+
if (!release) return c.json({ error: "team_setup_busy" }, 409);
|
|
18840
|
+
try {
|
|
18841
|
+
const result = await commitTeamRecovery(request.db, {
|
|
18842
|
+
...request.target,
|
|
18843
|
+
...input
|
|
18844
|
+
}, {
|
|
18845
|
+
readEvidence: () => read(request),
|
|
18846
|
+
nowMs: options.nowMs,
|
|
18847
|
+
stillAuthorized: request.stillAuthorized
|
|
18848
|
+
});
|
|
18849
|
+
if (result.state === "recovered") return c.json(result);
|
|
18850
|
+
const failure = commitFailure(result);
|
|
18851
|
+
return c.json(failure.body, failure.status);
|
|
18852
|
+
} finally {
|
|
18853
|
+
release();
|
|
18854
|
+
}
|
|
18855
|
+
});
|
|
18856
|
+
return app;
|
|
18857
|
+
}
|
|
18858
|
+
//#endregion
|
|
17513
18859
|
//#region src/routes/update-status.ts
|
|
17514
18860
|
function updateStatusRoutes(options = {}) {
|
|
17515
18861
|
const getUpdateStatus$1 = options.getUpdateStatus ?? getUpdateStatus;
|
|
@@ -17567,7 +18913,7 @@ function createSyncApp$1(opts) {
|
|
|
17567
18913
|
const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
|
|
17568
18914
|
const app = new Hono();
|
|
17569
18915
|
app.route("/", syncProtocolRoutes(storeFactory, {
|
|
17570
|
-
|
|
18916
|
+
mode: opts?.mode,
|
|
17571
18917
|
routeRateLimit: {
|
|
17572
18918
|
limiter: rateLimiter,
|
|
17573
18919
|
readLimit,
|
|
@@ -17968,6 +19314,37 @@ AUTH_CONTROLLER_CURRENT_SQL.replace("SELECT a.*", "SELECT e.*");
|
|
|
17968
19314
|
function ownerProfileConflict() {
|
|
17969
19315
|
throw new Error("Owner enrollment stopped for review. Keep the profile and saved request unchanged; no identity or access repair is automatic.");
|
|
17970
19316
|
}
|
|
19317
|
+
//#endregion
|
|
19318
|
+
//#region ../core/src/coordinator-history.ts
|
|
19319
|
+
var historyRow = (kind, source, deviceId, fingerprint) => `INSERT INTO coordinator_history(subject_kind, device_id, fingerprint, source, recorded_at)
|
|
19320
|
+
SELECT '${kind}', ${deviceId}, ${fingerprint}, '${source}', strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
|
|
19321
|
+
WHERE NOT EXISTS (SELECT 1 FROM coordinator_history
|
|
19322
|
+
WHERE subject_kind = '${kind}' AND device_id = ${deviceId} AND fingerprint = ${fingerprint});`;
|
|
19323
|
+
var STORE_ROW = (source) => historyRow("store", source, "''", "''");
|
|
19324
|
+
var DEVICE_ROW = (source, deviceId, fingerprint) => historyRow("device", source, deviceId, fingerprint);
|
|
19325
|
+
var PEER_COORDINATOR_FIELDS = `(NEW.discovered_via_coordinator_id IS NOT NULL
|
|
19326
|
+
OR NEW.discovered_via_group_id IS NOT NULL
|
|
19327
|
+
OR NEW.pending_bootstrap_grant_id IS NOT NULL
|
|
19328
|
+
OR NEW.trust_provenance = 'coordinator_policy')`;
|
|
19329
|
+
function trigger(name, table, event, when, body) {
|
|
19330
|
+
return {
|
|
19331
|
+
name,
|
|
19332
|
+
table,
|
|
19333
|
+
sql: `CREATE TRIGGER IF NOT EXISTS ${name} AFTER ${event} ON ${table} WHEN ${when}
|
|
19334
|
+
BEGIN ${body} END;`
|
|
19335
|
+
};
|
|
19336
|
+
}
|
|
19337
|
+
[
|
|
19338
|
+
...["INSERT", "UPDATE OF authority_type, coordinator_id"].map((event, index) => trigger(`coordinator_history_scope_${index ? "update" : "insert"}`, "replication_scopes", event, "NEW.authority_type <> 'local' OR NEW.coordinator_id IS NOT NULL", STORE_ROW("scope"))),
|
|
19339
|
+
...["INSERT", "UPDATE OF coordinator_id, group_id"].map((event, index) => trigger(`coordinator_history_membership_${index ? "update" : "insert"}`, "scope_memberships", event, "NEW.coordinator_id IS NOT NULL OR NEW.group_id IS NOT NULL", STORE_ROW("scope_membership") + DEVICE_ROW("scope_membership", "NEW.device_id", "''"))),
|
|
19340
|
+
trigger("coordinator_history_membership_cache_insert", "scope_membership_cache_state", "INSERT", "1", STORE_ROW("membership_cache")),
|
|
19341
|
+
...["INSERT", "UPDATE OF discovered_via_coordinator_id, discovered_via_group_id, pending_bootstrap_grant_id, trust_provenance"].map((event, index) => trigger(`coordinator_history_peer_${index ? "update" : "insert"}`, "sync_peers", event, PEER_COORDINATOR_FIELDS, STORE_ROW("peer_trust") + DEVICE_ROW("peer_trust", "NEW.peer_device_id", "COALESCE(NEW.pinned_fingerprint, '')"))),
|
|
19342
|
+
trigger("coordinator_history_project_projection_insert", "recipient_managed_project_projections", "INSERT", "1", STORE_ROW("invitation")),
|
|
19343
|
+
trigger("coordinator_history_filter_management_insert", "peer_project_filter_management", "INSERT", "1", STORE_ROW("filter_management"))
|
|
19344
|
+
];
|
|
19345
|
+
/** Evidence written before history existed, by table, as (kind, device_id, fingerprint) rows. */
|
|
19346
|
+
var STORE_EVIDENCE = "SELECT 'store' AS kind, '' AS device_id, '' AS fingerprint";
|
|
19347
|
+
`${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${PEER_COORDINATOR_FIELDS.replaceAll("NEW.", "")}`;
|
|
17971
19348
|
[{
|
|
17972
19349
|
name: "trg_identity_devices_assignment_version",
|
|
17973
19350
|
create: `CREATE TRIGGER trg_identity_devices_assignment_version
|
|
@@ -17986,6 +19363,49 @@ function ownerProfileConflict() {
|
|
|
17986
19363
|
DELETE FROM policy_team_device_decisions WHERE device_id = OLD.device_id;
|
|
17987
19364
|
END`
|
|
17988
19365
|
}].map(({ name, create }) => `DROP TRIGGER IF EXISTS ${name};\n${create};`).join("\n");
|
|
19366
|
+
//#endregion
|
|
19367
|
+
//#region ../core/src/transitioned-store-names.ts
|
|
19368
|
+
/**
|
|
19369
|
+
* On-disk names of a transitioned device store, and the SQL rewriting that lets
|
|
19370
|
+
* current code keep using the released names.
|
|
19371
|
+
*
|
|
19372
|
+
* Every object that holds memory content, or that can rebuild it, gets a name no
|
|
19373
|
+
* released client knows: memory text and its FTS index, embeddings, captured
|
|
19374
|
+
* transcripts and their flush records, prompts, summaries, artifacts, session
|
|
19375
|
+
* metadata (which keeps the first prompt), creation snapshots, extracted concept
|
|
19376
|
+
* and file references, replication op payloads and the sync identity. The
|
|
19377
|
+
* inventory test in `transitioned-store-inventory.test.ts` fails when a table with
|
|
19378
|
+
* a content-like column is added without either appearing here or being reviewed
|
|
19379
|
+
* as metadata there.
|
|
19380
|
+
*
|
|
19381
|
+
* Never expose a permanent view or trigger under a released name that routes reads
|
|
19382
|
+
* or writes to these objects.
|
|
19383
|
+
*/
|
|
19384
|
+
var transitionedNames = {
|
|
19385
|
+
sessions: "project_sessions",
|
|
19386
|
+
memory_items: "project_memory_items",
|
|
19387
|
+
memory_fts: "project_memory_fts",
|
|
19388
|
+
memory_items_ai: "project_memory_items_ai",
|
|
19389
|
+
memory_items_au: "project_memory_items_au",
|
|
19390
|
+
memory_items_ad: "project_memory_items_ad",
|
|
19391
|
+
memory_concept_refs: "project_memory_concept_refs",
|
|
19392
|
+
memory_file_refs: "project_memory_file_refs",
|
|
19393
|
+
memory_local_creation_snapshots: "project_memory_local_creation_snapshots",
|
|
19394
|
+
memory_vectors: "project_memory_vectors",
|
|
19395
|
+
memory_vectors_rowids: "project_memory_vectors_rowids",
|
|
19396
|
+
memory_vectors_v1: "project_memory_vectors_v1",
|
|
19397
|
+
memory_vectors_v1_rowids: "project_memory_vectors_v1_rowids",
|
|
19398
|
+
artifacts: "project_artifacts",
|
|
19399
|
+
user_prompts: "project_user_prompts",
|
|
19400
|
+
session_summaries: "project_session_summaries",
|
|
19401
|
+
raw_events: "project_raw_events",
|
|
19402
|
+
raw_event_flush_batches: "project_raw_event_flush_batches",
|
|
19403
|
+
replication_ops: "project_replication_ops",
|
|
19404
|
+
sync_device: "project_sync_device"
|
|
19405
|
+
};
|
|
19406
|
+
new Map(Object.entries(transitionedNames));
|
|
19407
|
+
new Map(Object.entries(transitionedNames).map(([logical, physical]) => [physical, logical]));
|
|
19408
|
+
`${Object.entries(transitionedNames).flat().map((name) => `'${name}'`).join(",")}`;
|
|
17989
19409
|
var BUMP = `UPDATE sync_peer_removal_check_state SET generation = generation + 1, applied_removal_seq = 0 WHERE id = 1`;
|
|
17990
19410
|
[
|
|
17991
19411
|
[
|
|
@@ -18013,6 +19433,15 @@ var BUMP = `UPDATE sync_peer_removal_check_state SET generation = generation + 1
|
|
|
18013
19433
|
sql: `CREATE TRIGGER sync_peer_removal_generation_${suffix} ${event} ${condition}
|
|
18014
19434
|
BEGIN ${BUMP}; END`
|
|
18015
19435
|
}));
|
|
19436
|
+
//#endregion
|
|
19437
|
+
//#region ../core/src/sync-transport-policy.ts
|
|
19438
|
+
var TABLE$1 = "sync_peer_transport_policy";
|
|
19439
|
+
`${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}`;
|
|
19440
|
+
//#endregion
|
|
19441
|
+
//#region ../core/src/unpaired-peer-pin.ts
|
|
19442
|
+
var TABLE = "unpaired_peer_pins";
|
|
19443
|
+
`${TABLE}`;
|
|
19444
|
+
`${TABLE}`;
|
|
18016
19445
|
[
|
|
18017
19446
|
[
|
|
18018
19447
|
"insert",
|
|
@@ -18148,6 +19577,8 @@ var memoryItems = sqliteTable("memory_items", {
|
|
|
18148
19577
|
index("idx_memory_items_active_created").on(table.active, table.created_at),
|
|
18149
19578
|
index("idx_memory_items_created_id").on(table.created_at, table.id),
|
|
18150
19579
|
index("idx_memory_items_origin_device_active").on(table.origin_device_id, table.active),
|
|
19580
|
+
index("idx_memory_items_origin_active_scope").on(table.origin_device_id, table.active, table.scope_id),
|
|
19581
|
+
index("idx_memory_items_updated_at").on(table.updated_at),
|
|
18151
19582
|
index("idx_memory_items_session").on(table.session_id),
|
|
18152
19583
|
index("idx_memory_items_project").on(table.project),
|
|
18153
19584
|
index("idx_memory_items_scope_visibility_created").on(table.scope_id, table.visibility, table.created_at),
|
|
@@ -18403,7 +19834,9 @@ sqliteTable("raw_event_flush_batches", {
|
|
|
18403
19834
|
index("idx_flush_batches_session_created").on(table.opencode_session_id, table.created_at),
|
|
18404
19835
|
index("idx_flush_batches_status_updated").on(table.status, table.updated_at),
|
|
18405
19836
|
index("idx_flush_batches_observer_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NOT NULL`),
|
|
18406
|
-
index("idx_flush_batches_capture_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NULL`)
|
|
19837
|
+
index("idx_flush_batches_capture_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NULL`),
|
|
19838
|
+
index("idx_flush_batches_auth_missing").on(table.source, table.stream_id, table.created_at).where(sql`${table.observer_error_code} = 'auth_missing' AND ${table.status} IN ('failed', 'gave_up')`),
|
|
19839
|
+
index("idx_flush_batches_recovery_attempts").on(table.updated_at, table.attempt_count).where(sql`${table.extractor_version} = 'raw_events_auth_recovery_v1' AND ${table.attempt_count} > 0`)
|
|
18407
19840
|
]);
|
|
18408
19841
|
sqliteTable("user_prompts", {
|
|
18409
19842
|
id: integer("id").primaryKey(),
|
|
@@ -18725,6 +20158,42 @@ sqliteTable("policy_team_member_removals", {
|
|
|
18725
20158
|
table.team_id,
|
|
18726
20159
|
table.identity_id
|
|
18727
20160
|
] })]);
|
|
20161
|
+
sqliteTable("policy_team_coordinator_links", {
|
|
20162
|
+
team_id: text("team_id").notNull(),
|
|
20163
|
+
coordinator_id: text("coordinator_id").notNull(),
|
|
20164
|
+
group_id: text("group_id").notNull(),
|
|
20165
|
+
source: text("source").notNull(),
|
|
20166
|
+
recorded_at: text("recorded_at").notNull()
|
|
20167
|
+
}, (table) => [primaryKey({ columns: [
|
|
20168
|
+
table.team_id,
|
|
20169
|
+
table.coordinator_id,
|
|
20170
|
+
table.group_id
|
|
20171
|
+
] })]);
|
|
20172
|
+
sqliteTable("policy_team_member_removal_enforcements", {
|
|
20173
|
+
team_id: text("team_id").notNull(),
|
|
20174
|
+
identity_id: text("identity_id").notNull(),
|
|
20175
|
+
enforced_at: text("enforced_at").notNull()
|
|
20176
|
+
}, (table) => [primaryKey({ columns: [table.team_id, table.identity_id] })]);
|
|
20177
|
+
sqliteTable("policy_team_recovery_exclusions", {
|
|
20178
|
+
team_id: text("team_id").notNull(),
|
|
20179
|
+
device_id: text("device_id").notNull(),
|
|
20180
|
+
key_fingerprint: text("key_fingerprint").notNull(),
|
|
20181
|
+
reason: text("reason").notNull(),
|
|
20182
|
+
excluded_at: text("excluded_at").notNull()
|
|
20183
|
+
}, (table) => [primaryKey({ columns: [table.team_id, table.device_id] })]);
|
|
20184
|
+
sqliteTable("policy_team_recovery_holds", {
|
|
20185
|
+
team_id: text("team_id").primaryKey().notNull(),
|
|
20186
|
+
recovery_id: text("recovery_id").notNull(),
|
|
20187
|
+
reason: text("reason").notNull(),
|
|
20188
|
+
held_at: text("held_at").notNull()
|
|
20189
|
+
});
|
|
20190
|
+
sqliteTable("policy_team_recovery_skipped_projects", {
|
|
20191
|
+
team_id: text("team_id").notNull(),
|
|
20192
|
+
project_identity: text("project_identity").notNull(),
|
|
20193
|
+
recovery_id: text("recovery_id").notNull(),
|
|
20194
|
+
reason: text("reason").notNull(),
|
|
20195
|
+
skipped_at: text("skipped_at").notNull()
|
|
20196
|
+
}, (table) => [primaryKey({ columns: [table.team_id, table.project_identity] })]);
|
|
18728
20197
|
sqliteTable("identity_devices", {
|
|
18729
20198
|
device_id: text("device_id").primaryKey(),
|
|
18730
20199
|
identity_id: text("identity_id").notNull(),
|
|
@@ -20166,19 +21635,35 @@ function prepareChannelRequest(input) {
|
|
|
20166
21635
|
peerPin
|
|
20167
21636
|
};
|
|
20168
21637
|
}
|
|
21638
|
+
function channelMode(kind, peers, maxEntryBytes) {
|
|
21639
|
+
if (kind === "relay") return {
|
|
21640
|
+
kind,
|
|
21641
|
+
maxEntryBytes,
|
|
21642
|
+
peerPin: (request) => peers.get(request)?.pin ?? null
|
|
21643
|
+
};
|
|
21644
|
+
return {
|
|
21645
|
+
kind,
|
|
21646
|
+
maxEntryBytes,
|
|
21647
|
+
peer: (request) => peers.get(request) ?? null
|
|
21648
|
+
};
|
|
21649
|
+
}
|
|
20169
21650
|
function createSyncChannelDispatcher(options) {
|
|
20170
21651
|
const storeFactory = options.storeFactory.bind(options);
|
|
20171
|
-
const
|
|
21652
|
+
const peers = /* @__PURE__ */ new WeakMap();
|
|
20172
21653
|
const app = createSyncApp$1({
|
|
20173
21654
|
storeFactory,
|
|
20174
|
-
|
|
21655
|
+
mode: channelMode(options.mode ?? "relay", peers, options.maxEntryBytes),
|
|
21656
|
+
syncRequestRateLimit: options.limiter ? { limiter: options.limiter } : void 0
|
|
20175
21657
|
});
|
|
20176
21658
|
return async (input) => {
|
|
20177
21659
|
const prepared = prepareChannelRequest(input);
|
|
20178
21660
|
if (!("request" in prepared)) return prepared;
|
|
20179
21661
|
const { request, peerPin } = prepared;
|
|
20180
21662
|
const signal = request.signal;
|
|
20181
|
-
|
|
21663
|
+
peers.set(request, {
|
|
21664
|
+
pin: peerPin,
|
|
21665
|
+
deviceId: input.peerDeviceId ?? ""
|
|
21666
|
+
});
|
|
20182
21667
|
try {
|
|
20183
21668
|
checkCancellation(signal);
|
|
20184
21669
|
const response = await app.fetch(request);
|
|
@@ -20189,7 +21674,7 @@ function createSyncChannelDispatcher(options) {
|
|
|
20189
21674
|
bodyBytes
|
|
20190
21675
|
};
|
|
20191
21676
|
} finally {
|
|
20192
|
-
|
|
21677
|
+
peers.delete(request);
|
|
20193
21678
|
}
|
|
20194
21679
|
};
|
|
20195
21680
|
}
|
|
@@ -20512,6 +21997,465 @@ function createViewerRelayReachability(options) {
|
|
|
20512
21997
|
};
|
|
20513
21998
|
}
|
|
20514
21999
|
//#endregion
|
|
22000
|
+
//#region src/response-byte-budget.ts
|
|
22001
|
+
/**
|
|
22002
|
+
* Bounds the response bytes a listener may hold in memory at once. Each
|
|
22003
|
+
* exchange reserves the largest response it could produce before the response
|
|
22004
|
+
* is collected, and releases the reservation once the response is written.
|
|
22005
|
+
* Waiters are served in arrival order.
|
|
22006
|
+
*/
|
|
22007
|
+
var ResponseByteBudget = class {
|
|
22008
|
+
totalBytes;
|
|
22009
|
+
available;
|
|
22010
|
+
waiters = [];
|
|
22011
|
+
constructor(totalBytes) {
|
|
22012
|
+
this.totalBytes = totalBytes;
|
|
22013
|
+
if (!Number.isSafeInteger(totalBytes) || totalBytes <= 0) throw new RangeError("Response byte budget must be a positive integer");
|
|
22014
|
+
this.available = totalBytes;
|
|
22015
|
+
}
|
|
22016
|
+
/** Resolves with a release function once the bytes are reserved. */
|
|
22017
|
+
async acquire(bytes, signal) {
|
|
22018
|
+
if (!Number.isSafeInteger(bytes) || bytes <= 0 || bytes > this.totalBytes) throw new RangeError("Response reservation exceeds the budget");
|
|
22019
|
+
signal?.throwIfAborted();
|
|
22020
|
+
if (this.waiters.length === 0 && this.available >= bytes) {
|
|
22021
|
+
this.available -= bytes;
|
|
22022
|
+
return this.releaser(bytes);
|
|
22023
|
+
}
|
|
22024
|
+
await new Promise((resolve, reject) => {
|
|
22025
|
+
const waiter = {
|
|
22026
|
+
bytes,
|
|
22027
|
+
resolve
|
|
22028
|
+
};
|
|
22029
|
+
this.waiters.push(waiter);
|
|
22030
|
+
signal?.addEventListener("abort", () => {
|
|
22031
|
+
const index = this.waiters.indexOf(waiter);
|
|
22032
|
+
if (index < 0) return;
|
|
22033
|
+
this.waiters.splice(index, 1);
|
|
22034
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("Response reservation cancelled"));
|
|
22035
|
+
this.drain();
|
|
22036
|
+
}, { once: true });
|
|
22037
|
+
});
|
|
22038
|
+
return this.releaser(bytes);
|
|
22039
|
+
}
|
|
22040
|
+
get availableBytes() {
|
|
22041
|
+
return this.available;
|
|
22042
|
+
}
|
|
22043
|
+
releaser(bytes) {
|
|
22044
|
+
let released = false;
|
|
22045
|
+
return () => {
|
|
22046
|
+
if (released) return;
|
|
22047
|
+
released = true;
|
|
22048
|
+
this.available += bytes;
|
|
22049
|
+
this.drain();
|
|
22050
|
+
};
|
|
22051
|
+
}
|
|
22052
|
+
drain() {
|
|
22053
|
+
while (this.waiters[0] && this.available >= this.waiters[0].bytes) {
|
|
22054
|
+
const next = this.waiters.shift();
|
|
22055
|
+
if (!next) return;
|
|
22056
|
+
this.available -= next.bytes;
|
|
22057
|
+
next.resolve();
|
|
22058
|
+
}
|
|
22059
|
+
}
|
|
22060
|
+
};
|
|
22061
|
+
//#endregion
|
|
22062
|
+
//#region src/sync-noise-gate.ts
|
|
22063
|
+
var DIRECT_NOISE_GATE_LIMITS = Object.freeze({
|
|
22064
|
+
pendingTotal: 32,
|
|
22065
|
+
pendingPerIp: 4,
|
|
22066
|
+
streamsTotal: 256,
|
|
22067
|
+
streamsPerPeer: 8,
|
|
22068
|
+
responseBudgetBytes: 134217728,
|
|
22069
|
+
handshakeMs: RELAY_NOISE_LIMITS.handshakeMs
|
|
22070
|
+
});
|
|
22071
|
+
/** Open slots in total and per key, each released exactly once. */
|
|
22072
|
+
var Counter = class {
|
|
22073
|
+
maxTotal;
|
|
22074
|
+
maxPerKey;
|
|
22075
|
+
total = 0;
|
|
22076
|
+
byKey = /* @__PURE__ */ new Map();
|
|
22077
|
+
constructor(maxTotal, maxPerKey) {
|
|
22078
|
+
this.maxTotal = maxTotal;
|
|
22079
|
+
this.maxPerKey = maxPerKey;
|
|
22080
|
+
}
|
|
22081
|
+
reserve(key) {
|
|
22082
|
+
const count = this.byKey.get(key) ?? 0;
|
|
22083
|
+
if (this.total >= this.maxTotal || count >= this.maxPerKey) return null;
|
|
22084
|
+
this.total += 1;
|
|
22085
|
+
this.byKey.set(key, count + 1);
|
|
22086
|
+
let released = false;
|
|
22087
|
+
return () => {
|
|
22088
|
+
if (released) return;
|
|
22089
|
+
released = true;
|
|
22090
|
+
this.total -= 1;
|
|
22091
|
+
const remaining = (this.byKey.get(key) ?? 1) - 1;
|
|
22092
|
+
if (remaining > 0) this.byKey.set(key, remaining);
|
|
22093
|
+
else this.byKey.delete(key);
|
|
22094
|
+
};
|
|
22095
|
+
}
|
|
22096
|
+
};
|
|
22097
|
+
var GateRefusal = class extends Error {
|
|
22098
|
+
status;
|
|
22099
|
+
body;
|
|
22100
|
+
constructor(status, body) {
|
|
22101
|
+
super(body);
|
|
22102
|
+
this.status = status;
|
|
22103
|
+
this.body = body;
|
|
22104
|
+
}
|
|
22105
|
+
};
|
|
22106
|
+
var STATUS_TEXT = {
|
|
22107
|
+
400: "Bad Request",
|
|
22108
|
+
401: "Unauthorized",
|
|
22109
|
+
429: "Too Many Requests",
|
|
22110
|
+
503: "Service Unavailable"
|
|
22111
|
+
};
|
|
22112
|
+
/** Time a refused client has to read its refusal before the socket is destroyed anyway. */
|
|
22113
|
+
var REFUSAL_FLUSH_MS = 1e3;
|
|
22114
|
+
/**
|
|
22115
|
+
* Sends a plain HTTP refusal, then destroys the socket. Ending it would wait
|
|
22116
|
+
* for the client to close its side, so a client that kept writing open would
|
|
22117
|
+
* keep holding the socket and its slot.
|
|
22118
|
+
*/
|
|
22119
|
+
function refuse(socket, refusal) {
|
|
22120
|
+
const body = JSON.stringify({ error: refusal.body });
|
|
22121
|
+
const timer = setTimeout(() => socket.destroy(), REFUSAL_FLUSH_MS);
|
|
22122
|
+
timer.unref();
|
|
22123
|
+
socket.write(`HTTP/1.1 ${refusal.status} ${STATUS_TEXT[refusal.status]}\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`, () => {
|
|
22124
|
+
clearTimeout(timer);
|
|
22125
|
+
socket.destroy();
|
|
22126
|
+
});
|
|
22127
|
+
}
|
|
22128
|
+
function headerValue(request, name) {
|
|
22129
|
+
const value = request.headers[name.toLowerCase()];
|
|
22130
|
+
return typeof value === "string" ? value : void 0;
|
|
22131
|
+
}
|
|
22132
|
+
/** A canonical upgrade request with nothing sent after its headers, or a refusal. */
|
|
22133
|
+
function parseUpgrade(request, head) {
|
|
22134
|
+
const target = parseDirectNoiseUpgradeTarget(request.url);
|
|
22135
|
+
const protocol = headerValue(request, "upgrade")?.trim().toLowerCase();
|
|
22136
|
+
if (request.method !== "GET" || protocol !== DIRECT_NOISE_UPGRADE_PROTOCOL || !target) throw new GateRefusal(400, "invalid_upgrade");
|
|
22137
|
+
if (head.byteLength !== 0) throw new GateRefusal(400, "invalid_upgrade");
|
|
22138
|
+
return target;
|
|
22139
|
+
}
|
|
22140
|
+
function authorize(store, request) {
|
|
22141
|
+
const auth = authorizeDirectNoiseUpgrade(store, {
|
|
22142
|
+
method: "GET",
|
|
22143
|
+
url: `${DIRECT_NOISE_LOGICAL_ORIGIN}${request.url}`,
|
|
22144
|
+
header: (name) => headerValue(request, name)
|
|
22145
|
+
});
|
|
22146
|
+
if (!auth.ok) throw new GateRefusal(auth.busy ? 503 : 401, auth.busy ? "busy" : "unauthorized");
|
|
22147
|
+
return auth;
|
|
22148
|
+
}
|
|
22149
|
+
function localIdentity(store, keysDir) {
|
|
22150
|
+
const row = store.db.prepare("SELECT device_id, public_key FROM sync_device LIMIT 1").get();
|
|
22151
|
+
const bytes = row ? loadPrivateKey(keysDir, store.dbPath, row.device_id) : null;
|
|
22152
|
+
if (!row?.public_key || !bytes) throw new GateRefusal(503, "unavailable");
|
|
22153
|
+
return {
|
|
22154
|
+
key: createPrivateKey(bytes),
|
|
22155
|
+
expectedPin: row.public_key.trim()
|
|
22156
|
+
};
|
|
22157
|
+
}
|
|
22158
|
+
/** The peer's key as pinned now. A re-pin during the handshake ends the stream. */
|
|
22159
|
+
function currentPin(store, deviceId) {
|
|
22160
|
+
const row = store.db.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
|
|
22161
|
+
const publicKey = row?.public_key?.trim();
|
|
22162
|
+
if (!publicKey || fingerprintPublicKey(publicKey) !== row?.pinned_fingerprint) return null;
|
|
22163
|
+
return publicKey;
|
|
22164
|
+
}
|
|
22165
|
+
function switchProtocols(socket) {
|
|
22166
|
+
return new Promise((resolve, reject) => {
|
|
22167
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: ${DIRECT_NOISE_UPGRADE_PROTOCOL}\r\nConnection: Upgrade\r\n\r\n`, (error) => error ? reject(error) : resolve());
|
|
22168
|
+
});
|
|
22169
|
+
}
|
|
22170
|
+
function ownStream(socket, duplex) {
|
|
22171
|
+
const completion = Promise.all([finished(duplex, { cleanup: true }), finished(socket, { cleanup: true })]).then(() => {});
|
|
22172
|
+
completion.catch(() => {});
|
|
22173
|
+
return {
|
|
22174
|
+
duplex,
|
|
22175
|
+
completion,
|
|
22176
|
+
async dispose(error) {
|
|
22177
|
+
duplex.destroy(error);
|
|
22178
|
+
socket.destroy(error);
|
|
22179
|
+
await completion.catch(() => {});
|
|
22180
|
+
}
|
|
22181
|
+
};
|
|
22182
|
+
}
|
|
22183
|
+
/**
|
|
22184
|
+
* Milliseconds left before the gate's one deadline, which starts when the
|
|
22185
|
+
* upgrade arrives. Synchronous work such as signature checks or key loading
|
|
22186
|
+
* cannot run the timer, so each step checks the clock itself.
|
|
22187
|
+
*/
|
|
22188
|
+
function remainingMs(deadlineAt) {
|
|
22189
|
+
const remaining = Math.floor(deadlineAt - performance$1.now());
|
|
22190
|
+
if (remaining <= 0) throw new Error("Direct Noise admission deadline passed");
|
|
22191
|
+
return remaining;
|
|
22192
|
+
}
|
|
22193
|
+
async function handshake(context, socket, admission, peer) {
|
|
22194
|
+
const store = context.options.storeFactory();
|
|
22195
|
+
const identity = localIdentity(store, context.options.keysDir);
|
|
22196
|
+
remainingMs(admission.deadlineAt);
|
|
22197
|
+
await switchProtocols(socket);
|
|
22198
|
+
const acceptedAtMs = performance$1.now();
|
|
22199
|
+
const handshakeMs = remainingMs(admission.deadlineAt);
|
|
22200
|
+
const secured = await acceptRelayNoiseResponder({
|
|
22201
|
+
transport: socket,
|
|
22202
|
+
localIdentity: identity,
|
|
22203
|
+
expectedRemotePin: peer.publicKey,
|
|
22204
|
+
context: {
|
|
22205
|
+
transportLabel: DIRECT_NOISE_TRANSPORT_LABEL,
|
|
22206
|
+
sessionId: admission.target.sessionId
|
|
22207
|
+
},
|
|
22208
|
+
verifiedMessageADigest: admission.target.openingDigest,
|
|
22209
|
+
acceptedAtMs,
|
|
22210
|
+
deadlineMs: acceptedAtMs + handshakeMs + PEER_HTTP_LIMITS.exchangeMs,
|
|
22211
|
+
limits: { handshakeMs }
|
|
22212
|
+
});
|
|
22213
|
+
if (currentPin(store, peer.deviceId) !== peer.publicKey) {
|
|
22214
|
+
secured.duplex.destroy();
|
|
22215
|
+
throw new Error("Peer key changed during the handshake");
|
|
22216
|
+
}
|
|
22217
|
+
return secured.duplex;
|
|
22218
|
+
}
|
|
22219
|
+
/** One exchange, holding a response reservation from dispatch until the response is written. */
|
|
22220
|
+
async function serveStream(context, socket, duplex, deviceId) {
|
|
22221
|
+
let release;
|
|
22222
|
+
try {
|
|
22223
|
+
await servePeerHttpConnection(ownStream(socket, duplex), {
|
|
22224
|
+
origin: DIRECT_NOISE_LOGICAL_ORIGIN,
|
|
22225
|
+
dispatch: async (request) => {
|
|
22226
|
+
release = await context.budget.acquire(PEER_HTTP_LIMITS.responseBytes, request.signal);
|
|
22227
|
+
return context.dispatch({
|
|
22228
|
+
...request,
|
|
22229
|
+
peerDeviceId: deviceId
|
|
22230
|
+
});
|
|
22231
|
+
}
|
|
22232
|
+
});
|
|
22233
|
+
} finally {
|
|
22234
|
+
release?.();
|
|
22235
|
+
}
|
|
22236
|
+
}
|
|
22237
|
+
async function handleUpgrade(context, request, socket, head, upgrade) {
|
|
22238
|
+
const releasePending = context.pending.reserve(upgrade.address);
|
|
22239
|
+
if (!releasePending) throw new GateRefusal(503, "busy");
|
|
22240
|
+
const deadline = setTimeout(() => socket.destroy(), Math.max(1, upgrade.deadlineAt - performance$1.now()));
|
|
22241
|
+
deadline.unref();
|
|
22242
|
+
let releaseStream = null;
|
|
22243
|
+
try {
|
|
22244
|
+
const target = parseUpgrade(request, head);
|
|
22245
|
+
const peer = authorize(context.options.storeFactory(), request);
|
|
22246
|
+
releaseStream = context.streams.reserve(peer.deviceId);
|
|
22247
|
+
if (!releaseStream) throw new GateRefusal(503, "busy");
|
|
22248
|
+
const duplex = await handshake(context, socket, {
|
|
22249
|
+
target,
|
|
22250
|
+
deadlineAt: upgrade.deadlineAt
|
|
22251
|
+
}, peer);
|
|
22252
|
+
clearTimeout(deadline);
|
|
22253
|
+
if (performance$1.now() >= upgrade.deadlineAt) {
|
|
22254
|
+
duplex.destroy();
|
|
22255
|
+
throw new Error("Direct Noise admission deadline passed");
|
|
22256
|
+
}
|
|
22257
|
+
releasePending();
|
|
22258
|
+
await serveStream(context, socket, duplex, peer.deviceId);
|
|
22259
|
+
} finally {
|
|
22260
|
+
clearTimeout(deadline);
|
|
22261
|
+
releasePending();
|
|
22262
|
+
releaseStream?.();
|
|
22263
|
+
}
|
|
22264
|
+
}
|
|
22265
|
+
/**
|
|
22266
|
+
* Accepts direct Noise upgrades on the sync listener. Each address is
|
|
22267
|
+
* throttled with the listener's own budget before any signature check, and
|
|
22268
|
+
* every refusal before 101 is plain HTTP that carries no Noise bytes.
|
|
22269
|
+
*/
|
|
22270
|
+
function attachDirectNoiseGate(server, options, admit, addressOf) {
|
|
22271
|
+
const limits = {
|
|
22272
|
+
...DIRECT_NOISE_GATE_LIMITS,
|
|
22273
|
+
...options.limits
|
|
22274
|
+
};
|
|
22275
|
+
const context = {
|
|
22276
|
+
options,
|
|
22277
|
+
limits,
|
|
22278
|
+
pending: new Counter(limits.pendingTotal, limits.pendingPerIp),
|
|
22279
|
+
streams: new Counter(limits.streamsTotal, limits.streamsPerPeer),
|
|
22280
|
+
budget: new ResponseByteBudget(limits.responseBudgetBytes),
|
|
22281
|
+
dispatch: createSyncChannelDispatcher({
|
|
22282
|
+
storeFactory: () => options.storeFactory(),
|
|
22283
|
+
mode: "noise-direct",
|
|
22284
|
+
limiter: admit.limiter
|
|
22285
|
+
})
|
|
22286
|
+
};
|
|
22287
|
+
server.on("upgrade", (request, socket, head) => {
|
|
22288
|
+
const deadlineAt = performance$1.now() + limits.handshakeMs;
|
|
22289
|
+
admit.settle(socket);
|
|
22290
|
+
socket.on("error", () => {});
|
|
22291
|
+
const address = addressOf(socket);
|
|
22292
|
+
if (!(admit.perMinute === void 0 ? { allowed: true } : admit.limiter.check(`sync-listener:${address}`, admit.perMinute)).allowed) {
|
|
22293
|
+
refuse(socket, new GateRefusal(429, "rate_limited"));
|
|
22294
|
+
return;
|
|
22295
|
+
}
|
|
22296
|
+
handleUpgrade(context, request, socket, head, {
|
|
22297
|
+
address,
|
|
22298
|
+
deadlineAt
|
|
22299
|
+
}).catch((error) => {
|
|
22300
|
+
if (error instanceof GateRefusal && !socket.destroyed) refuse(socket, error);
|
|
22301
|
+
else socket.destroy();
|
|
22302
|
+
});
|
|
22303
|
+
});
|
|
22304
|
+
}
|
|
22305
|
+
//#endregion
|
|
22306
|
+
//#region src/sync-listener-guard.ts
|
|
22307
|
+
var SYNC_LISTENER_LIMITS = Object.freeze({
|
|
22308
|
+
headerMs: 1e4,
|
|
22309
|
+
requestMs: 3e4,
|
|
22310
|
+
checkIntervalMs: 1e3
|
|
22311
|
+
});
|
|
22312
|
+
/**
|
|
22313
|
+
* Caps from `pnpm run load:sync-listener`
|
|
22314
|
+
* (packages/viewer-server/scripts/sync-listener-load.ts). With them, an
|
|
22315
|
+
* authenticated flood or idle streams from one address left another
|
|
22316
|
+
* address's sync p95 within 10% of idle, at under 16 MiB added memory, and
|
|
22317
|
+
* 128 devices behind one address that start syncing within 10 s all succeed.
|
|
22318
|
+
* They apply only while the listener runs direct Noise, so the plain listener
|
|
22319
|
+
* behaves as before until activation.
|
|
22320
|
+
*/
|
|
22321
|
+
var SYNC_LISTENER_CAPS = Object.freeze({
|
|
22322
|
+
maxSockets: 256,
|
|
22323
|
+
maxSocketsPerIp: 16,
|
|
22324
|
+
requestsPerIpPerMinute: 600
|
|
22325
|
+
});
|
|
22326
|
+
/**
|
|
22327
|
+
* Distinct address buckets the listener's limiter keeps. When it is full, new
|
|
22328
|
+
* addresses share one overflow budget until a bucket goes unused for a minute.
|
|
22329
|
+
*/
|
|
22330
|
+
var SYNC_LISTENER_MAX_BUCKETS = 4096;
|
|
22331
|
+
/**
|
|
22332
|
+
* The limiter the sync listener, its routes and its Noise streams share. It
|
|
22333
|
+
* holds at most SYNC_LISTENER_MAX_BUCKETS buckets.
|
|
22334
|
+
*/
|
|
22335
|
+
function createSyncListenerLimiter() {
|
|
22336
|
+
return createInMemoryRequestRateLimiter(6e4, { maxBuckets: SYNC_LISTENER_MAX_BUCKETS });
|
|
22337
|
+
}
|
|
22338
|
+
/** The eight 16-bit groups of an IPv6 address, or null when it does not parse. */
|
|
22339
|
+
function ipv6Groups(address) {
|
|
22340
|
+
const [head = "", tail, extra] = address.split("::");
|
|
22341
|
+
if (extra !== void 0) return null;
|
|
22342
|
+
const left = head ? head.split(":") : [];
|
|
22343
|
+
const right = tail ? tail.split(":") : [];
|
|
22344
|
+
const missing = 8 - left.length - right.length;
|
|
22345
|
+
if (tail === void 0 && missing !== 0 || tail !== void 0 && missing < 1) return null;
|
|
22346
|
+
const groups = [
|
|
22347
|
+
...left,
|
|
22348
|
+
...Array(tail === void 0 ? 0 : missing).fill("0"),
|
|
22349
|
+
...right
|
|
22350
|
+
];
|
|
22351
|
+
if (!groups.every((group) => /^[0-9a-f]{1,4}$/i.test(group))) return null;
|
|
22352
|
+
return groups.map((group) => Number.parseInt(group, 16));
|
|
22353
|
+
}
|
|
22354
|
+
/**
|
|
22355
|
+
* One key per client address. IPv4 clients of a dual-stack socket arrive as
|
|
22356
|
+
* ::ffff:a.b.c.d. An IPv6 client usually holds a whole /64, so its addresses
|
|
22357
|
+
* share one key and cannot multiply its share of the caps.
|
|
22358
|
+
*/
|
|
22359
|
+
function remoteAddressKey(socket) {
|
|
22360
|
+
const address = (socket.remoteAddress ?? "unknown").split("%")[0] ?? "unknown";
|
|
22361
|
+
if (address.startsWith("::ffff:") && address.includes(".")) return address.slice(7);
|
|
22362
|
+
if (!address.includes(":")) return address;
|
|
22363
|
+
const groups = ipv6Groups(address);
|
|
22364
|
+
if (!groups) return address;
|
|
22365
|
+
return `${groups.slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
|
|
22366
|
+
}
|
|
22367
|
+
function refuseRateLimited(response, retryAfterS) {
|
|
22368
|
+
response.writeHead(429, {
|
|
22369
|
+
"content-type": "application/json",
|
|
22370
|
+
"retry-after": String(retryAfterS),
|
|
22371
|
+
connection: "close"
|
|
22372
|
+
});
|
|
22373
|
+
response.end(JSON.stringify({
|
|
22374
|
+
error: "rate_limited",
|
|
22375
|
+
retry_after_s: retryAfterS
|
|
22376
|
+
}));
|
|
22377
|
+
}
|
|
22378
|
+
/** Counts open sockets per address and closes any over the cap as soon as it connects. */
|
|
22379
|
+
function capSocketsPerAddress(server, maxPerAddress) {
|
|
22380
|
+
const open = /* @__PURE__ */ new Map();
|
|
22381
|
+
server.on("connection", (socket) => {
|
|
22382
|
+
const key = remoteAddressKey(socket);
|
|
22383
|
+
const count = (open.get(key) ?? 0) + 1;
|
|
22384
|
+
open.set(key, count);
|
|
22385
|
+
socket.once("close", () => {
|
|
22386
|
+
const remaining = (open.get(key) ?? 1) - 1;
|
|
22387
|
+
if (remaining > 0) open.set(key, remaining);
|
|
22388
|
+
else open.delete(key);
|
|
22389
|
+
});
|
|
22390
|
+
if (count > maxPerAddress) socket.destroy();
|
|
22391
|
+
});
|
|
22392
|
+
}
|
|
22393
|
+
/**
|
|
22394
|
+
* Closes a socket that has not delivered complete headers in time. Node's own
|
|
22395
|
+
* header timeout also applies, but this timer starts at connect and does not
|
|
22396
|
+
* depend on Node's check interval. Returns the function that stops a socket's
|
|
22397
|
+
* timer. An upgrade handler must call it, because Node applies no timeouts to
|
|
22398
|
+
* an upgraded socket. With no upgrade handler, Node serves an Upgrade request
|
|
22399
|
+
* as an ordinary request, which stops the timer.
|
|
22400
|
+
*/
|
|
22401
|
+
function closeSilentSockets(server, limits) {
|
|
22402
|
+
const timers = /* @__PURE__ */ new WeakMap();
|
|
22403
|
+
const settle = (socket) => {
|
|
22404
|
+
clearTimeout(timers.get(socket));
|
|
22405
|
+
timers.delete(socket);
|
|
22406
|
+
};
|
|
22407
|
+
server.on("connection", (socket) => {
|
|
22408
|
+
const timer = setTimeout(() => socket.destroy(), limits.headerMs);
|
|
22409
|
+
timer.unref();
|
|
22410
|
+
timers.set(socket, timer);
|
|
22411
|
+
socket.once("close", () => settle(socket));
|
|
22412
|
+
});
|
|
22413
|
+
server.on("request", (request) => settle(request.socket));
|
|
22414
|
+
return settle;
|
|
22415
|
+
}
|
|
22416
|
+
/** Answers 429 when the address is over its budget. Always allows while the limit is off. */
|
|
22417
|
+
function admitRequest(limiter, perMinute, request, response) {
|
|
22418
|
+
if (perMinute === void 0) return true;
|
|
22419
|
+
const result = limiter.check(`sync-listener:${remoteAddressKey(request.socket)}`, perMinute);
|
|
22420
|
+
if (!result.allowed) refuseRateLimited(response, result.retryAfterS);
|
|
22421
|
+
return result.allowed;
|
|
22422
|
+
}
|
|
22423
|
+
/**
|
|
22424
|
+
* A createServer replacement for the sync listener. It bounds how long headers
|
|
22425
|
+
* and requests may take, and can cap sockets and throttle each address before
|
|
22426
|
+
* the sync routes verify any signature.
|
|
22427
|
+
*/
|
|
22428
|
+
function createGuardedSyncServer(options = {}) {
|
|
22429
|
+
const noiseActive = options.directNoise?.active ?? DIRECT_NOISE_ACTIVE;
|
|
22430
|
+
const caps = noiseActive ? SYNC_LISTENER_CAPS : {};
|
|
22431
|
+
const limits = {
|
|
22432
|
+
...SYNC_LISTENER_LIMITS,
|
|
22433
|
+
...caps,
|
|
22434
|
+
...options.limits
|
|
22435
|
+
};
|
|
22436
|
+
const limiter = options.limiter ?? createSyncListenerLimiter();
|
|
22437
|
+
const guarded = (_serverOptions, listener) => {
|
|
22438
|
+
const server = createServer({
|
|
22439
|
+
headersTimeout: limits.headerMs,
|
|
22440
|
+
requestTimeout: limits.requestMs,
|
|
22441
|
+
connectionsCheckingInterval: limits.checkIntervalMs
|
|
22442
|
+
}, (request, response) => {
|
|
22443
|
+
if (admitRequest(limiter, limits.requestsPerIpPerMinute, request, response)) listener?.(request, response);
|
|
22444
|
+
});
|
|
22445
|
+
if (limits.maxSockets !== void 0) server.maxConnections = limits.maxSockets;
|
|
22446
|
+
if (limits.maxSocketsPerIp !== void 0) capSocketsPerAddress(server, limits.maxSocketsPerIp);
|
|
22447
|
+
const settle = closeSilentSockets(server, limits);
|
|
22448
|
+
const directNoise = options.directNoise;
|
|
22449
|
+
if (directNoise && noiseActive) attachDirectNoiseGate(server, directNoise, {
|
|
22450
|
+
limiter,
|
|
22451
|
+
perMinute: limits.requestsPerIpPerMinute,
|
|
22452
|
+
settle
|
|
22453
|
+
}, remoteAddressKey);
|
|
22454
|
+
return server;
|
|
22455
|
+
};
|
|
22456
|
+
return guarded;
|
|
22457
|
+
}
|
|
22458
|
+
//#endregion
|
|
20515
22459
|
//#region src/index.ts
|
|
20516
22460
|
/**
|
|
20517
22461
|
* @codemem/server — HTTP server (viewer, sync, API).
|
|
@@ -20552,11 +22496,12 @@ function registerStaticRoutes(app) {
|
|
|
20552
22496
|
return c.html(indexHtml);
|
|
20553
22497
|
});
|
|
20554
22498
|
}
|
|
20555
|
-
function registerConfigRoutes(app, opts, sweeper) {
|
|
22499
|
+
function registerConfigRoutes(app, opts, sweeper, onCoordinatorConfigChanged) {
|
|
20556
22500
|
app.route("/", configRoutes({
|
|
20557
22501
|
getSweeper: () => sweeper,
|
|
20558
22502
|
scheduleObserverApply: opts?.scheduleObserverApply,
|
|
20559
|
-
getObserverApplyStatus: opts?.getObserverApplyStatus
|
|
22503
|
+
getObserverApplyStatus: opts?.getObserverApplyStatus,
|
|
22504
|
+
onCoordinatorConfigChanged
|
|
20560
22505
|
}));
|
|
20561
22506
|
}
|
|
20562
22507
|
function registerViewerBoundary(app, opts) {
|
|
@@ -20596,10 +22541,15 @@ function registerViewerSyncRoutes(app, storeFactory, opts, onRecipientPolicyTeam
|
|
|
20596
22541
|
readCoordinatorConfig: opts?.readCoordinatorConfig,
|
|
20597
22542
|
runManualCoordinatorRefresh: opts?.runManualCoordinatorRefresh,
|
|
20598
22543
|
renameCoordinatorGroup: opts?.renameCoordinatorGroup,
|
|
20599
|
-
lookupCoordinatorDeviceAnswer: opts?.lookupCoordinatorDeviceAnswer,
|
|
20600
22544
|
deviceLifecycleActions: Boolean(opts?.createDeviceRemovalRefreshHooks)
|
|
20601
22545
|
}));
|
|
20602
22546
|
}
|
|
22547
|
+
/** Routes only an admin device may use on a Team: removing a member, and recovering a disabled Team. */
|
|
22548
|
+
function registerTeamAdminRoutes(app, storeFactory, opts) {
|
|
22549
|
+
const options = { readCoordinatorConfig: opts?.readCoordinatorConfig };
|
|
22550
|
+
app.route("/", teamMemberRemovalRoutes(storeFactory, options));
|
|
22551
|
+
app.route("/", teamRecoveryRoutes(storeFactory, options));
|
|
22552
|
+
}
|
|
20603
22553
|
function registerViewerDeviceRemoval(app, storeFactory, opts) {
|
|
20604
22554
|
const createDeviceRemovalRefreshHooks = opts?.createDeviceRemovalRefreshHooks;
|
|
20605
22555
|
app.route("/", deviceRejoinEventRoutes({
|
|
@@ -20665,12 +22615,13 @@ function createApp(opts) {
|
|
|
20665
22615
|
getSweeper: () => sweeper,
|
|
20666
22616
|
getObserver
|
|
20667
22617
|
}));
|
|
20668
|
-
registerConfigRoutes(app, opts, sweeper);
|
|
22618
|
+
registerConfigRoutes(app, opts, sweeper, () => invalidateTeamSetupSummary());
|
|
20669
22619
|
app.route("/", rawEventsRoutes(storeFactory, sweeper, opts?.rawEventInbox, opts?.rawEventTarget));
|
|
20670
22620
|
installRecipientAccessChangeGate(app, storeFactory, opts?.readCoordinatorConfig);
|
|
20671
22621
|
registerViewerSyncRoutes(app, storeFactory, opts, () => invalidateTeamSetupSummary());
|
|
20672
22622
|
registerViewerDeviceRemoval(app, storeFactory, opts);
|
|
20673
22623
|
app.route("/", teamCreateRoutes(storeFactory, opts?.readCoordinatorConfig));
|
|
22624
|
+
registerTeamAdminRoutes(app, storeFactory, opts);
|
|
20674
22625
|
app.route("/", projectWithdrawalRoutes(storeFactory));
|
|
20675
22626
|
app.route("/", teamSetupRoutes({
|
|
20676
22627
|
getStore: storeFactory,
|
|
@@ -20679,17 +22630,23 @@ function createApp(opts) {
|
|
|
20679
22630
|
readCoordinatorConfig: opts?.readCoordinatorConfig,
|
|
20680
22631
|
registerSummaryInvalidator: (invalidate) => {
|
|
20681
22632
|
invalidateTeamSetupSummary = invalidate;
|
|
20682
|
-
}
|
|
22633
|
+
},
|
|
22634
|
+
registerReconciliation: (reconciliation) => startTeamSetupReconciliation(reconciliation, opts)
|
|
20683
22635
|
}));
|
|
20684
22636
|
app.route("/", updateStatusRoutes({ getUpdateStatus: opts?.getUpdateStatus }));
|
|
20685
22637
|
registerStaticRoutes(app);
|
|
20686
22638
|
return app;
|
|
20687
22639
|
}
|
|
22640
|
+
function startTeamSetupReconciliation(reconciliation, opts) {
|
|
22641
|
+
opts?.onTeamSetupReconciliation?.(reconciliation);
|
|
22642
|
+
const intervalMs = opts?.teamSetupReconciliationIntervalMs;
|
|
22643
|
+
if (intervalMs) reconciliation.startPeriodic(intervalMs);
|
|
22644
|
+
}
|
|
20688
22645
|
/** Preserve the public server options while transport adapters use the narrower factory. */
|
|
20689
22646
|
function createSyncApp(opts) {
|
|
20690
22647
|
return createSyncApp$1(opts);
|
|
20691
22648
|
}
|
|
20692
22649
|
//#endregion
|
|
20693
|
-
export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, convertLegacyPairingAssignmentsOperation, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientInvitation, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, previewRecipientInvitation, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
|
|
22650
|
+
export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, convertLegacyPairingAssignmentsOperation, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createGuardedSyncServer, createRecipientInvitation, createRecipientPolicyReconcilerEffects, createSyncApp, createSyncListenerLimiter, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, previewRecipientInvitation, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
|
|
20694
22651
|
|
|
20695
22652
|
//# sourceMappingURL=index.js.map
|