Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Cleanup unused methods replaced by native Rust internal sync (#2159)

Leendert de Borste2111f8d6cb4
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 60ddc3f51..1a3ab15f1 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -51,7 +51,7 @@ import { t } from '@/i18n/StandaloneI18n';
import type { ItemUsageAction } from '@aliasvault/client/database';
import type { DraftItem } from '@aliasvault/client/database/ItemRef';
-import type { ISqliteDatabase, ISqliteStatement, SqliteValue } from '@aliasvault/client/platform';
+import type { ISqliteDatabase, SqliteValue } from '@aliasvault/client/platform';
import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
/**
@@ -95,8 +95,6 @@ const syncEngineHost: IVaultSyncEngineHost = {
query: <T,>(sql: string, params?: SqliteValue[]): T[] => db.query<T>(sql, params),
/** Run raw SQL. */
exec: (sql: string): void => db.exec(sql),
- /** Compile a statement. */
- prepare: (sql: string): ISqliteStatement => db.prepare(sql),
/** Export through the client so it can compact the file first. */
export: (): Uint8Array => sqliteClient.exportToBytes(),
/** The cached client owns the database's lifetime. */
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
index a35ca6607..0b80f3b54 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
@@ -17,7 +17,6 @@ import uniffi.aliasvault_core.generateRandomEmailPrefix
import uniffi.aliasvault_core.getDicewareLanguages
import uniffi.aliasvault_core.getIdentityAgeRanges
import uniffi.aliasvault_core.getIdentityLanguages
-import uniffi.aliasvault_core.getPruneTableQueries
import uniffi.aliasvault_core.getSyncableTableNames
import uniffi.aliasvault_core.parseEmailSource
import uniffi.aliasvault_core.pruneVaultJson
@@ -27,24 +26,12 @@ import uniffi.aliasvault_core.srpDeriveSession
import uniffi.aliasvault_core.srpDeriveVerifier
import uniffi.aliasvault_core.srpGenerateEphemeral
import uniffi.aliasvault_core.srpGenerateSalt
-import uniffi.aliasvault_core.vaultCodecBucketLayout
import uniffi.aliasvault_core.vaultCodecCanonicalizeFromSqlite
-import uniffi.aliasvault_core.vaultCodecComputeCiphertextHash
-import uniffi.aliasvault_core.vaultCodecComputeContentFingerprint
-import uniffi.aliasvault_core.vaultCodecExtractBuckets
-import uniffi.aliasvault_core.vaultCodecExtractEncryptionKeyForPublicKey
import uniffi.aliasvault_core.vaultCodecGenerateManifestSalt
import uniffi.aliasvault_core.vaultCodecLogoContentHash
import uniffi.aliasvault_core.vaultCodecLogoIdFor
-import uniffi.aliasvault_core.vaultCodecLogoIdForSource
-import uniffi.aliasvault_core.vaultCodecMaterializeAsSqlite
-import uniffi.aliasvault_core.vaultCodecOverflowTable
import uniffi.aliasvault_core.vaultCodecPackPayload
import uniffi.aliasvault_core.vaultCodecUnpackPayload
-import uniffi.aliasvault_core.vaultCodecValidateDataBucket
-import uniffi.aliasvault_core.vaultCodecValidateManifest
-import uniffi.aliasvault_core.vaultSharingPartitionManifestAccess
-import uniffi.aliasvault_core.vaultSharingResolveManifestWriteSet
/**
* Routes `rustCall` invocations from React Native onto the uniffi bindings: one case per exported core
@@ -100,31 +87,13 @@ object RustCoreDispatcher {
"getSyncableTableNames" -> json(getSyncableTableNames())
"pruneVaultJson" -> pruneVaultJson(args.string(0))
- "getPruneTableQueries" -> {
- val queries = JSONArray()
- getPruneTableQueries().forEach { queries.put(JSONObject().put("name", it.name).put("query", it.query)) }
- queries.toString()
- }
"vaultCodecCanonicalizeFromSqlite" -> vaultCodecCanonicalizeFromSqlite(args.string(0))
- "vaultCodecMaterializeAsSqlite" -> vaultCodecMaterializeAsSqlite(args.string(0))
- "vaultCodecExtractBuckets" -> vaultCodecExtractBuckets(args.string(0))
- "vaultCodecBucketLayout" -> vaultCodecBucketLayout()
- "vaultCodecOverflowTable" -> json(vaultCodecOverflowTable())
"vaultCodecGenerateManifestSalt" -> json(vaultCodecGenerateManifestSalt())
- "vaultCodecLogoIdForSource" -> json(vaultCodecLogoIdForSource(args.string(0), args.string(1)))
"vaultCodecLogoIdFor" -> json(vaultCodecLogoIdFor(args.string(0), args.string(1), args.string(2)))
"vaultCodecLogoContentHash" -> json(vaultCodecLogoContentHash(args.bytes(0)))
"vaultCodecPackPayload" -> json(vaultCodecPackPayload(args.string(0)))
"vaultCodecUnpackPayload" -> json(vaultCodecUnpackPayload(args.bytes(0)))
- "vaultCodecValidateManifest" -> vaultCodecValidateManifest(args.string(0))
- "vaultCodecValidateDataBucket" -> vaultCodecValidateDataBucket(args.string(0))
- "vaultCodecComputeCiphertextHash" -> json(vaultCodecComputeCiphertextHash(args.string(0)))
- "vaultCodecComputeContentFingerprint" -> json(vaultCodecComputeContentFingerprint(args.string(0)))
- "vaultCodecExtractEncryptionKeyForPublicKey" -> vaultCodecExtractEncryptionKeyForPublicKey(args.string(0), args.string(1))
-
- "vaultSharingResolveManifestWriteSet" -> vaultSharingResolveManifestWriteSet(args.string(0))
- "vaultSharingPartitionManifestAccess" -> vaultSharingPartitionManifestAccess(args.string(0))
else -> throw IllegalArgumentException("Unknown Rust core function '$name'")
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index eb024c34a..f11be85e0 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -1572,28 +1572,13 @@ private enum RustCoreDispatcher {
case "getSyncableTableNames": return try json(RustCoreFramework.getSyncableTableNames())
case "pruneVaultJson": return try RustCoreFramework.pruneVaultJson(inputJson: try args.string(0))
- case "getPruneTableQueries": return try json(RustCoreFramework.getPruneTableQueries().map { ["name": $0.name, "query": $0.query] })
case "vaultCodecCanonicalizeFromSqlite": return try RustCoreFramework.vaultCodecCanonicalizeFromSqlite(inputJson: try args.string(0))
- case "vaultCodecMaterializeAsSqlite": return try RustCoreFramework.vaultCodecMaterializeAsSqlite(inputJson: try args.string(0))
- case "vaultCodecExtractBuckets": return try RustCoreFramework.vaultCodecExtractBuckets(inputJson: try args.string(0))
- case "vaultCodecBucketLayout": return try RustCoreFramework.vaultCodecBucketLayout()
- case "vaultCodecOverflowTable": return try json(RustCoreFramework.vaultCodecOverflowTable())
case "vaultCodecGenerateManifestSalt": return try json(RustCoreFramework.vaultCodecGenerateManifestSalt())
- case "vaultCodecLogoIdForSource": return try json(RustCoreFramework.vaultCodecLogoIdForSource(manifestId: try args.string(0), source: try args.string(1)))
case "vaultCodecLogoIdFor": return try json(RustCoreFramework.vaultCodecLogoIdFor(manifestId: try args.string(0), kind: try args.string(1), source: try args.string(2)))
case "vaultCodecLogoContentHash": return try json(RustCoreFramework.vaultCodecLogoContentHash(bytes: try args.data(0)))
case "vaultCodecPackPayload": return try json(bytes: try RustCoreFramework.vaultCodecPackPayload(payloadJson: try args.string(0)))
case "vaultCodecUnpackPayload": return try json(try RustCoreFramework.vaultCodecUnpackPayload(plainBytes: try args.data(0)))
- case "vaultCodecValidateManifest": return try RustCoreFramework.vaultCodecValidateManifest(manifestJson: try args.string(0))
- case "vaultCodecValidateDataBucket": return try RustCoreFramework.vaultCodecValidateDataBucket(dataBucketJson: try args.string(0))
- case "vaultCodecComputeCiphertextHash": return try json(RustCoreFramework.vaultCodecComputeCiphertextHash(base64Ciphertext: try args.string(0)))
- case "vaultCodecComputeContentFingerprint": return try json(RustCoreFramework.vaultCodecComputeContentFingerprint(payloadJson: try args.string(0)))
- case "vaultCodecExtractEncryptionKeyForPublicKey":
- return try RustCoreFramework.vaultCodecExtractEncryptionKeyForPublicKey(manifestJson: try args.string(0), publicKey: try args.string(1))
-
- case "vaultSharingResolveManifestWriteSet": return try RustCoreFramework.vaultSharingResolveManifestWriteSet(inputJson: try args.string(0))
- case "vaultSharingPartitionManifestAccess": return try RustCoreFramework.vaultSharingPartitionManifestAccess(inputJson: try args.string(0))
default: throw DispatchError.unknownFunction(name)
}
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index 216764d72..2c495fe36 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -63,27 +63,13 @@ export const nativeRustCore: IRustCore = {
srpDeriveSession: (clientSecret, serverPublic, salt, identity, privateKey) => call('srpDeriveSession', clientSecret, serverPublic, salt, identity, privateKey),
getSyncableTableNames: () => call('getSyncableTableNames'),
- getPruneTableQueries: () => call('getPruneTableQueries'),
vaultCodecCanonicalizeFromSqlite: (input) => call('vaultCodecCanonicalizeFromSqlite', JSON.stringify(input)),
- vaultCodecMaterializeAsSqlite: (input) => call('vaultCodecMaterializeAsSqlite', JSON.stringify(input)),
- vaultCodecExtractBuckets: (input) => call('vaultCodecExtractBuckets', JSON.stringify(input)),
- vaultCodecBucketLayout: () => call('vaultCodecBucketLayout'),
- vaultCodecOverflowTable: () => call('vaultCodecOverflowTable'),
vaultCodecGenerateManifestSalt: () => call('vaultCodecGenerateManifestSalt'),
- vaultCodecLogoIdForSource: (manifestId, source) => call('vaultCodecLogoIdForSource', manifestId, source),
vaultCodecLogoIdFor: (manifestId, kind, source) => call('vaultCodecLogoIdFor', manifestId, kind, source),
vaultCodecLogoContentHash: (bytes) => call('vaultCodecLogoContentHash', base64(bytes)),
vaultCodecPackPayload: (payloadJson) => callForBytes('vaultCodecPackPayload', payloadJson),
vaultCodecUnpackPayload: (plainBytes) => call('vaultCodecUnpackPayload', base64(plainBytes)),
- vaultCodecValidateManifest: (manifest) => call('vaultCodecValidateManifest', JSON.stringify(manifest)),
- vaultCodecValidateDataBucket: (bucket) => call('vaultCodecValidateDataBucket', JSON.stringify(bucket)),
- vaultCodecComputeCiphertextHash: (base64Ciphertext) => call('vaultCodecComputeCiphertextHash', base64Ciphertext),
- vaultCodecComputeContentFingerprint: (payloadJson) => call('vaultCodecComputeContentFingerprint', payloadJson),
- vaultCodecExtractEncryptionKeyForPublicKey: (manifest, publicKey) => call('vaultCodecExtractEncryptionKeyForPublicKey', JSON.stringify(manifest), publicKey),
-
- vaultSharingResolveManifestWriteSet: (input) => call('vaultSharingResolveManifestWriteSet', JSON.stringify(input)),
- vaultSharingPartitionManifestAccess: (input) => call('vaultSharingPartitionManifestAccess', JSON.stringify(input)),
createVaultSyncSession: () => Promise.reject(new Error('The vault sync engine is driven natively on mobile and has no JavaScript session.')),
};
diff --git a/core/client/src/database/ItemRef.ts b/core/client/src/database/ItemRef.ts
index 250a44bfd..357c1f27e 100644
--- a/core/client/src/database/ItemRef.ts
+++ b/core/client/src/database/ItemRef.ts
@@ -26,15 +26,6 @@ export function scopedKey(manifestId: string, id: string): string {
return `${manifestId}${id}`;
}
-/**
- * The grouping key of an item reference. Shorthand for {@link scopedKey}.
- * @param ref - The item reference
- * @returns A key unique across manifests
- */
-export function itemKey(ref: ItemRef): string {
- return scopedKey(ref.ManifestId, ref.Id);
-}
-
/**
* Flatten item references into the bind list a row-value `IN (VALUES (?, ?), …)` match expects:
* manifest first, then id, for each item in order.
diff --git a/core/client/src/database/RustSqliteEngine.ts b/core/client/src/database/RustSqliteEngine.ts
index c1f6166a4..de7ca0231 100644
--- a/core/client/src/database/RustSqliteEngine.ts
+++ b/core/client/src/database/RustSqliteEngine.ts
@@ -3,7 +3,7 @@
*/
import * as core from '../../wasm/aliasvault_core.js';
-import type { ISqliteDatabase, ISqliteEngine, ISqliteStatement, SqliteValue } from '../platform/SqliteEngine';
+import type { ISqliteDatabase, ISqliteEngine, SqliteValue } from '../platform/SqliteEngine';
import type { IRustCore } from '../rust/RustCoreBinding';
/**
@@ -31,21 +31,6 @@ class RustSqliteDatabase implements ISqliteDatabase {
this.db.exec(sql);
}
- /**
- * The core caches prepared statements per connection, so binding the same SQL again is a lookup, not a parse.
- * @param sql - the statement
- */
- public prepare(sql: string): ISqliteStatement {
- return {
- /** Bind and run. */
- run: (params: SqliteValue[]): void => {
- this.db.run(sql, params);
- },
- /** Nothing to release: the statement lives in the core's cache. */
- finalize: (): void => {},
- };
- }
-
/** @inheritdoc */
public export(): Uint8Array {
return this.db.export();
diff --git a/core/client/src/database/queries/BaseQueries.ts b/core/client/src/database/queries/BaseQueries.ts
index 9e833c3bc..214b8fa3b 100644
--- a/core/client/src/database/queries/BaseQueries.ts
+++ b/core/client/src/database/queries/BaseQueries.ts
@@ -23,18 +23,6 @@ export class BaseQueries {
*/
public static readonly MANIFEST_OF_ITEM = 'COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?)';
- /**
- * SQL fragment joining a row to another manifest-scoped table on both halves of the key. A join on
- * the id alone would let a row resolve against a same-id row in a manifest it has nothing to do
- * with, which is precisely what (ManifestId, Id) exists to prevent.
- * @param left - Alias of the referencing table
- * @param right - Alias of the referenced table
- * @returns The predicate, for appending to a JOIN's ON clause
- */
- public static sameManifest(left: string, right: string): string {
- return `${left}.ManifestId = ${right}.ManifestId`;
- }
-
/**
* Re-stamp a folder's whole subtree with `?` (a manifest id).
* Used when a folder is shared (its subtree joins that manifest's namespace) and when the share is
diff --git a/core/client/src/database/queries/EncryptionKeyQueries.ts b/core/client/src/database/queries/EncryptionKeyQueries.ts
index d8e1922e5..53cf605f3 100644
--- a/core/client/src/database/queries/EncryptionKeyQueries.ts
+++ b/core/client/src/database/queries/EncryptionKeyQueries.ts
@@ -14,21 +14,6 @@ export class EncryptionKeyQueries {
FROM EncryptionKeys x
WHERE x.IsDeleted = 0`;
- /**
- * Get one manifest's active keypair: the key whose public half is published for SMTP delivery. Passed
- * the root manifest's id, this is the user's personal keypair — `IsPrimary` alone would not identify it,
- * as every manifest has a primary row of its own.
- */
- public static readonly GET_ACTIVE_FOR_MANIFEST = `
- SELECT
- x.Id,
- x.PublicKey,
- x.PrivateKey,
- x.IsPrimary
- FROM EncryptionKeys x
- WHERE x.ManifestId = ? AND x.IsPrimary = 1 AND x.IsDeleted = 0
- LIMIT 1`;
-
/**
* Get the account keypair matching the given public half.
*/
diff --git a/core/client/src/database/queries/FolderQueries.ts b/core/client/src/database/queries/FolderQueries.ts
index d36e1b471..a881aba42 100644
--- a/core/client/src/database/queries/FolderQueries.ts
+++ b/core/client/src/database/queries/FolderQueries.ts
@@ -93,14 +93,4 @@ export class FolderQueries {
SET ParentFolderId = ?,
UpdatedAt = ?
WHERE ParentFolderId = ?`;
-
- /**
- * Move item to folder.
- */
- public static readonly MOVE_ITEM = `
- UPDATE Items
- SET FolderId = ?,
- ManifestId = ${BaseQueries.MANIFEST_OF_FOLDER},
- UpdatedAt = ?
- WHERE Id = ?`;
}
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index 1235c32b1..30848d07d 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -86,32 +86,6 @@ export class ItemQueries {
LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
WHERE i.Id = ? AND i.ManifestId = ? AND i.IsDeleted = 0`;
- /**
- * Get all recently deleted items (in trash).
- */
- public static readonly GET_RECENTLY_DELETED = `
- SELECT
- i.Id,
- i.ManifestId,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- l.Id as LogoId,
- l.Kind as LogoKind,
- l.Source as LogoSource,
- l.Name as LogoName,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.ManifestId = i.ManifestId AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.ManifestId = i.ManifestId AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.ManifestId = i.ManifestId AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.DeletedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
- ORDER BY i.DeletedAt DESC`;
-
/**
* Count of recently deleted items.
*/
@@ -217,19 +191,6 @@ export class ItemQueries {
INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
VALUES (?, ?, ?, ?, ?, ${BaseQueries.MANIFEST_OF_FOLDER}, ?, ?, ?)`;
- /**
- * Update an existing item (preserves LogoId if null is passed).
- */
- public static readonly UPDATE_ITEM = `
- UPDATE Items
- SET Name = ?,
- ItemType = ?,
- FolderId = ?,
- ManifestId = ${BaseQueries.MANIFEST_OF_FOLDER},
- LogoId = COALESCE(?, LogoId),
- UpdatedAt = ?
- WHERE Id = ? AND ManifestId = ?`;
-
/**
* Update an existing item with explicit LogoId setting (can clear LogoId to null).
*/
diff --git a/core/client/src/database/queries/ItemStatsQueries.ts b/core/client/src/database/queries/ItemStatsQueries.ts
index 101799427..2135faf84 100644
--- a/core/client/src/database/queries/ItemStatsQueries.ts
+++ b/core/client/src/database/queries/ItemStatsQueries.ts
@@ -45,25 +45,4 @@ export class ItemStatsQueries {
IsDeleted = 0
WHERE ManifestId = ? AND Id = ?`;
}
-
- /**
- * Read one item's statistics.
- */
- public static readonly GET_FOR_ITEM = `
- SELECT LastUsedAt, UseCount, LastAutofilledAt, AutofillCount, LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount
- FROM ItemStats
- WHERE ManifestId = ? AND Id = ? AND IsDeleted = 0`;
-
- /**
- * Read the last-used timestamp of every item that has one, newest first.
- *
- * Joined on both halves of the key: an item id alone is ambiguous across manifests, which is exactly
- * what the composite key exists to prevent.
- */
- public static readonly GET_LAST_USED_ALL = `
- SELECT s.ManifestId, s.Id, s.LastUsedAt, s.UseCount
- FROM ItemStats s
- INNER JOIN Items i ON i.Id = s.Id AND i.ManifestId = s.ManifestId
- WHERE s.IsDeleted = 0 AND s.LastUsedAt IS NOT NULL AND i.IsDeleted = 0
- ORDER BY s.LastUsedAt DESC`;
}
diff --git a/core/client/src/database/queries/LogoQueries.ts b/core/client/src/database/queries/LogoQueries.ts
index ddd6c8107..e95f3001f 100644
--- a/core/client/src/database/queries/LogoQueries.ts
+++ b/core/client/src/database/queries/LogoQueries.ts
@@ -49,14 +49,6 @@ export class LogoQueries {
UpdatedAt = excluded.UpdatedAt,
IsDeleted = 0`;
- /**
- * One manifest's library of uploaded logos, newest first. Favicons are excluded.
- */
- public static readonly LIST_CUSTOM = `
- SELECT Id, Kind, Source, Name, FileData FROM Logos
- WHERE ManifestId = ? AND Kind = 'custom' AND IsDeleted = 0
- ORDER BY UpdatedAt DESC`;
-
/**
* Every item whose logo lives outside the item's own manifest, with the kind and key needed to bring a
* copy in.
@@ -73,10 +65,4 @@ export class LogoQueries {
*/
public static readonly REPOINT_ITEM_LOGO = `
UPDATE Items SET LogoId = ? WHERE Id = ? AND ManifestId = ?`;
-
- /**
- * Soft-delete an uploaded logo, removing it from the library.
- */
- public static readonly SOFT_DELETE = `
- UPDATE Logos SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?`;
}
diff --git a/core/client/src/database/queries/PasskeyQueries.ts b/core/client/src/database/queries/PasskeyQueries.ts
index 4e7555879..2cfb89122 100644
--- a/core/client/src/database/queries/PasskeyQueries.ts
+++ b/core/client/src/database/queries/PasskeyQueries.ts
@@ -7,50 +7,6 @@ import { BaseQueries } from './BaseQueries';
* Centralizes all passkey-related queries to avoid duplication.
*/
export class PasskeyQueries {
- /**
- * Base SELECT for passkeys with item information.
- */
- public static readonly BASE_SELECT_WITH_ITEM = `
- SELECT
- p.Id,
- p.ItemId,
- p.ManifestId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.DisplayName,
- p.PrfKey,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
- i.Name as ServiceName,
- (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LoginUsername}' AND fv.IsDeleted = 0 LIMIT 1) as Username,
- (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LoginEmail}' AND fv.IsDeleted = 0 LIMIT 1) as Email
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId`;
-
- /**
- * Base SELECT for passkeys without item information.
- */
- public static readonly BASE_SELECT = `
- SELECT
- p.Id,
- p.ItemId,
- p.ManifestId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.DisplayName,
- p.PrfKey,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted
- FROM Passkeys p`;
-
/**
* Get passkeys by relying party ID.
*/
@@ -137,15 +93,6 @@ export class PasskeyQueries {
)
VALUES (?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
- /**
- * Update passkey display name.
- */
- public static readonly UPDATE_DISPLAY_NAME = `
- UPDATE Passkeys
- SET DisplayName = ?,
- UpdatedAt = ?
- WHERE Id = ? AND ManifestId = ?`;
-
/**
* Soft delete passkey by ID.
*/
@@ -154,13 +101,4 @@ export class PasskeyQueries {
SET IsDeleted = 1,
UpdatedAt = ?
WHERE Id = ? AND ManifestId = ?`;
-
- /**
- * Soft delete passkeys by item ID.
- */
- public static readonly SOFT_DELETE_BY_ITEM = `
- UPDATE Passkeys
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE ItemId = ? AND ManifestId = ?`;
}
diff --git a/core/client/src/database/repositories/EncryptionKeyRepository.ts b/core/client/src/database/repositories/EncryptionKeyRepository.ts
index 4f3537ad8..b2886bd02 100644
--- a/core/client/src/database/repositories/EncryptionKeyRepository.ts
+++ b/core/client/src/database/repositories/EncryptionKeyRepository.ts
@@ -20,17 +20,6 @@ export class EncryptionKeyRepository extends BaseRepository {
return yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ALL);
}
- /**
- * Get a manifest's active keypair, whose public half is published to the server as that manifest's delivery
- * key. Returns null for a manifest that has no keypair in this vault.
- * @param manifestId - The manifest id the keypair is stamped with
- * @returns The active keypair, or null when the manifest has none
- */
- public *getActiveForManifest(manifestId: string): DbOp<EncryptionKey | null> {
- const results = yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ACTIVE_FOR_MANIFEST, [manifestId]);
- return results.length > 0 ? results[0] : null;
- }
-
/**
* Get the account keypair matching the given public half.
* @param publicKey - The public half the grant was encrypted for
diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.ts
index 4b5ab54f3..f5548a8c3 100644
--- a/core/client/src/database/repositories/FolderRepository.ts
+++ b/core/client/src/database/repositories/FolderRepository.ts
@@ -230,28 +230,4 @@ export class FolderRepository extends BaseRepository {
return folders + items;
});
}
-
- /**
- * Move an item to a folder.
- * @param itemId - The ID of the item to move
- * @param folderId - The ID of the destination folder (null to remove from folder)
- * @returns The number of rows updated
- */
- public async moveItem(itemId: string, folderId: string | null): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const manifestId = await this.run(this.writeManifestId());
- const moved = await this.run(this.execute(FolderQueries.MOVE_ITEM, [
- folderId,
- // Second bind of the destination: the item adopts that folder's manifest.
- folderId,
- manifestId,
- currentDateTime,
- itemId
- ]));
- // The destination folder may sit in another manifest; the item's logo has to follow it there.
- await this.logoRepository.reconcileItemLogoScopes(currentDateTime);
- return moved;
- });
- }
}
diff --git a/core/client/src/database/repositories/ItemStatsRepository.ts b/core/client/src/database/repositories/ItemStatsRepository.ts
index 2319c77d4..ac6317f7e 100644
--- a/core/client/src/database/repositories/ItemStatsRepository.ts
+++ b/core/client/src/database/repositories/ItemStatsRepository.ts
@@ -55,27 +55,6 @@ export class ItemStatsRepository extends BaseRepository {
return true;
}
- /**
- * Get one item's statistics.
- * @param itemId - The item to read
- * @returns The statistics, or null when the item has never been used
- */
- public *getForItem(itemId: string): DbOp<ItemStats | null> {
- const manifestId = yield* this.itemManifestId(itemId);
- if (!manifestId) {
- return null;
- }
- return (yield* this.query<ItemStats>(ItemStatsQueries.GET_FOR_ITEM, [manifestId, itemId]))[0] ?? null;
- }
-
- /**
- * Get the last-used timestamp of every item that has one, newest first.
- * @returns One entry per used item
- */
- public *getLastUsed(): DbOp<{ ManifestId: string; Id: string; LastUsedAt: string; UseCount: number }[]> {
- return yield* this.query<{ ManifestId: string; Id: string; LastUsedAt: string; UseCount: number }>(ItemStatsQueries.GET_LAST_USED_ALL);
- }
-
/**
* The manifest the given item belongs to.
* @param itemId - The item id
diff --git a/core/client/src/database/repositories/LogoRepository.ts b/core/client/src/database/repositories/LogoRepository.ts
index 78ae5c24a..a1b05412a 100644
--- a/core/client/src/database/repositories/LogoRepository.ts
+++ b/core/client/src/database/repositories/LogoRepository.ts
@@ -7,13 +7,6 @@ import { LogoQueries } from '../queries/LogoQueries';
import type { DbOp } from '../DbOp';
import type { ItemLogo, LogoKind } from '@aliasvault/models/vault';
-/**
- * An uploaded logo as shown in the user's logo library.
- */
-export type CustomLogoEntry = ItemLogo & {
- FileData: Uint8Array | null;
-};
-
/**
* Repository for item logo operations.
*
@@ -24,14 +17,6 @@ export type CustomLogoEntry = ItemLogo & {
* UNIQUE(ManifestId, Kind, Source).
*/
export class LogoRepository extends BaseRepository {
- /**
- * The manifest the user's own logo library lives in: this client's own.
- * @returns The manifest id, or the empty scope when it is not known yet
- */
- private *ownScope(): DbOp<string> {
- return (yield* this.personalManifestId()) ?? '';
- }
-
/**
* Check whether the vault already holds a favicon for this domain, in any manifest.
* @param source The normalized source domain (e.g., 'github.com')
@@ -163,26 +148,6 @@ export class LogoRepository extends BaseRepository {
return this.getOrCreate(manifestId, LogoKinds.Custom, contentHash, fileData, currentDateTime, options);
}
- /**
- * The user's own library of uploaded logos, newest first.
- * @returns The uploaded logos, with their image data
- */
- public *listCustom(): DbOp<CustomLogoEntry[]> {
- const scope = yield* this.ownScope();
- const rows = yield* this.query<{ Id: string; Kind: LogoKind; Source: string; Name: string | null; FileData: Uint8Array | null }>(LogoQueries.LIST_CUSTOM, [scope]);
- return rows.map(row => ({ ...row, FileData: row.FileData ? new Uint8Array(row.FileData) : null }));
- }
-
- /**
- * Remove an uploaded logo from the library (soft delete). Items still using it fall back to a placeholder.
- * @param logoId The logo id to delete
- * @param currentDateTime The current date/time string for timestamps
- * @returns The number of rows modified
- */
- public *deleteById(logoId: string, currentDateTime: string): DbOp<number> {
- return yield* this.execute(LogoQueries.SOFT_DELETE, [currentDateTime, logoId]);
- }
-
/**
* Convert image data from various formats to Uint8Array.
* @param image The image data in various possible formats
diff --git a/core/client/src/database/repositories/PasskeyRepository.ts b/core/client/src/database/repositories/PasskeyRepository.ts
index 529f24c56..e7f2ab0aa 100644
--- a/core/client/src/database/repositories/PasskeyRepository.ts
+++ b/core/client/src/database/repositories/PasskeyRepository.ts
@@ -112,37 +112,4 @@ export class PasskeyRepository extends BaseRepository {
return this.run(this.execute(PasskeyQueries.SOFT_DELETE, [this.now(), passkeyId, scope]));
});
}
-
- /**
- * Delete all passkeys for a specific item (soft delete).
- * @param itemId - The ID of the item
- * @param manifestId - The manifest the item belongs to, when known
- * @returns The number of rows updated
- */
- public async deleteByItemId(itemId: string, manifestId?: string): Promise<number> {
- return this.withTransaction(async () => {
- const scope = manifestId ?? await this.run(this.resolveRowManifestId('Items', itemId));
- if (!scope) {
- return 0;
- }
- return this.run(this.execute(PasskeyQueries.SOFT_DELETE_BY_ITEM, [this.now(), itemId, scope]));
- });
- }
-
- /**
- * Update a passkey's display name.
- * @param passkeyId - The ID of the passkey to update
- * @param displayName - The new display name
- * @param manifestId - The manifest the passkey belongs to, when known
- * @returns The number of rows updated
- */
- public async updateDisplayName(passkeyId: string, displayName: string, manifestId?: string): Promise<number> {
- return this.withTransaction(async () => {
- const scope = manifestId ?? await this.run(this.resolveRowManifestId('Passkeys', passkeyId));
- if (!scope) {
- return 0;
- }
- return this.run(this.execute(PasskeyQueries.UPDATE_DISPLAY_NAME, [displayName, this.now(), passkeyId, scope]));
- });
- }
}
diff --git a/core/client/src/platform/SqliteEngine.ts b/core/client/src/platform/SqliteEngine.ts
index 2def81ef7..b99f30c7c 100644
--- a/core/client/src/platform/SqliteEngine.ts
+++ b/core/client/src/platform/SqliteEngine.ts
@@ -9,18 +9,7 @@ export type SqliteValue = string | number | null | Uint8Array;
export type SqliteRow = Record<string, SqliteValue>;
/**
- * A compiled statement, for bulk inserts that bind the same SQL many times.
- */
-export interface ISqliteStatement {
- /** Bind the parameters and run the statement to completion. */
- run(params: SqliteValue[]): void;
-
- /** Release the statement. */
- finalize(): void;
-}
-
-/**
- * One open SQLite database. Every call is synchronous: the repositories and the codec drive the database
+ * One open SQLite database. Every call is synchronous: the repositories drive the database
* step by step, which only a synchronous engine can do without turning every read into a promise.
*/
export interface ISqliteDatabase {
@@ -39,11 +28,6 @@ export interface ISqliteDatabase {
*/
exec(sql: string): void;
- /**
- * Compile a statement for repeated execution.
- */
- prepare(sql: string): ISqliteStatement;
-
/**
* The database as SQLite file bytes.
*/
diff --git a/core/client/src/platform/index.ts b/core/client/src/platform/index.ts
index 7a9293fde..6fc42448a 100644
--- a/core/client/src/platform/index.ts
+++ b/core/client/src/platform/index.ts
@@ -2,6 +2,6 @@ export type { IAppIdentity } from './AppIdentity';
export { getPlatform, setPlatform, tryGetPlatform, type IClientPlatform } from './ClientPlatform';
export type { IKeyValueStore, StorageKey } from './KeyValueStore';
export { devError, devLog, devWarn, type ILogger } from './Logger';
-export type { ISqliteDatabase, ISqliteEngine, ISqliteStatement, SqliteRow, SqliteValue } from './SqliteEngine';
+export type { ISqliteDatabase, ISqliteEngine, SqliteRow, SqliteValue } from './SqliteEngine';
export { TranslatableMessage } from './TranslatableMessage';
export type { IRustCore } from '../rust/RustCoreBinding';
diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.ts
index de618be23..86d63e26b 100644
--- a/core/client/src/rust/RustCore.ts
+++ b/core/client/src/rust/RustCore.ts
@@ -12,12 +12,12 @@ import { deviceLanguage } from '../platform/DeviceLanguage';
import { AutofillMatchingMode } from './RustCoreTypes';
import type { IRustCore } from './RustCoreBinding';
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
+import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail } from './RustCoreTypes';
import type { Identity } from '@aliasvault/models/identity';
import type { Item, PasswordSettings } from '@aliasvault/models/vault';
export { AutofillMatchingMode } from './RustCoreTypes';
-export type { CodecBlobEntry, CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecTableData, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
+export type { CodecBlobEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecTableData, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment } from './RustCoreTypes';
/**
* The host's Rust core binding.
@@ -237,35 +237,6 @@ export async function vaultCodecCanonicalizeFromSqlite(input: CodecCanonicalizeI
return rustCore().vaultCodecCanonicalizeFromSqlite(input);
}
-/**
- * Materialize the vault's manifests + data buckets into the table set the platform inserts.
- */
-export async function vaultCodecMaterializeAsSqlite(manifests: CodecManifest[], dataBuckets: CodecDataBucket[], schemaColumns: Record<string, string[]>): Promise<CodecMaterialized> {
- return rustCore().vaultCodecMaterializeAsSqlite({ manifests, dataBuckets, schemaColumns });
-}
-
-/**
- * Extract the encryption-key row whose `PublicKey` matches `publicKey` from a decrypted manifest.
- */
-export async function vaultCodecExtractEncryptionKeyForPublicKey(manifest: CodecManifest, publicKey: string): Promise<Record<string, unknown> | null> {
- return rustCore().vaultCodecExtractEncryptionKeyForPublicKey(manifest, publicKey);
-}
-
-/**
- * Build a bucket category's data buckets from its tables, one per manifest in `manifestIds` (bucket-only push
- * path).
- */
-export async function vaultCodecExtractBuckets(category: string, manifestIds: string[], tables: Record<string, Array<Record<string, unknown>>>): Promise<CodecDataBucket[]> {
- return rustCore().vaultCodecExtractBuckets({ category, manifestIds, tables });
-}
-
-/**
- * The name of the client-local SQLite table that carries the codec overflow inside the vault DB.
- */
-export async function vaultCodecOverflowTable(): Promise<string> {
- return rustCore().vaultCodecOverflowTable();
-}
-
/**
* The vault tables that take part in sync, as declared by the shared vault table registry.
*/
@@ -274,28 +245,13 @@ export async function getSyncableTableNames(): Promise<string[]> {
}
/**
- * The bucket layout: every category and the tables it owns.
- */
-export async function vaultCodecBucketLayout(): Promise<CodecBucketLayoutEntry[]> {
- return rustCore().vaultCodecBucketLayout();
-}
-
-/**
- * The `Logos.Id` to use for a source domain inside the manifest with id `manifestId` (pass the root
- * manifest's own id for personal logos).
+ * The `Logos.Id` to use for the logo `(kind, source)` inside the manifest with id `manifestId`.
*
* Logo identity is derived: two devices that fetch the same favicon independently produce
* the same row and merge by LWW. The same domain in two different manifests deliberately yields
* two different ids, so a shared manifest's logo and the user's own logo for that domain never
* overwrite each other.
*/
-export async function vaultCodecLogoIdForSource(manifestId: string, source: string): Promise<string> {
- return rustCore().vaultCodecLogoIdForSource(manifestId, source);
-}
-
-/**
- * The `Logos.Id` to use for the logo `(kind, source)` inside the manifest with id `manifestId`.
- */
export async function vaultCodecLogoIdFor(manifestId: string, kind: string, source: string): Promise<string> {
return rustCore().vaultCodecLogoIdFor(manifestId, kind, source);
}
@@ -329,52 +285,6 @@ export async function vaultCodecUnpackPayload(plainBytes: Uint8Array): Promise<s
return rustCore().vaultCodecUnpackPayload(plainBytes);
}
-/**
- * Structurally validate a manifest before upload.
- */
-export async function vaultCodecValidateManifest(manifest: CodecManifest): Promise<CodecValidation> {
- return rustCore().vaultCodecValidateManifest(manifest);
-}
-
-/**
- * Validate a data bucket before upload.
- */
-export async function vaultCodecValidateDataBucket(bucket: CodecDataBucket): Promise<CodecValidation> {
- return rustCore().vaultCodecValidateDataBucket(bucket);
-}
-
-/**
- * SHA-256 (lowercase hex) of a base64 ciphertext string.
- */
-export async function vaultCodecComputeCiphertextHash(base64Ciphertext: string): Promise<string> {
- return rustCore().vaultCodecComputeCiphertextHash(base64Ciphertext);
-}
-
-/**
- * Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase hex)
- * of the Rust codec's canonical JSON, excluding the volatile `canonicalizedAt` timestamp. Calculated in Rust so
- * every platform uses the same fingerprinting algorithm.
- */
-export async function vaultCodecComputeContentFingerprint(payloadJson: string): Promise<string> {
- return rustCore().vaultCodecComputeContentFingerprint(payloadJson);
-}
-
-/**
- * Work out which manifests the next push writes, personal manifest first.
- * @param input - the personal manifest, what the vault holds rows for, what opened, and the held records.
- */
-export async function vaultSharingResolveManifestWriteSet(input: { personalManifestId: string; personalManifestSalt: string; stampedManifestIds: string[]; openedManifestIds: string[]; heldRecords: SharingManifestRecord[]; displayNames: Record<string, string> }): Promise<SharingWriteSet> {
- return rustCore().vaultSharingResolveManifestWriteSet(input);
-}
-
-/**
- * Split what the local vault holds by what this account can still open.
- * @param input - what the vault holds, what this session can write, and what the last snapshot served.
- */
-export async function vaultSharingPartitionManifestAccess(input: { manifestIdsInVault: string[]; writableManifestIds: string[]; grantedManifestIds: string[] }): Promise<SharingAccessPartition> {
- return rustCore().vaultSharingPartitionManifestAccess(input);
-}
-
/**
* Read all non-empty values for a field key from an item, returning them as
* a string array (single-value fields are wrapped to a 1-element array).
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index cd4330c3f..00b245bd6 100644
--- a/core/client/src/rust/RustCoreBinding.ts
+++ b/core/client/src/rust/RustCoreBinding.ts
@@ -1,4 +1,4 @@
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* One running operation of the Rust vault sync engine.
@@ -47,27 +47,13 @@ export interface IRustCore {
srpDeriveSession(clientSecret: string, serverPublic: string, salt: string, identity: string, privateKey: string): Promise<SrpSession>;
getSyncableTableNames(): Promise<string[]>;
- getPruneTableQueries(): Promise<PruneTableQuery[]>;
vaultCodecCanonicalizeFromSqlite(input: CodecCanonicalizeInput): Promise<CodecCanonicalized>;
- vaultCodecMaterializeAsSqlite(input: CodecMaterializeInput): Promise<CodecMaterialized>;
- vaultCodecExtractBuckets(input: CodecExtractBucketsInput): Promise<CodecDataBucket[]>;
- vaultCodecBucketLayout(): Promise<CodecBucketLayoutEntry[]>;
- vaultCodecOverflowTable(): Promise<string>;
vaultCodecGenerateManifestSalt(): Promise<string>;
- vaultCodecLogoIdForSource(manifestId: string, source: string): Promise<string>;
vaultCodecLogoIdFor(manifestId: string, kind: string, source: string): Promise<string>;
vaultCodecLogoContentHash(bytes: Uint8Array): Promise<string>;
vaultCodecPackPayload(payloadJson: string): Promise<Uint8Array>;
vaultCodecUnpackPayload(plainBytes: Uint8Array): Promise<string>;
- vaultCodecValidateManifest(manifest: CodecManifest): Promise<CodecValidation>;
- vaultCodecValidateDataBucket(bucket: CodecDataBucket): Promise<CodecValidation>;
- vaultCodecComputeCiphertextHash(base64Ciphertext: string): Promise<string>;
- vaultCodecComputeContentFingerprint(payloadJson: string): Promise<string>;
- vaultCodecExtractEncryptionKeyForPublicKey(manifest: CodecManifest, publicKey: string): Promise<Record<string, unknown> | null>;
-
- vaultSharingResolveManifestWriteSet(input: SharingResolveWriteSetInput): Promise<SharingWriteSet>;
- vaultSharingPartitionManifestAccess(input: SharingPartitionAccessInput): Promise<SharingAccessPartition>;
createVaultSyncSession(requestJson: string): Promise<IVaultSyncSession>;
}
diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.ts
index f67a996aa..576dd5f4c 100644
--- a/core/client/src/rust/RustCoreTypes.ts
+++ b/core/client/src/rust/RustCoreTypes.ts
@@ -80,9 +80,6 @@ export type SrpSession = {
key: string;
};
-/** One per-table SELECT the pruner reads its input with. */
-export type PruneTableQuery = { name: string; query: string };
-
/*
* Vault codec (manifest-v1 storage format).
*/
@@ -154,65 +151,3 @@ export type CodecCanonicalizeInput = {
/** For legacy sqlite-blob migration: the manifest that unstamped rows are adopted into. TODO: delete this field once the migration is complete. */
adoptUnstampedInto?: string | null;
};
-
-/** Input for materialize. */
-export type CodecMaterializeInput = {
- manifests: CodecManifest[];
- dataBuckets: CodecDataBucket[];
- schemaColumns: Record<string, string[]>;
-};
-
-/** Materialized tables the platform inserts into a fresh SQLite DB (`overflow` is a diagnostics copy). */
-export type CodecMaterialized = { tables: CodecTableData[]; overflow: CodecOverflow };
-
-/** Input for the bucket-only extraction. */
-export type CodecExtractBucketsInput = { category: string; manifestIds: string[]; tables: Record<string, Array<Record<string, unknown>>> };
-
-/** One entry in the bucket layout: a category and the tables it owns. */
-export type CodecBucketLayoutEntry = { category: string; tables: string[] };
-
-/** Structural validation outcome. */
-export type CodecValidation = { ok: boolean; failedRules: string[]; message: string };
-
-/** A shared manifest's key record. */
-export type SharingManifestRecord = {
- manifestId: string;
- salt: string;
- name?: string | null;
- canAdminister?: boolean;
-};
-
-/** One manifest the next push writes. */
-export type SharingWriteRecord = {
- manifestId: string;
- isPersonal: boolean;
- salt: string;
- name: string | null;
- canAdminister: boolean;
-};
-
-/** The manifests a push writes, personal first, plus what was left out and why. */
-export type SharingWriteSet = {
- records: SharingWriteRecord[];
- skipped: Array<{ manifestId: string; reason: 'NO_ROWS_IN_VAULT' | 'KEY_DID_NOT_OPEN' }>;
-};
-
-/** Input of the manifest write-set resolution. */
-export type SharingResolveWriteSetInput = {
- personalManifestId: string;
- personalManifestSalt: string;
- stampedManifestIds: string[];
- openedManifestIds: string[];
- heldRecords: SharingManifestRecord[];
- displayNames: Record<string, string>;
-};
-
-/** Input of the manifest access partition. */
-export type SharingPartitionAccessInput = {
- manifestIdsInVault: string[];
- writableManifestIds: string[];
- grantedManifestIds: string[];
-};
-
-/** What the vault holds but cannot write, and what it holds but has lost access to. */
-export type SharingAccessPartition = { unwritable: string[]; lost: string[] };
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index ae25a7ca5..36f964a55 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -5,7 +5,7 @@
import initWasm, * as core from '../../wasm/aliasvault_core.js';
import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.
@@ -74,24 +74,13 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
ready(() => core.srpDeriveSession(clientSecret, serverPublic, salt, identity, privateKey) as SrpSession),
getSyncableTableNames: (): Promise<string[]> => ready(() => core.getSyncableTableNames()),
- getPruneTableQueries: (): Promise<PruneTableQuery[]> => ready(() => core.getPruneTableQueries() as PruneTableQuery[]),
vaultCodecCanonicalizeFromSqlite: (input: CodecCanonicalizeInput): Promise<CodecCanonicalized> => ready(() => core.vaultCodecCanonicalizeFromSqlite(input) as CodecCanonicalized),
- vaultCodecMaterializeAsSqlite: (input: CodecMaterializeInput): Promise<CodecMaterialized> => ready(() => core.vaultCodecMaterializeAsSqlite(input) as CodecMaterialized),
- vaultCodecExtractBuckets: (input: CodecExtractBucketsInput): Promise<CodecDataBucket[]> => ready(() => core.vaultCodecExtractBuckets(input) as CodecDataBucket[]),
- vaultCodecBucketLayout: (): Promise<CodecBucketLayoutEntry[]> => ready(() => core.vaultCodecBucketLayout() as CodecBucketLayoutEntry[]),
- vaultCodecOverflowTable: (): Promise<string> => ready(() => core.vaultCodecOverflowTable()),
vaultCodecGenerateManifestSalt: (): Promise<string> => ready(() => core.vaultCodecGenerateManifestSalt()),
- vaultCodecLogoIdForSource: (manifestId, source): Promise<string> => ready(() => core.vaultCodecLogoIdForSource(manifestId, source)),
vaultCodecLogoIdFor: (manifestId, kind, source): Promise<string> => ready(() => core.vaultCodecLogoIdFor(manifestId, kind, source)),
vaultCodecLogoContentHash: (bytes): Promise<string> => ready(() => core.vaultCodecLogoContentHash(bytes)),
vaultCodecPackPayload: (payloadJson): Promise<Uint8Array> => ready(() => core.vaultCodecPackPayload(payloadJson)),
vaultCodecUnpackPayload: (plainBytes): Promise<string> => ready(() => core.vaultCodecUnpackPayload(plainBytes)),
- vaultCodecValidateManifest: (manifest: CodecManifest): Promise<CodecValidation> => ready(() => core.vaultCodecValidateManifest(manifest) as CodecValidation),
- vaultCodecValidateDataBucket: (bucket: CodecDataBucket): Promise<CodecValidation> => ready(() => core.vaultCodecValidateDataBucket(bucket) as CodecValidation),
- vaultCodecComputeCiphertextHash: (base64Ciphertext): Promise<string> => ready(() => core.vaultCodecComputeCiphertextHash(base64Ciphertext)),
- vaultCodecComputeContentFingerprint: (payloadJson): Promise<string> => ready(() => core.vaultCodecComputeContentFingerprint(payloadJson)),
- vaultCodecExtractEncryptionKeyForPublicKey: (manifest: CodecManifest, publicKey): Promise<Record<string, unknown> | null> => ready(() => (core.vaultCodecExtractEncryptionKeyForPublicKey(manifest, publicKey) ?? null) as Record<string, unknown> | null),
createVaultSyncSession: (requestJson): Promise<IVaultSyncSession> => ready((): IVaultSyncSession => {
const session = new core.VaultSyncSession(requestJson);
@@ -101,8 +90,5 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
free: (): void => session.free(),
};
}),
-
- vaultSharingResolveManifestWriteSet: (input: SharingResolveWriteSetInput): Promise<SharingWriteSet> => ready(() => core.vaultSharingResolveManifestWriteSet(input) as SharingWriteSet),
- vaultSharingPartitionManifestAccess: (input: SharingPartitionAccessInput): Promise<SharingAccessPartition> => ready(() => core.vaultSharingPartitionManifestAccess(input) as SharingAccessPartition),
};
}
diff --git a/core/client/src/sharing/MultiManifestRendering.ts b/core/client/src/sharing/MultiManifestRendering.ts
index f077f92ef..68f9f037c 100644
--- a/core/client/src/sharing/MultiManifestRendering.ts
+++ b/core/client/src/sharing/MultiManifestRendering.ts
@@ -1,7 +1,3 @@
-import { getPlatform } from '../platform/ClientPlatform';
-import { devWarn } from '../platform/Logger';
-import { TranslatableMessage } from '../platform/TranslatableMessage';
-
import type { Folder } from '../database/repositories/FolderRepository';
import type { SqliteClient } from '../database/SqliteClient';
@@ -16,15 +12,6 @@ import type { SqliteClient } from '../database/SqliteClient';
*/
export type MultiManifestRenderingMode = 'subfolder' | 'switcher';
-/**
- * Rendering policy for a shared manifest.
- */
-export type RenderableManifest = {
- manifestId: string;
- name?: string | null;
- canAdminister?: boolean;
-};
-
/**
* The presentation policy for a multi-manifest vault, as one swappable unit.
*/
@@ -48,14 +35,6 @@ export type MultiManifestRenderer = {
*/
render(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void>;
- /**
- * Restore that presence for every administered manifest that is missing it.
- * @param sqliteClient - The open local vault
- * @param manifests - The shared manifests this session holds a key for
- * @returns Whether the vault was mutated
- */
- reconcile(sqliteClient: SqliteClient, manifests: RenderableManifest[]): Promise<boolean>;
-
/**
* What each shared manifest is called, keyed by lower-cased manifest id. This is the authority for the name that
* gets pushed into the manifest, so a rename in the UI follows the vault.
@@ -64,13 +43,6 @@ export type MultiManifestRenderer = {
displayNames(sqliteClient: SqliteClient): Record<string, string>;
};
-/**
- * What a shared manifest is called when this client has no name for it yet.
- */
-async function defaultSharedVaultName(): Promise<string> {
- return getPlatform().translate(TranslatableMessage.UnnamedSharedVault);
-}
-
/**
* Renders every shared manifest as a top-level folder whose id is the manifest id, which is what makes the folder
* findable from a manifest id alone and what lets its subtree be re-stamped in one statement.
@@ -98,34 +70,6 @@ const subfolderRendering: MultiManifestRenderer = {
await sqliteClient.folders.restampSubtree(folderId, manifestId);
},
- /**
- * Re-create the folder of any administered manifest that has none.
- * @param sqliteClient - The open local vault
- * @param manifests - The shared manifests this session holds a key for
- * @returns Whether the vault was mutated
- */
- async reconcile(sqliteClient: SqliteClient, manifests: RenderableManifest[]): Promise<boolean> {
- let mutated = false;
-
- for (const manifest of manifests) {
- if (!manifest.canAdminister) {
- // A member waiting for the administrator's first push has nothing to render yet.
- continue;
- }
-
- const rendered = sqliteClient.executeQuery<{ Id: string }>('SELECT Id FROM Folders WHERE ManifestId = ? AND IsDeleted = 0 AND ParentFolderId IS NULL', [manifest.manifestId]);
- if (rendered.length > 0) {
- continue;
- }
-
- await this.render(sqliteClient, manifest.manifestId, manifest.name ?? await defaultSharedVaultName());
- devWarn(`[Sharing] Shared manifest ${manifest.manifestId} had no folder; recreated it.`);
- mutated = true;
- }
-
- return mutated;
- },
-
/**
* The name of a shared manifest is the name of the folder it is rendered as.
* @param sqliteClient - The open local vault
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 4c609c3e6..1080ad5d5 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -300,21 +300,6 @@ export class SharingService {
}
}
- /**
- * Unwrap the VEK of every shared manifest this session holds a grant on, keyed by manifest id.
- * @param sqliteClient - the open local vault.
- */
- public static async openSharedManifestVeks(sqliteClient: SqliteClient): Promise<Map<string, string>> {
- const veks = new Map<string, string>();
- for (const record of Object.values(await this.getSharedManifestRecords())) {
- const vek = await this.openSharedManifestVek(sqliteClient, record);
- if (vek) {
- veks.set(record.manifestId, vek);
- }
- }
- return veks;
- }
-
/**
* The private key that opens a grant made out to `publicKey`.
* @param sqliteClient - the open local vault.
diff --git a/core/client/src/sync/ManifestIdsInVault.test.ts b/core/client/src/sync/ManifestIdsInVault.test.ts
deleted file mode 100644
index d4157e876..000000000
--- a/core/client/src/sync/ManifestIdsInVault.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { getPlatform } from '../platform/ClientPlatform';
-
-import { VaultCodec } from './VaultCodec';
-
-import type SqliteClient from '../database/SqliteClient';
-import type { ISqliteDatabase, SqliteValue } from '../platform/SqliteEngine';
-
-const PERSONAL = 'PERSONAL-MANIFEST';
-const SHARED = 'SHARED-MANIFEST';
-
-/**
- * Wrap an in-memory database as the sliver of {@link SqliteClient} the codec reads through.
- * @param db - the database to read
- * @returns A client that can answer `executeQuery`
- */
-function asClient(db: ISqliteDatabase): SqliteClient {
- return {
- /**
- * Run a statement and return its rows as plain objects.
- * @param query - the statement
- * @param params - bound parameters
- * @returns The rows
- */
- executeQuery: <T>(query: string, params: unknown[] = []): T[] => db.query<T>(query, params as SqliteValue[]),
- } as unknown as SqliteClient;
-}
-
-/**
- * Build a vault holding a stamped table, an unstamped one, and a table this check must discover on its own.
- * @returns The prepared database
- */
-async function makeDb(): Promise<ISqliteDatabase> {
- const db = await getPlatform().sqlite.open();
- db.exec(`
- CREATE TABLE Folders (ManifestId TEXT NOT NULL, Id TEXT NOT NULL, Name TEXT, PRIMARY KEY (ManifestId, Id));
- CREATE TABLE Items (ManifestId TEXT NOT NULL, Id TEXT NOT NULL, PRIMARY KEY (ManifestId, Id));
- CREATE TABLE __EFMigrationsHistory (MigrationId TEXT NOT NULL PRIMARY KEY, ProductVersion TEXT NOT NULL);
- INSERT INTO Folders VALUES ('${PERSONAL}', 'FOLDER-MINE', 'Mine'), ('${SHARED}', 'FOLDER-SHARED', 'Team');
- INSERT INTO Items VALUES ('${PERSONAL}', 'ITEM-MINE');
- INSERT INTO __EFMigrationsHistory VALUES ('20260101_Init', '9.0.0');
- `);
- return db;
-}
-
-describe('VaultCodec.manifestIdsInVault', () => {
- it('reports every manifest the vault holds a row for, from every stamped table', async () => {
- const ids = VaultCodec.manifestIdsInVault(asClient(await makeDb()));
- expect([...ids].sort()).toEqual([PERSONAL, SHARED]);
- });
-
- it('finds a table nothing lists, because it reads the stamp column off the schema', async () => {
- const db = await makeDb();
- db.exec(`CREATE TABLE SomethingNewer (ManifestId TEXT NOT NULL, Id TEXT NOT NULL); INSERT INTO SomethingNewer VALUES ('THIRD-MANIFEST', 'X');`);
- expect(VaultCodec.manifestIdsInVault(asClient(db)).has('THIRD-MANIFEST')).toBe(true);
- });
-
- it('keeps the stamp exactly as written, since that is how the codec routes it', async () => {
- const db = await makeDb();
- db.exec(`INSERT INTO Items VALUES ('${SHARED.toLowerCase()}', 'ITEM-OTHERCASE');`);
- const ids = VaultCodec.manifestIdsInVault(asClient(db));
- expect(ids.has(SHARED)).toBe(true);
- expect(ids.has(SHARED.toLowerCase())).toBe(true);
- });
-
- it('ignores unstamped rows and unstamped tables', async () => {
- const db = await makeDb();
- db.exec(`CREATE TABLE Unstamped (Id TEXT NOT NULL); INSERT INTO Unstamped VALUES ('X');`);
- db.exec(`CREATE TABLE Loose (ManifestId TEXT, Id TEXT NOT NULL); INSERT INTO Loose VALUES (NULL, 'A'), ('', 'B');`);
- expect([...VaultCodec.manifestIdsInVault(asClient(db))].sort()).toEqual([PERSONAL, SHARED]);
- });
-
- it('is empty for a vault predating the stamps, so a legacy vault never looks unwritable', async () => {
- const db = await getPlatform().sqlite.open();
- db.exec(`CREATE TABLE Folders (Id TEXT NOT NULL PRIMARY KEY, Name TEXT); INSERT INTO Folders VALUES ('FOLDER-LEGACY', 'Mine');`);
- expect(VaultCodec.manifestIdsInVault(asClient(db)).size).toBe(0);
- });
-});
diff --git a/core/client/src/sync/ManifestRevisions.ts b/core/client/src/sync/ManifestRevisions.ts
index 56ab377b8..0ae400a88 100644
--- a/core/client/src/sync/ManifestRevisions.ts
+++ b/core/client/src/sync/ManifestRevisions.ts
@@ -21,10 +21,3 @@ async function getManifestRevisions(): Promise<Record<string, number>> {
export async function recordManifestRevisions(revisions: Record<string, number>): Promise<void> {
await getPlatform().storage.set(StorageKeys.SERVER_MANIFEST_REVISIONS, { ...await getManifestRevisions(), ...revisions });
}
-
-/**
- * The id of this vault's own (personal) manifest, as reported by the server on the last pull.
- */
-export async function getPersonalManifestId(): Promise<string | null> {
- return (await getPlatform().storage.get(StorageKeys.VAULT_PERSONAL_MANIFEST_ID)) as string | null;
-}
diff --git a/core/client/src/sync/VaultCodec.ts b/core/client/src/sync/VaultCodec.ts
index a3e8a10f5..8bee33604 100644
--- a/core/client/src/sync/VaultCodec.ts
+++ b/core/client/src/sync/VaultCodec.ts
@@ -1,87 +1,13 @@
/**
- * VaultCodec: SQLite materialization methods for the manifest-v1 storage format.
+ * VaultCodec: the EF migration ids that tell whether a local vault's schema is current.
*/
-import { getPlatform } from '../platform/ClientPlatform';
-import { devLog } from '../platform/Logger';
-import { base64ToBytes as decodeBase64, bytesToBase64 as encodeBase64 } from '../utilities/Base64';
-
import type SqliteClient from '../database/SqliteClient';
-import type { ISqliteDatabase, ISqliteStatement, SqliteValue } from '../platform/SqliteEngine';
-import type {
- CodecManifest,
- CodecMaterialized,
- CodecTableData,
-} from '../rust/RustCore';
-
-/** A single table's rows, byte columns rendered as `{ __b64 }`. */
-type TableData = CodecTableData;
-
-/** Manifest-v1 manifest. */
-export type VaultManifest = CodecManifest;
-
-/**
- * Marker for an extracted blob reference inside a materialized row.
- */
-type BlobRef = {
- __blobRef: string;
- __blobKind?: string;
-};
/**
- * The stamp a row carries while it belongs to no manifest yet.
- */
-const UNSTAMPED_MANIFEST_ID = '00000000-0000-0000-0000-000000000000';
-
-/**
- * Column sets already derived from a schema, keyed by the schema SQL that produced them.
- */
-const schemaColumnsCache = new Map<string, Promise<Record<string, string[]>>>();
-
-/**
- * Whether a stamp names no manifest, so it must never be mistaken for one the vault holds rows for.
- * @param manifestId - the stamp as the row carries it
- */
-function isUnstampedScope(manifestId: string | null | undefined): boolean {
- return !manifestId || manifestId.toLowerCase() === UNSTAMPED_MANIFEST_ID;
-}
-
-/**
- * VaultCodec: SQLite read/insert methods, on whichever engine the host provides.
+ * VaultCodec: reads the migration a vault was stamped with and the one a schema would stamp.
*/
export class VaultCodec {
- /**
- * Read every user table into `TableData[]`, normalizing SQLite byte columns to `{ __b64 }`.
- * @param sqliteClient - client wrapping the open SQLite DB
- */
- public static readTables(sqliteClient: SqliteClient): TableData[] {
- const tableNames = this.listUserTables(sqliteClient);
- const tables: TableData[] = [];
- for (const name of tableNames) {
- const rows = sqliteClient.executeQuery<Record<string, unknown>>(`SELECT * FROM "${name}"`);
- tables.push({ name, records: rows.map(r => this.normalizeRowForJson(r)) });
- }
- return tables;
- }
-
- /**
- * Read the named tables (normalized), keyed by table name.
- * @param sqliteClient - client wrapping the open SQLite DB
- * @param names - the table names to read (a bucket's tables)
- */
- public static readNamedTables(sqliteClient: SqliteClient, names: string[]): Record<string, Array<Record<string, unknown>>> {
- const existing = new Set(this.listUserTables(sqliteClient));
- const out: Record<string, Array<Record<string, unknown>>> = {};
- for (const name of names) {
- if (!existing.has(name)) {
- continue;
- }
- const rows = sqliteClient.executeQuery<Record<string, unknown>>(`SELECT * FROM "${name}"`);
- out[name] = rows.map(r => this.normalizeRowForJson(r));
- }
- return out;
- }
-
/**
* Read the latest EF migration ID from `__EFMigrationsHistory` (empty string if not stamped).
* @param sqliteClient - opened client
@@ -105,276 +31,6 @@ export class VaultCodec {
const ids = [...schemaSql.matchAll(/INSERT\s+INTO\s+"__EFMigrationsHistory"[^;]*?VALUES\s*\(\s*'([^']+)'/gi)].map(m => m[1]);
return ids.length === 0 ? '' : ids.reduce((a, b) => (b > a ? b : a));
}
-
- /**
- * The column set of the local client schema, per table: the input Rust's materialize uses to
- * split off anything a newer writer stored that this schema cannot hold (see `CodecOverflow`).
- * @param schemaSql - the COMPLETE_SCHEMA_SQL string for the target client version
- */
- public static async getSchemaColumns(schemaSql: string): Promise<Record<string, string[]>> {
- let columns = schemaColumnsCache.get(schemaSql);
- if (!columns) {
- columns = this.readSchemaColumns(schemaSql).catch((error: unknown) => {
- // A failed probe must not stay cached, or every later call inherits the failure.
- schemaColumnsCache.delete(schemaSql);
- throw error;
- });
- schemaColumnsCache.set(schemaSql, columns);
- }
-
- return Object.fromEntries(Object.entries(await columns).map(([table, cols]) => [table, [...cols]]));
- }
-
- /**
- * Derive the column set of a schema by applying it to a throwaway database.
- * @param schemaSql - the COMPLETE_SCHEMA_SQL string for the target client version
- */
- private static async readSchemaColumns(schemaSql: string): Promise<Record<string, string[]>> {
- const db = await this.createDatabase();
- try {
- db.exec(schemaSql);
- const tables = db.query<{ name: string }>("SELECT name FROM sqlite_master WHERE type='table'").map(row => row.name);
- const out: Record<string, string[]> = {};
- for (const table of tables) {
- out[table] = db.query<{ name: string }>(`PRAGMA table_info("${table}")`).map(row => row.name);
- }
- return out;
- } finally {
- db.close();
- }
- }
-
- /**
- * Insert the materialized tables into a fresh SQLite database and export it.
- * @param materialized - tables produced by the Rust `materialize_as_sqlite`
- * @param blobs - map of `hash -> plaintext bytes` (caller fetched + decrypted these)
- * @param schemaSql - the COMPLETE_SCHEMA_SQL string for the target client version
- * @returns The SQLite database bytes, identical (in row content) to the original.
- */
- public static async insertTables(materialized: CodecMaterialized, blobs: Map<string, Uint8Array>, schemaSql: string): Promise<Uint8Array> {
- const db = await this.createDatabase();
-
- try {
- // 1) Apply the schema.
- db.exec(schemaSql);
- devLog('[VaultCodec] Schema applied.');
-
- /*
- * SQLite enforces foreign keys immediately (no deferral), and tables are inserted in the order Rust
- * emitted them, so child rows (e.g. Attachments) may precede their parents (Items). Disable enforcement
- * for the bulk load; an explicit foreign_key_check below validates the fully-assembled result instead.
- */
- db.exec('PRAGMA foreign_keys = OFF');
- db.exec('BEGIN TRANSACTION');
-
- // Compiled INSERT statements, keyed by table name plus the row's column set.
- const statements = new Map<string, ISqliteStatement>();
-
- // Tables present in the freshly-created schema; rows for tables outside it cannot be inserted.
- const schemaTables = new Set<string>(db.query<{ name: string }>("SELECT name FROM sqlite_master WHERE type='table'").map(row => row.name));
-
- // 2) Insert every materialized table's rows.
- for (const { name: tableName, records: rows } of materialized.tables) {
- if (rows.length === 0) {
- continue;
- }
-
- if (!schemaTables.has(tableName)) {
- // Skip tables that are not present in the schema definition.
- console.warn(`[VaultCodec] Skipping table "${tableName}" (${rows.length} rows), not present in the schema.`);
- continue;
- }
-
- devLog(`[VaultCodec] Inserting ${rows.length} rows into "${tableName}"...`);
- for (const row of rows) {
- const cols = Object.keys(row);
- const values: SqliteValue[] = cols.map(c => {
- const v = row[c];
- if (this.isBlobRef(v)) {
- return blobs.get((v as BlobRef).__blobRef) ?? null;
- }
- // Decode inlined byte payloads ({ __b64 }) back to raw bytes.
- if (this.isInlineB64(v)) {
- return this.base64ToBytes((v as { __b64: string }).__b64);
- }
- return (v === undefined ? null : v) as SqliteValue;
- });
-
- const statementKey = `${tableName}\u0000${cols.join('\u0000')}`;
- let statement = statements.get(statementKey);
- if (!statement) {
- const quotedCols = cols.map(c => `"${c}"`).join(', ');
- const placeholders = cols.map(() => '?').join(', ');
- statement = db.prepare(`INSERT INTO "${tableName}" (${quotedCols}) VALUES (${placeholders})`);
- statements.set(statementKey, statement);
- }
-
- try {
- statement.run(values);
- } catch (e) {
- throw new Error(`VaultCodec: failed to insert row into "${tableName}" (columns: ${cols.join(', ')}): ${e instanceof Error ? e.message : String(e)}`);
- }
- }
- }
-
- for (const statement of statements.values()) {
- statement.finalize();
- }
- statements.clear();
-
- db.exec('COMMIT');
-
- // 3) Verify referential integrity of the fully-assembled database.
- const fkViolations = db.query<{ table: string; rowid: number; parent: string }>('PRAGMA foreign_key_check');
- if (fkViolations.length > 0) {
- const sample = fkViolations.slice(0, 5).map(v => `${v.table} row ${v.rowid} > missing parent in ${v.parent}`).join('; ');
- throw new Error(`VaultCodec: materialized database fails foreign key check (${fkViolations.length} violations): ${sample}`);
- }
- devLog('[VaultCodec] Foreign key check passed.');
-
- // 4) Export.
- const bytes = db.export();
- devLog(`[VaultCodec] Reassembly complete: exported SQLite of ${bytes.length} bytes.`);
- return bytes;
- } finally {
- db.close();
- }
- }
-
- /**
- * Open a fresh in-memory database through the host's SQLite engine.
- */
- private static async createDatabase(): Promise<ISqliteDatabase> {
- return getPlatform().sqlite.open();
- }
-
- /**
- * Enumerate the names of all user tables in the database (excluding SQLite internals).
- * @param sqliteClient - opened client
- */
- private static listUserTables(sqliteClient: SqliteClient): string[] {
- const rows = sqliteClient.executeQuery<{ name: string }>(
- "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
- );
- return rows.map(r => r.name);
- }
-
- /**
- * The tables carrying a manifest stamp.
- * @param sqliteClient - client wrapping the open SQLite DB
- */
- public static stampedTables(sqliteClient: SqliteClient): string[] {
- return this.listUserTables(sqliteClient).filter(
- name => sqliteClient.executeQuery<{ name: string }>(`SELECT name FROM pragma_table_info("${name}") WHERE name = 'ManifestId'`).length > 0
- );
- }
-
- /**
- * Every manifest id this vault holds a row for.
- * @param sqliteClient - client wrapping the open SQLite DB
- */
- public static manifestIdsInVault(sqliteClient: SqliteClient): Set<string> {
- const ids = new Set<string>();
- for (const name of this.stampedTables(sqliteClient)) {
- for (const row of sqliteClient.executeQuery<{ ManifestId: string | null }>(`SELECT DISTINCT ManifestId FROM "${name}" WHERE ManifestId IS NOT NULL AND ManifestId != ''`)) {
- if (row.ManifestId && !isUnstampedScope(row.ManifestId)) {
- ids.add(row.ManifestId);
- }
- }
- }
- return ids;
- }
-
- /**
- * Normalize a SQLite-returned row into a JSON-safe shape: Uint8Array bytes become `{ __b64: ... }`.
- * @param row - raw row from the SQLite engine
- */
- private static normalizeRowForJson(row: Record<string, unknown>): Record<string, unknown> {
- /*
- * SQLite returns BLOB columns as Uint8Array. JSON.stringify turns those into an object of numeric keys
- * which round-trips poorly, so we encode any byte-shaped values as base64 with a discriminator. Rust then
- * decides which columns are extracted blobs vs. inline bytes.
- */
- const out: Record<string, unknown> = {};
- for (const [k, v] of Object.entries(row)) {
- if (v == null) {
- out[k] = null;
- continue;
- }
-
- if (this.looksLikeBytes(v)) {
- out[k] = { __b64: this.bytesToBase64(this.toUint8Array(v)) };
- continue;
- }
-
- out[k] = v;
- }
- return out;
- }
-
- /**
- * Heuristic: true if the value looks like a byte buffer (Uint8Array, number array, or sparse number map).
- * @param v - value to inspect
- */
- private static looksLikeBytes(v: unknown): boolean {
- return v instanceof Uint8Array
- || Array.isArray(v)
- || (typeof v === 'object' && v !== null && Object.values(v).every(x => typeof x === 'number'));
- }
-
- /**
- * Coerce a byte-shaped value into a Uint8Array. Counterpart of {@link looksLikeBytes}.
- * @param v - value to coerce
- */
- private static toUint8Array(v: unknown): Uint8Array {
- if (v instanceof Uint8Array) {
- return v;
- }
-
- if (Array.isArray(v)) {
- return new Uint8Array(v as number[]);
- }
-
- const obj = v as { [key: number]: number };
- const length = Object.keys(obj).length;
- const arr = new Uint8Array(length);
- for (let i = 0; i < length; i++) {
- arr[i] = obj[i];
- }
- return arr;
- }
-
- /**
- * Type guard: true if `v` is a manifest-row blob reference (the marker Rust substitutes for extracted bytes).
- * @param v - value to inspect
- */
- private static isBlobRef(v: unknown): v is BlobRef {
- return typeof v === 'object' && v !== null && '__blobRef' in v;
- }
-
- /**
- * Type guard: true if `v` is an inlined byte payload (`{ __b64 }`).
- * @param v - value to inspect
- */
- private static isInlineB64(v: unknown): v is { __b64: string } {
- return typeof v === 'object' && v !== null && '__b64' in v;
- }
-
- /**
- * Decode a base64 string back into raw bytes. Counterpart of {@link bytesToBase64}.
- * @param base64 - base64-encoded bytes
- */
- public static base64ToBytes(base64: string): Uint8Array {
- return decodeBase64(base64);
- }
-
- /**
- * Base64-encode a byte array via latin-1 character codes.
- * @param bytes - bytes to encode
- */
- private static bytesToBase64(bytes: Uint8Array): string {
- return encodeBase64(bytes);
- }
}
export default VaultCodec;
diff --git a/core/client/src/utilities/DateFormatter.ts b/core/client/src/utilities/DateFormatter.ts
index 462e69842..0d256a610 100644
--- a/core/client/src/utilities/DateFormatter.ts
+++ b/core/client/src/utilities/DateFormatter.ts
@@ -29,18 +29,6 @@ export function now(): string {
return toStandardFormat(new Date());
}
-/**
- * Formats a Date to the birth date format (no milliseconds, time set to 00:00:00).
- * Format: "yyyy-MM-dd 00:00:00" (19 characters).
- * @param date - The Date to format
- * @returns Formatted date string in format "yyyy-MM-dd 00:00:00"
- */
-export function toBirthDateFormat(date: Date): string {
- const isoString = date.toISOString();
- const datePart = isoString.substring(0, 10); // yyyy-MM-dd
- return `${datePart} 00:00:00`;
-}
-
/**
* Formats a date-time returned by the API (UTC by default) for display in the user's own locale and timezone.
* @param value - The date-time string as returned by the API