@tearleads/client-sdk 0.1.250 → 0.1.252
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 +14 -25
- package/Tearleads.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 +1 -1
- package/client/runtime/workflowRuntime.js +20 -77
- 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/documents/shared/events.js +2 -1
- package/data/documents/shared/events.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/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/internal/validators/documentCreateSeedRefinements.js +2 -2
- package/internal/validators/documentCreateSeedRefinements.js.map +1 -1
- package/internal/validators/operation/auth.d.ts +50 -1703
- package/internal/validators/operation/auth.js +2 -2
- package/internal/validators/operation/auth.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +1 -294
- package/internal/validators/operation/containerMutations.js +2 -2
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/documentMutations.d.ts +1 -294
- package/internal/validators/operation/documentMutations.js +2 -2
- package/internal/validators/operation/documentMutations.js.map +1 -1
- package/internal/validators/operation/organizations.d.ts +50 -1703
- package/internal/validators/operation/organizations.js +2 -2
- package/internal/validators/operation/organizations.js.map +1 -1
- package/internal/validators/organizationProvisioningRefinements.js +2 -2
- package/internal/validators/organizationProvisioningRefinements.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -276
- package/internal/validators/request/containerMetadata.js +5 -4
- package/internal/validators/request/containerMetadata.js.map +1 -1
- package/internal/validators/request/document.d.ts +0 -277
- package/internal/validators/request/document.js +8 -4
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentCreateSeed.d.ts +99 -0
- package/internal/validators/request/documentCreateSeed.js +132 -9
- package/internal/validators/request/documentCreateSeed.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +41 -0
- package/internal/validators/request/documentSyncSchema.js +1 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -0
- package/internal/validators/request/index.js +1 -0
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organizationProvisioning.d.ts +263 -5567
- package/internal/validators/request/organizationProvisioning.js +10 -4
- package/internal/validators/request/organizationProvisioning.js.map +1 -1
- package/internal/validators/request/registration.d.ts +71 -1703
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +6 -3
- package/workflows/container-contents/container-state/create/createWithMetadata.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/documents/create/index.js +4 -4
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.d.ts +26 -11
- package/workflows/documents/sync/initialSync.js +32 -12
- package/workflows/documents/sync/initialSync.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/provisionedProfileDocument.js +2 -2
- package/workflows/registration/provisionedProfileDocument.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -68
- package/workflows/registration/provisioningBootstrapBuilders.js +3 -3
- package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -1 +1 @@
|
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type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\nimport {\n createDecryptedBlobByteSource,\n createEncryptedBlobByteSource,\n} from \"./encryptedBlobByteSource\";\nimport {\n asBlobBytes,\n assertNamespace,\n createAesGcmIv,\n createKeyDerivationEnvelope,\n ENCRYPTED_BLOB_CHUNK_SIZE,\n ENCRYPTED_BLOB_STORE_FORMAT,\n ENCRYPTED_BLOB_STORE_VERSION,\n type EncryptedBlobEnvelope,\n type EncryptedBlobStoreCipher,\n getChunkCount,\n type KeyDerivationEnvelope,\n normalizeCipher,\n normalizeKdfIterations,\n readBase64Bytes,\n readEncryptedBlobEnvelope,\n serializeEncryptedBlobEnvelope,\n} from \"./encryptedBlobEnvelope\";\nimport { createOpfsBlobStore, isOpfsBlobStoreSupported } from \"./opfsBlobStore\";\n\nexport type { EncryptedBlobStoreCipher };\nexport type EncryptedBlobStoreKey = string | Uint8Array | CryptoKey;\n\nexport interface EncryptedBlobStoreOptions {\n cipher?: EncryptedBlobStoreCipher | undefined;\n kdfIterations?: number | undefined;\n key: EncryptedBlobStoreKey;\n}\n\nexport interface WrapEncryptedBlobStoreOptions\n extends EncryptedBlobStoreOptions {\n namespace: string;\n}\n\nconst AES_256_KEY_BYTES = 32;\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof CryptoKey !== \"undefined\" && value instanceof CryptoKey;\n}\n\nfunction assertCryptoKey(key: CryptoKey): void {\n if (key.type !== \"secret\" || key.algorithm.name !== \"AES-GCM\") {\n throw new Error(\n \"Encrypted blob store CryptoKey must be an AES-GCM secret.\",\n );\n }\n if (!key.usages.includes(\"encrypt\") || !key.usages.includes(\"decrypt\")) {\n throw new Error(\n \"Encrypted blob store CryptoKey must allow encrypt and decrypt.\",\n );\n }\n}\n\nasync function importRawAesKey(key: Uint8Array): Promise<CryptoKey> {\n if (key.byteLength !== AES_256_KEY_BYTES) {\n throw new Error(\"Encrypted blob store AES-256-GCM key must be 32 bytes.\");\n }\n\n return crypto.subtle.importKey(\"raw\", asBlobBytes(key), \"AES-GCM\", false, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\nclass EncryptedBlobStore implements BlobStore {\n private readonly cipher: EncryptedBlobStoreCipher;\n private readonly derivedKeyByEnvelope = new Map<string, Promise<CryptoKey>>();\n private readonly kdfIterations: number;\n private readonly namespace: string;\n private readonly passphraseMaterialPromise: Promise<CryptoKey> | null;\n private readonly rawKeyPromise: Promise<CryptoKey> | null;\n\n constructor(\n private readonly innerStore: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n ) {\n if (!options || !(\"key\" in options)) {\n throw new Error(\"Encrypted blob store key is required.\");\n }\n assertNamespace(options.namespace);\n this.namespace = options.namespace;\n this.cipher = normalizeCipher(options.cipher);\n this.kdfIterations = normalizeKdfIterations(options.kdfIterations);\n\n if (typeof options.key === \"string\") {\n if (options.key.length === 0) {\n throw new Error(\"Encrypted blob store key must be non-empty.\");\n }\n this.rawKeyPromise = null;\n this.passphraseMaterialPromise = crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(options.key),\n \"PBKDF2\",\n false,\n [\"deriveKey\"],\n );\n return;\n }\n\n this.passphraseMaterialPromise = null;\n if (isCryptoKey(options.key)) {\n assertCryptoKey(options.key);\n this.rawKeyPromise = Promise.resolve(options.key);\n return;\n }\n\n if (!(options.key instanceof Uint8Array)) {\n throw new Error(\n \"Encrypted blob store key must be a string, Uint8Array, or CryptoKey.\",\n );\n }\n\n this.rawKeyPromise = importRawAesKey(options.key);\n }\n\n async deleteBytes(storageKey: string): Promise<void> {\n await this.innerStore.deleteBytes(storageKey);\n }\n\n async openByteSource(storageKey: string): Promise<BlobByteSource | null> {\n const encryptedSource = await this.innerStore.openByteSource(storageKey);\n if (!encryptedSource) {\n return null;\n }\n\n const parsed = await readEncryptedBlobEnvelope(encryptedSource);\n const key = await this.getCipherKey(parsed.envelope.keyDerivation);\n return createDecryptedBlobByteSource({\n encryptedSource,\n headerBytes: parsed.headerBytes,\n iv: parsed.iv,\n key,\n namespace: this.namespace,\n parsed,\n storageKey,\n });\n }\n\n async readBytes(storageKey: string): Promise<BlobBytes | null> {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n ): Promise<void> {\n const keyDerivation = this.createKeyDerivationEnvelope();\n const key = await this.getCipherKey(keyDerivation);\n const iv = createAesGcmIv();\n const envelope: EncryptedBlobEnvelope = {\n chunkCount: getChunkCount(source.byteLength),\n chunkSize: ENCRYPTED_BLOB_CHUNK_SIZE,\n cipher: this.cipher,\n format: ENCRYPTED_BLOB_STORE_FORMAT,\n iv: bytesToBase64(iv),\n keyDerivation,\n plaintextByteLength: source.byteLength,\n version: ENCRYPTED_BLOB_STORE_VERSION,\n };\n const { headerBytes, prefixBytes } =\n serializeEncryptedBlobEnvelope(envelope);\n await this.innerStore.writeByteSource(\n storageKey,\n createEncryptedBlobByteSource({\n envelope,\n headerBytes,\n iv,\n key,\n namespace: this.namespace,\n plaintextSource: source,\n prefixBytes,\n storageKey,\n }),\n );\n }\n\n async writeBytes(storageKey: string, bytes: BlobBytes): Promise<void> {\n await this.writeByteSource(storageKey, createBlobByteSource(bytes));\n }\n\n private createKeyDerivationEnvelope(): KeyDerivationEnvelope | null {\n if (!this.passphraseMaterialPromise) {\n return null;\n }\n\n return createKeyDerivationEnvelope({\n cipher: this.cipher,\n iterations: this.kdfIterations,\n namespace: this.namespace,\n });\n }\n\n private async getCipherKey(\n keyDerivation: KeyDerivationEnvelope | null,\n ): Promise<CryptoKey> {\n if (!keyDerivation) {\n if (!this.rawKeyPromise) {\n throw new Error(\n \"Encrypted blob store payload was not written with passphrase key derivation.\",\n );\n }\n\n return this.rawKeyPromise;\n }\n\n if (!this.passphraseMaterialPromise) {\n throw new Error(\n \"Encrypted blob store payload requires a passphrase key.\",\n );\n }\n\n const cacheKey = JSON.stringify(keyDerivation);\n let derivedKeyPromise = this.derivedKeyByEnvelope.get(cacheKey);\n if (!derivedKeyPromise) {\n derivedKeyPromise = this.derivePassphraseKey(keyDerivation);\n derivedKeyPromise.catch(() => {\n if (this.derivedKeyByEnvelope.get(cacheKey) === derivedKeyPromise) {\n this.derivedKeyByEnvelope.delete(cacheKey);\n }\n });\n this.derivedKeyByEnvelope.set(cacheKey, derivedKeyPromise);\n }\n\n return derivedKeyPromise;\n }\n\n private async derivePassphraseKey(\n keyDerivation: KeyDerivationEnvelope,\n ): Promise<CryptoKey> {\n const passphraseMaterial = await this.passphraseMaterialPromise;\n if (!passphraseMaterial) {\n throw new Error(\"Encrypted blob store passphrase material is missing.\");\n }\n\n return crypto.subtle.deriveKey(\n {\n name: \"PBKDF2\",\n hash: \"SHA-256\",\n iterations: keyDerivation.iterations,\n salt: readBase64Bytes(\n { salt: keyDerivation.salt },\n \"salt\",\n \"Encrypted blob store keyDerivation\",\n ),\n },\n passphraseMaterial,\n {\n name: \"AES-GCM\",\n length: 256,\n },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n }\n}\n\nexport function wrapEncryptedBlobStore(\n store: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n): BlobStore {\n return new EncryptedBlobStore(store, options);\n}\n\nexport function createEncryptedBlobStore(\n namespace: string,\n options: EncryptedBlobStoreOptions,\n): BlobStore {\n if (!isOpfsBlobStoreSupported()) {\n throw new Error(\"OPFS blob store is not supported.\");\n }\n\n return wrapEncryptedBlobStore(createOpfsBlobStore(namespace), {\n ...options,\n namespace,\n });\n}\n\nexport function createLazyEncryptedBlobStore(\n namespace: string,\n keyProvider: () => Promise<EncryptedBlobStoreKey>,\n): BlobStore {\n let innerStorePromise: Promise<BlobStore> | null = null;\n\n function getStore(): Promise<BlobStore> {\n if (!innerStorePromise) {\n innerStorePromise = (async () => {\n const key = await keyProvider();\n return createEncryptedBlobStore(namespace, { key });\n })().catch((error: unknown) => {\n // Run cleanup after assignment, even if keyProvider throws synchronously.\n innerStorePromise = null;\n throw error;\n });\n }\n\n return innerStorePromise;\n }\n\n return {\n deleteBytes: async (storageKey) => {\n const store = await getStore();\n return store.deleteBytes(storageKey);\n },\n openByteSource: async (storageKey) => {\n const store = await getStore();\n return store.openByteSource(storageKey);\n },\n readBytes: async (storageKey) => {\n const store = await getStore();\n return store.readBytes(storageKey);\n },\n writeByteSource: async (storageKey, source) => {\n const store = await getStore();\n return store.writeByteSource(storageKey, source);\n },\n writeBytes: async (storageKey, bytes) => {\n const store = await getStore();\n return store.writeBytes(storageKey, bytes);\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"encryptedBlobStore.js","sourceRoot":"","sources":["encryptedBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAIL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,WAAW,EACX,eAAe,EACf,cAAc,EACd,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC3B,4BAA4B,EAG5B,aAAa,EAEb,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAgBhF,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC;AAEvC,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,OAAO,SAAS,KAAK,WAAW,IAAI,KAAK,YAAY,SAAS,CAAC;AACxE,CAAC;AAED,SAAS,eAAe,CAAC,GAAc;IACrC,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,SAAS,EAAE,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,CAAC;YAC/B,OAAO,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC;QACD,eAAe,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,EAAE;YAC3D,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,aAAa,EAAE,EAAE,CAAC;YAClB,OAAO,KAAK,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC;QAClE,CAAC;QACD,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YACrD,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,aAAa,EAAE,EAAE,CAAC;YAClB,OAAO,KAAK,CAAC,UAAU,CAAC,UAAU,EAAE,KAAK,EAAE,aAAa,CAAC,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\nimport {\n createDecryptedBlobByteSource,\n createEncryptedBlobByteSource,\n} from \"./encryptedBlobByteSource\";\nimport {\n asBlobBytes,\n assertNamespace,\n createAesGcmIv,\n createKeyDerivationEnvelope,\n ENCRYPTED_BLOB_CHUNK_SIZE,\n ENCRYPTED_BLOB_STORE_FORMAT,\n ENCRYPTED_BLOB_STORE_VERSION,\n type EncryptedBlobEnvelope,\n type EncryptedBlobStoreCipher,\n getChunkCount,\n type KeyDerivationEnvelope,\n normalizeCipher,\n normalizeKdfIterations,\n readBase64Bytes,\n readEncryptedBlobEnvelope,\n serializeEncryptedBlobEnvelope,\n} from \"./encryptedBlobEnvelope\";\nimport { createOpfsBlobStore, isOpfsBlobStoreSupported } from \"./opfsBlobStore\";\n\nexport type { EncryptedBlobStoreCipher };\nexport type EncryptedBlobStoreKey = string | Uint8Array | CryptoKey;\n\nexport interface EncryptedBlobStoreOptions {\n cipher?: EncryptedBlobStoreCipher | undefined;\n kdfIterations?: number | undefined;\n key: EncryptedBlobStoreKey;\n}\n\nexport interface WrapEncryptedBlobStoreOptions\n extends EncryptedBlobStoreOptions {\n namespace: string;\n}\n\nconst AES_256_KEY_BYTES = 32;\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof CryptoKey !== \"undefined\" && value instanceof CryptoKey;\n}\n\nfunction assertCryptoKey(key: CryptoKey): void {\n if (key.type !== \"secret\" || key.algorithm.name !== \"AES-GCM\") {\n throw new Error(\n \"Encrypted blob store CryptoKey must be an AES-GCM secret.\",\n );\n }\n if (!key.usages.includes(\"encrypt\") || !key.usages.includes(\"decrypt\")) {\n throw new Error(\n \"Encrypted blob store CryptoKey must allow encrypt and decrypt.\",\n );\n }\n}\n\nasync function importRawAesKey(key: Uint8Array): Promise<CryptoKey> {\n if (key.byteLength !== AES_256_KEY_BYTES) {\n throw new Error(\"Encrypted blob store AES-256-GCM key must be 32 bytes.\");\n }\n\n return crypto.subtle.importKey(\"raw\", asBlobBytes(key), \"AES-GCM\", false, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\nclass EncryptedBlobStore implements BlobStore {\n private readonly cipher: EncryptedBlobStoreCipher;\n private readonly derivedKeyByEnvelope = new Map<string, Promise<CryptoKey>>();\n private readonly kdfIterations: number;\n private readonly namespace: string;\n private readonly passphraseMaterialPromise: Promise<CryptoKey> | null;\n private readonly rawKeyPromise: Promise<CryptoKey> | null;\n\n constructor(\n private readonly innerStore: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n ) {\n if (!options || !(\"key\" in options)) {\n throw new Error(\"Encrypted blob store key is required.\");\n }\n assertNamespace(options.namespace);\n this.namespace = options.namespace;\n this.cipher = normalizeCipher(options.cipher);\n this.kdfIterations = normalizeKdfIterations(options.kdfIterations);\n\n if (typeof options.key === \"string\") {\n if (options.key.length === 0) {\n throw new Error(\"Encrypted blob store key must be non-empty.\");\n }\n this.rawKeyPromise = null;\n this.passphraseMaterialPromise = crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(options.key),\n \"PBKDF2\",\n false,\n [\"deriveKey\"],\n );\n return;\n }\n\n this.passphraseMaterialPromise = null;\n if (isCryptoKey(options.key)) {\n assertCryptoKey(options.key);\n this.rawKeyPromise = Promise.resolve(options.key);\n return;\n }\n\n if (!(options.key instanceof Uint8Array)) {\n throw new Error(\n \"Encrypted blob store key must be a string, Uint8Array, or CryptoKey.\",\n );\n }\n\n this.rawKeyPromise = importRawAesKey(options.key);\n }\n\n async deleteBytes(\n storageKey: string,\n assertCurrent?: () => void,\n ): Promise<void> {\n assertCurrent?.();\n await this.innerStore.deleteBytes(storageKey, assertCurrent);\n }\n\n async openByteSource(storageKey: string): Promise<BlobByteSource | null> {\n const encryptedSource = await this.innerStore.openByteSource(storageKey);\n if (!encryptedSource) {\n return null;\n }\n\n const parsed = await readEncryptedBlobEnvelope(encryptedSource);\n const key = await this.getCipherKey(parsed.envelope.keyDerivation);\n return createDecryptedBlobByteSource({\n encryptedSource,\n headerBytes: parsed.headerBytes,\n iv: parsed.iv,\n key,\n namespace: this.namespace,\n parsed,\n storageKey,\n });\n }\n\n async readBytes(storageKey: string): Promise<BlobBytes | null> {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ): Promise<void> {\n const keyDerivation = this.createKeyDerivationEnvelope();\n const key = await this.getCipherKey(keyDerivation);\n const iv = createAesGcmIv();\n const envelope: EncryptedBlobEnvelope = {\n chunkCount: getChunkCount(source.byteLength),\n chunkSize: ENCRYPTED_BLOB_CHUNK_SIZE,\n cipher: this.cipher,\n format: ENCRYPTED_BLOB_STORE_FORMAT,\n iv: bytesToBase64(iv),\n keyDerivation,\n plaintextByteLength: source.byteLength,\n version: ENCRYPTED_BLOB_STORE_VERSION,\n };\n const { headerBytes, prefixBytes } =\n serializeEncryptedBlobEnvelope(envelope);\n assertCurrent?.();\n await this.innerStore.writeByteSource(\n storageKey,\n createEncryptedBlobByteSource({\n envelope,\n headerBytes,\n iv,\n key,\n namespace: this.namespace,\n plaintextSource: source,\n prefixBytes,\n storageKey,\n }),\n assertCurrent,\n );\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ): Promise<void> {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n\n private createKeyDerivationEnvelope(): KeyDerivationEnvelope | null {\n if (!this.passphraseMaterialPromise) {\n return null;\n }\n\n return createKeyDerivationEnvelope({\n cipher: this.cipher,\n iterations: this.kdfIterations,\n namespace: this.namespace,\n });\n }\n\n private async getCipherKey(\n keyDerivation: KeyDerivationEnvelope | null,\n ): Promise<CryptoKey> {\n if (!keyDerivation) {\n if (!this.rawKeyPromise) {\n throw new Error(\n \"Encrypted blob store payload was not written with passphrase key derivation.\",\n );\n }\n\n return this.rawKeyPromise;\n }\n\n if (!this.passphraseMaterialPromise) {\n throw new Error(\n \"Encrypted blob store payload requires a passphrase key.\",\n );\n }\n\n const cacheKey = JSON.stringify(keyDerivation);\n let derivedKeyPromise = this.derivedKeyByEnvelope.get(cacheKey);\n if (!derivedKeyPromise) {\n derivedKeyPromise = this.derivePassphraseKey(keyDerivation);\n derivedKeyPromise.catch(() => {\n if (this.derivedKeyByEnvelope.get(cacheKey) === derivedKeyPromise) {\n this.derivedKeyByEnvelope.delete(cacheKey);\n }\n });\n this.derivedKeyByEnvelope.set(cacheKey, derivedKeyPromise);\n }\n\n return derivedKeyPromise;\n }\n\n private async derivePassphraseKey(\n keyDerivation: KeyDerivationEnvelope,\n ): Promise<CryptoKey> {\n const passphraseMaterial = await this.passphraseMaterialPromise;\n if (!passphraseMaterial) {\n throw new Error(\"Encrypted blob store passphrase material is missing.\");\n }\n\n return crypto.subtle.deriveKey(\n {\n name: \"PBKDF2\",\n hash: \"SHA-256\",\n iterations: keyDerivation.iterations,\n salt: readBase64Bytes(\n { salt: keyDerivation.salt },\n \"salt\",\n \"Encrypted blob store keyDerivation\",\n ),\n },\n passphraseMaterial,\n {\n name: \"AES-GCM\",\n length: 256,\n },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n }\n}\n\nexport function wrapEncryptedBlobStore(\n store: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n): BlobStore {\n return new EncryptedBlobStore(store, options);\n}\n\nexport function createEncryptedBlobStore(\n namespace: string,\n options: EncryptedBlobStoreOptions,\n): BlobStore {\n if (!isOpfsBlobStoreSupported()) {\n throw new Error(\"OPFS blob store is not supported.\");\n }\n\n return wrapEncryptedBlobStore(createOpfsBlobStore(namespace), {\n ...options,\n namespace,\n });\n}\n\nexport function createLazyEncryptedBlobStore(\n namespace: string,\n keyProvider: () => Promise<EncryptedBlobStoreKey>,\n): BlobStore {\n let innerStorePromise: Promise<BlobStore> | null = null;\n\n function getStore(): Promise<BlobStore> {\n if (!innerStorePromise) {\n innerStorePromise = (async () => {\n const key = await keyProvider();\n return createEncryptedBlobStore(namespace, { key });\n })().catch((error: unknown) => {\n // Run cleanup after assignment, even if keyProvider throws synchronously.\n innerStorePromise = null;\n throw error;\n });\n }\n\n return innerStorePromise;\n }\n\n return {\n deleteBytes: async (storageKey, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.deleteBytes(storageKey, assertCurrent);\n },\n openByteSource: async (storageKey) => {\n const store = await getStore();\n return store.openByteSource(storageKey);\n },\n readBytes: async (storageKey) => {\n const store = await getStore();\n return store.readBytes(storageKey);\n },\n writeByteSource: async (storageKey, source, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.writeByteSource(storageKey, source, assertCurrent);\n },\n writeBytes: async (storageKey, bytes, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.writeBytes(storageKey, bytes, assertCurrent);\n },\n };\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createBlobByteSource, readBlobByteSource, } from "./blobContracts.js";
|
|
2
2
|
class MemoryBlobStore {
|
|
3
3
|
bytesByKey = new Map();
|
|
4
|
-
async deleteBytes(storageKey) {
|
|
4
|
+
async deleteBytes(storageKey, assertCurrent) {
|
|
5
|
+
assertCurrent?.();
|
|
5
6
|
this.bytesByKey.delete(storageKey);
|
|
6
7
|
}
|
|
7
8
|
async openByteSource(storageKey) {
|
|
@@ -12,11 +13,13 @@ class MemoryBlobStore {
|
|
|
12
13
|
const source = await this.openByteSource(storageKey);
|
|
13
14
|
return source ? readBlobByteSource(source) : null;
|
|
14
15
|
}
|
|
15
|
-
async writeByteSource(storageKey, source) {
|
|
16
|
-
|
|
16
|
+
async writeByteSource(storageKey, source, assertCurrent) {
|
|
17
|
+
const bytes = await readBlobByteSource(source);
|
|
18
|
+
assertCurrent?.();
|
|
19
|
+
this.bytesByKey.set(storageKey, bytes);
|
|
17
20
|
}
|
|
18
|
-
async writeBytes(storageKey, bytes) {
|
|
19
|
-
await this.writeByteSource(storageKey, createBlobByteSource(bytes));
|
|
21
|
+
async writeBytes(storageKey, bytes, assertCurrent) {
|
|
22
|
+
await this.writeByteSource(storageKey, createBlobByteSource(bytes), assertCurrent);
|
|
20
23
|
}
|
|
21
24
|
}
|
|
22
25
|
export function createMemoryBlobStore() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoryBlobStore.js","sourceRoot":"","sources":["memoryBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,eAAe;IACF,UAAU,GAAG,IAAI,GAAG,EAAqB,CAAC;IAE3D,KAAK,CAAC,WAAW,CAAC,UAAkB;
|
|
1
|
+
{"version":3,"file":"memoryBlobStore.js","sourceRoot":"","sources":["memoryBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAI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\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\nclass MemoryBlobStore implements BlobStore {\n private readonly bytesByKey = new Map<string, BlobBytes>();\n\n async deleteBytes(storageKey: string, assertCurrent?: () => void) {\n assertCurrent?.();\n this.bytesByKey.delete(storageKey);\n }\n\n async openByteSource(storageKey: string) {\n const bytes = this.bytesByKey.get(storageKey);\n return bytes ? createBlobByteSource(bytes) : null;\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n const bytes = await readBlobByteSource(source);\n assertCurrent?.();\n this.bytesByKey.set(storageKey, bytes);\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ) {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n}\n\nexport function createMemoryBlobStore(): BlobStore {\n return new MemoryBlobStore();\n}\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
async function openDestination(directory, name, assertCurrent) {
|
|
2
|
+
try {
|
|
3
|
+
return { handle: await directory.getFileHandle(name), created: false };
|
|
4
|
+
}
|
|
5
|
+
catch (error) {
|
|
6
|
+
if (!(error instanceof DOMException && error.name === "NotFoundError"))
|
|
7
|
+
throw error;
|
|
8
|
+
}
|
|
9
|
+
assertCurrent?.();
|
|
10
|
+
return {
|
|
11
|
+
handle: await directory.getFileHandle(name, { create: true }),
|
|
12
|
+
created: true,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** The caller holds the destination's write lock until rollback finishes. */
|
|
16
|
+
export async function commitOpfsFile(directory, name, assertCurrent, stage) {
|
|
17
|
+
assertCurrent?.();
|
|
18
|
+
const { handle, created } = await openDestination(directory, name, assertCurrent);
|
|
19
|
+
let writable;
|
|
20
|
+
try {
|
|
21
|
+
assertCurrent?.();
|
|
22
|
+
writable = await handle.createWritable();
|
|
23
|
+
await stage(writable);
|
|
24
|
+
assertCurrent?.();
|
|
25
|
+
await writable.close();
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
await writable?.abort(error).catch(() => { });
|
|
29
|
+
// Aborting discards staged bytes, but OPFS created the directory entry
|
|
30
|
+
// eagerly. Undo only this write's creation; an existing file is intact.
|
|
31
|
+
if (created)
|
|
32
|
+
await directory.removeEntry(name);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=opfsBlobFile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"opfsBlobFile.js","sourceRoot":"","sources":["opfsBlobFile.ts"],"names":[],"mappings":"AAAA,KAAK,UAAU,eAAe,CAC5B,SAAoC,EACpC,IAAY,EACZ,aAA0B;IAE1B,IAAI,CAAC;QACH,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACzE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC;YACpE,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,aAAa,EAAE,EAAE,CAAC;IAClB,OAAO;QACL,MAAM,EAAE,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QAC7D,OAAO,EAAE,IAAI;KACd,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,SAAoC,EACpC,IAAY,EACZ,aAAuC,EACvC,KAAgE;IAEhE,aAAa,EAAE,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,eAAe,CAC/C,SAAS,EACT,IAAI,EACJ,aAAa,CACd,CAAC;IACF,IAAI,QAAkD,CAAC;IACvD,IAAI,CAAC;QACH,aAAa,EAAE,EAAE,CAAC;QAClB,QAAQ,GAAG,MAAM,MAAM,CAAC,cAAc,EAAE,CAAC;QACzC,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;QACtB,aAAa,EAAE,EAAE,CAAC;QAClB,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC7C,uEAAuE;QACvE,wEAAwE;QACxE,IAAI,OAAO;YAAE,MAAM,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["async function openDestination(\n directory: FileSystemDirectoryHandle,\n name: string,\n assertCurrent?: () => void,\n) {\n try {\n return { handle: await directory.getFileHandle(name), created: false };\n } catch (error) {\n if (!(error instanceof DOMException && error.name === \"NotFoundError\"))\n throw error;\n }\n assertCurrent?.();\n return {\n handle: await directory.getFileHandle(name, { create: true }),\n created: true,\n };\n}\n\n/** The caller holds the destination's write lock until rollback finishes. */\nexport async function commitOpfsFile(\n directory: FileSystemDirectoryHandle,\n name: string,\n assertCurrent: (() => void) | undefined,\n stage: (writable: FileSystemWritableFileStream) => Promise<void>,\n): Promise<void> {\n assertCurrent?.();\n const { handle, created } = await openDestination(\n directory,\n name,\n assertCurrent,\n );\n let writable: FileSystemWritableFileStream | undefined;\n try {\n assertCurrent?.();\n writable = await handle.createWritable();\n await stage(writable);\n assertCurrent?.();\n await writable.close();\n } catch (error) {\n await writable?.abort(error).catch(() => {});\n // Aborting discards staged bytes, but OPFS created the directory entry\n // eagerly. Undo only this write's creation; an existing file is intact.\n if (created) await directory.removeEntry(name);\n throw error;\n }\n}\n"]}
|
|
@@ -7,4 +7,4 @@ export declare function createOpfsBlobStore(namespace: string): BlobStore;
|
|
|
7
7
|
* Used to forget local data on logout. No-op when OPFS is unavailable or the
|
|
8
8
|
* directory was never created; never throws on a missing directory.
|
|
9
9
|
*/
|
|
10
|
-
export declare function purgeOpfsBlobStore(namespace: string): Promise<void>;
|
|
10
|
+
export declare function purgeOpfsBlobStore(namespace: string, current?: () => boolean): Promise<void>;
|
|
@@ -1,14 +1,65 @@
|
|
|
1
1
|
import { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "./blobContracts.js";
|
|
2
|
+
import { commitOpfsFile } from "./opfsBlobFile.js";
|
|
2
3
|
const OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;
|
|
3
4
|
class OpfsBlobStore {
|
|
4
5
|
namespace;
|
|
5
6
|
directoryPromise = null;
|
|
7
|
+
active = new Set();
|
|
8
|
+
writers = new Map();
|
|
9
|
+
purgeBarrier;
|
|
6
10
|
constructor(namespace) {
|
|
7
11
|
this.namespace = namespace;
|
|
8
12
|
}
|
|
9
|
-
|
|
13
|
+
// File operations run concurrently. A directory removal waits for all
|
|
14
|
+
// of them and any later file operation opens the surviving directory.
|
|
15
|
+
async useFile(key, mode, run) {
|
|
16
|
+
const locked = () => {
|
|
17
|
+
const locks = navigator.locks;
|
|
18
|
+
return typeof locks?.request === "function"
|
|
19
|
+
? locks.request(JSON.stringify(["tearleads.opfs.blob", this.namespace, key]), { mode }, run)
|
|
20
|
+
: run();
|
|
21
|
+
};
|
|
22
|
+
const writer = this.writers.get(key);
|
|
23
|
+
const operation = writer || this.purgeBarrier
|
|
24
|
+
? Promise.allSettled([writer, this.purgeBarrier]).then(locked)
|
|
25
|
+
: locked();
|
|
26
|
+
if (mode === "exclusive")
|
|
27
|
+
this.writers.set(key, operation);
|
|
28
|
+
this.active.add(operation);
|
|
29
|
+
try {
|
|
30
|
+
return await operation;
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
this.active.delete(operation);
|
|
34
|
+
if (this.writers.get(key) === operation)
|
|
35
|
+
this.writers.delete(key);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async purge(current) {
|
|
39
|
+
const pending = Promise.allSettled([
|
|
40
|
+
...this.active,
|
|
41
|
+
this.purgeBarrier,
|
|
42
|
+
]).then(async () => {
|
|
43
|
+
if (current() && (await removeNamespace(this.namespace, current)))
|
|
44
|
+
this.directoryPromise = null;
|
|
45
|
+
});
|
|
46
|
+
const barrier = pending.catch(() => { });
|
|
47
|
+
this.purgeBarrier = barrier;
|
|
48
|
+
try {
|
|
49
|
+
await pending;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
if (this.purgeBarrier === barrier)
|
|
53
|
+
this.purgeBarrier = undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
deleteBytes(storageKey, assertCurrent) {
|
|
57
|
+
return this.useFile(storageKey, "exclusive", () => this.removeFile(storageKey, assertCurrent));
|
|
58
|
+
}
|
|
59
|
+
async removeFile(storageKey, assertCurrent) {
|
|
10
60
|
const directory = await this.getDirectory();
|
|
11
61
|
try {
|
|
62
|
+
assertCurrent?.();
|
|
12
63
|
await directory.removeEntry(this.getFileName(storageKey));
|
|
13
64
|
}
|
|
14
65
|
catch (error) {
|
|
@@ -22,7 +73,10 @@ class OpfsBlobStore {
|
|
|
22
73
|
const source = await this.openByteSource(storageKey);
|
|
23
74
|
return source ? readBlobByteSource(source) : null;
|
|
24
75
|
}
|
|
25
|
-
|
|
76
|
+
openByteSource(storageKey) {
|
|
77
|
+
return this.useFile(storageKey, "shared", () => this.openFile(storageKey));
|
|
78
|
+
}
|
|
79
|
+
async openFile(storageKey) {
|
|
26
80
|
const directory = await this.getDirectory();
|
|
27
81
|
try {
|
|
28
82
|
const fileHandle = await directory.getFileHandle(this.getFileName(storageKey));
|
|
@@ -36,12 +90,13 @@ class OpfsBlobStore {
|
|
|
36
90
|
throw error;
|
|
37
91
|
}
|
|
38
92
|
}
|
|
39
|
-
|
|
93
|
+
writeByteSource(storageKey, source, assertCurrent) {
|
|
94
|
+
return this.useFile(storageKey, "exclusive", () => this.writeFile(storageKey, source, assertCurrent));
|
|
95
|
+
}
|
|
96
|
+
async writeFile(storageKey, source, assertCurrent) {
|
|
40
97
|
const sourceByteLength = blobByteSourceInputLength(source);
|
|
41
98
|
const directory = await this.getDirectory();
|
|
42
|
-
|
|
43
|
-
const writable = await fileHandle.createWritable();
|
|
44
|
-
try {
|
|
99
|
+
await commitOpfsFile(directory, this.getFileName(storageKey), assertCurrent, async (writable) => {
|
|
45
100
|
for (let offset = 0; offset < sourceByteLength;) {
|
|
46
101
|
const byteLength = Math.min(OPFS_WRITE_CHUNK_SIZE, sourceByteLength - offset);
|
|
47
102
|
const chunk = await source.read(offset, byteLength);
|
|
@@ -51,15 +106,10 @@ class OpfsBlobStore {
|
|
|
51
106
|
await writable.write(chunk);
|
|
52
107
|
offset += byteLength;
|
|
53
108
|
}
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
catch (error) {
|
|
57
|
-
await writable.abort(error).catch(() => undefined);
|
|
58
|
-
throw error;
|
|
59
|
-
}
|
|
109
|
+
});
|
|
60
110
|
}
|
|
61
|
-
async writeBytes(storageKey, bytes) {
|
|
62
|
-
await this.writeByteSource(storageKey, createBlobByteSource(bytes));
|
|
111
|
+
async writeBytes(storageKey, bytes, assertCurrent) {
|
|
112
|
+
await this.writeByteSource(storageKey, createBlobByteSource(bytes), assertCurrent);
|
|
63
113
|
}
|
|
64
114
|
getFileName(storageKey) {
|
|
65
115
|
return `${encodeURIComponent(storageKey)}.blob`;
|
|
@@ -89,8 +139,24 @@ function hasStorageDirectory(storage) {
|
|
|
89
139
|
export function isOpfsBlobStoreSupported() {
|
|
90
140
|
return (typeof navigator === "object" && hasStorageDirectory(navigator.storage));
|
|
91
141
|
}
|
|
142
|
+
// Plain and encrypted stores address the same OPFS namespace.
|
|
143
|
+
const namespaces = new WeakMap();
|
|
144
|
+
function namespaceStore(namespace) {
|
|
145
|
+
const storage = navigator.storage;
|
|
146
|
+
let stores = namespaces.get(storage);
|
|
147
|
+
if (!stores) {
|
|
148
|
+
stores = new Map();
|
|
149
|
+
namespaces.set(storage, stores);
|
|
150
|
+
}
|
|
151
|
+
let store = stores.get(namespace);
|
|
152
|
+
if (!store) {
|
|
153
|
+
store = new OpfsBlobStore(namespace);
|
|
154
|
+
stores.set(namespace, store);
|
|
155
|
+
}
|
|
156
|
+
return store;
|
|
157
|
+
}
|
|
92
158
|
export function createOpfsBlobStore(namespace) {
|
|
93
|
-
return
|
|
159
|
+
return namespaceStore(namespace);
|
|
94
160
|
}
|
|
95
161
|
/**
|
|
96
162
|
* Permanently remove the OPFS directory backing a namespace's blob store
|
|
@@ -98,10 +164,11 @@ export function createOpfsBlobStore(namespace) {
|
|
|
98
164
|
* Used to forget local data on logout. No-op when OPFS is unavailable or the
|
|
99
165
|
* directory was never created; never throws on a missing directory.
|
|
100
166
|
*/
|
|
101
|
-
export async function purgeOpfsBlobStore(namespace) {
|
|
102
|
-
if (
|
|
103
|
-
|
|
104
|
-
|
|
167
|
+
export async function purgeOpfsBlobStore(namespace, current = () => true) {
|
|
168
|
+
if (isOpfsBlobStoreSupported())
|
|
169
|
+
await namespaceStore(namespace).purge(current);
|
|
170
|
+
}
|
|
171
|
+
async function removeNamespace(namespace, current) {
|
|
105
172
|
const rootDirectory = await navigator.storage.getDirectory();
|
|
106
173
|
let appDirectory;
|
|
107
174
|
try {
|
|
@@ -109,16 +176,19 @@ export async function purgeOpfsBlobStore(namespace) {
|
|
|
109
176
|
}
|
|
110
177
|
catch (error) {
|
|
111
178
|
if (error instanceof DOMException && error.name === "NotFoundError") {
|
|
112
|
-
return;
|
|
179
|
+
return true;
|
|
113
180
|
}
|
|
114
181
|
throw error;
|
|
115
182
|
}
|
|
116
183
|
try {
|
|
184
|
+
if (!current())
|
|
185
|
+
return false;
|
|
117
186
|
await appDirectory.removeEntry(namespace, { recursive: true });
|
|
187
|
+
return true;
|
|
118
188
|
}
|
|
119
189
|
catch (error) {
|
|
120
190
|
if (error instanceof DOMException && error.name === "NotFoundError") {
|
|
121
|
-
return;
|
|
191
|
+
return true;
|
|
122
192
|
}
|
|
123
193
|
throw error;
|
|
124
194
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opfsBlobStore.js","sourceRoot":"","sources":["opfsBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAMzB,MAAM,qBAAqB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAE9C,MAAM,aAAa;IAGY;IAFrB,gBAAgB,GAA8C,IAAI,CAAC;IAE3E,YAA6B,SAAiB;QAAjB,cAAS,GAAT,SAAS,CAAQ;IAAG,CAAC;IAElD,KAAK,CAAC,WAAW,CAAC,UAAkB;QAClC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QAE5C,IAAI,CAAC;YACH,MAAM,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC;QAC5D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;gBACpE,OAAO;YACT,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,UAAkB;QAChC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;QACrD,OAAO,MAAM,CAAC,CAAC,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,UAAkB;QACrC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,E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Source,\n readBlobByteSource,\n} from \"./blobContracts\";\n\ninterface StorageDirectoryProvider {\n getDirectory: () => Promise<FileSystemDirectoryHandle>;\n}\n\nconst OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;\n\nclass OpfsBlobStore implements BlobStore {\n private directoryPromise: Promise<FileSystemDirectoryHandle> | null = null;\n\n constructor(private readonly namespace: string) {}\n\n async deleteBytes(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n await directory.removeEntry(this.getFileName(storageKey));\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n\n throw error;\n }\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async openByteSource(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n );\n const file = await fileHandle.getFile();\n return createBlobByteSource(file);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return null;\n }\n\n throw error;\n }\n }\n\n async writeByteSource(storageKey: string, source: BlobByteSource) {\n const sourceByteLength = blobByteSourceInputLength(source);\n const directory = await this.getDirectory();\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n { create: true },\n );\n const writable = await fileHandle.createWritable();\n\n try {\n for (let offset = 0; offset < sourceByteLength; ) {\n const byteLength = Math.min(\n OPFS_WRITE_CHUNK_SIZE,\n sourceByteLength - offset,\n );\n const chunk = await source.read(offset, byteLength);\n if (chunk.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n await writable.write(chunk);\n offset += byteLength;\n }\n await writable.close();\n } catch (error) {\n await writable.abort(error).catch(() => undefined);\n throw error;\n }\n }\n\n async writeBytes(storageKey: string, bytes: BlobBytes) {\n await this.writeByteSource(storageKey, createBlobByteSource(bytes));\n }\n\n private getFileName(storageKey: string): string {\n return `${encodeURIComponent(storageKey)}.blob`;\n }\n\n private async getDirectory() {\n if (!this.directoryPromise) {\n this.directoryPromise = this.createDirectory().catch((error: unknown) => {\n this.directoryPromise = null;\n throw error;\n });\n }\n\n return this.directoryPromise;\n }\n\n private async createDirectory() {\n const rootDirectory = await navigator.storage.getDirectory();\n const appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\", {\n create: true,\n });\n\n return appDirectory.getDirectoryHandle(this.namespace, { create: true });\n }\n}\n\nfunction hasStorageDirectory(\n storage: StorageManager | undefined,\n): storage is StorageManager & StorageDirectoryProvider {\n return (\n storage !== undefined &&\n \"getDirectory\" in storage &&\n typeof storage.getDirectory === \"function\"\n );\n}\n\nexport function isOpfsBlobStoreSupported(): boolean {\n return (\n typeof navigator === \"object\" && hasStorageDirectory(navigator.storage)\n );\n}\n\nexport function createOpfsBlobStore(namespace: string): BlobStore {\n return new OpfsBlobStore(namespace);\n}\n\n/**\n * Permanently remove the OPFS directory backing a namespace's blob store\n * (`tearleads/<namespace>`), discarding every stored blob for that namespace.\n * Used to forget local data on logout. No-op when OPFS is unavailable or the\n * directory was never created; never throws on a missing directory.\n */\nexport async function purgeOpfsBlobStore(namespace: string): Promise<void> {\n if (!isOpfsBlobStoreSupported()) {\n return;\n }\n\n const rootDirectory = await navigator.storage.getDirectory();\n let appDirectory: FileSystemDirectoryHandle;\n try {\n appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\");\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n throw error;\n }\n\n try {\n await appDirectory.removeEntry(namespace, { recursive: true });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n throw error;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"opfsBlobStore.js","sourceRoot":"","sources":["opfsBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,gBA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AS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACpE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n blobByteSourceInputLength,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\nimport { commitOpfsFile } from \"./opfsBlobFile\";\n\ninterface StorageDirectoryProvider {\n getDirectory: () => Promise<FileSystemDirectoryHandle>;\n}\n\nconst OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;\n\nclass OpfsBlobStore implements BlobStore {\n private directoryPromise: Promise<FileSystemDirectoryHandle> | null = null;\n\n private readonly active = new Set<Promise<unknown>>();\n private readonly writers = new Map<string, Promise<unknown>>();\n private purgeBarrier: Promise<void> | undefined;\n\n constructor(private readonly namespace: string) {}\n\n // File operations run concurrently. A directory removal waits for all\n // of them and any later file operation opens the surviving directory.\n private async useFile<T>(\n key: string,\n mode: LockMode,\n run: () => Promise<T>,\n ): Promise<T> {\n const locked = () => {\n const locks = navigator.locks;\n return typeof locks?.request === \"function\"\n ? locks.request(\n JSON.stringify([\"tearleads.opfs.blob\", this.namespace, key]),\n { mode },\n run,\n )\n : run();\n };\n const writer = this.writers.get(key);\n const operation =\n writer || this.purgeBarrier\n ? Promise.allSettled([writer, this.purgeBarrier]).then(locked)\n : locked();\n if (mode === \"exclusive\") this.writers.set(key, operation);\n this.active.add(operation);\n try {\n return await operation;\n } finally {\n this.active.delete(operation);\n if (this.writers.get(key) === operation) this.writers.delete(key);\n }\n }\n\n async purge(current: () => boolean): Promise<void> {\n const pending = Promise.allSettled([\n ...this.active,\n this.purgeBarrier,\n ]).then(async () => {\n if (current() && (await removeNamespace(this.namespace, current)))\n this.directoryPromise = null;\n });\n const barrier = pending.catch(() => {});\n this.purgeBarrier = barrier;\n try {\n await pending;\n } finally {\n if (this.purgeBarrier === barrier) this.purgeBarrier = undefined;\n }\n }\n\n deleteBytes(storageKey: string, assertCurrent?: () => void) {\n return this.useFile(storageKey, \"exclusive\", () =>\n this.removeFile(storageKey, assertCurrent),\n );\n }\n\n private async removeFile(storageKey: string, assertCurrent?: () => void) {\n const directory = await this.getDirectory();\n\n try {\n assertCurrent?.();\n await directory.removeEntry(this.getFileName(storageKey));\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n\n throw error;\n }\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n openByteSource(storageKey: string) {\n return this.useFile(storageKey, \"shared\", () => this.openFile(storageKey));\n }\n\n private async openFile(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n );\n const file = await fileHandle.getFile();\n return createBlobByteSource(file);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return null;\n }\n\n throw error;\n }\n }\n\n writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n return this.useFile(storageKey, \"exclusive\", () =>\n this.writeFile(storageKey, source, assertCurrent),\n );\n }\n\n private async writeFile(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n const sourceByteLength = blobByteSourceInputLength(source);\n const directory = await this.getDirectory();\n await commitOpfsFile(\n directory,\n this.getFileName(storageKey),\n assertCurrent,\n async (writable) => {\n for (let offset = 0; offset < sourceByteLength; ) {\n const byteLength = Math.min(\n OPFS_WRITE_CHUNK_SIZE,\n sourceByteLength - offset,\n );\n const chunk = await source.read(offset, byteLength);\n if (chunk.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n await writable.write(chunk);\n offset += byteLength;\n }\n },\n );\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ) {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n\n private getFileName(storageKey: string): string {\n return `${encodeURIComponent(storageKey)}.blob`;\n }\n\n private async getDirectory() {\n if (!this.directoryPromise) {\n this.directoryPromise = this.createDirectory().catch((error: unknown) => {\n this.directoryPromise = null;\n throw error;\n });\n }\n\n return this.directoryPromise;\n }\n\n private async createDirectory() {\n const rootDirectory = await navigator.storage.getDirectory();\n const appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\", {\n create: true,\n });\n\n return appDirectory.getDirectoryHandle(this.namespace, { create: true });\n }\n}\n\nfunction hasStorageDirectory(\n storage: StorageManager | undefined,\n): storage is StorageManager & StorageDirectoryProvider {\n return (\n storage !== undefined &&\n \"getDirectory\" in storage &&\n typeof storage.getDirectory === \"function\"\n );\n}\n\nexport function isOpfsBlobStoreSupported(): boolean {\n return (\n typeof navigator === \"object\" && hasStorageDirectory(navigator.storage)\n );\n}\n\n// Plain and encrypted stores address the same OPFS namespace.\nconst namespaces = new WeakMap<StorageManager, Map<string, OpfsBlobStore>>();\n\nfunction namespaceStore(namespace: string): OpfsBlobStore {\n const storage = navigator.storage;\n let stores = namespaces.get(storage);\n if (!stores) {\n stores = new Map();\n namespaces.set(storage, stores);\n }\n let store = stores.get(namespace);\n if (!store) {\n store = new OpfsBlobStore(namespace);\n stores.set(namespace, store);\n }\n return store;\n}\n\nexport function createOpfsBlobStore(namespace: string): BlobStore {\n return namespaceStore(namespace);\n}\n\n/**\n * Permanently remove the OPFS directory backing a namespace's blob store\n * (`tearleads/<namespace>`), discarding every stored blob for that namespace.\n * Used to forget local data on logout. No-op when OPFS is unavailable or the\n * directory was never created; never throws on a missing directory.\n */\nexport async function purgeOpfsBlobStore(\n namespace: string,\n current: () => boolean = () => true,\n): Promise<void> {\n if (isOpfsBlobStoreSupported())\n await namespaceStore(namespace).purge(current);\n}\n\nasync function removeNamespace(\n namespace: string,\n current: () => boolean,\n): Promise<boolean> {\n const rootDirectory = await navigator.storage.getDirectory();\n let appDirectory: FileSystemDirectoryHandle;\n try {\n appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\");\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return true;\n }\n throw error;\n }\n\n try {\n if (!current()) return false;\n await appDirectory.removeEntry(namespace, { recursive: true });\n return true;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return true;\n }\n throw error;\n }\n}\n"]}
|
|
@@ -60,8 +60,9 @@ export async function buildDocumentCreatePlan({ author, containerProjection, con
|
|
|
60
60
|
request: {
|
|
61
61
|
event: readCanonicalRecord(event, "Document create event"),
|
|
62
62
|
body: readCanonicalRecord(body, "Document create body"),
|
|
63
|
+
// The API derives the initial manifest; the request commits to it by
|
|
64
|
+
// hash.
|
|
63
65
|
expectedManifestHash: manifestHash,
|
|
64
|
-
manifest: readCanonicalRecord(manifest, "Document create manifest"),
|
|
65
66
|
targetContainerPathRefs: containerPathRefs(containerProjection.path),
|
|
66
67
|
contentKeyBundle: {
|
|
67
68
|
contentKeyEpoch,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","sourceRoot":"","sources":["events.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,yBAAyB,EACzB,mCAAmC,EAGnC,6BAA6B,EAC7B,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,sCAAsC,EACtC,iBAAiB,EACjB,2BAA2B,EAC3B,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAW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ACR,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;QACvC,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QAC3C,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,oBAAoB;QACvD,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,eAAe,CACjC,aAAa,EACb,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAC9B,CAAC;IACF,MAAM,SAAS,GAAG,MAAM,sBAAsB,CAAC,KAAK,CAAC,CAAC;IAEtD,OAAO;QACL,4BAA4B;QAC5B,IAAI;QACJ,KAAK;QACL,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n computeAccessEventHash,\n computeAccessManifestHash,\n computeDocumentContentKeyTargetHash,\n type DocumentLinkAccessEventBody,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n readKeyingCanonicalJson,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { ContainerManifestRef } from \"@tearleads/validators/request\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport {\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n deriveDocumentCreateTargets,\n mergeTargetEnvelopes,\n} from \"./projection\";\nimport { sortDocumentTargets, uniqueSortedStrings } from \"./readers\";\nimport type {\n BuildDocumentCreatePlanInput,\n DocumentCreateAuthor,\n DocumentCreatePlan,\n DocumentLinkSetEventPlan,\n DocumentLinkSetMutationBody,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetTargetState,\n} from \"./types\";\n\nexport async function buildDocumentCreatePlan({\n author,\n containerProjection,\n contentKeyEpoch = 1,\n documentId = crypto.randomUUID(),\n eventId = crypto.randomUUID(),\n signedAt = new Date().toISOString(),\n targetEnvelopes,\n}: BuildDocumentCreatePlanInput): Promise<DocumentCreatePlan> {\n // The document belongs to its container's organization, not the author's. A\n // member authoring a document under another org's shared container creates a\n // document owned by that org; the author supplies only the signer identity.\n const organizationId = containerProjection.organizationId;\n\n const targets = deriveDocumentCreateTargets(containerProjection);\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targets,\n targetEnvelopes,\n );\n const targetContainerManifestHash = targets[0]?.containerManifestHash;\n const targetContainerId = targets[0]?.containerId;\n if (!targetContainerManifestHash || !targetContainerId) {\n throw new Error(\"Document create target is unavailable\");\n }\n\n const body: DocumentLinkAccessEventBody = {\n blobRewraps: [],\n eventType: \"document.link\",\n containerId: targetContainerId,\n containerManifestHash: targetContainerManifestHash,\n };\n const bodyHash = await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document create body\"),\n );\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId,\n eventType: \"document.link\",\n objectKind: \"document\",\n objectId: documentId,\n organizationId,\n previousManifestHash: null,\n dependencyManifestHashes: uniqueSortedStrings(\n containerProjection.path.map((bundle) => bundle.manifestHash),\n ),\n bodyHash,\n signerUserId: author.signerUserId,\n signerDeviceId: author.signerDeviceId,\n signerKeyFingerprint: author.signerKeyFingerprint,\n signedAt,\n };\n const event = await signAccessEvent(unsignedEvent, author.signerPrivateKey);\n const eventHash = await computeAccessEventHash(event);\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId,\n organizationId,\n epoch: 1,\n previousManifestHash: null,\n eventHash,\n linkedContainerIds: [targetContainerId],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(targets);\n\n return {\n body,\n documentId,\n event,\n eventHash,\n manifest,\n manifestHash,\n request: {\n event: readCanonicalRecord(event, \"Document create event\"),\n body: readCanonicalRecord(body, \"Document create body\"),\n expectedManifestHash: manifestHash,\n manifest: readCanonicalRecord(manifest, \"Document create manifest\"),\n targetContainerPathRefs: containerPathRefs(containerProjection.path),\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targets),\n };\n}\n\nexport async function buildDocumentLinkSetEventPlan(input: {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n eventId: string;\n operation: DocumentLinkSetMutationOperation;\n // The document's existing organization (from its manifest). Link/unlink does\n // not change ownership, so the event keeps the document's org, which is the\n // container's org — never the acting member's personal org.\n organizationId: string;\n signedAt: string;\n targetContainerPathRefs: readonly ContainerManifestRef[];\n targetState: DocumentLinkSetTargetState;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentLinkSetEventPlan> {\n const eventType =\n input.operation === \"link\" ? \"document.link\" : \"document.unlink\";\n const body: DocumentLinkSetMutationBody = {\n blobRewraps: input.blobRewraps,\n eventType,\n containerId: input.targetState.target.containerId,\n containerManifestHash: input.targetState.target.containerManifestHash,\n };\n const bodyHash = await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document link-set body\"),\n );\n const authorizingContainerPathRefs = authorizingContainerPathRefsForLinkSet({\n operation: input.operation,\n targetContainerId: input.targetState.target.containerId,\n writerProjection: input.writerProjection,\n });\n const dependencyManifestHashes = uniqueSortedStrings(\n [\n ...input.targetContainerPathRefs,\n ...authorizingContainerPathRefs.flat(),\n ].map((ref) => ref.manifestHash),\n );\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId,\n eventType,\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes,\n bodyHash,\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt,\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n const eventHash = await computeAccessEventHash(event);\n\n return {\n authorizingContainerPathRefs,\n body,\n event,\n eventHash,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["events.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,yBAAyB,EACzB,mCAAmC,EAGnC,6BAA6B,EAC7B,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,sCAAsC,EACtC,iBAAiB,EACjB,2BAA2B,EAC3B,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAWrE,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,EAC5C,MAAM,EACN,mBAAmB,EACnB,eAAe,GAAG,CAAC,EACnB,UAAU,GAAG,MAAM,CAAC,UAAU,EAAE,EAChC,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,EAC7B,QAAQ,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACnC,eAAe,GACc;IAC7B,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,cAAc,GAAG,mBAAmB,CAAC,cAAc,CAAC;IAE1D,MAAM,OAAO,GAAG,2BAA2B,CAAC,mBAAmB,CAAC,CAAC;IACjE,MAAM,yBAAyB,GAAG,oBAAoB,CACpD,OAAO,EACP,eAAe,CAChB,CAAC;IACF,MAAM,2BAA2B,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,qBAAqB,CAAC;IACtE,MAAM,iBAAiB,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC;IAClD,IAAI,CAAC,2BAA2B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvD,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D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QACE,GAAG,KAAK,CAAC,uBAAuB;QAChC,GAAG,4BAA4B,CAAC,IAAI,EAAE;KACvC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,CACjC,CAAC;IACF,MAAM,aAAa,GAAwB;QACzC,OAAO,EAAE,CAAC;QACV,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS;QACT,UAAU,EAAE,UAAU;QACtB,QAAQ,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;QAC3C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,gBAAgB,CAAC,YAAY;QAC1E,wBAAwB;QACxB,QAAQ;QACR,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;QACvC,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QAC3C,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,oBAAoB;QACvD,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,eAAe,CACjC,aAAa,EACb,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAC9B,CAAC;IACF,MAAM,SAAS,GAAG,MAAM,sBAAsB,CAAC,KAAK,CAAC,CAAC;IAEtD,OAAO;QACL,4BAA4B;QAC5B,IAAI;QACJ,KAAK;QACL,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n computeAccessEventHash,\n computeAccessManifestHash,\n computeDocumentContentKeyTargetHash,\n type DocumentLinkAccessEventBody,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n readKeyingCanonicalJson,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { ContainerManifestRef } from \"@tearleads/validators/request\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport {\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n deriveDocumentCreateTargets,\n mergeTargetEnvelopes,\n} from \"./projection\";\nimport { sortDocumentTargets, uniqueSortedStrings } from \"./readers\";\nimport type {\n BuildDocumentCreatePlanInput,\n DocumentCreateAuthor,\n DocumentCreatePlan,\n DocumentLinkSetEventPlan,\n DocumentLinkSetMutationBody,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetTargetState,\n} from \"./types\";\n\nexport async function buildDocumentCreatePlan({\n author,\n containerProjection,\n contentKeyEpoch = 1,\n documentId = crypto.randomUUID(),\n eventId = crypto.randomUUID(),\n signedAt = new Date().toISOString(),\n targetEnvelopes,\n}: BuildDocumentCreatePlanInput): Promise<DocumentCreatePlan> {\n // The document belongs to its container's organization, not the author's. A\n // member authoring a document under another org's shared container creates a\n // document owned by that org; the author supplies only the signer identity.\n const organizationId = containerProjection.organizationId;\n\n const targets = deriveDocumentCreateTargets(containerProjection);\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targets,\n targetEnvelopes,\n );\n const targetContainerManifestHash = targets[0]?.containerManifestHash;\n const targetContainerId = targets[0]?.containerId;\n if (!targetContainerManifestHash || !targetContainerId) {\n throw new Error(\"Document create target is unavailable\");\n }\n\n const body: DocumentLinkAccessEventBody = {\n blobRewraps: [],\n eventType: \"document.link\",\n containerId: targetContainerId,\n containerManifestHash: targetContainerManifestHash,\n };\n const bodyHash = await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document create body\"),\n );\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId,\n eventType: \"document.link\",\n objectKind: \"document\",\n objectId: documentId,\n organizationId,\n previousManifestHash: null,\n dependencyManifestHashes: uniqueSortedStrings(\n containerProjection.path.map((bundle) => bundle.manifestHash),\n ),\n bodyHash,\n signerUserId: author.signerUserId,\n signerDeviceId: author.signerDeviceId,\n signerKeyFingerprint: author.signerKeyFingerprint,\n signedAt,\n };\n const event = await signAccessEvent(unsignedEvent, author.signerPrivateKey);\n const eventHash = await computeAccessEventHash(event);\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId,\n organizationId,\n epoch: 1,\n previousManifestHash: null,\n eventHash,\n linkedContainerIds: [targetContainerId],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(targets);\n\n return {\n body,\n documentId,\n event,\n eventHash,\n manifest,\n manifestHash,\n request: {\n event: readCanonicalRecord(event, \"Document create event\"),\n body: readCanonicalRecord(body, \"Document create body\"),\n // The API derives the initial manifest; the request commits to it by\n // hash.\n expectedManifestHash: manifestHash,\n targetContainerPathRefs: containerPathRefs(containerProjection.path),\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targets),\n };\n}\n\nexport async function buildDocumentLinkSetEventPlan(input: {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n eventId: string;\n operation: DocumentLinkSetMutationOperation;\n // The document's existing organization (from its manifest). Link/unlink does\n // not change ownership, so the event keeps the document's org, which is the\n // container's org — never the acting member's personal org.\n organizationId: string;\n signedAt: string;\n targetContainerPathRefs: readonly ContainerManifestRef[];\n targetState: DocumentLinkSetTargetState;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentLinkSetEventPlan> {\n const eventType =\n input.operation === \"link\" ? \"document.link\" : \"document.unlink\";\n const body: DocumentLinkSetMutationBody = {\n blobRewraps: input.blobRewraps,\n eventType,\n containerId: input.targetState.target.containerId,\n containerManifestHash: input.targetState.target.containerManifestHash,\n };\n const bodyHash = await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document link-set body\"),\n );\n const authorizingContainerPathRefs = authorizingContainerPathRefsForLinkSet({\n operation: input.operation,\n targetContainerId: input.targetState.target.containerId,\n writerProjection: input.writerProjection,\n });\n const dependencyManifestHashes = uniqueSortedStrings(\n [\n ...input.targetContainerPathRefs,\n ...authorizingContainerPathRefs.flat(),\n ].map((ref) => ref.manifestHash),\n );\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId,\n eventType,\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes,\n bodyHash,\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt,\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n const eventHash = await computeAccessEventHash(event);\n\n return {\n authorizingContainerPathRefs,\n body,\n event,\n eventHash,\n };\n}\n"]}
|
|
@@ -1,22 +1,9 @@
|
|
|
1
|
+
import { createKeyedQueue } from "../shared/keyedQueue.js";
|
|
2
|
+
import { sqlConnectionIdentity } from "../sqlite/sqlExec.js";
|
|
1
3
|
import { resolveCanonicalExecSql } from "../sqlite/sqlSchema.js";
|
|
2
4
|
import { principalMutationJournalScopeId, } from "./principalMutationJournal.js";
|
|
3
|
-
|
|
4
|
-
function createKeyedQueue() {
|
|
5
|
-
const tails = new Map();
|
|
6
|
-
return (key, work) => {
|
|
7
|
-
const operation = (tails.get(key) ?? Promise.resolve()).then(work);
|
|
8
|
-
const settled = operation.then(() => undefined, () => undefined);
|
|
9
|
-
tails.set(key, settled);
|
|
10
|
-
void settled.then(() => {
|
|
11
|
-
if (tails.get(key) === settled)
|
|
12
|
-
tails.delete(key);
|
|
13
|
-
});
|
|
14
|
-
return operation;
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
function createPrincipalPolicyCoordinator() {
|
|
5
|
+
function createPrincipalPolicyCoordinator(journalScopes) {
|
|
18
6
|
const recoveries = createKeyedQueue();
|
|
19
|
-
const journalScopes = createKeyedQueue();
|
|
20
7
|
const epochs = new Map();
|
|
21
8
|
return {
|
|
22
9
|
queueRecovery: recoveries,
|
|
@@ -27,12 +14,16 @@ function createPrincipalPolicyCoordinator() {
|
|
|
27
14
|
runJournalOperation: async (scope, run) => journalScopes(await principalMutationJournalScopeId(scope), run),
|
|
28
15
|
};
|
|
29
16
|
}
|
|
17
|
+
const journals = new WeakMap();
|
|
30
18
|
const coordinators = new WeakMap();
|
|
31
19
|
export function getOrCreatePrincipalPolicyCoordinator(execSql) {
|
|
32
20
|
const database = resolveCanonicalExecSql(execSql);
|
|
33
21
|
let coordinator = coordinators.get(database);
|
|
34
22
|
if (!coordinator) {
|
|
35
|
-
|
|
23
|
+
const connection = sqlConnectionIdentity(execSql);
|
|
24
|
+
const journal = journals.get(connection) ?? createKeyedQueue();
|
|
25
|
+
journals.set(connection, journal);
|
|
26
|
+
coordinator = createPrincipalPolicyCoordinator(journal);
|
|
36
27
|
coordinators.set(database, coordinator);
|
|
37
28
|
}
|
|
38
29
|
return coordinator;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCoordinator.js","sourceRoot":"","sources":["principalPolicyCoordinator.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"principalPolicyCoordinator.js","sourceRoot":"","sources":["principalPolicyCoordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAgB,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAEL,+BAA+B,GAChC,MAAM,4BAA4B,CAAC;AA+BpC,SAAS,gCAAgC,CACvC,aAAkD;IAElD,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;IACtC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,CAAC,cAAc,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC;QAClE,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACpE,CAAC;QACD,mBAAmB,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,CACxC,aAAa,CAAC,MAAM,+BAA+B,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA+C,CAAC;AAC5E,MAAM,YAAY,GAAG,IAAI,OAAO,EAAuC,CAAC;AAExE,MAAM,UAAU,qCAAqC,CACnD,OAAgB;IAEhB,MAAM,QAAQ,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAClD,IAAI,WAAW,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,UAAU,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,gBAAgB,EAAE,CAAC;QAC/D,QAAQ,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAClC,WAAW,GAAG,gCAAgC,CAAC,OAAO,CAAC,CAAC;QACxD,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { createKeyedQueue } from \"../shared/keyedQueue\";\nimport { sqlConnectionIdentity } from \"../sqlite/sqlExec\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../sqlite/sqlSchema\";\nimport {\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n} from \"./principalMutationJournal\";\n\n/**\n * Recovery hints belong to one scoped executor and its nested transactions.\n * Journal dispatch and recovery share the physical database's mutation lock\n * across sign-ins.\n */\nexport interface PrincipalPolicyCoordinator {\n /**\n * Runs recovery for an organization after the recovery already queued for\n * it. Directory and Admins stages are shared by every reference in an\n * organization, so warmers and registration take turns. Queued work must not\n * queue again for the same organization.\n */\n queueRecovery<T>(organizationId: string, work: () => Promise<T>): Promise<T>;\n /**\n * The organization hints applied in this process. Operation-scoped recovery\n * records it before producing a result and recovers again once it changes.\n * Hints are lossy, so this only shortens reuse; each operation still\n * discovers the current head.\n */\n recoveryEpoch(organizationId: string): number;\n /** Evicts recovered directory and Admins views for this organization. */\n invalidateRecovery(organizationId: string): void;\n /** An owned dispatch finishes before another caller can recover or abandon it. */\n runJournalOperation<T>(\n scope: PrincipalMutationJournalScope,\n run: () => Promise<T>,\n ): Promise<T>;\n}\n\nfunction createPrincipalPolicyCoordinator(\n journalScopes: ReturnType<typeof createKeyedQueue>,\n): PrincipalPolicyCoordinator {\n const recoveries = createKeyedQueue();\n const epochs = new Map<string, number>();\n return {\n queueRecovery: recoveries,\n recoveryEpoch: (organizationId) => epochs.get(organizationId) ?? 0,\n invalidateRecovery: (organizationId) => {\n epochs.set(organizationId, (epochs.get(organizationId) ?? 0) + 1);\n },\n runJournalOperation: async (scope, run) =>\n journalScopes(await principalMutationJournalScopeId(scope), run),\n };\n}\n\nconst journals = new WeakMap<object, ReturnType<typeof createKeyedQueue>>();\nconst coordinators = new WeakMap<ExecSql, PrincipalPolicyCoordinator>();\n\nexport function getOrCreatePrincipalPolicyCoordinator(\n execSql: ExecSql,\n): PrincipalPolicyCoordinator {\n const database = resolveCanonicalExecSql(execSql);\n let coordinator = coordinators.get(database);\n if (!coordinator) {\n const connection = sqlConnectionIdentity(execSql);\n const journal = journals.get(connection) ?? createKeyedQueue();\n journals.set(connection, journal);\n coordinator = createPrincipalPolicyCoordinator(journal);\n coordinators.set(database, coordinator);\n }\n return coordinator;\n}\n"]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
declare const domainScopeBrand: unique symbol;
|
|
2
2
|
export interface DomainScope {
|
|
3
3
|
readonly [domainScopeBrand]: true;
|
|
4
|
+
/** Process-local identity for host components that need a scalar key. */
|
|
5
|
+
readonly id: number;
|
|
4
6
|
}
|
|
5
7
|
export declare function createDomainScope(): DomainScope;
|
|
6
8
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"domainScope.js","sourceRoot":"","sources":["domainScope.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"domainScope.js","sourceRoot":"","sources":["domainScope.ts"],"names":[],"mappings":"AAAA,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,MAAM,gBAAgB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAUzD,MAAM,UAAU,iBAAiB;IAC/B,OAAO,EAAE,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,WAAW,EAAwB,CAAC;AAC/E,CAAC","sourcesContent":["let nextScopeId = 0;\nconst domainScopeBrand = Symbol(\"tearleads.domainScope\");\n\n// Identity token for in-process caches that must rotate together when the\n// active database, signing identity, or sign-in changes.\nexport interface DomainScope {\n readonly [domainScopeBrand]: true;\n /** Process-local identity for host components that need a scalar key. */\n readonly id: number;\n}\n\nexport function createDomainScope(): DomainScope {\n return { [domainScopeBrand]: true, id: ++nextScopeId } satisfies DomainScope;\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Runs work for a key after the work already queued for it; idle keys hold nothing. */
|
|
2
|
+
export function createKeyedQueue() {
|
|
3
|
+
const tails = new Map();
|
|
4
|
+
return (key, work) => {
|
|
5
|
+
const operation = (tails.get(key) ?? Promise.resolve()).then(work);
|
|
6
|
+
const settled = operation.then(() => undefined, () => undefined);
|
|
7
|
+
tails.set(key, settled);
|
|
8
|
+
void settled.then(() => {
|
|
9
|
+
if (tails.get(key) === settled)
|
|
10
|
+
tails.delete(key);
|
|
11
|
+
});
|
|
12
|
+
return operation;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=keyedQueue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keyedQueue.js","sourceRoot":"","sources":["keyedQueue.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,MAAM,UAAU,gBAAgB;IAC9B,MAAM,KAAK,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC/C,OAAO,CAAI,GAAW,EAAE,IAAsB,EAAc,EAAE;QAC5D,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnE,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAC5B,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACxB,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE;YACrB,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;gBAAE,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/** Runs work for a key after the work already queued for it; idle keys hold nothing. */\nexport function createKeyedQueue() {\n const tails = new Map<string, Promise<void>>();\n return <T>(key: string, work: () => Promise<T>): Promise<T> => {\n const operation = (tails.get(key) ?? Promise.resolve()).then(work);\n const settled = operation.then(\n () => undefined,\n () => undefined,\n );\n tails.set(key, settled);\n void settled.then(() => {\n if (tails.get(key) === settled) tails.delete(key);\n });\n return operation;\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { hasCompletedConnectionOnce, markCompletedConnectionOnce, runSerializedSqlMutation, } from "../sqlExec.js";
|
|
1
|
+
import { hasCompletedConnectionOnce, markCompletedConnectionOnce, rollbackSqlSavepoint, runSerializedSqlMutation, } from "../sqlExec.js";
|
|
2
2
|
import { assertLocalSchemaMigrations, localSchemaMigrations, } from "./localSchemaMigrations.js";
|
|
3
3
|
import { classifyLocalSchema, localSchemaStateError, parseLocalSchemaLedger, } from "./localSchemaState.js";
|
|
4
4
|
/** The ledger table; a local backup carries it like any other table. */
|
|
@@ -64,8 +64,7 @@ async function applyPendingSteps(execSql, state, now, verify) {
|
|
|
64
64
|
await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`);
|
|
65
65
|
}
|
|
66
66
|
catch (error) {
|
|
67
|
-
await execSql
|
|
68
|
-
await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`).catch(() => undefined);
|
|
67
|
+
await rollbackSqlSavepoint(execSql, SAVEPOINT).catch(() => undefined);
|
|
69
68
|
throw error;
|
|
70
69
|
}
|
|
71
70
|
}
|