@tearleads/client-sdk 0.1.251 → 0.1.253
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/Tearleads.d.ts +0 -2
- package/Tearleads.js +17 -28
- package/Tearleads.js.map +1 -1
- package/client/containerContents/index.d.ts +2 -0
- package/client/containerContents/index.js +4 -9
- package/client/containerContents/index.js.map +1 -1
- package/client/containerContents/storeRuntime.d.ts +17 -0
- package/client/containerContents/storeRuntime.js +31 -0
- package/client/containerContents/storeRuntime.js.map +1 -0
- package/client/deviceFirst/index.d.ts +2 -3
- package/client/deviceFirst/index.js +44 -22
- package/client/deviceFirst/index.js.map +1 -1
- package/client/organizations/organizationReadModelPresentation.js +7 -4
- package/client/organizations/organizationReadModelPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.js +6 -5
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +4 -0
- package/client/runtime/principalMutationApi.js +9 -5
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +23 -0
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/runtimeSubscription.js +68 -0
- package/client/runtime/runtimeSubscription.js.map +1 -0
- package/client/runtime/workflowRuntime.d.ts +3 -1
- package/client/runtime/workflowRuntime.js +31 -81
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/session/authenticationMachine.js +47 -0
- package/client/session/authenticationMachine.js.map +1 -0
- package/client/session/index.js +75 -93
- package/client/session/index.js.map +1 -1
- package/client/session/sessionBlobStore.js +39 -0
- package/client/session/sessionBlobStore.js.map +1 -0
- package/client/session/sessionContext.js +11 -0
- package/client/session/sessionContext.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +2 -1
- package/client/session/sessionIdentityTrust.js +8 -4
- package/client/session/sessionIdentityTrust.js.map +1 -1
- package/client/session/sessionLifetime.js +87 -0
- package/client/session/sessionLifetime.js.map +1 -0
- package/client/session/sessionLogin.js +114 -0
- package/client/session/sessionLogin.js.map +1 -0
- package/client/session/sessionOrganizationCreation.js +3 -2
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js +11 -3
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionTypes.d.ts +6 -2
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/blobContracts.d.ts +4 -3
- package/data/blobs/blobContracts.js.map +1 -1
- package/data/blobs/createBlobStore.js +1 -8
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobStore.js +17 -12
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.js +8 -5
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobFile.js +36 -0
- package/data/blobs/opfsBlobFile.js.map +1 -0
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +91 -21
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/principals/principalPolicyCoordinator.js +8 -17
- package/data/principals/principalPolicyCoordinator.js.map +1 -1
- package/data/shared/domainScope.d.ts +2 -0
- package/data/shared/domainScope.js +2 -1
- package/data/shared/domainScope.js.map +1 -1
- package/data/shared/keyedQueue.js +15 -0
- package/data/shared/keyedQueue.js.map +1 -0
- package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
- package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
- package/data/sqlite/sqlExec.d.ts +6 -0
- package/data/sqlite/sqlExec.js +64 -13
- package/data/sqlite/sqlExec.js.map +1 -1
- package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
- package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
- package/data/sync/syncCoordinator.js +17 -10
- package/data/sync/syncCoordinator.js.map +1 -1
- package/data/trustedUserIdentity/service.js +2 -1
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/data/trustedUserIdentity/types.d.ts +1 -1
- package/data/trustedUserIdentity/types.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -1
- package/internal/api-client/apiRequestRuntime.d.ts +6 -3
- package/internal/api-client/apiRequestRuntime.js +86 -101
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryRequestOperationTransport.js +2 -1
- package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +6 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -0
- package/internal/api-client/client/blobs.js +12 -3
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/laneListingRequest.js +4 -0
- package/internal/api-client/client/laneListingRequest.js.map +1 -1
- package/internal/api-client/client/session.d.ts +5 -1
- package/internal/api-client/client/session.js +12 -4
- package/internal/api-client/client/session.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +12 -13
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.d.ts +1 -1
- package/internal/api-client/operationResponse.js +10 -23
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/operationTransport.js +2 -1
- package/internal/api-client/operationTransport.js.map +1 -1
- package/internal/api-client/principalHistoryRequest.js +25 -20
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequestContext.js +30 -6
- package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +4 -1
- package/internal/api-client/principalPolicyPages.js +4 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
- package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
- package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
- package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
- package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
- package/internal/api-client/routes/blobs/get.js +9 -67
- package/internal/api-client/routes/blobs/get.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +1 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionRenewal.d.ts +31 -0
- package/internal/api-client/sessionRenewal.js +91 -6
- package/internal/api-client/sessionRenewal.js.map +1 -1
- package/internal/api-client/sessionRequestInit.js +22 -0
- package/internal/api-client/sessionRequestInit.js.map +1 -0
- package/internal/api-client/sessionResponse.js +39 -0
- package/internal/api-client/sessionResponse.js.map +1 -0
- package/internal/api-client/types.d.ts +1 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/webSocketTickets.d.ts +1 -0
- package/internal/api-client/webSocketTickets.js +4 -0
- package/internal/api-client/webSocketTickets.js.map +1 -1
- package/internal/sqlite-worker/client.d.ts +1 -1
- package/internal/sqlite-worker/client.js +6 -1
- package/internal/sqlite-worker/client.js.map +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
- package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
- package/internal/sqlite-worker/types.d.ts +4 -0
- package/internal/sqlite-worker/types.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +3 -9
- package/stores/container-contents/containerContentsStore.js +24 -21
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/containerState/storeScope.js +6 -0
- package/stores/container-contents/containerState/storeScope.js.map +1 -0
- package/stores/container-contents/hydration/backgroundHydration.js +2 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
- package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
- package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
- package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
- package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
- package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
- package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +2 -9
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/hydration/treeResetMachine.js +61 -0
- package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
- package/stores/container-contents/localRefresh.js +28 -12
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
- package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
- package/stores/container-contents/state.d.ts +3 -7
- package/stores/container-contents/state.js +27 -16
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/index.d.ts +7 -2
- package/stores/container-contents/syncAgent/index.js +77 -49
- package/stores/container-contents/syncAgent/index.js.map +1 -1
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/stores/local-projection/localProjectionStore.js +24 -15
- package/stores/local-projection/localProjectionStore.js.map +1 -1
- package/stores/local-projection/registry.js +2 -2
- package/stores/local-projection/registry.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.js +3 -15
- package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +4 -8
- package/workflows/container-contents/containerPersistence.js +22 -12
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/localState.js +3 -0
- package/workflows/container-contents/localState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
- package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
- package/workflows/container-contents/remoteHydration/index.js +17 -66
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/storedContainerState.js +17 -7
- package/workflows/container-contents/storedContainerState.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -0
- package/workflows/container-contents/syncLane.js +9 -1
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
- package/workflows/documents/attachments/blobMutationLock.js +2 -2
- package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
- package/workflows/shared/runtimeInput.d.ts +2 -0
- package/workflows/shared/runtimeInput.js.map +1 -1
- package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
- package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GAEpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAClH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAC;AAEtF,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EACL,wBAAwB,EACxB,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GAKpC,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAEtB,SAAS,kBAAkB,CACzB,YAAoD;IAEpD,0EAA0E;IAC1E,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,CAAC;Q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oBACb,YAAY;oBACZ,OAAO;oBACP,QAAQ,EAAE,SAAS,CAAC,QAAQ;oBAC5B,UAAU,EAAE,SAAS,CAAC,MAAM;iBAC7B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC,EACD;YACE,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;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B,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate, assertCurrent) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n assertCurrent,\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
|
@@ -83,7 +83,7 @@ export interface TrustedUserIdentityService {
|
|
|
83
83
|
loadAdmissionPin(userId: string, admittingExecSql: ExecSql | null): Promise<TrustedUserIdentityAdmissionPin | null>;
|
|
84
84
|
/** The user this device's trust store already binds a signing key to. */
|
|
85
85
|
boundUserId(signingKeyFingerprint: string): Promise<string | null>;
|
|
86
|
-
pinLocal(userId: string, candidate: LocalUserIdentityCandidate): Promise<TrustedUserIdentity>;
|
|
86
|
+
pinLocal(userId: string, candidate: LocalUserIdentityCandidate, assertCurrent?: () => void): Promise<TrustedUserIdentity>;
|
|
87
87
|
/** Pins on first sight as `observed`; for users signed state references. */
|
|
88
88
|
resolve: TrustedUserIdentityResolver;
|
|
89
89
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAwJ3C,MAAM,UAAU,wBAAwB,CACtC,KAAqC;IAErC,OAAO;QACL,GAAG,KAAK;QACR,CAAC,wBAAwB,CAAC,EAAE,6BAA6B;KAC1D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,wBAAwB,CAAC;YAC1C,6BAA6B,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import type { ExecSql } from \"../sqlite/sqlSchema\";\n\nexport const TRUSTED_USER_IDENTITY_FORMAT_VERSION = 1;\nexport const TRUSTED_USER_IDENTITY_SIGNING_SUITE = \"ML-DSA-87\";\nexport const TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE = \"ML-KEM-1024\";\n\nconst trustedUserIdentityBrand: unique symbol = Symbol(\"trustedUserIdentity\");\nconst trustedUserIdentityBrandValue = true;\n\n/**\n * A complete user identity bundle that has passed strict key validation and\n * the durable pin comparison for its trust domain.\n *\n * The nominal brand keeps raw API and organization response objects from being\n * accepted at cryptographic boundaries by structural typing. Its private\n * symbol and constructor remain package-private to the SDK trust gateway.\n */\nexport interface TrustedUserIdentity {\n readonly [trustedUserIdentityBrand]: true;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\n/** Strictly decoded and self-consistent, but not yet accepted by durable TOFU. */\nexport interface ValidatedUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentitySource {\n invalidate(userId: string): void;\n /**\n * `null` only when the server asserts the user does not exist. A transport\n * or non-404 HTTP failure throws a retryable availability error instead.\n */\n load(userId: string): Promise<RemoteUserIdentityCandidate | null>;\n}\n\nexport interface LocalUserIdentityCandidate {\n readonly encapsulationPublicKey: Uint8Array;\n readonly signingKeyFingerprint?: string | null | undefined;\n readonly signingPublicKey: Uint8Array;\n}\n\n/** An existing pin as an admission reads it: never admits by itself. */\nexport interface TrustedUserIdentityAdmissionPin {\n readonly identity: TrustedUserIdentity;\n /** Established by a verified identity link or this device's own keys. */\n readonly verified: boolean;\n}\n\nexport interface TrustedUserIdentityService {\n createLink(appUrl: string): Promise<string>;\n /**\n * Link for `userId` from a pin a verified link or this device's keys\n * established; the local user's own keys for the signed-in user; `null`\n * when no such pin exists (never from an observed pin).\n */\n createLinkFor(userId: string, appUrl: string): Promise<string | null>;\n verifyLink(link: string): Promise<TrustedUserIdentity>;\n /** Any existing pin, including one observed on first sight. Never admits. */\n resolvePinned(userId: string): Promise<TrustedUserIdentity | null>;\n /** An existing pin established by a verified link or this device's keys. */\n resolveVerified(userId: string): Promise<TrustedUserIdentity | null>;\n /**\n * Like `resolveVerified`, but throws `UnverifiedUserIdentityError`. An\n * admission passes the database its mutation captured: a trust store that\n * is not, or stops being, that database fails with `DatabaseUnavailableError`\n * instead of admitting against another scope.\n */\n requireVerified(\n userId: string,\n admittingExecSql: ExecSql | null,\n ): Promise<TrustedUserIdentity>;\n /**\n * Any existing pin and whether a link or this device's keys established it,\n * read with `requireVerified`'s database scoping. Admissions that accept\n * evidence other than a verified pin compare against it.\n */\n loadAdmissionPin(\n userId: string,\n admittingExecSql: ExecSql | null,\n ): Promise<TrustedUserIdentityAdmissionPin | null>;\n /** The user this device's trust store already binds a signing key to. */\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocal(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n ): Promise<TrustedUserIdentity>;\n /** Pins on first sight as `observed`; for users signed state references. */\n resolve: TrustedUserIdentityResolver;\n}\n\n/**\n * Within one structural check: an existing pin, this user's own local keys,\n * or a first-sight candidate that is staged rather than pinned.\n */\nexport type StagedUserIdentityResolver = (\n userId: string,\n) => Promise<ValidatedUserIdentityCandidate | null>;\n\nexport interface StagedUserIdentityOptions {\n /**\n * Pin staged first sights as `observed` once `verify` succeeds. Set only\n * when the checked projections' signed states already verified: data an\n * unauthenticated projection names must never reach the durable store.\n */\n readonly publish: boolean;\n /**\n * The calling operation's own lifetime (cancellation, superseded recovery),\n * checked with the trust store's scope at every step and inside each pin's\n * write transaction, so a cancelled operation commits no first sight.\n */\n readonly assertCurrent?: (() => void) | undefined;\n}\n\n/** Callable resolution always compares the candidate with durable pins.\n * Structural commitment verification may reuse validated immutable pins for\n * one scoped operation; this capability never admits users or promotes pins.\n */\nexport type TrustedUserIdentityResolver = ((\n userId: string,\n) => Promise<TrustedUserIdentity | null>) & {\n readonly withPinnedIdentities?: <T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ) => Promise<T>;\n};\n\nexport interface TrustedUserIdentityServiceDependencies {\n readonly getExecSql: () => ExecSql | null;\n readonly getScopeGeneration?: (() => unknown) | undefined;\n readonly getLocalIdentity: (\n userId: string,\n ) => LocalUserIdentityCandidate | null;\n readonly getLocalUserId: () => string | null;\n readonly identityTrustDomain: string | null;\n readonly now?: (() => Date) | undefined;\n readonly remoteSource: RemoteUserIdentitySource;\n}\n\nexport function brandTrustedUserIdentity(\n input: ValidatedUserIdentityCandidate,\n): TrustedUserIdentity {\n return {\n ...input,\n [trustedUserIdentityBrand]: trustedUserIdentityBrandValue,\n };\n}\n\nexport function isTrustedUserIdentity(\n value: unknown,\n): value is TrustedUserIdentity {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, trustedUserIdentityBrand) ===\n trustedUserIdentityBrandValue\n );\n}\n"]}
|
|
@@ -14,7 +14,10 @@ export declare class ApiClient extends ApiClientAreas {
|
|
|
14
14
|
setOnSessionExpired: (handler: (() => boolean | Promise<boolean>) | null) => void;
|
|
15
15
|
setOnPaymentRequired: (handler: ((organizationId: string | null) => void) | null) => void;
|
|
16
16
|
setVerifiedManifestCitations: (source: import("./verifiedManifestCitations.js").VerifiedManifestCitations | null) => void;
|
|
17
|
-
setAuthToken: (token: string | null
|
|
17
|
+
setAuthToken: (token: string | null, options?: {
|
|
18
|
+
boundary?: import("./sessionRenewal.js").SessionBoundary | undefined;
|
|
19
|
+
verifiedTicket?: string | undefined;
|
|
20
|
+
}) => void;
|
|
18
21
|
getAuthToken: () => string | null;
|
|
19
22
|
getRequestFailure: (input: {
|
|
20
23
|
method: import("./types.js").HttpMethod;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ApiRequestInstrumentation } from "./apiRequestMetrics.js";
|
|
2
2
|
import { type ApiNetworkError } from "./networkFailure.js";
|
|
3
|
-
import
|
|
3
|
+
import { type SessionBoundary } from "./sessionRenewal.js";
|
|
4
|
+
import type { HttpMethod, OperationRequestFn, OperationRequestResultFn, OperationResponseRequestFn, RequestFailure, RequestResultOptions } from "./types.js";
|
|
4
5
|
type ExpiredHandler = () => boolean | Promise<boolean>;
|
|
5
6
|
type PaymentRequiredHandler = (organizationId: string | null) => void;
|
|
6
7
|
export declare class ApiRequestRuntime {
|
|
@@ -37,17 +38,19 @@ export declare class ApiRequestRuntime {
|
|
|
37
38
|
setOnApiVersion(handler: ((version: number) => void) | null): void;
|
|
38
39
|
setOnSessionExpired(handler: ExpiredHandler | null): void;
|
|
39
40
|
setOnPaymentRequired(handler: PaymentRequiredHandler | null): void;
|
|
40
|
-
setAuthToken(token: string | null): boolean;
|
|
41
|
+
setAuthToken(token: string | null, boundary?: SessionBoundary): boolean;
|
|
42
|
+
captureCredential(): () => boolean | Promise<boolean>;
|
|
43
|
+
withSessionSignal(options: RequestResultOptions): RequestResultOptions;
|
|
41
44
|
getAuthToken(): string | null;
|
|
42
45
|
getRequestFailure(input: {
|
|
43
46
|
method: HttpMethod;
|
|
44
47
|
path: string;
|
|
45
48
|
}): RequestFailure | null;
|
|
46
|
-
private buildHeaders;
|
|
47
49
|
private makeRequest;
|
|
48
50
|
private requestFailure;
|
|
49
51
|
private makeRequestResult;
|
|
50
52
|
private makeResponseRequest;
|
|
53
|
+
private retiredResponse;
|
|
51
54
|
private fetchResponseRequest;
|
|
52
55
|
private httpFailure;
|
|
53
56
|
private reportResponseRequestFailure;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { authChallengeSigningBytes, canonicalAuthOrigin, } from "../crypto/index.js";
|
|
2
1
|
import { apiVersionHeaderName, parseApiVersion, } from "../validators/operation/index.js";
|
|
3
2
|
import { measureApiRequest } from "./measureApiRequest.js";
|
|
4
3
|
import { networkFailureMessage, settleNetworkFailure, } from "./networkFailure.js";
|
|
5
|
-
import { bindPrototypeMethods, describeErrorResponse,
|
|
6
|
-
import { responseBodyFailure } from "./responseBodyFailure.js";
|
|
4
|
+
import { bindPrototypeMethods, describeErrorResponse, isSuccessfulResponse, normalizeApiBaseUrl, requestFailureKey, } from "./requestInternals.js";
|
|
7
5
|
import { shouldRetryAfterSessionExpired } from "./sessionRefresh.js";
|
|
8
|
-
import { SessionRenewalTracker } from "./sessionRenewal.js";
|
|
6
|
+
import { SessionRenewalTracker, sessionAuthChallengeBytes, } from "./sessionRenewal.js";
|
|
7
|
+
import { sessionRequestInit } from "./sessionRequestInit.js";
|
|
8
|
+
import { readSessionJson, retiredRequest } from "./sessionResponse.js";
|
|
9
9
|
export class ApiRequestRuntime {
|
|
10
10
|
instrumentation;
|
|
11
11
|
authToken = null;
|
|
@@ -30,6 +30,7 @@ export class ApiRequestRuntime {
|
|
|
30
30
|
this.requestResult = this.makeRequestResult;
|
|
31
31
|
this.responseRequest = Object.assign(this.makeResponseRequest, {
|
|
32
32
|
reportFailure: this.reportResponseRequestFailure,
|
|
33
|
+
sessionSignal: () => this.sessionRenewals.signal,
|
|
33
34
|
});
|
|
34
35
|
}
|
|
35
36
|
/**
|
|
@@ -38,14 +39,7 @@ export class ApiRequestRuntime {
|
|
|
38
39
|
* do; with neither, there is no API origin to sign for.
|
|
39
40
|
*/
|
|
40
41
|
authChallengeBytes(challengeHex, fingerprint) {
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
apiOrigin = canonicalAuthOrigin(new URL(this.baseUrl || "/", globalThis.location?.href).href);
|
|
44
|
-
}
|
|
45
|
-
catch {
|
|
46
|
-
throw new Error("The API origin is unavailable for authentication");
|
|
47
|
-
}
|
|
48
|
-
return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });
|
|
42
|
+
return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);
|
|
49
43
|
}
|
|
50
44
|
setOnError(handler) {
|
|
51
45
|
this.onError = handler;
|
|
@@ -74,28 +68,27 @@ export class ApiRequestRuntime {
|
|
|
74
68
|
setOnPaymentRequired(handler) {
|
|
75
69
|
this.onPaymentRequired = handler;
|
|
76
70
|
}
|
|
77
|
-
setAuthToken(token) {
|
|
78
|
-
const changed = this.authToken !== token;
|
|
71
|
+
setAuthToken(token, boundary) {
|
|
72
|
+
const changed = Boolean(boundary) || this.authToken !== token;
|
|
73
|
+
if (boundary)
|
|
74
|
+
this.requestFailuresByKey.clear();
|
|
79
75
|
if (changed)
|
|
80
|
-
this.sessionRenewals.tokenChanged();
|
|
76
|
+
this.sessionRenewals.tokenChanged(boundary);
|
|
81
77
|
this.authToken = token;
|
|
82
78
|
return changed;
|
|
83
79
|
}
|
|
80
|
+
captureCredential() {
|
|
81
|
+
return this.sessionRenewals.captureCredential();
|
|
82
|
+
}
|
|
83
|
+
withSessionSignal(options) {
|
|
84
|
+
return this.sessionRenewals.withSessionSignal(options);
|
|
85
|
+
}
|
|
84
86
|
getAuthToken() {
|
|
85
87
|
return this.authToken;
|
|
86
88
|
}
|
|
87
89
|
getRequestFailure(input) {
|
|
88
90
|
return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;
|
|
89
91
|
}
|
|
90
|
-
buildHeaders(body, headers, authToken) {
|
|
91
|
-
return {
|
|
92
|
-
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
93
|
-
...(typeof body === "string" && !hasHeader(headers, "Content-Type")
|
|
94
|
-
? { "Content-Type": "application/json" }
|
|
95
|
-
: {}),
|
|
96
|
-
...headers,
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
92
|
async makeRequest(path, validator, method, body, options, failureOperation) {
|
|
100
93
|
const result = await this.makeRequestResult(path, validator, method, body, options, failureOperation);
|
|
101
94
|
return result.ok ? result.data : null;
|
|
@@ -129,31 +122,19 @@ export class ApiRequestRuntime {
|
|
|
129
122
|
return failure;
|
|
130
123
|
}
|
|
131
124
|
async makeRequestResult(path, validator, method, body, options, failureOperation) {
|
|
125
|
+
const session = this.sessionRenewals.signal;
|
|
132
126
|
const responseResult = await this.makeResponseRequest(path, method, body, options ?? {}, [], failureOperation);
|
|
133
127
|
if (!responseResult.ok) {
|
|
134
128
|
return responseResult;
|
|
135
129
|
}
|
|
136
130
|
const response = responseResult.data;
|
|
137
131
|
const reportErrors = options?.reportErrors ?? true;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (failure.kind === "network")
|
|
145
|
-
this.onNetworkError?.();
|
|
146
|
-
return this.requestFailure({
|
|
147
|
-
...failure,
|
|
148
|
-
message: `${method} ${path}: ${failure.message}`,
|
|
149
|
-
method,
|
|
150
|
-
path,
|
|
151
|
-
reportErrors: failure.kind !== "cancelled" && reportErrors,
|
|
152
|
-
stalePrincipalHeads: undefined,
|
|
153
|
-
status: response.status,
|
|
154
|
-
statusText: response.statusText,
|
|
155
|
-
});
|
|
156
|
-
}
|
|
132
|
+
const decoded = await readSessionJson(this.responseRequest, response, method, path, options ?? {}, session);
|
|
133
|
+
if (session.aborted)
|
|
134
|
+
return retiredRequest(method, path);
|
|
135
|
+
if (!decoded.ok)
|
|
136
|
+
return decoded;
|
|
137
|
+
const data = decoded.data;
|
|
157
138
|
if (!validator(data)) {
|
|
158
139
|
return this.requestFailure({
|
|
159
140
|
kind: "shape",
|
|
@@ -168,17 +149,37 @@ export class ApiRequestRuntime {
|
|
|
168
149
|
}
|
|
169
150
|
return { data, ok: true };
|
|
170
151
|
}
|
|
171
|
-
async makeResponseRequest(path, method, body, options, additionalSuccessStatuses, failureOperation) {
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
const
|
|
152
|
+
async makeResponseRequest(path, method, body, options, additionalSuccessStatuses, failureOperation, authToken = this.authToken, attempt = 1) {
|
|
153
|
+
const session = this.sessionRenewals.signal;
|
|
154
|
+
const callerOptions = options;
|
|
155
|
+
const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);
|
|
156
|
+
options = this.sessionRenewals.withSessionSignal(options);
|
|
157
|
+
const result = await this.fetchResponseRequest(path, method, body, options, authToken, failureOperation, attempt);
|
|
158
|
+
if (!result.ok)
|
|
159
|
+
return result;
|
|
160
|
+
if (session.aborted)
|
|
161
|
+
return this.retiredResponse(session, method, path, result.data);
|
|
162
|
+
const response = result.data;
|
|
177
163
|
if (isSuccessfulResponse(response, additionalSuccessStatuses)) {
|
|
178
164
|
this.requestFailuresByKey.delete(requestFailureKey({ method, path }));
|
|
179
|
-
return
|
|
165
|
+
return result;
|
|
180
166
|
}
|
|
181
167
|
const errorDescription = await describeErrorResponse(response, failureOperation, options.expectedPaymentRequiredOrganizationId);
|
|
168
|
+
const retired = () => this.retiredResponse(session, method, path, response, errorDescription.code);
|
|
169
|
+
if (session.aborted)
|
|
170
|
+
return retired();
|
|
171
|
+
const failure = {
|
|
172
|
+
errorDescription,
|
|
173
|
+
failureOperation,
|
|
174
|
+
method,
|
|
175
|
+
options,
|
|
176
|
+
path,
|
|
177
|
+
response,
|
|
178
|
+
};
|
|
179
|
+
if (attempt === 2)
|
|
180
|
+
return this.httpFailure(failure);
|
|
181
|
+
// An independent replacement or caller cancellation ends this wait. A
|
|
182
|
+
// refusal from the renewal itself must finish reporting its typed error.
|
|
182
183
|
const shouldRetry = await shouldRetryAfterSessionExpired({
|
|
183
184
|
authToken,
|
|
184
185
|
body,
|
|
@@ -186,74 +187,54 @@ export class ApiRequestRuntime {
|
|
|
186
187
|
getCurrentAuthToken: () => this.authToken,
|
|
187
188
|
isKnownSessionRenewal: (from, to) => this.sessionRenewals.isKnown(from, to),
|
|
188
189
|
pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),
|
|
189
|
-
options,
|
|
190
|
+
options: waitOptions,
|
|
190
191
|
refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),
|
|
191
192
|
reportError: (message) => this.onError?.(message),
|
|
192
193
|
responseStatus: response.status,
|
|
193
194
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
failureOperation,
|
|
201
|
-
method,
|
|
202
|
-
options: {
|
|
203
|
-
...options,
|
|
204
|
-
reportErrors: method === "GET" ? false : options.reportErrors,
|
|
205
|
-
},
|
|
206
|
-
path,
|
|
207
|
-
response,
|
|
208
|
-
});
|
|
209
|
-
const retryResult = await this.fetchResponseRequest(path, method, body, options, retryAuthToken, failureOperation, 2);
|
|
210
|
-
if (!retryResult.ok)
|
|
211
|
-
return retryResult;
|
|
212
|
-
const retryResponse = retryResult.data;
|
|
213
|
-
if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {
|
|
214
|
-
this.requestFailuresByKey.delete(requestFailureKey({ method, path }));
|
|
215
|
-
return { data: retryResponse, ok: true };
|
|
216
|
-
}
|
|
195
|
+
if (session.aborted)
|
|
196
|
+
return retired();
|
|
197
|
+
const retryToken = this.sessionRenewals.currentToken(authToken);
|
|
198
|
+
if (!shouldRetry || !retryToken)
|
|
199
|
+
return this.httpFailure(failure);
|
|
200
|
+
if (options.retryOnSessionExpired === "renew-only")
|
|
217
201
|
return this.httpFailure({
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
response: retryResponse,
|
|
202
|
+
...failure,
|
|
203
|
+
options: {
|
|
204
|
+
...options,
|
|
205
|
+
reportErrors: method === "GET" ? false : options.reportErrors,
|
|
206
|
+
},
|
|
224
207
|
});
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
208
|
+
return this.makeResponseRequest(path, method, body, callerOptions, additionalSuccessStatuses, failureOperation, retryToken, 2);
|
|
209
|
+
}
|
|
210
|
+
retiredResponse(session, method, path, response, code) {
|
|
211
|
+
const retired = retiredRequest(method, path);
|
|
212
|
+
// Principal writes refused before dispatch have a definitive outcome.
|
|
213
|
+
if (response.status !== 401 || !this.sessionRenewals.refused(session))
|
|
214
|
+
return retired;
|
|
215
|
+
return {
|
|
216
|
+
...retired,
|
|
217
|
+
kind: "http",
|
|
218
|
+
status: 401,
|
|
219
|
+
statusText: response.statusText,
|
|
220
|
+
code: code ?? undefined,
|
|
221
|
+
message: `${method} ${path}: 401 ${response.statusText}`,
|
|
222
|
+
};
|
|
234
223
|
}
|
|
235
224
|
async fetchResponseRequest(path, method, body, options, authToken, operation,
|
|
236
225
|
/** 2 is the retry after a session renewal. */
|
|
237
226
|
attempt = 1) {
|
|
227
|
+
const session = this.sessionRenewals.signal;
|
|
238
228
|
const reportErrors = options.reportErrors ?? true;
|
|
239
|
-
const headers =
|
|
240
|
-
const init = {
|
|
241
|
-
method,
|
|
242
|
-
headers,
|
|
243
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
244
|
-
};
|
|
245
|
-
if (body !== undefined) {
|
|
246
|
-
init.body = body;
|
|
247
|
-
if (body instanceof ReadableStream) {
|
|
248
|
-
init.duplex = "half";
|
|
249
|
-
}
|
|
250
|
-
}
|
|
229
|
+
const { headers, init } = sessionRequestInit(method, body, options, authToken);
|
|
251
230
|
let response;
|
|
252
231
|
const startedAt = Date.now();
|
|
253
232
|
try {
|
|
254
233
|
response = await measureApiRequest(this.instrumentation, operation, () => fetch(`${this.baseUrl}${path}`, init), options.signal);
|
|
255
234
|
}
|
|
256
235
|
catch (error) {
|
|
236
|
+
if (session.aborted)
|
|
237
|
+
return retiredRequest(method, path);
|
|
257
238
|
const { cancelled, networkError } = await settleNetworkFailure({
|
|
258
239
|
attempt,
|
|
259
240
|
baseUrl: this.baseUrl,
|
|
@@ -268,6 +249,8 @@ export class ApiRequestRuntime {
|
|
|
268
249
|
signal: options.signal,
|
|
269
250
|
onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),
|
|
270
251
|
});
|
|
252
|
+
if (session.aborted)
|
|
253
|
+
return retiredRequest(method, path);
|
|
271
254
|
return this.requestFailure({
|
|
272
255
|
...(cancelled ? { code: "request_aborted" } : {}),
|
|
273
256
|
kind: cancelled ? "cancelled" : "network",
|
|
@@ -281,6 +264,8 @@ export class ApiRequestRuntime {
|
|
|
281
264
|
statusText: "",
|
|
282
265
|
});
|
|
283
266
|
}
|
|
267
|
+
if (session.aborted)
|
|
268
|
+
return this.retiredResponse(session, method, path, response);
|
|
284
269
|
this.onNetworkSuccess?.();
|
|
285
270
|
const apiVersion = parseApiVersion(response.headers.get(apiVersionHeaderName));
|
|
286
271
|
if (apiVersion !== null)
|