Skip to content

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

Move apps generic queries and passkey inner logic to Rust core

Leendert de Borstf5a21cfb8ef1
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
index 1205b3718..3dc0ef09e 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -313,7 +313,6 @@ const PasskeyCreate: React.FC = () => {
// Create passkey using static method (generates keys and credential ID)
const result = await PasskeyAuthenticator.createPasskey(newPasskeyGuidBytes, createRequest, {
uvPerformed: true,
- credentialIdBytes: 16,
enablePrf,
prfInputs: prfEvalInputs // Pass PRF evaluation salts if provided
});
@@ -473,6 +472,9 @@ const PasskeyCreate: React.FC = () => {
rawId: newPasskeyGuidBase64url,
clientDataJSON: credential.response.clientDataJSON,
attestationObject: credential.response.attestationObject,
+ authenticatorData: credential.response.authenticatorData,
+ publicKey: credential.response.publicKey,
+ publicKeyAlgorithm: credential.response.publicKeyAlgorithm,
extensions: prfExtensionResponse
};
diff --git a/apps/browser-extension/src/entrypoints/webauthn.ts b/apps/browser-extension/src/entrypoints/webauthn.ts
index 22e15fe43..fd47685cb 100644
--- a/apps/browser-extension/src/entrypoints/webauthn.ts
+++ b/apps/browser-extension/src/entrypoints/webauthn.ts
@@ -148,42 +148,6 @@ export default defineUnlistedScript(() => {
// Create a proper credential object with required methods
const cred: ProviderCreateCredential = e.detail.credential;
try {
- // Decode the attestation object to extract authenticator data
- const attestationObjectBuffer = base64ToBuffer(cred.attestationObject);
- const attObjBytes = new Uint8Array(attestationObjectBuffer);
-
- /*
- * Simple CBOR parser to extract authData
- * CBOR map starts with 0xA3 (map with 3 items)
- * Keys are: "fmt" (0x63), "attStmt" (0x67), "authData" (0x68)
- */
- let authDataBuffer = new ArrayBuffer(0);
- try {
- // Find "authData" key (0x68 0x61 0x75 0x74 0x68 0x44 0x61 0x74 0x61)
- const authDataKeyBytes = [0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61];
- for (let i = 0; i < attObjBytes.length - authDataKeyBytes.length; i++) {
- let match = true;
- for (let j = 0; j < authDataKeyBytes.length; j++) {
- if (attObjBytes[i + j] !== authDataKeyBytes[j]) {
- match = false;
- break;
- }
- }
- if (match) {
- // Found "authData" key, next byte is the type (0x58 = byte string)
- const typeIdx = i + authDataKeyBytes.length;
- if (attObjBytes[typeIdx] === 0x58) {
- // Next byte is the length
- const length = attObjBytes[typeIdx + 1];
- authDataBuffer = attObjBytes.slice(typeIdx + 2, typeIdx + 2 + length).buffer;
- }
- break;
- }
- }
- } catch {
- // Ignore
- }
-
// Create response object with proper prototype
const response = Object.create(AuthenticatorAttestationResponse.prototype);
const clientDataJSONBuffer = base64ToBuffer(cred.clientDataJSON);
@@ -195,7 +159,7 @@ export default defineUnlistedScript(() => {
configurable: true
},
attestationObject: {
- value: attestationObjectBuffer,
+ value: base64ToBuffer(cred.attestationObject),
writable: false,
enumerable: true,
configurable: true
@@ -216,7 +180,7 @@ export default defineUnlistedScript(() => {
* getAuthenticatorData
*/
value: function() : ArrayBuffer {
- return authDataBuffer;
+ return base64ToBuffer(cred.authenticatorData);
},
writable: true,
enumerable: true,
@@ -226,8 +190,8 @@ export default defineUnlistedScript(() => {
/**
* getPublicKey
*/
- value: function() : JsonWebKey | null {
- return null;
+ value: function() : ArrayBuffer {
+ return base64ToBuffer(cred.publicKey);
},
writable: true,
enumerable: true,
@@ -238,7 +202,7 @@ export default defineUnlistedScript(() => {
* getPublicKeyAlgorithm
*/
value: function() : number {
- return -7; // ES256
+ return cred.publicKeyAlgorithm;
},
writable: true,
enumerable: true,
diff --git a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
index 388b56a31..faa42d28f 100644
--- a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
+++ b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
@@ -142,7 +142,6 @@ export async function buildPasskeyAssertion(
const assertion = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {
uvPerformed: true,
- includeBEBS: true,
prfInputs: extractPrfInputs(request.publicKey)
});
diff --git a/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts b/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts
index a015d5828..e65de47dc 100644
--- a/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts
+++ b/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts
@@ -1,31 +1,15 @@
-/**
- * PasskeyAuthenticator
- * -------------------------
- * A WebAuthn "virtual authenticator" for browser extensions.
- * Implements passkey creation (registration) and authentication (assertion) following
- * the WebAuthn Level 2 specification.
- *
- * This is the reference TypeScript implementation:
- * - iOS: apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
- * - Android: apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
- *
- * Key features:
- * - ES256 (ECDSA P-256) and RS256 (RSASSA-PKCS1-v1.5) key pair generation
- * - CBOR/COSE encoding for attestation objects
- * - Proper authenticator data with WebAuthn flags
- * - Self-attestation (packed format) or none attestation
- * - Consistent base64url handling
- * - Sign count always 0 for syncable passkeys
- * - BE/BS flags for backup-eligible and backed-up status
- */
+import { passkeyCreate, passkeyGetAssertion, passkeyPickAlgorithm } from '@aliasvault/client/rust/WasmPasskey';
+
+import { PasskeyHelper } from './PasskeyHelper';
import type { CreateRequest, GetRequest, StoredPasskeyRecord } from './types';
+import type { PasskeyPrfResults } from '@aliasvault/client/rust/WasmPasskey';
/**
- * PasskeyAuthenticator - Static utility class for WebAuthn operations
+ * The WebAuthn authenticator of the browser extension. It builds the client data JSON and the responses the page
+ * receives; key generation, authenticator data, the attestation object, signatures and PRF run in the Rust core
+ * (core/rust/src/passkey).
+ * Other platform implementations: PasskeyAuthenticator.swift (iOS), PasskeyAuthenticator.kt (Android).
*/
export class PasskeyAuthenticator {
/**
@@ -33,29 +17,6 @@ export class PasskeyAuthenticator {
*/
private constructor() {}
- /** AliasVault AAGUID: a11a5faa-9f32-4b8c-8c5d-2f7d13e8c942 */
- private static readonly AAGUID = new Uint8Array([
- 0xa1, 0x1a, 0x5f, 0xaa, 0x9f, 0x32, 0x4b, 0x8c,
- 0x8c, 0x5d, 0x2f, 0x7d, 0x13, 0xe8, 0xc9, 0x42
- ]);
-
- /** COSE algorithm identifier for ES256 (ECDSA P-256 with SHA-256). */
- private static readonly ALG_ES256 = -7;
-
- /** COSE algorithm identifier for RS256 (RSASSA-PKCS1-v1.5 with SHA-256). */
- private static readonly ALG_RS256 = -257;
-
- /**
- * Algorithms supported by this authenticator, in our order of preference.
- * When an RP lists multiple, we honor the RP's order and pick the first match.
- */
- private static readonly SUPPORTED_ALGORITHMS = [
- PasskeyAuthenticator.ALG_ES256,
- PasskeyAuthenticator.ALG_RS256
- ];
-
- // MARK: - Public API
-
/**
* Create a new passkey (registration).
*/
@@ -64,133 +25,73 @@ export class PasskeyAuthenticator {
req: CreateRequest,
opts?: {
uvPerformed?: boolean;
- credentialIdBytes?: number;
enablePrf?: boolean;
prfInputs?: { first: string; second?: string };
}
): Promise<PasskeyCreationResult> {
- // 1. Validate algorithm support and pick the credential algorithm
- const alg = PasskeyAuthenticator.pickSupportedAlgorithm(req.publicKey.pubKeyCredParams);
-
- // 2. Compute RP ID hash
+ const algorithm = await PasskeyAuthenticator.pickAlgorithm(req.publicKey.pubKeyCredParams);
const rpId = req.publicKey.rp?.id || new URL(req.origin).hostname;
- const rpIdHash = new Uint8Array(await crypto.subtle.digest('SHA-256', PasskeyAuthenticator.te(rpId) as BufferSource));
-
- // 3. Generate key pair for the chosen algorithm
- const keyPair = await crypto.subtle.generateKey(
- PasskeyAuthenticator.keyGenParams(alg),
- true,
- ['sign', 'verify']
- ) as CryptoKeyPair;
- const pubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
- const prvJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
-
- // 4. Build credential ID and COSE key
- const credentialIdB64u = PasskeyAuthenticator.toB64u(credentialIdBytes);
- const coseKey = alg === PasskeyAuthenticator.ALG_RS256
- ? PasskeyAuthenticator.buildCoseRsaRs256(pubJwk)
- : PasskeyAuthenticator.buildCoseEc2Es256(pubJwk);
-
- // 5. Build authenticator flags.
- let flags = 0x41; // UP (bit 0) + AT (bit 6)
/*
- * As in getAssertion, an omitted authenticatorSelection.userVerification defaults to
- * "preferred" per the WebAuthn spec. Keep registration and assertion symmetric so a
- * credential registered as verified also asserts as verified.
+ * An omitted authenticatorSelection.userVerification defaults to "preferred" per the WebAuthn spec. Keep
+ * registration and assertion symmetric so a credential registered as verified also asserts as verified.
*/
const uvReq = req.publicKey.authenticatorSelection?.userVerification ?? 'preferred';
- const uvPerformed = !!opts?.uvPerformed;
- if (uvReq === 'required' || (uvReq === 'preferred' && uvPerformed)) {
- flags |= 0x04; // UV (bit 2)
- }
- flags |= 0x08; // BE (bit 3)
- flags |= 0x10; // BS (bit 4)
+ const uvPerformed = uvReq === 'required' || (uvReq === 'preferred' && !!opts?.uvPerformed);
- // 6. Sign count (always 0 for syncable credentials)
- const signCount = new Uint8Array([0, 0, 0, 0]);
+ const clientDataJSON = PasskeyAuthenticator.clientDataJSON('webauthn.create', req.publicKey.challenge, req.origin);
- // 7. Build attested credential data
- const credIdLenBytes = new Uint8Array([(credentialIdBytes.length >> 8) & 0xff, credentialIdBytes.length & 0xff]);
- const attestedCredData = PasskeyAuthenticator.concat(PasskeyAuthenticator.AAGUID, credIdLenBytes, credentialIdBytes, coseKey);
+ // "direct" and "enterprise" get packed self-attestation over the client data; "none" and "indirect" get none.
+ const attestation = req.publicKey.attestation || 'none';
+ const selfAttestationClientDataHash = attestation === 'none' || attestation === 'indirect' ? undefined : await PasskeyAuthenticator.sha256(clientDataJSON);
- // 8. Build authenticator data
- const authenticatorData = PasskeyAuthenticator.concat(rpIdHash, new Uint8Array([flags]), signCount, attestedCredData);
-
- // 9. Build client data JSON
- const challengeB64u = PasskeyAuthenticator.challengeToB64u(req.publicKey.challenge);
- const clientDataObj = {
- type: 'webauthn.create',
- challenge: challengeB64u,
- origin: req.origin,
- crossOrigin: false
- };
- const clientDataJSONStr = JSON.stringify(clientDataObj);
- const clientDataJSONBytes = PasskeyAuthenticator.te(clientDataJSONStr);
+ const prfInputs = opts?.enablePrf && opts.prfInputs
+ ? { first: PasskeyHelper.base64urlToBytes(opts.prfInputs.first), second: opts.prfInputs.second ? PasskeyHelper.base64urlToBytes(opts.prfInputs.second) : undefined }
+ : undefined;
- // 10. Build attestation object
- const attPref = req.publicKey.attestation || 'none';
- const attObjBytes =
- attPref === 'none' || attPref === 'indirect'
- ? PasskeyAuthenticator.buildAttObjNone(authenticatorData)
- : await PasskeyAuthenticator.buildAttObjPackedSelf(authenticatorData, clientDataJSONBytes, keyPair.privateKey, alg);
+ const created = await passkeyCreate({
+ credentialId: credentialIdBytes,
+ rpId,
+ algorithm,
+ uvPerformed,
+ enablePrf: !!opts?.enablePrf,
+ prfInputs,
+ selfAttestationClientDataHash
+ });
- // 11. Process user ID
let userIdB64: string | null = null;
if (req.publicKey.user?.id) {
userIdB64 = typeof req.publicKey.user.id === 'string'
? req.publicKey.user.id
- : PasskeyAuthenticator.toB64(req.publicKey.user.id instanceof Uint8Array ? req.publicKey.user.id : new Uint8Array(req.publicKey.user.id));
- }
-
- // 12. Generate PRF secret if requested
- let prfSecret: string | undefined;
- let prfEnabled = false;
- let prfResults: { first: ArrayBuffer; second?: ArrayBuffer } | undefined;
- if (opts?.enablePrf) {
- const prfSecretBytes = new Uint8Array(32);
- crypto.getRandomValues(prfSecretBytes);
- prfSecret = PasskeyAuthenticator.toB64u(prfSecretBytes);
- prfEnabled = true;
-
- // 13. Evaluate PRF values if requested during registration
- if (opts?.prfInputs) {
- const firstSalt = PasskeyAuthenticator.fromB64u(opts.prfInputs.first);
- prfResults = {
- first: await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, firstSalt)
- };
-
- if (opts.prfInputs.second) {
- const secondSalt = PasskeyAuthenticator.fromB64u(opts.prfInputs.second);
- prfResults.second = await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, secondSalt);
- }
- }
+ : PasskeyHelper.arrayBufferToBase64(req.publicKey.user.id);
}
- // 14. Build stored record
+ const credentialIdB64u = PasskeyHelper.bytesToBase64url(credentialIdBytes);
const stored: StoredPasskeyRecord = {
rpId,
credentialId: credentialIdB64u,
- publicKey: pubJwk,
- privateKey: prvJwk,
+ publicKey: JSON.parse(created.publicKeyJwk) as JsonWebKey,
+ privateKey: JSON.parse(created.privateKeyJwk) as JsonWebKey,
userId: userIdB64,
userName: req.publicKey.user?.name,
userDisplayName: req.publicKey.user?.displayName,
- prfSecret
+ prfSecret: created.prfSecret ? PasskeyHelper.bytesToBase64url(created.prfSecret) : undefined
};
- // 15. Build credential response
const credential = {
id: credentialIdB64u,
rawId: credentialIdB64u,
response: {
- clientDataJSON: PasskeyAuthenticator.toB64u(clientDataJSONBytes),
- attestationObject: PasskeyAuthenticator.toB64u(attObjBytes)
+ clientDataJSON: PasskeyHelper.bytesToBase64url(clientDataJSON),
+ attestationObject: PasskeyHelper.bytesToBase64url(created.attestationObject),
+ authenticatorData: PasskeyHelper.bytesToBase64url(created.authenticatorData),
+ publicKey: PasskeyHelper.bytesToBase64url(created.publicKeySpki),
+ publicKeyAlgorithm: algorithm
},
type: 'public-key' as const
};
- return { credential, stored, prfEnabled, prfResults };
+ return { credential, stored, prfEnabled: !!opts?.enablePrf, prfResults: PasskeyAuthenticator.prfResults(created.prfResults) };
}
/**
@@ -200,403 +101,99 @@ export class PasskeyAuthenticator {
public static async getAssertion(
req: GetRequest,
storedRecord: StoredPasskeyRecord,
- opts?: { uvPerformed?: boolean; includeBEBS?: boolean; prfInputs?: { first: ArrayBuffer | Uint8Array; second?: ArrayBuffer | Uint8Array } }
+ opts?: { uvPerformed?: boolean; prfInputs?: { first: ArrayBuffer | Uint8Array; second?: ArrayBuffer | Uint8Array } }
): Promise<PasskeyAssertionResult> {
const rec = storedRecord;
-
- // 1. Compute RP ID hash
const rpId = req.publicKey.rpId || new URL(req.origin).hostname;
- const rpIdHash = new Uint8Array(await crypto.subtle.digest('SHA-256', PasskeyAuthenticator.te(rpId) as BufferSource));
-
- // 2. Build authenticator flags.
- let flags = 0x01; // UP (bit 0)
/*
- * An omitted userVerification defaults to "preferred" per the WebAuthn spec (not
- * "discouraged"), and this authenticator always performs UV, so set the UV flag for
- * required/preferred. RPs that registered with UV "required" reject UV=0 assertions.
+ * An omitted userVerification defaults to "preferred" per the WebAuthn spec (not "discouraged"), and this
+ * authenticator always performs UV, so set the UV flag for required/preferred. RPs that registered with UV
+ * "required" reject UV=0 assertions.
*/
const uvReq = req.publicKey.userVerification ?? 'preferred';
- const uvPerformed = !!opts?.uvPerformed;
- if (uvReq === 'required' || (uvReq === 'preferred' && uvPerformed)) {
- flags |= 0x04; // UV (bit 2)
- }
- if (opts?.includeBEBS ?? true) {
- flags |= 0x08; // BE (bit 3)
- flags |= 0x10; // BS (bit 4)
- }
-
- // 3. Sign count (always 0 for syncable credentials)
- const signCount = new Uint8Array([0, 0, 0, 0]);
-
- // 4. Build authenticator data
- const authenticatorData = PasskeyAuthenticator.concat(rpIdHash, new Uint8Array([flags]), signCount);
-
- // 5. Build client data JSON
- const challengeB64u = PasskeyAuthenticator.challengeToB64u(req.publicKey.challenge);
- const clientDataObj = {
- type: 'webauthn.get',
- challenge: challengeB64u,
- origin: req.origin,
- crossOrigin: false
- };
- const clientDataJSONStr = JSON.stringify(clientDataObj);
- const clientDataJSONBytes = PasskeyAuthenticator.te(clientDataJSONStr);
-
- // 6. Build data to sign: authenticatorData || clientDataHash
- const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', clientDataJSONBytes as BufferSource));
- const toSign = PasskeyAuthenticator.concat(authenticatorData, clientDataHash);
+ const uvPerformed = uvReq === 'required' || (uvReq === 'preferred' && !!opts?.uvPerformed);
- /*
- * 7. Determine algorithm from the stored key, import it, and sign.
- * The signature is already in the form the RP expects (DER for ES256, raw for RS256).
- */
- const alg = rec.privateKey.kty === 'RSA' ? PasskeyAuthenticator.ALG_RS256 : PasskeyAuthenticator.ALG_ES256;
- const privateKey = await crypto.subtle.importKey(
- 'jwk',
- rec.privateKey,
- PasskeyAuthenticator.keyImportParams(alg),
- false,
- ['sign']
- );
- const signature = await PasskeyAuthenticator.sign(privateKey, toSign, alg);
+ const clientDataJSON = PasskeyAuthenticator.clientDataJSON('webauthn.get', req.publicKey.challenge, req.origin);
+ const prfInputs = opts?.prfInputs && rec.prfSecret
+ ? { first: PasskeyAuthenticator.bytes(opts.prfInputs.first), second: opts.prfInputs.second ? PasskeyAuthenticator.bytes(opts.prfInputs.second) : undefined }
+ : undefined;
- // 9. Process user handle
- let userHandleB64u: string | null = null;
- if (rec.userId) {
- userHandleB64u = rec.userId.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
- }
-
- // 10. Evaluate PRF if requested
- let prfResults: { first: ArrayBuffer; second?: ArrayBuffer } | undefined;
- if (opts?.prfInputs && rec.prfSecret) {
- const prfSecretBytes = PasskeyAuthenticator.fromB64u(rec.prfSecret);
-
- const firstResult = await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, opts.prfInputs.first);
- prfResults = { first: firstResult };
-
- if (opts.prfInputs.second) {
- const secondResult = await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, opts.prfInputs.second);
- prfResults.second = secondResult;
- }
- }
+ const assertion = await passkeyGetAssertion({
+ rpId,
+ clientDataHash: await PasskeyAuthenticator.sha256(clientDataJSON),
+ privateKeyJwk: JSON.stringify(rec.privateKey),
+ uvPerformed,
+ prfInputs,
+ prfSecret: rec.prfSecret ? PasskeyHelper.base64urlToBytes(rec.prfSecret) : undefined
+ });
return {
id: rec.credentialId,
rawId: rec.credentialId,
- clientDataJSON: PasskeyAuthenticator.toB64u(clientDataJSONBytes),
- authenticatorData: PasskeyAuthenticator.toB64u(authenticatorData),
- signature: PasskeyAuthenticator.toB64u(signature),
- userHandle: userHandleB64u,
- prfResults
+ clientDataJSON: PasskeyHelper.bytesToBase64url(clientDataJSON),
+ authenticatorData: PasskeyHelper.bytesToBase64url(assertion.authenticatorData),
+ signature: PasskeyHelper.bytesToBase64url(assertion.signature),
+ userHandle: rec.userId ? rec.userId.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') : null,
+ prfResults: PasskeyAuthenticator.prfResults(assertion.prfResults)
};
}
- // MARK: - PRF Extension
-
- /**
- * Evaluate PRF (hmac-secret extension).
- * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt)).
- */
- private static async evaluatePrf(prfSecretBytes: Uint8Array, salt: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {
- const saltBytes = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
-
- const prefix = PasskeyAuthenticator.te('WebAuthn PRF\x00');
- const domainSeparatedSalt = PasskeyAuthenticator.concat(prefix, saltBytes);
- const hashedSalt = await crypto.subtle.digest('SHA-256', domainSeparatedSalt as BufferSource);
-
- const hmacKey = await crypto.subtle.importKey(
- 'raw',
- prfSecretBytes as BufferSource,
- { name: 'HMAC', hash: 'SHA-256' },
- false,
- ['sign']
- );
-
- const prfOutput = await crypto.subtle.sign('HMAC', hmacKey, hashedSalt);
-
- return prfOutput;
- }
-
- // MARK: - CBOR Encoding
-
/**
- * Pick a supported credential algorithm from the RP's pubKeyCredParams.
- * Honors the RP's preference order and returns the first algorithm we support.
- * Defaults to ES256 when the RP provides no params.
+ * The credential algorithm for the RP's pubKeyCredParams, in the RP's order; ES256 when it lists none.
* @param params - Public key credential parameters
* @returns COSE algorithm identifier (-7 for ES256, -257 for RS256)
*/
- private static pickSupportedAlgorithm(params?: Array<{ type: 'public-key'; alg: number }>): number {
+ private static async pickAlgorithm(params?: Array<{ type: 'public-key'; alg: number }>): Promise<number> {
if (!params || params.length === 0) {
- return PasskeyAuthenticator.ALG_ES256;
- }
- for (const p of params) {
- if (p.type === 'public-key' && PasskeyAuthenticator.SUPPORTED_ALGORITHMS.includes(p.alg)) {
- return p.alg;
- }
- }
- throw new Error('No supported algorithm (ES256, RS256) in pubKeyCredParams');
- }
-
- /**
- * WebCrypto key generation parameters for a COSE algorithm.
- */
- private static keyGenParams(alg: number): EcKeyGenParams | RsaHashedKeyGenParams {
- if (alg === PasskeyAuthenticator.ALG_RS256) {
- return {
- name: 'RSASSA-PKCS1-v1_5',
- modulusLength: 2048,
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
- hash: 'SHA-256'
- };
- }
- return { name: 'ECDSA', namedCurve: 'P-256' };
- }
-
- /**
- * WebCrypto key import parameters for a COSE algorithm.
- */
- private static keyImportParams(alg: number): EcKeyImportParams | RsaHashedImportParams {
- if (alg === PasskeyAuthenticator.ALG_RS256) {
- return { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
- }
- return { name: 'ECDSA', namedCurve: 'P-256' };
- }
-
- /**
- * Sign data with the given private key, returning the signature in the encoding
- * the RP expects: DER-encoded for ES256, raw PKCS#1 v1.5 for RS256.
- */
- private static async sign(privateKey: CryptoKey, data: Uint8Array, alg: number): Promise<Uint8Array> {
- if (alg === PasskeyAuthenticator.ALG_RS256) {
- return new Uint8Array(
- await crypto.subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, data as BufferSource)
- );
+ return passkeyPickAlgorithm([]);
}
- const rawSig = new Uint8Array(
- await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, data as BufferSource)
- );
- return PasskeyAuthenticator.ecdsaRawToDer(rawSig);
- }
-
- /**
- * Build COSE EC2 public key for ES256.
- * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}.
- */
- private static buildCoseEc2Es256(jwk: JsonWebKey): Uint8Array {
- const x = PasskeyAuthenticator.pad32(PasskeyAuthenticator.fromB64u(jwk.x!));
- const y = PasskeyAuthenticator.pad32(PasskeyAuthenticator.fromB64u(jwk.y!));
-
- return new Uint8Array([
- 0xa5,
- 0x01, 0x02, // 1: 2 (kty: EC2)
- 0x03, 0x26, // 3: -7 (alg: ES256)
- 0x20, 0x01, // -1: 1 (crv: P-256)
- 0x21, 0x58, 0x20, ...x, // -2: bytes(32) for x
- 0x22, 0x58, 0x20, ...y // -3: bytes(32) for y
- ]);
- }
-
- /**
- * Build COSE RSA public key for RS256 (RFC 8230).
- * CBOR map: {1: 3 (kty: RSA), 3: -257 (alg: RS256), -1: n (modulus), -2: e (exponent)}.
- */
- private static buildCoseRsaRs256(jwk: JsonWebKey): Uint8Array {
- const n = PasskeyAuthenticator.fromB64u(jwk.n!);
- const e = PasskeyAuthenticator.fromB64u(jwk.e!);
-
- return PasskeyAuthenticator.concat(
- new Uint8Array([0xa4]), // map of 4 pairs
- new Uint8Array([0x01, 0x03]), // 1: 3 (kty: RSA)
- new Uint8Array([0x03]), PasskeyAuthenticator.cborInt(PasskeyAuthenticator.ALG_RS256), // 3: -257 (alg: RS256)
- new Uint8Array([0x20]), PasskeyAuthenticator.cborBstr(n), // -1: modulus n
- new Uint8Array([0x21]), PasskeyAuthenticator.cborBstr(e) // -2: exponent e
- );
- }
-
- /**
- * Build attestation object with "none" format.
- * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}.
- */
- private static buildAttObjNone(authenticatorData: Uint8Array): Uint8Array {
- const fmtKey = PasskeyAuthenticator.cborText('fmt');
- const fmtVal = PasskeyAuthenticator.cborText('none');
- const attStmtKey = PasskeyAuthenticator.cborText('attStmt');
- const attStmtVal = new Uint8Array([0xa0]);
- const authDataKey = PasskeyAuthenticator.cborText('authData');
- const authDataVal = PasskeyAuthenticator.cborBstr(authenticatorData);
-
- return PasskeyAuthenticator.concat(
- new Uint8Array([0xa3]),
- fmtKey, fmtVal,
- attStmtKey, attStmtVal,
- authDataKey, authDataVal
- );
- }
-
- /**
- * Build "packed" self-attestation object (no x5c).
- */
- private static async buildAttObjPackedSelf(
- authenticatorData: Uint8Array,
- clientDataJSON: Uint8Array,
- privateKey: CryptoKey,
- alg: number
- ): Promise<Uint8Array> {
- const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', clientDataJSON as BufferSource));
- const toSign = PasskeyAuthenticator.concat(authenticatorData, clientDataHash);
- const sig = await PasskeyAuthenticator.sign(privateKey, toSign, alg);
-
- const attStmtMap = PasskeyAuthenticator.concat(
- PasskeyAuthenticator.cborText('alg'), PasskeyAuthenticator.cborInt(alg),
- PasskeyAuthenticator.cborText('sig'), PasskeyAuthenticator.cborBstr(sig)
- );
- const attStmt = PasskeyAuthenticator.concat(new Uint8Array([0xa2]), attStmtMap);
-
- const fmtKey = PasskeyAuthenticator.cborText('fmt');
- const fmtVal = PasskeyAuthenticator.cborText('packed');
- const attStmtKey = PasskeyAuthenticator.cborText('attStmt');
- const authDataKey = PasskeyAuthenticator.cborText('authData');
- const authDataVal = PasskeyAuthenticator.cborBstr(authenticatorData);
-
- return PasskeyAuthenticator.concat(
- new Uint8Array([0xa3]),
- fmtKey, fmtVal,
- attStmtKey, attStmt,
- authDataKey, authDataVal
- );
- }
-
- /**
- * Encode a string as CBOR text.
- */
- private static cborText(s: string): Uint8Array {
- const bytes = PasskeyAuthenticator.te(s);
- if (bytes.length <= 23) {
- return new Uint8Array([0x60 | bytes.length, ...bytes]);
- }
- if (bytes.length <= 0xff) {
- return new Uint8Array([0x78, bytes.length, ...bytes]);
+ const publicKeyAlgorithms = params.filter(p => p.type === 'public-key').map(p => p.alg);
+ if (publicKeyAlgorithms.length === 0) {
+ throw new Error('No supported algorithm (ES256, RS256) in pubKeyCredParams');
}
- return new Uint8Array([0x79, (bytes.length >> 8) & 0xff, bytes.length & 0xff, ...bytes]);
+ return passkeyPickAlgorithm(publicKeyAlgorithms);
}
/**
- * Encode an integer as CBOR (major type 0 for non-negative, 1 for negative).
- * Used for COSE algorithm identifiers, e.g. -7 (ES256) and -257 (RS256).
+ * The client data JSON bytes of a ceremony.
+ * @param type - The ceremony type
+ * @param challenge - The RP's challenge
+ * @param origin - The calling origin
+ * @returns The UTF-8 JSON bytes
*/
- private static cborInt(value: number): Uint8Array {
- /*
- * Major type 0 (positive) uses the value directly; major type 1 (negative)
- * encodes -1 - value (so -7 -> 6, -257 -> 256) under the 0x20 prefix.
- */
- const major = value < 0 ? 0x20 : 0x00;
- const n = value < 0 ? -1 - value : value;
- if (n <= 23) {
- return new Uint8Array([major | n]);
- }
- if (n <= 0xff) {
- return new Uint8Array([major | 0x18, n]);
- }
- return new Uint8Array([major | 0x19, (n >> 8) & 0xff, n & 0xff]);
+ private static clientDataJSON(type: 'webauthn.create' | 'webauthn.get', challenge: ArrayBuffer | Uint8Array | string, origin: string): Uint8Array {
+ return new TextEncoder().encode(JSON.stringify({ type, challenge: PasskeyAuthenticator.challengeToB64u(challenge), origin, crossOrigin: false }));
}
/**
- * Encode bytes as CBOR byte string.
+ * PRF results from the Rust core in the shape the callers expect.
+ * @param results - The PRF outputs, or null
+ * @returns The outputs as ArrayBuffers
*/
- private static cborBstr(b: Uint8Array): Uint8Array {
- if (b.length <= 23) {
- return new Uint8Array([0x40 | b.length, ...b]);
+ private static prfResults(results: PasskeyPrfResults | null): { first: ArrayBuffer; second?: ArrayBuffer } | undefined {
+ if (!results) {
+ return undefined;
}
- if (b.length <= 0xff) {
- return new Uint8Array([0x58, b.length, ...b]);
- }
- return new Uint8Array([0x59, (b.length >> 8) & 0xff, b.length & 0xff, ...b]);
+ return { first: results.first.slice().buffer, second: results.second ? results.second.slice().buffer : undefined };
}
- // MARK: - Signature Conversion
-
/**
- * Convert raw ECDSA signature (r|s, 64 bytes) to DER SEQUENCE.
+ * SHA-256 of bytes.
+ * @param bytes - The bytes to hash
+ * @returns The digest
*/
- private static ecdsaRawToDer(raw: Uint8Array): Uint8Array {
- if (raw.length !== 64) {
- throw new Error('Unexpected ECDSA signature length');
- }
- const r = raw.slice(0, 32);
- const s = raw.slice(32, 64);
- const rDer = PasskeyAuthenticator.derInt(r);
- const sDer = PasskeyAuthenticator.derInt(s);
- return new Uint8Array([0x30, rDer.length + sDer.length, ...rDer, ...sDer]);
- }
-
- /**
- * Encode a positive big integer as DER INTEGER.
- */
- private static derInt(src: Uint8Array): Uint8Array {
- let i = 0;
- while (i < src.length - 1 && src[i] === 0x00) {
- i++;
- }
- let v = src.slice(i);
- if ((v[0] & 0x80) !== 0) {
- const padded = new Uint8Array(v.length + 1);
- padded[0] = 0x00;
- padded.set(v, 1);
- v = padded;
- }
- return new Uint8Array([0x02, v.length, ...v]);
- }
-
- // MARK: - Base64 Encoding
-
- /**
- * UTF-8 encode string to bytes.
- * @param s - String to encode
- * @returns Encoded bytes
- */
- private static te(s: string): Uint8Array {
- const encoder = new TextEncoder();
- return encoder.encode(s);
- }
-
- /**
- * Base64 encode bytes.
- * @param bytes - Bytes to encode
- * @returns Base64 string
- */
- private static toB64(bytes: Uint8Array): string {
- let bin = '';
- for (let i = 0; i < bytes.length; i++) {
- bin += String.fromCharCode(bytes[i]);
- }
- return btoa(bin);
- }
-
- /**
- * Base64url encode bytes.
- * @param bytes - Bytes to encode
- * @returns Base64url string
- */
- private static toB64u(bytes: Uint8Array): string {
- return PasskeyAuthenticator.toB64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
+ private static async sha256(bytes: Uint8Array): Promise<Uint8Array> {
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as BufferSource));
}
/**
- * Base64url decode to bytes.
- * @param b64u - Base64url string
- * @returns Decoded bytes
+ * Bytes of an ArrayBuffer or Uint8Array.
+ * @param value - The buffer
+ * @returns The bytes
*/
- private static fromB64u(b64u: string): Uint8Array {
- const b64 = b64u.replace(/-/g, '+').replace(/_/g, '/');
- const pad = b64.length % 4 === 2 ? '==' : b64.length % 4 === 3 ? '=' : '';
- const s = atob(b64 + pad);
- const out = new Uint8Array(s.length);
- for (let i = 0; i < s.length; i++) {
- out[i] = s.charCodeAt(i);
- }
- return out;
+ private static bytes(value: ArrayBuffer | Uint8Array): Uint8Array {
+ return value instanceof Uint8Array ? value : new Uint8Array(value);
}
/**
@@ -608,38 +205,7 @@ export class PasskeyAuthenticator {
if (typeof challenge === 'string') {
return challenge.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
- const bytes = challenge instanceof Uint8Array ? challenge : new Uint8Array(challenge);
- return PasskeyAuthenticator.toB64u(bytes);
- }
-
- /**
- * Left-pad to 32 bytes for P-256 coordinates.
- * @param b - Bytes to pad
- * @returns Padded bytes
- */
- private static pad32(b: Uint8Array): Uint8Array {
- if (b.length === 32) {
- return b;
- }
- const out = new Uint8Array(32);
- out.set(b, 32 - b.length);
- return out;
- }
-
- /**
- * Concatenate typed arrays.
- * @param chunks - Arrays to concatenate
- * @returns Concatenated array
- */
- private static concat(...chunks: Uint8Array[]): Uint8Array {
- const total = chunks.reduce((s, c) => s + c.length, 0);
- const out = new Uint8Array(total);
- let o = 0;
- for (const c of chunks) {
- out.set(c, o);
- o += c.length;
- }
- return out;
+ return PasskeyHelper.bytesToBase64url(PasskeyAuthenticator.bytes(challenge));
}
}
@@ -654,6 +220,12 @@ export type PasskeyCreationResult = {
response: {
clientDataJSON: string;
attestationObject: string;
+ /** The authenticator data inside the attestation object (base64url). */
+ authenticatorData: string;
+ /** The public key as DER SubjectPublicKeyInfo (base64url). */
+ publicKey: string;
+ /** The COSE algorithm of the key. */
+ publicKeyAlgorithm: number;
};
type: 'public-key';
};
diff --git a/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts b/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts
index 0883a870f..f4b3ba640 100644
--- a/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts
+++ b/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts
@@ -1,14 +1,5 @@
/**
- * PasskeyHelper
- * -------------------------
- * Utility class for passkey-related operations, including GUID/base64url conversions.
- *
- * This is the reference implementation. Platform-specific ports of this class:
- * - iOS: apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyHelper.swift
- * - Android: apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
+ * Credential id conversions between GUID text, bytes and base64url, plus the base64 helpers of the passkey flow.
*/
export class PasskeyHelper {
/**
@@ -102,10 +93,10 @@ export class PasskeyHelper {
}
/**
- * Convert ArrayBuffer to base64 string (standard base64, not URL-safe)
+ * Convert bytes to a standard (not URL-safe) base64 string
*/
- public static arrayBufferToBase64(buffer: ArrayBuffer): string {
- const bytes = new Uint8Array(buffer);
+ public static arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string {
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
diff --git a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts
index 828ba324e..350917980 100644
--- a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts
+++ b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts
@@ -682,47 +682,6 @@ describe('PasskeyAuthenticator', () => {
expect(assertion.userHandle).toBeNull();
});
- it('should not set BE/BS flags when includeBEBS is false', async () => {
- // Create passkey
- const createRequest: CreateRequest = {
- origin: 'https://example.com',
- publicKey: {
- challenge: 'create-challenge',
- pubKeyCredParams: [{ type: 'public-key', alg: -7 }]
- }
- };
-
- const credentialIdBytes = crypto.getRandomValues(new Uint8Array(16));
- const createResult = await PasskeyAuthenticator.createPasskey(credentialIdBytes, createRequest);
- storedPasskeys.set(createResult.credential.id, createResult.stored);
-
- // Authenticate without BE/BS flags
- const getRequest: GetRequest = {
- origin: 'https://example.com',
- publicKey: {
- challenge: 'auth-challenge'
- }
- };
-
- const storedRecord = storedPasskeys.get(createResult.credential.id)!;
- const assertion = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {
- includeBEBS: false
- });
-
- // Decode authenticatorData and check flags
- const authDataBytes = Uint8Array.from(fromBase64url(assertion.authenticatorData), c => c.charCodeAt(0));
- const flags = authDataBytes[32];
-
- // Should not have BE (0x08) or BS (0x10) set
- expect(flags & 0x08).toBe(0x00);
- expect(flags & 0x10).toBe(0x00);
-
- // Should still have UP (0x01) set
- expect(flags & 0x01).toBe(0x01);
- });
- });
-
- describe('Storage callbacks verification', () => {
it('should call store callback with userId when creating passkey', async () => {
const userIdBytes = new Uint8Array([10, 20, 30, 40]);
const createRequest: CreateRequest = {
@@ -850,6 +809,52 @@ describe('PasskeyAuthenticator', () => {
});
describe('Cross-verification', () => {
+ it.each([
+ { alg: -7, importParams: { name: 'ECDSA', namedCurve: 'P-256' } as EcKeyImportParams, verifyParams: { name: 'ECDSA', hash: 'SHA-256' } as EcdsaParams },
+ { alg: -257, importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as RsaHashedImportParams, verifyParams: { name: 'RSASSA-PKCS1-v1_5' } as AlgorithmIdentifier }
+ ])('should hand the page the authenticator data, SPKI public key and algorithm for alg $alg', async ({ alg, importParams, verifyParams }) => {
+ const createRequest: CreateRequest = {
+ origin: 'https://example.com',
+ publicKey: {
+ rp: { id: 'example.com' },
+ challenge: 'create-challenge',
+ pubKeyCredParams: [{ type: 'public-key', alg }]
+ }
+ };
+
+ const createResult = await PasskeyAuthenticator.createPasskey(crypto.getRandomValues(new Uint8Array(16)), createRequest);
+ const { response } = createResult.credential;
+ expect(response.publicKeyAlgorithm).toBe(alg);
+
+ // The authenticator data is the tail of the attestation object, after its authData byte-string header.
+ const attestationObject = fromBase64url(response.attestationObject);
+ expect(attestationObject.endsWith(fromBase64url(response.authenticatorData))).toBe(true);
+
+ // The SPKI key verifies an assertion made with the stored private key.
+ const spki = Uint8Array.from(fromBase64url(response.publicKey), c => c.charCodeAt(0));
+ const publicKey = await crypto.subtle.importKey('spki', spki, importParams, false, ['verify']);
+ const getRequest: GetRequest = { origin: 'https://example.com', publicKey: { rpId: 'example.com', challenge: 'auth-challenge' } };
+ const assertion = await PasskeyAuthenticator.getAssertion(getRequest, createResult.stored);
+
+ const authData = Uint8Array.from(fromBase64url(assertion.authenticatorData), c => c.charCodeAt(0));
+ const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(fromBase64url(assertion.clientDataJSON))));
+ let signature = Uint8Array.from(fromBase64url(assertion.signature), c => c.charCodeAt(0));
+ if (alg === -7) {
+ // WebCrypto verifies ECDSA over raw r||s, not DER.
+ const rLength = signature[3];
+ const r = signature.slice(4, 4 + rLength);
+ const s = signature.slice(6 + rLength, 6 + rLength + signature[5 + rLength]);
+ /**
+ * One DER integer as 32 big-endian bytes.
+ * @param v - The integer bytes
+ * @returns The padded or trimmed bytes
+ */
+ const pad = (v: Uint8Array): Uint8Array => (v.length > 32 ? v.slice(v.length - 32) : new Uint8Array([...new Uint8Array(32 - v.length), ...v]));
+ signature = new Uint8Array([...pad(r), ...pad(s)]);
+ }
+ expect(await crypto.subtle.verify(verifyParams, publicKey, signature, new Uint8Array([...authData, ...clientDataHash]))).toBe(true);
+ });
+
it('should verify signature with public key', async () => {
// Create passkey
const createRequest: CreateRequest = {
diff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.ts
index a6ec2ba8c..f2f150ef4 100644
--- a/apps/browser-extension/src/utils/passkey/types.ts
+++ b/apps/browser-extension/src/utils/passkey/types.ts
@@ -11,6 +11,9 @@ export type PasskeyCreateCredentialResponse = {
rawId: string; // base64url (same as id for compatibility)
clientDataJSON: string; // base64url encoded client data JSON
attestationObject: string; // base64url encoded attestation object (CBOR)
+ authenticatorData: string; // base64url encoded authenticator data
+ publicKey: string; // base64url encoded DER SubjectPublicKeyInfo
+ publicKeyAlgorithm: number; // COSE algorithm of the key
extensions?: {
prf?: {
enabled: boolean;
diff --git a/apps/browser-extension/src/utils/passkey/webauthn.types.ts b/apps/browser-extension/src/utils/passkey/webauthn.types.ts
index 52c9663e6..06982c9e6 100644
--- a/apps/browser-extension/src/utils/passkey/webauthn.types.ts
+++ b/apps/browser-extension/src/utils/passkey/webauthn.types.ts
@@ -11,6 +11,9 @@ export type ProviderCreateCredential = {
rawId: string;
clientDataJSON: string;
attestationObject: string;
+ authenticatorData: string;
+ publicKey: string;
+ publicKeyAlgorithm: number;
extensions?: ProviderCreateCredentialExtensions;
};
diff --git a/apps/browser-extension/vitest.config.ts b/apps/browser-extension/vitest.config.ts
index c9124ceb0..033c94053 100644
--- a/apps/browser-extension/vitest.config.ts
+++ b/apps/browser-extension/vitest.config.ts
@@ -7,5 +7,6 @@ export default defineConfig({
],
test: {
exclude: ['**/node_modules/**', '**/tests/**'],
+ setupFiles: ['./vitest.setup.ts'],
},
});
diff --git a/apps/browser-extension/vitest.setup.ts b/apps/browser-extension/vitest.setup.ts
new file mode 100644
index 000000000..9bf0f8bcb
--- /dev/null
+++ b/apps/browser-extension/vitest.setup.ts
@@ -0,0 +1,4 @@
+/*
+ * The passkey tests run the real Rust core, so they need the same platform as the core/client unit tests.
+ */
+import '../../core/client/vitest.setup';
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
index 59d0afc6a..51d8eeb88 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
@@ -14,7 +14,7 @@ import net.aliasvault.app.autofill.models.FieldType
import net.aliasvault.app.autofill.utils.AutofillFieldMapper
import net.aliasvault.app.utils.TotpClipboard
import net.aliasvault.app.vaultstore.VaultStore
-import net.aliasvault.app.vaultstore.repositories.ItemUsageAction
+import uniffi.aliasvault_core.ItemUsageAction
/**
* Transparent activity launched by the OS when the user picks an autofill
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
index 21dcf8990..f12029dc4 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
@@ -3,7 +3,6 @@ package net.aliasvault.app.autofill.utils
import android.util.Log
import net.aliasvault.app.rustcore.JnaInitializer
import net.aliasvault.app.vaultstore.models.Item
-import net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo
import org.json.JSONArray
import org.json.JSONObject
@@ -104,83 +103,4 @@ object RustItemMatcher {
return emptyList()
}
}
-
- /**
- * Filter ItemWithCredentialInfo items based on rpId using the Rust core credential matcher.
- * Used during passkey registration to find existing credentials that can have a passkey merged into them.
- *
- * @param items List of items to filter (without passkeys).
- * @param rpId The relying party identifier (domain) to match against.
- * @param rpName The relying party name (used for title matching fallback).
- * @param matchingMode The matching mode to use (default: URL_SUBDOMAIN).
- * @return List of items that match the rpId, in priority order.
- */
- fun filterItemsForPasskeyMerge(
- items: List<ItemWithCredentialInfo>,
- rpId: String,
- rpName: String? = null,
- matchingMode: MatchingMode = MatchingMode.URL_SUBDOMAIN,
- ): List<ItemWithCredentialInfo> {
- // Early return for empty rpId or items
- if (rpId.isEmpty() || items.isEmpty()) {
- return emptyList()
- }
-
- try {
- // Convert items to JSON format expected by Rust
- val rustCredentials = JSONArray()
- val itemMap = mutableMapOf<String, ItemWithCredentialInfo>()
-
- for (item in items) {
- val idString = "${item.manifestId}${item.itemId}"
- val urlsArray = JSONArray()
- item.urls.forEach { urlsArray.put(it) }
-
- val credJson = JSONObject().apply {
- put("id", idString)
- put("itemName", item.serviceName ?: JSONObject.NULL)
- put("itemUrls", urlsArray)
- put("username", item.username ?: JSONObject.NULL)
- }
- rustCredentials.put(credJson)
- itemMap[idString] = item
- }
-
- // Prepare input JSON for Rust
- // Use https:// prefix for the rpId to match URL format
- val input = JSONObject().apply {
- put("credentials", rustCredentials)
- put("currentUrl", "https://$rpId")
- put("pageTitle", rpName ?: "")
- put("matchingMode", matchingMode.value)
- }
-
- // Call Rust via UniFFI
- val outputJson = uniffi.aliasvault_core.filterCredentialsJson(input.toString())
-
- // Parse output
- val output = JSONObject(outputJson)
- val matchedIds = output.getJSONArray("matchedIds")
-
- // If no matches found, return empty list
- if (matchedIds.length() == 0) {
- return emptyList()
- }
-
- // Convert matched IDs back to items, maintaining Rust's priority order
- val result = mutableListOf<ItemWithCredentialInfo>()
- for (i in 0 until matchedIds.length()) {
- val id = matchedIds.getString(i)
- itemMap[id]?.let {
- result.add(it)
- }
- }
-
- return result
- } catch (e: Exception) {
- Log.e(TAG, "Error filtering items for passkey merge: ${e.message}", e)
- // Return empty list on error
- return emptyList()
- }
- }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt
index 32ec62273..fbfb90909 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt
@@ -4,9 +4,8 @@ import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import net.aliasvault.app.utils.Helpers
-import net.aliasvault.app.vaultstore.models.Item
-import net.aliasvault.app.vaultstore.models.Passkey
-import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
+import net.aliasvault.app.vaultstore.PasskeyWithItem
+import net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator
import org.json.JSONArray
import org.json.JSONObject
@@ -98,11 +97,7 @@ class CredentialIdentityStore private constructor(context: Context) {
// This replaces the N+1 query pattern that was calling getPasskeysForItem() for each item
val passkeysWithItems = vaultStore.getAllPasskeysWithItems()
- passkeysWithItems.forEach { (passkey, item) ->
- if (!passkey.isDeleted) {
- passkeyIdentities.add(createPasskeyIdentity(passkey, item))
- }
- }
+ passkeysWithItems.forEach { passkeyIdentities.add(createPasskeyIdentity(it)) }
// Serialize to JSON and save
val jsonArray = JSONArray()
@@ -178,14 +173,15 @@ class CredentialIdentityStore private constructor(context: Context) {
}
/**
- * Create a PasskeyIdentity from a Passkey and its parent Item.
+ * Create a PasskeyIdentity from a passkey and the account of its item.
*/
- private fun createPasskeyIdentity(passkey: Passkey, item: Item): PasskeyIdentity {
- // Get userName - prefer passkey's userName, fallback to item's username or email fields
- val userName = passkey.userName ?: item.username ?: item.email
+ private fun createPasskeyIdentity(entry: PasskeyWithItem): PasskeyIdentity {
+ val passkey = entry.passkey
+ // Get userName - prefer passkey's userName, fallback to the item's username or email
+ val userName = passkey.userName ?: entry.username ?: entry.email
// Convert passkey ID to credential ID (base64url-encoded bytes)
- val credentialIdBytes = PasskeyHelper.guidToBytes(passkey.id.toString())
+ val credentialIdBytes = PasskeyAuthenticator.guidToBytes(passkey.id.toString())
val credentialId = Helpers.bytesToBase64url(credentialIdBytes)
// Convert user handle to base64url if present
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
index 981a91f4e..152ececd7 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
@@ -20,10 +20,9 @@ import net.aliasvault.app.utils.TotpClipboard
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator
-import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
-import net.aliasvault.app.vaultstore.repositories.ItemUsageAction
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import org.json.JSONObject
+import uniffi.aliasvault_core.ItemUsageAction
import java.security.MessageDigest
import java.util.UUID
@@ -242,7 +241,7 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
}
// Use PasskeyAuthenticator.getAssertion for signing
- val credentialId = PasskeyHelper.guidToBytes(passkey.id.toString())
+ val credentialId = PasskeyAuthenticator.guidToBytes(passkey.id.toString())
val prfInputs = extractPrfInputs(requestObj)
val assertion = PasskeyAuthenticator.getAssertion(
credentialId = credentialId,
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
index e2d5722a4..7cdec7c83 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
@@ -26,12 +26,11 @@ import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel
import net.aliasvault.app.exceptions.PasskeyOperationException
import net.aliasvault.app.exceptions.VaultOperationException
import net.aliasvault.app.utils.Helpers
+import net.aliasvault.app.vaultstore.ItemWithCredentialInfo
+import net.aliasvault.app.vaultstore.PasskeyWithItem
import net.aliasvault.app.vaultstore.VaultStore
-import net.aliasvault.app.vaultstore.mappers.PasskeyWithItem
import net.aliasvault.app.vaultstore.models.Passkey
import net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator
-import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
-import net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo
import net.aliasvault.app.webapi.WebApiService
import org.json.JSONObject
import java.util.Date
@@ -287,7 +286,7 @@ class PasskeyFormFragment : Fragment() {
// Generate passkey credentials
val passkeyId = UUID.randomUUID()
- val credentialId = PasskeyHelper.guidToBytes(passkeyId.toString())
+ val credentialId = PasskeyAuthenticator.guidToBytes(passkeyId.toString())
// Parse request to get challenge (for building response clientDataJSON later)
val requestObj = JSONObject(viewModel.requestJson)
@@ -494,7 +493,7 @@ class PasskeyFormFragment : Fragment() {
// Generate new passkey credentials
val newPasskeyId = UUID.randomUUID()
- val credentialId = PasskeyHelper.guidToBytes(newPasskeyId.toString())
+ val credentialId = PasskeyAuthenticator.guidToBytes(newPasskeyId.toString())
// Parse request to get challenge
val requestObj = JSONObject(viewModel.requestJson)
@@ -549,6 +548,7 @@ class PasskeyFormFragment : Fragment() {
vaultStore.replacePasskey(
oldPasskeyId = passkeyToReplace.passkey.id,
+ manifestId = requireNotNull(passkeyToReplace.passkey.manifestId),
newPasskey = newPasskey,
displayName = displayName,
url = url,
@@ -706,7 +706,7 @@ class PasskeyFormFragment : Fragment() {
// Generate passkey credentials
val passkeyId = UUID.randomUUID()
- val credentialId = PasskeyHelper.guidToBytes(passkeyId.toString())
+ val credentialId = PasskeyAuthenticator.guidToBytes(passkeyId.toString())
// Parse request to get challenge
val requestObj = JSONObject(viewModel.requestJson)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.kt
index 07cc2bcca..6e63a119f 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.kt
@@ -1,8 +1,8 @@
package net.aliasvault.app.credentialprovider.models
import androidx.lifecycle.ViewModel
-import net.aliasvault.app.vaultstore.mappers.PasskeyWithItem
-import net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo
+import net.aliasvault.app.vaultstore.ItemWithCredentialInfo
+import net.aliasvault.app.vaultstore.PasskeyWithItem
import java.util.UUID
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/DateHelpers.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/DateHelpers.kt
deleted file mode 100644
index 0d1148040..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/DateHelpers.kt
+++ /dev/null
@@ -1,110 +0,0 @@
-package net.aliasvault.app.utils
-
-import android.util.Log
-import java.text.SimpleDateFormat
-import java.util.Date
-import java.util.Locale
-import java.util.TimeZone
-
-/**
- * DateHelpers
- * -------------------------
- * Centralized utility for formatting Date values consistently across the client application.
- * All dates are stored in UTC with the format: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
- * This format ensures:
- * - SQLite native support for date functions
- * - No timezone ambiguity (all dates are UTC)
- * - Consistent precision with milliseconds for accurate sorting/comparison
- * - Readable space separator instead of 'T'
- * - Lexicographic sorting works correctly
- * Other platform implementations: DateHelpers.ts (core/client), DateHelpers.swift (iOS).
- */
-object DateHelpers {
- private const val TAG = "DateHelpers"
-
- /**
- * Standard date format for database storage: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
- */
- private const val STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"
-
- /**
- * Format a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
- *
- * @param date The Date to format
- * @return Formatted date-time string in format "yyyy-MM-dd HH:mm:ss.SSS"
- */
- fun toStandardFormat(date: Date): String {
- val formatter = SimpleDateFormat(STANDARD_FORMAT, Locale.US)
- formatter.timeZone = TimeZone.getTimeZone("UTC")
- return formatter.format(date)
- }
-
- /**
- * Format the current UTC time to the standard format string.
- *
- * @return Formatted current UTC date-time string
- */
- fun now(): String {
- return toStandardFormat(Date())
- }
-
- /**
- * Parse a date string to a Date object for use in queries.
- * Supports multiple formats for backward compatibility:
- * - "yyyy-MM-dd HH:mm:ss.SSS" (standard format with milliseconds)
- * - "yyyy-MM-dd HH:mm:ss" (standard format without milliseconds)
- * - "yyyy-MM-ddTHH:mm:ss.SSSZ" (ISO 8601 with milliseconds)
- * - "yyyy-MM-ddTHH:mm:ssZ" (ISO 8601 without milliseconds)
- *
- * @param dateString The date string to parse
- * @return Parsed Date or null if parsing fails
- */
- fun parseDateString(dateString: String?): Date? {
- if (dateString == null) {
- return null
- }
-
- // Normalize milliseconds to exactly 3 digits
- // Handles: 2025-10-20 13:48:10.4 -> 2025-10-20 13:48:10.400
- // 1992-10-21T23:49:44.336Z -> 1992-10-21T23:49:44.336Z (unchanged)
- // 2025-10-20 13:48:10 -> 2025-10-20 13:48:10 (unchanged)
- val normalizedDate = dateString.replace(
- Regex("""(\d{2}:\d{2}:\d{2})\.(\d{1,2})(?=[TZ\s]|$)"""),
- ) { matchResult ->
- val base = matchResult.groupValues[1]
- val millis = matchResult.groupValues[2].padEnd(3, '0')
- "$base.$millis"
- }
-
- // Try all supported formats
- val formats = listOf(
- // SQLite formats (local storage - most common, try first)
- SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).apply {
- timeZone = TimeZone.getTimeZone("UTC")
- },
- SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).apply {
- timeZone = TimeZone.getTimeZone("UTC")
- },
- // ISO 8601 formats (from server/API)
- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
- timeZone = TimeZone.getTimeZone("UTC")
- },
- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
- timeZone = TimeZone.getTimeZone("UTC")
- },
- )
-
- for (format in formats) {
- @Suppress("SwallowedException")
- try {
- return format.parse(normalizedDate)
- } catch (e: Exception) {
- // Try next format
- continue
- }
- }
-
- Log.e(TAG, "Error parsing date: $dateString (normalized: $normalizedDate)")
- return null
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
index cc7999649..3277e736b 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
@@ -176,6 +176,21 @@ class VaultDatabase(
connection().executeBatch("ROLLBACK")
}
+ /**
+ * Run [operation] in a transaction whose commit persists the vault and marks it dirty for [scope].
+ */
+ fun <T> withTransaction(scope: String = VaultMutationScope.MAIN, operation: (SqliteMemoryDatabase) -> T): T {
+ beginTransaction()
+ return try {
+ val result = operation(connection())
+ commitTransaction(scope)
+ result
+ } catch (e: Exception) {
+ rollbackTransaction()
+ throw e
+ }
+ }
+
/**
* Persist the in-memory database and mark it as changed locally, without committing a SQL transaction.
* Used after migrations, whose scripts manage their own transactions.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
index 293387f20..5d586bf39 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
@@ -1,91 +1,56 @@
package net.aliasvault.app.vaultstore
-import net.aliasvault.app.vaultstore.mappers.PasskeyWithItem
-import net.aliasvault.app.vaultstore.models.Item
import net.aliasvault.app.vaultstore.models.Passkey
-import net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo
-import net.aliasvault.app.vaultstore.repositories.PasskeyAndItem
-import net.aliasvault.app.vaultstore.repositories.PasskeyRepository
+import uniffi.aliasvault_core.NewPasskey
+import uniffi.aliasvault_core.PasskeyMergeCandidate
+import uniffi.aliasvault_core.VaultPasskeyWithItem
+import java.util.Date
import java.util.UUID
+import uniffi.aliasvault_core.VaultPasskey as StoredPasskey
/**
- * Handles passkey operations for the vault.
- * This class uses composition to organize passkey-specific functionality.
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
+ * Passkey reads and writes, run by the Rust core on the open vault database.
+ * Other platform implementations: VaultStore+Passkey.swift (iOS).
*/
class VaultPasskey(
- database: VaultDatabase,
+ private val database: VaultDatabase,
) {
- private val passkeyRepository = PasskeyRepository(database)
-
// region Passkey Queries
/**
- * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Item UUID).
- */
- fun getPasskeyByCredentialId(credentialId: ByteArray): Passkey? {
- return passkeyRepository.getByCredentialId(credentialId)
- }
-
- /**
- * Get all passkeys for an item.
+ * Get a passkey by its id (the WebAuthn credential id, not the parent item id), in any manifest.
*/
- fun getPasskeysForItem(itemId: UUID, manifestId: String): List<Passkey> {
- return passkeyRepository.getByItemId(itemId, manifestId)
+ fun getPasskeyById(passkeyId: UUID): Passkey? {
+ return database.connection().getPasskeyById(passkeyId.toString())?.let { toPasskey(it.passkey) }
}
/**
- * Get all passkeys for a specific relying party identifier (RP ID).
+ * Get passkeys with item info for an rpId, narrowed to an account when a user name or handle is given.
+ * Used for finding existing passkeys that might be replaced during registration.
*/
- fun getPasskeysForRpId(rpId: String): List<Passkey> {
- return passkeyRepository.getByRpId(rpId)
+ fun getPasskeysWithCredentialInfo(rpId: String, userName: String? = null, userId: ByteArray? = null): List<PasskeyWithItem> {
+ if (!database.isOpen()) return emptyList()
+ return database.connection().getPasskeysForRpId(rpId, userName, userId).mapNotNull(::toPasskeyWithItem)
}
/**
- * Get passkeys with item info for a specific rpId and optionally username.
- * Used for finding existing passkeys that might be replaced during registration.
+ * Get every passkey whose item is live, with the item's name and account.
*/
- fun getPasskeysWithCredentialInfo(
- rpId: String,
- userName: String? = null,
- userId: ByteArray? = null,
- ): List<PasskeyWithItem> {
- return passkeyRepository.getWithItem(rpId, userName, userId)
+ fun getAllPasskeysWithItems(): List<PasskeyWithItem> {
+ if (!database.isOpen()) return emptyList()
+ return database.connection().getAllPasskeysWithItems().mapNotNull(::toPasskeyWithItem)
}
/**
- * Get Items that match an rpId but don't have a passkey yet.
- * Used for finding existing credentials that could have a passkey added to them.
+ * Get the Login items without a passkey that match an rpId, best match first, which a new passkey could be added to.
*
* @param rpId The relying party identifier to match against the login URL.
* @param rpName The relying party name (used for title matching fallback).
* @param userName Optional username to filter by.
- * @return List of ItemWithCredentialInfo objects representing Items without passkeys.
*/
- fun getItemsWithoutPasskeyForRpId(
- rpId: String,
- rpName: String? = null,
- userName: String? = null,
- ): List<ItemWithCredentialInfo> {
- return passkeyRepository.getItemsWithoutPasskeyForRpId(rpId, rpName, userName)
- }
-
- /**
- * Get all passkeys with their associated items in a single query.
- * This is much more efficient than calling getPasskeysForItem() for each item.
- * Uses a JOIN to get passkeys and their items in one database query.
- */
- fun getAllPasskeysWithItems(): List<PasskeyAndItem> {
- return passkeyRepository.getAllWithItems()
- }
-
- /**
- * Get a passkey by its ID.
- */
- fun getPasskeyById(passkeyId: UUID): Passkey? {
- return passkeyRepository.getById(passkeyId)
+ fun getItemsWithoutPasskeyForRpId(rpId: String, rpName: String? = null, userName: String? = null): List<ItemWithCredentialInfo> {
+ if (!database.isOpen()) return emptyList()
+ return database.connection().getItemsWithoutPasskeyForRpId(rpId, rpName, userName).mapNotNull(::toItemWithCredentialInfo)
}
// endregion
@@ -93,78 +58,149 @@ class VaultPasskey(
// region Passkey Storage
/**
- * Create a new item with an associated passkey.
+ * Create a Login item in the personal manifest holding a new passkey.
*
* @param url The item's login URL, which the favicon was fetched for.
*/
- fun createItemWithPasskey(
- url: String,
- userName: String?,
- displayName: String,
- passkey: Passkey,
- logo: ByteArray? = null,
- ): Item {
- return passkeyRepository.createItemWithPasskey(url, userName, displayName, passkey, logo)
+ fun createItemWithPasskey(url: String, userName: String?, displayName: String, passkey: Passkey, logo: ByteArray? = null) {
+ val manifestId = database.getPersonalManifestId() ?: throw AppError.ManifestNotRecorded()
+ database.withTransaction { db ->
+ db.createItemWithPasskey(manifestId, passkey.parentItemId.toString(), displayName, url, userName, toNewPasskey(passkey, passkey.displayName), logo)
+ }
}
/**
- * Replace an existing passkey with a new one.
+ * Replace an existing passkey with a new one on the same item, in the same manifest.
*
* @param url The login URL the favicon was fetched for.
*/
- fun replacePasskey(
- oldPasskeyId: UUID,
- newPasskey: Passkey,
- displayName: String,
- url: String,
- logo: ByteArray? = null,
- ) {
- passkeyRepository.replace(oldPasskeyId, newPasskey, displayName, url, logo)
+ @Suppress("LongParameterList") // One argument per value the replacement writes
+ fun replacePasskey(oldPasskeyId: UUID, manifestId: String, newPasskey: Passkey, displayName: String, url: String, logo: ByteArray? = null) {
+ database.withTransaction { db ->
+ db.replacePasskey(oldPasskeyId.toString(), manifestId, toNewPasskey(newPasskey, displayName), url, logo)
+ }
}
/**
- * Add a passkey to an existing Item (merge passkey into existing credential).
+ * Add a passkey to an existing item (merge the passkey into an existing credential).
*
- * @param itemId The UUID of the existing Item to add the passkey to.
- * @param manifestId The manifest the item belongs to.
- * @param passkey The passkey to add.
* @param url The login URL the favicon was fetched for.
- * @param logo Optional logo to update/add.
*/
- fun addPasskeyToExistingItem(
- itemId: UUID,
- manifestId: String,
- passkey: Passkey,
- url: String,
- logo: ByteArray? = null,
- ) {
- passkeyRepository.addPasskeyToExistingItem(itemId, manifestId, passkey, url, logo)
+ fun addPasskeyToExistingItem(itemId: UUID, manifestId: String, passkey: Passkey, url: String, logo: ByteArray? = null) {
+ database.withTransaction { db ->
+ db.addPasskeyToItem(itemId.toString(), manifestId, toNewPasskey(passkey, passkey.displayName), url, logo)
+ }
+ }
+
+ // endregion
+
+ // region Mapping
+
+ private fun toPasskey(row: StoredPasskey): Passkey? {
+ return try {
+ Passkey(
+ id = UUID.fromString(row.id),
+ parentItemId = UUID.fromString(row.itemId),
+ manifestId = row.manifestId,
+ rpId = row.rpId,
+ userHandle = row.userHandle,
+ userName = null,
+ publicKey = row.publicKey.toByteArray(Charsets.UTF_8),
+ privateKey = row.privateKey.toByteArray(Charsets.UTF_8),
+ prfKey = row.prfKey,
+ displayName = row.displayName,
+ additionalData = row.additionalData,
+ createdAt = Date(row.createdAtMs),
+ updatedAt = Date(row.updatedAtMs),
+ isDeleted = false,
+ )
+ } catch (_: IllegalArgumentException) {
+ null
+ }
+ }
+
+ private fun toPasskeyWithItem(row: VaultPasskeyWithItem): PasskeyWithItem? {
+ val passkey = toPasskey(row.passkey) ?: return null
+ return PasskeyWithItem(passkey, row.serviceName, row.username, row.email)
+ }
+
+ private fun toItemWithCredentialInfo(row: PasskeyMergeCandidate): ItemWithCredentialInfo? {
+ return try {
+ ItemWithCredentialInfo(
+ itemId = UUID.fromString(row.itemId),
+ manifestId = row.manifestId,
+ serviceName = row.serviceName,
+ urls = row.urls,
+ username = row.username,
+ email = row.email,
+ hasPassword = row.hasPassword,
+ createdAt = Date(row.createdAtMs),
+ updatedAt = Date(row.updatedAtMs),
+ )
+ } catch (_: IllegalArgumentException) {
+ null
+ }
+ }
+
+ private fun toNewPasskey(passkey: Passkey, displayName: String): NewPasskey {
+ return NewPasskey(
+ id = passkey.id.toString(),
+ rpId = passkey.rpId,
+ userHandle = passkey.userHandle,
+ publicKey = String(passkey.publicKey, Charsets.UTF_8),
+ privateKey = String(passkey.privateKey, Charsets.UTF_8),
+ prfKey = passkey.prfKey,
+ displayName = displayName,
+ )
}
// endregion
}
/**
- * VaultPasskey-specific errors.
+ * A passkey with the name and account of the item it belongs to.
+ *
+ * @property passkey The passkey.
+ * @property serviceName The item name.
+ * @property username The item's login.username value.
+ * @property email The item's login.email value, used as display fallback when there is no username.
*/
-sealed class VaultPasskeyError(message: String) : Exception(message) {
- /**
- * Error indicating vault is not unlocked.
- */
- class VaultNotUnlocked(message: String) : VaultPasskeyError(message)
-
- /**
- * Error indicating passkey was not found.
- */
- class PasskeyNotFound(message: String) : VaultPasskeyError(message)
-
- /**
- * Error indicating item was not found.
- */
- class ItemNotFound(message: String) : VaultPasskeyError(message)
+data class PasskeyWithItem(
+ val passkey: Passkey,
+ val serviceName: String?,
+ val username: String?,
+ val email: String? = null,
+) {
+ /** The account identifier to display: the username, or the email when no username is set. */
+ val accountLabel: String?
+ get() = username?.takeIf { it.isNotBlank() } ?: email?.takeIf { it.isNotBlank() }
+}
- /**
- * Error indicating a database operation failure.
- */
- class DatabaseError(message: String) : VaultPasskeyError(message)
+/**
+ * A Login item without a passkey that a new passkey could be added to.
+ *
+ * @property itemId The UUID of the item.
+ * @property manifestId The manifest the item belongs to.
+ * @property serviceName The service name (Item.Name).
+ * @property urls All login URLs associated with this item.
+ * @property username The username from field values.
+ * @property email The email from field values, used as display fallback when there is no username.
+ * @property hasPassword Whether the item has a password.
+ * @property createdAt When the item was created.
+ * @property updatedAt When the item was last updated.
+ */
+data class ItemWithCredentialInfo(
+ val itemId: UUID,
+ val manifestId: String,
+ val serviceName: String?,
+ val urls: List<String>,
+ val username: String?,
+ val email: String? = null,
+ val hasPassword: Boolean,
+ val createdAt: Date,
+ val updatedAt: Date,
+) {
+ /** The account identifier to display: the username, or the email when no username is set. */
+ val accountLabel: String?
+ get() = username?.takeIf { it.isNotBlank() } ?: email?.takeIf { it.isNotBlank() }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 0c3ab786e..ec29b3b9e 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -7,14 +7,21 @@ import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
import net.aliasvault.app.vaultstore.interfaces.ItemOperationCallback
import net.aliasvault.app.vaultstore.keystoreprovider.BiometricAuthCallback
import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
+import net.aliasvault.app.vaultstore.models.BuiltinLogos
import net.aliasvault.app.vaultstore.models.Item
+import net.aliasvault.app.vaultstore.models.ItemField
import net.aliasvault.app.vaultstore.models.StoreVaultResult
import net.aliasvault.app.vaultstore.models.TotpCode
+import net.aliasvault.app.vaultstore.models.VaultDataBucketCategory
import net.aliasvault.app.vaultstore.models.VaultMutationScope
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import org.json.JSONObject
+import uniffi.aliasvault_core.ItemUsageAction
import uniffi.aliasvault_core.VaultException
+import uniffi.aliasvault_core.VaultItem
import uniffi.aliasvault_core.rsaDecrypt
+import java.util.Date
+import java.util.UUID
import kotlin.coroutines.resume
/**
@@ -122,8 +129,6 @@ class VaultStore(
private val crypto = VaultCrypto(keystoreProvider, storageProvider)
internal val metadata = VaultMetadataManager(storageProvider)
internal val database = VaultDatabase(storageProvider, crypto, metadata)
- private val itemRepository = net.aliasvault.app.vaultstore.repositories.ItemRepository(database)
- private val itemStatsRepository = net.aliasvault.app.vaultstore.repositories.ItemStatsRepository(database)
private val auth = VaultAuth(
storageProvider,
onClearCache = {
@@ -445,7 +450,7 @@ class VaultStore(
* as the autofill candidate list.
*/
fun getAllItems(): List<Item> {
- return itemRepository.getAll()
+ return database.connection().getAllActiveItems().mapNotNull(::toItem)
}
/**
@@ -458,7 +463,9 @@ class VaultStore(
return null
}
return try {
- itemRepository.getTotpForItem(itemId, manifestId)
+ database.connection().getTotpCodesForItem(itemId.lowercase(), manifestId).firstOrNull()?.let {
+ TotpCode(secretKey = it.secretKey, algorithm = it.algorithm, digits = it.digits.toInt(), period = it.period.toInt())
+ }
} catch (e: Exception) {
android.util.Log.e(TAG, "Error getting TOTP code for item", e)
null
@@ -469,8 +476,35 @@ class VaultStore(
* Record one use of an item (autofill, copy or passkey assertion) in its usage statistics.
* Persists the vault and marks it dirty, so the next sync pushes it.
*/
- fun recordItemUsage(itemId: String, manifestId: String, action: net.aliasvault.app.vaultstore.repositories.ItemUsageAction) {
- itemStatsRepository.recordUsage(itemId, manifestId, action)
+ fun recordItemUsage(itemId: String, manifestId: String, action: ItemUsageAction) {
+ // Usage statistics live in their own data bucket, pushed without a full manifest write.
+ database.withTransaction(VaultDataBucketCategory.STATS) { db -> db.recordItemUse(itemId.lowercase(), manifestId, action) }
+ }
+
+ /**
+ * An item from the Rust core as the model the autofill layer works with.
+ */
+ private fun toItem(row: VaultItem): Item? {
+ val id = runCatching { UUID.fromString(row.id) }.getOrNull() ?: return null
+ // A built-in logo carries no bytes: it is drawn from the shared catalog, keyed by its Source.
+ val logo = if (row.logoKind == "builtin") row.logoSource?.let { BuiltinLogos.svgFor(it) }?.toByteArray(Charsets.UTF_8) else row.logo
+ return Item(
+ id = id,
+ manifestId = row.manifestId,
+ name = row.name,
+ itemType = row.itemType,
+ logo = logo,
+ folderId = row.folderId?.let { runCatching { UUID.fromString(it) }.getOrNull() },
+ folderPath = row.folderPath.ifEmpty { null },
+ fields = row.fields.map {
+ ItemField(it.fieldKey, it.label, it.fieldType, it.value, it.isHidden, it.displayOrder.toInt(), it.isCustomField, it.enableHistory)
+ },
+ hasPasskey = row.hasPasskey,
+ hasAttachment = row.hasAttachment,
+ hasTotp = row.hasTotp,
+ createdAt = Date(row.createdAtMs),
+ updatedAt = Date(row.updatedAtMs),
+ )
}
/**
@@ -487,7 +521,7 @@ class VaultStore(
unlockVault()
}
- callback.onSuccess(itemRepository.getAll())
+ callback.onSuccess(getAllItems())
return true
} catch (e: Exception) {
android.util.Log.e(TAG, "Error retrieving items", e)
@@ -791,51 +825,24 @@ class VaultStore(
// region Passkey Methods
- /**
- * Get a passkey by its credential ID (the WebAuthn credential ID).
- */
- fun getPasskeyByCredentialId(credentialId: ByteArray): net.aliasvault.app.vaultstore.models.Passkey? {
- return passkey.getPasskeyByCredentialId(credentialId)
- }
-
- /**
- * Get all passkeys for an item.
- */
- fun getPasskeysForItem(itemId: java.util.UUID, manifestId: String): List<net.aliasvault.app.vaultstore.models.Passkey> {
- return passkey.getPasskeysForItem(itemId, manifestId)
- }
-
- /**
- * Get all passkeys for a specific relying party identifier (RP ID).
- */
- fun getPasskeysForRpId(
- rpId: String,
- ): List<net.aliasvault.app.vaultstore.models.Passkey> {
- return passkey.getPasskeysForRpId(rpId)
- }
-
/**
* Get passkeys with credential info for a specific rpId.
*/
- fun getPasskeysWithCredentialInfo(
- rpId: String,
- userName: String? = null,
- userId: ByteArray? = null,
- ): List<net.aliasvault.app.vaultstore.mappers.PasskeyWithItem> {
+ fun getPasskeysWithCredentialInfo(rpId: String, userName: String? = null, userId: ByteArray? = null): List<PasskeyWithItem> {
return passkey.getPasskeysWithCredentialInfo(rpId, userName, userId)
}
/**
- * Get all passkeys with their associated items in a single query.
+ * Get every passkey whose item is live, with the item's name and account.
*/
- fun getAllPasskeysWithItems(): List<net.aliasvault.app.vaultstore.repositories.PasskeyAndItem> {
+ fun getAllPasskeysWithItems(): List<PasskeyWithItem> {
return passkey.getAllPasskeysWithItems()
}
/**
- * Get a passkey by its ID.
+ * Get a passkey by its ID, in any manifest.
*/
- fun getPasskeyById(passkeyId: java.util.UUID): net.aliasvault.app.vaultstore.models.Passkey? {
+ fun getPasskeyById(passkeyId: UUID): net.aliasvault.app.vaultstore.models.Passkey? {
return passkey.getPasskeyById(passkeyId)
}
@@ -848,32 +855,30 @@ class VaultStore(
displayName: String,
passkeyObj: net.aliasvault.app.vaultstore.models.Passkey,
logo: ByteArray? = null,
- ): net.aliasvault.app.vaultstore.models.Item {
- return passkey.createItemWithPasskey(url, userName, displayName, passkeyObj, logo)
+ ) {
+ passkey.createItemWithPasskey(url, userName, displayName, passkeyObj, logo)
}
/**
- * Replace an existing passkey with a new one. The url names the domain the favicon was fetched for.
+ * Replace an existing passkey with a new one on the same item. The url names the domain the favicon was fetched for.
*/
+ @Suppress("LongParameterList") // One argument per value the replacement writes
fun replacePasskey(
- oldPasskeyId: java.util.UUID,
+ oldPasskeyId: UUID,
+ manifestId: String,
newPasskey: net.aliasvault.app.vaultstore.models.Passkey,
displayName: String,
url: String,
logo: ByteArray? = null,
) {
- passkey.replacePasskey(oldPasskeyId, newPasskey, displayName, url, logo)
+ passkey.replacePasskey(oldPasskeyId, manifestId, newPasskey, displayName, url, logo)
}
/**
* Get Items that match an rpId but don't have a passkey yet.
* Used for finding existing credentials that could have a passkey added to them.
*/
- fun getItemsWithoutPasskeyForRpId(
- rpId: String,
- rpName: String? = null,
- userName: String? = null,
- ): List<net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo> {
+ fun getItemsWithoutPasskeyForRpId(rpId: String, rpName: String? = null, userName: String? = null): List<ItemWithCredentialInfo> {
return passkey.getItemsWithoutPasskeyForRpId(rpId, rpName, userName)
}
@@ -882,7 +887,7 @@ class VaultStore(
* the favicon was fetched for.
*/
fun addPasskeyToExistingItem(
- itemId: java.util.UUID,
+ itemId: UUID,
manifestId: String,
passkeyObj: net.aliasvault.app.vaultstore.models.Passkey,
url: String,
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
index 37c7f929d..c820b91e5 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
@@ -5,7 +5,6 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.aliasvault.app.rustcore.JnaInitializer
import net.aliasvault.app.utils.AppInfo
-import net.aliasvault.app.vaultstore.models.VaultSql
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import net.aliasvault.app.webapi.WebApiService
import org.json.JSONArray
@@ -317,10 +316,7 @@ class VaultSyncEngine(
*/
private fun openStaging() {
closeStaging()
- staging = SqliteMemoryDatabase.withSchema(VaultSql.completeSchema).also {
- // The schema script ends by turning foreign keys on; the engine inserts rows in codec order, not FK order.
- it.executeBatch("PRAGMA foreign_keys = OFF")
- }
+ staging = SqliteMemoryDatabase.withLatestSchema()
}
private fun closeStaging() {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/FieldMapper.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/FieldMapper.kt
deleted file mode 100644
index 6ad25aa20..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/FieldMapper.kt
+++ /dev/null
@@ -1,128 +0,0 @@
-package net.aliasvault.app.vaultstore.mappers
-
-import net.aliasvault.app.vaultstore.models.FieldKey
-import net.aliasvault.app.vaultstore.models.FieldType
-import net.aliasvault.app.vaultstore.models.ItemField
-import net.aliasvault.app.vaultstore.repositories.scopedKey
-
-/**
- * Raw field row from a database query.
- *
- * @property itemId The item the value belongs to.
- * @property manifestId The manifest the item lives in.
- * @property fieldKey The system field key, null for a custom field.
- * @property fieldDefinitionId The custom field definition, null for a system field.
- * @property customLabel The custom field's label.
- * @property customFieldType The custom field's type.
- * @property customIsHidden Whether the custom field is masked.
- * @property customEnableHistory Whether the custom field keeps a value history.
- * @property value The field value.
- * @property displayOrder The position of the field on the item.
- */
-data class FieldRow(
- val itemId: String,
- val manifestId: String,
- val fieldKey: String?,
- val fieldDefinitionId: String?,
- val customLabel: String?,
- val customFieldType: String?,
- val customIsHidden: Boolean,
- val customEnableHistory: Boolean,
- val value: String,
- val displayOrder: Int,
-) {
- companion object {
- /**
- * Read a row from a query result, or null when the item key is missing.
- */
- fun fromRow(row: Map<String, Any?>): FieldRow? {
- val itemId = row["ItemId"] as? String ?: return null
- val manifestId = row["ManifestId"] as? String ?: return null
- return FieldRow(
- itemId = itemId,
- manifestId = manifestId,
- fieldKey = row["FieldKey"] as? String,
- fieldDefinitionId = row["FieldDefinitionId"] as? String,
- customLabel = row["CustomLabel"] as? String,
- customFieldType = row["CustomFieldType"] as? String,
- customIsHidden = (row["CustomIsHidden"] as? Long) == 1L,
- customEnableHistory = (row["CustomEnableHistory"] as? Long) == 1L,
- value = row["Value"] as? String ?: "",
- displayOrder = (row["DisplayOrder"] as? Long)?.toInt() ?: 0,
- )
- }
- }
-}
-
-/**
- * Maps field rows to ItemField objects: system fields (FieldKey) get their metadata from the registry below,
- * custom fields (FieldDefinitionId) from the row.
- * Other platform implementations: FieldMapper.ts (core/client), FieldMapper.swift (iOS).
- */
-object FieldMapper {
- /**
- * Resolved metadata of one field.
- */
- private data class FieldMetadata(
- val label: String,
- val fieldType: String,
- val isHidden: Boolean,
- val enableHistory: Boolean,
- )
-
- /**
- * Group field rows by scoped item key (see `scopedKey`). Multi-value fields keep one ItemField per row.
- */
- fun processFieldRows(rows: List<FieldRow>): Map<String, List<ItemField>> {
- val fieldsByItem = mutableMapOf<String, MutableList<ItemField>>()
- for (row in rows) {
- fieldsByItem.getOrPut(scopedKey(row.manifestId, row.itemId)) { mutableListOf() }.add(processFieldRow(row))
- }
- return fieldsByItem
- }
-
- private fun processFieldRow(row: FieldRow): ItemField {
- val isCustomField = row.fieldDefinitionId != null && row.fieldKey == null
- val fieldKey = row.fieldKey ?: row.fieldDefinitionId ?: ""
- val metadata = if (isCustomField) {
- FieldMetadata(row.customLabel ?: fieldKey, row.customFieldType ?: FieldType.TEXT, row.customIsHidden, row.customEnableHistory)
- } else {
- resolveSystemFieldMetadata(fieldKey)
- }
- return ItemField(
- fieldKey = fieldKey,
- label = metadata.label,
- fieldType = metadata.fieldType,
- value = row.value,
- isHidden = metadata.isHidden,
- displayOrder = row.displayOrder,
- isCustomField = isCustomField,
- enableHistory = metadata.enableHistory,
- )
- }
-
- /**
- * Metadata of a system field; an unknown key is shown as plain text under its own name.
- */
- @Suppress("CyclomaticComplexMethod")
- private fun resolveSystemFieldMetadata(fieldKey: String): FieldMetadata {
- return when (fieldKey) {
- FieldKey.LOGIN_USERNAME -> FieldMetadata("Username", FieldType.TEXT, false, false)
- FieldKey.LOGIN_PASSWORD -> FieldMetadata("Password", FieldType.PASSWORD, true, true)
- FieldKey.LOGIN_EMAIL -> FieldMetadata("Email", FieldType.EMAIL, false, false)
- FieldKey.LOGIN_URL -> FieldMetadata("URL", FieldType.U_R_L, false, false)
- FieldKey.CARD_NUMBER -> FieldMetadata("Card Number", FieldType.TEXT, true, false)
- FieldKey.CARD_CARDHOLDER_NAME -> FieldMetadata("Cardholder Name", FieldType.TEXT, false, false)
- FieldKey.CARD_EXPIRY_MONTH -> FieldMetadata("Expiry Month", FieldType.TEXT, false, false)
- FieldKey.CARD_EXPIRY_YEAR -> FieldMetadata("Expiry Year", FieldType.TEXT, false, false)
- FieldKey.CARD_CVV -> FieldMetadata("CVV", FieldType.PASSWORD, true, false)
- FieldKey.CARD_PIN -> FieldMetadata("PIN", FieldType.PASSWORD, true, false)
- FieldKey.ALIAS_FIRST_NAME -> FieldMetadata("First Name", FieldType.TEXT, false, false)
- FieldKey.ALIAS_LAST_NAME -> FieldMetadata("Last Name", FieldType.TEXT, false, false)
- FieldKey.ALIAS_GENDER -> FieldMetadata("Gender", FieldType.TEXT, false, false)
- FieldKey.ALIAS_BIRTHDATE -> FieldMetadata("Birth Date", FieldType.DATE, false, false)
- FieldKey.NOTES_CONTENT -> FieldMetadata("Notes", FieldType.TEXT_AREA, false, false)
- else -> FieldMetadata(fieldKey, FieldType.TEXT, false, false)
- }
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/ItemMapper.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/ItemMapper.kt
deleted file mode 100644
index 056fce990..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/ItemMapper.kt
+++ /dev/null
@@ -1,130 +0,0 @@
-package net.aliasvault.app.vaultstore.mappers
-
-import net.aliasvault.app.utils.DateHelpers
-import net.aliasvault.app.vaultstore.models.BuiltinLogos
-import net.aliasvault.app.vaultstore.models.Item
-import net.aliasvault.app.vaultstore.models.ItemField
-import net.aliasvault.app.vaultstore.repositories.scopedKey
-import java.util.Calendar
-import java.util.Date
-import java.util.TimeZone
-import java.util.UUID
-
-/**
- * Raw item row from a database query.
- *
- * @property id The item id.
- * @property manifestId The manifest the item lives in.
- * @property name The item name.
- * @property itemType The item type.
- * @property folderId The folder the item is in, if any.
- * @property logo The logo bytes, resolved from the built-in catalog when the logo is built in.
- * @property hasPasskey Whether the item has a live passkey.
- * @property hasAttachment Whether the item has a live attachment.
- * @property hasTotp Whether the item has a live TOTP code.
- * @property createdAt Creation timestamp text.
- * @property updatedAt Update timestamp text.
- */
-data class ItemRow(
- val id: String,
- val manifestId: String,
- val name: String?,
- val itemType: String,
- val folderId: String?,
- val logo: ByteArray?,
- val hasPasskey: Boolean,
- val hasAttachment: Boolean,
- val hasTotp: Boolean,
- val createdAt: String,
- val updatedAt: String,
-) {
- /**
- * The key this item's child rows are grouped under (see `scopedKey`).
- */
- val scopedItemKey: String
- get() = scopedKey(manifestId, id)
-
- companion object {
- private const val LOGO_KIND_BUILTIN = "builtin"
-
- /**
- * Read a row from a query result, or null when a required column is missing.
- */
- fun fromRow(row: Map<String, Any?>): ItemRow? {
- return ItemRow(
- id = row["Id"] as? String ?: return null,
- manifestId = row["ManifestId"] as? String ?: return null,
- name = row["Name"] as? String,
- itemType = row["ItemType"] as? String ?: return null,
- folderId = row["FolderId"] as? String,
- logo = resolveLogo(row),
- hasPasskey = (row["HasPasskey"] as? Long) == 1L,
- hasAttachment = (row["HasAttachment"] as? Long) == 1L,
- hasTotp = (row["HasTotp"] as? Long) == 1L,
- createdAt = row["CreatedAt"] as? String ?: "",
- updatedAt = row["UpdatedAt"] as? String ?: "",
- )
- }
-
- /**
- * The bytes an item's logo is drawn from. A built-in logo carries none: it is drawn from the shared catalog, keyed by its Source.
- */
- private fun resolveLogo(row: Map<String, Any?>): ByteArray? {
- if (row["LogoKind"] as? String == LOGO_KIND_BUILTIN) {
- return (row["LogoSource"] as? String)?.let { BuiltinLogos.svgFor(it) }?.toByteArray(Charsets.UTF_8)
- }
- return row["Logo"] as? ByteArray
- }
- }
-}
-
-/**
- * Maps item rows to Item objects.
- * Other platform implementations: ItemMapper.ts (core/client), ItemMapper.swift (iOS).
- */
-object ItemMapper {
- /**
- * The date an unparseable timestamp falls back to.
- */
- val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
- set(Calendar.YEAR, 1)
- set(Calendar.MONTH, Calendar.JANUARY)
- set(Calendar.DAY_OF_MONTH, 1)
- set(Calendar.HOUR_OF_DAY, 0)
- set(Calendar.MINUTE, 0)
- set(Calendar.SECOND, 0)
- set(Calendar.MILLISECOND, 0)
- }.time
-
- /**
- * Map one item row to an Item with its fields and folder path.
- */
- fun mapRow(row: ItemRow, fields: List<ItemField> = emptyList(), folderPath: List<String>? = null): Item {
- return Item(
- id = UUID.fromString(row.id),
- manifestId = row.manifestId,
- name = row.name,
- itemType = row.itemType,
- logo = row.logo,
- folderId = row.folderId?.let { UUID.fromString(it) },
- folderPath = folderPath,
- fields = fields,
- hasPasskey = row.hasPasskey,
- hasAttachment = row.hasAttachment,
- hasTotp = row.hasTotp,
- createdAt = DateHelpers.parseDateString(row.createdAt) ?: MIN_DATE,
- updatedAt = DateHelpers.parseDateString(row.updatedAt) ?: MIN_DATE,
- )
- }
-
- /**
- * Map item rows to Items, joining the fields and folder paths by scoped key.
- */
- fun mapRows(rows: List<ItemRow>, fieldsByItem: Map<String, List<ItemField>>, folderPathsByFolderKey: Map<String, List<String>> = emptyMap()): List<Item> {
- return rows.map { row ->
- val fields = fieldsByItem[row.scopedItemKey] ?: emptyList()
- val folderPath = row.folderId?.let { folderPathsByFolderKey[scopedKey(row.manifestId, it)] }
- mapRow(row, fields, folderPath)
- }
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/PasskeyMapper.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/PasskeyMapper.kt
deleted file mode 100644
index 16f784467..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/mappers/PasskeyMapper.kt
+++ /dev/null
@@ -1,160 +0,0 @@
-package net.aliasvault.app.vaultstore.mappers
-
-import android.util.Log
-import net.aliasvault.app.utils.DateHelpers
-import net.aliasvault.app.vaultstore.models.Passkey
-import java.util.UUID
-
-/**
- * Raw passkey row from a database query.
- *
- * @property id The passkey id, also its WebAuthn credential id.
- * @property itemId The item the passkey belongs to.
- * @property manifestId The manifest the item lives in.
- * @property rpId The relying party id.
- * @property userHandle The WebAuthn user handle.
- * @property publicKey The public key as JWK text.
- * @property privateKey The private key as JWK text.
- * @property prfKey The PRF extension key.
- * @property displayName The display name.
- * @property additionalData Extra authenticator data.
- * @property createdAt Creation timestamp text.
- * @property updatedAt Update timestamp text.
- * @property isDeleted Whether the passkey is soft deleted.
- */
-data class PasskeyRow(
- val id: String,
- val itemId: String,
- val manifestId: String,
- val rpId: String,
- val userHandle: ByteArray?,
- val publicKey: String,
- val privateKey: String,
- val prfKey: ByteArray?,
- val displayName: String,
- val additionalData: ByteArray?,
- val createdAt: String,
- val updatedAt: String,
- val isDeleted: Boolean,
-) {
- companion object {
- /**
- * Read a row from a query result, or null when a required column is missing.
- */
- @Suppress("ReturnCount") // One early return per required column
- fun fromRow(row: Map<String, Any?>): PasskeyRow? {
- return PasskeyRow(
- id = row["Id"] as? String ?: return null,
- itemId = row["ItemId"] as? String ?: return null,
- manifestId = row["ManifestId"] as? String ?: return null,
- rpId = row["RpId"] as? String ?: return null,
- userHandle = row["UserHandle"] as? ByteArray,
- publicKey = row["PublicKey"] as? String ?: return null,
- privateKey = row["PrivateKey"] as? String ?: return null,
- prfKey = row["PrfKey"] as? ByteArray,
- displayName = row["DisplayName"] as? String ?: return null,
- additionalData = row["AdditionalData"] as? ByteArray,
- createdAt = row["CreatedAt"] as? String ?: return null,
- updatedAt = row["UpdatedAt"] as? String ?: return null,
- isDeleted = (row["IsDeleted"] as? Long) == 1L,
- )
- }
- }
-}
-
-/**
- * Passkey row joined with the display fields of its item.
- *
- * @property passkeyRow The passkey columns.
- * @property serviceName The item name.
- * @property username The item's login.username value.
- * @property email The item's login.email value.
- */
-data class PasskeyWithItemRow(
- val passkeyRow: PasskeyRow,
- val serviceName: String?,
- val username: String?,
- val email: String?,
-) {
- companion object {
- /**
- * Read a joined row from a query result, or null when the passkey columns are missing.
- */
- fun fromRow(row: Map<String, Any?>): PasskeyWithItemRow? {
- val passkeyRow = PasskeyRow.fromRow(row) ?: return null
- return PasskeyWithItemRow(passkeyRow, row["ServiceName"] as? String, row["Username"] as? String, row["Email"] as? String)
- }
- }
-}
-
-/**
- * A passkey with the display fields of its item.
- *
- * @property passkey The passkey.
- * @property serviceName The service name from the item.
- * @property username The username from the item.
- * @property email The email from the item, used as display fallback when there is no username.
- */
-data class PasskeyWithItem(
- val passkey: Passkey,
- val serviceName: String?,
- val username: String?,
- val email: String? = null,
-) {
- /** The account identifier to display: the username, or the email when no username is set. */
- val accountLabel: String?
- get() = username?.takeIf { it.isNotBlank() } ?: email?.takeIf { it.isNotBlank() }
-}
-
-/**
- * Maps passkey rows to Passkey objects.
- * Other platform implementations: PasskeyMapper.ts (core/client), PasskeyMapper.swift (iOS).
- */
-object PasskeyMapper {
- private const val TAG = "PasskeyMapper"
-
- /**
- * Map one passkey row to a Passkey, or null when its ids are not valid UUIDs.
- */
- fun mapRow(row: PasskeyRow): Passkey? {
- return try {
- Passkey(
- id = UUID.fromString(row.id),
- parentItemId = UUID.fromString(row.itemId),
- manifestId = row.manifestId,
- rpId = row.rpId,
- userHandle = row.userHandle,
- userName = null,
- publicKey = row.publicKey.toByteArray(Charsets.UTF_8),
- privateKey = row.privateKey.toByteArray(Charsets.UTF_8),
- prfKey = row.prfKey,
- displayName = row.displayName,
- additionalData = row.additionalData,
- createdAt = DateHelpers.parseDateString(row.createdAt) ?: ItemMapper.MIN_DATE,
- updatedAt = DateHelpers.parseDateString(row.updatedAt) ?: ItemMapper.MIN_DATE,
- isDeleted = row.isDeleted,
- )
- } catch (e: IllegalArgumentException) {
- Log.e(TAG, "Invalid UUID in passkey row: id=${row.id}, itemId=${row.itemId}", e)
- null
- }
- }
-
- /**
- * Map passkey rows to Passkeys, skipping rows that do not map.
- */
- fun mapRows(rows: List<PasskeyRow>): List<Passkey> = rows.mapNotNull { mapRow(it) }
-
- /**
- * Map one joined row to a PasskeyWithItem.
- */
- fun mapRowWithItem(row: PasskeyWithItemRow): PasskeyWithItem? {
- val passkey = mapRow(row.passkeyRow) ?: return null
- return PasskeyWithItem(passkey, row.serviceName, row.username, row.email)
- }
-
- /**
- * Map joined rows to PasskeyWithItem objects, skipping rows that do not map.
- */
- fun mapRowsWithItem(rows: List<PasskeyWithItemRow>): List<PasskeyWithItem> = rows.mapNotNull { mapRowWithItem(it) }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultVersions.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultVersions.kt
deleted file mode 100644
index 6c59a7c9d..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultVersions.kt
+++ /dev/null
@@ -1,156 +0,0 @@
-// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/VaultVersions.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-@file:Suppress("all")
-
-package net.aliasvault.app.vaultstore.models
-
-/**
- * Vault database version information.
- */
-data class VaultVersion(
- /** The migration revision number. */
- val revision: Int,
- /** The internal migration version number that equals the AliasClientDb database version (e.g., "1.5.0"). */
- val version: String,
- /** Description of changes in this version. */
- val description: String,
- /** The AliasVault release that this vault version was introduced in (e.g., "0.14.0"). */
- val releaseVersion: String,
- /** The last AliasVault release version that the vault was compatible with before requiring this migration. */
- val compatibleUpToVersion: String,
-)
-
-/**
- * Registry of all vault versions.
- */
-object VaultVersions {
- /**
- * All vault migrations/versions in chronological order.
- */
- val all: List<VaultVersion> = listOf(
- VaultVersion(
- revision = 1,
- version = "1.0.0",
- description = "Initial Migration",
- releaseVersion = "0.1.0",
- compatibleUpToVersion = "0.0.0",
- ),
- VaultVersion(
- revision = 2,
- version = "1.0.1",
- description = "Empty Test Migration",
- releaseVersion = "0.2.0",
- compatibleUpToVersion = "0.1.0",
- ),
- VaultVersion(
- revision = 3,
- version = "1.0.2",
- description = "Change Email Column",
- releaseVersion = "0.3.0",
- compatibleUpToVersion = "0.2.0",
- ),
- VaultVersion(
- revision = 4,
- version = "1.1.0",
- description = "Add Pki Tables",
- releaseVersion = "0.4.0",
- compatibleUpToVersion = "0.3.0",
- ),
- VaultVersion(
- revision = 5,
- version = "1.2.0",
- description = "Add Settings Table",
- releaseVersion = "0.4.0",
- compatibleUpToVersion = "0.3.0",
- ),
- VaultVersion(
- revision = 6,
- version = "1.3.0",
- description = "Update Identity Structure",
- releaseVersion = "0.5.0",
- compatibleUpToVersion = "0.4.0",
- ),
- VaultVersion(
- revision = 7,
- version = "1.3.1",
- description = "Make Username Optional",
- releaseVersion = "0.5.0",
- compatibleUpToVersion = "0.4.0",
- ),
- VaultVersion(
- revision = 8,
- version = "1.4.0",
- description = "Add Sync Support",
- releaseVersion = "0.6.0",
- compatibleUpToVersion = "0.5.0",
- ),
- VaultVersion(
- revision = 9,
- version = "1.4.1",
- description = "Rename Attachments Plural",
- releaseVersion = "0.6.0",
- compatibleUpToVersion = "0.13.0",
- ),
- VaultVersion(
- revision = 10,
- version = "1.5.0",
- description = "Add 2FA Tokens to credentials",
- releaseVersion = "0.14.0",
- compatibleUpToVersion = "0.23.0",
- ),
- VaultVersion(
- revision = 11,
- version = "1.6.0",
- description = "Add Passkey support",
- releaseVersion = "0.24.0",
- compatibleUpToVersion = "0.25.0",
- ),
- VaultVersion(
- revision = 12,
- version = "1.7.0",
- description = "Update to Field-Based Data Model",
- releaseVersion = "0.26.0",
- compatibleUpToVersion = "0.25.0",
- ),
- VaultVersion(
- revision = 13,
- version = "2.0.0",
- description = "Update to Field-Based Data Model",
- releaseVersion = "0.26.1",
- compatibleUpToVersion = "0.25.0",
- ),
- )
-
- /**
- * Get the latest vault version.
- */
- val latest: VaultVersion
- get() = all.last()
-
- /**
- * Get the latest vault version string (e.g., "1.7.0").
- */
- val latestVersion: String
- get() = latest.version
-
- /**
- * Get the latest vault revision number.
- */
- val latestRevision: Int
- get() = latest.revision
-
- /**
- * Find a vault version by revision number.
- */
- fun findByRevision(revision: Int): VaultVersion? {
- return all.find { it.revision == revision }
- }
-
- /**
- * Find a vault version by version string.
- */
- fun findByVersion(version: String): VaultVersion? {
- return all.find { it.version == version }
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt
index ed05ad1a0..fc61210a2 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt
@@ -1,93 +1,36 @@
package net.aliasvault.app.vaultstore.passkey
-import net.aliasvault.app.utils.Helpers
-import org.json.JSONObject
-import java.security.KeyPairGenerator
-import java.security.MessageDigest
-import java.security.SecureRandom
-import java.security.Signature
-import java.security.interfaces.ECPrivateKey
-import java.security.interfaces.ECPublicKey
-import java.security.interfaces.RSAPrivateCrtKey
-import java.security.interfaces.RSAPublicKey
-import java.security.spec.ECGenParameterSpec
-import javax.crypto.Mac
-import javax.crypto.spec.SecretKeySpec
+import uniffi.aliasvault_core.PasskeyPrfInputs
+import uniffi.aliasvault_core.passkeyCreate
+import uniffi.aliasvault_core.passkeyGetAssertion
+import uniffi.aliasvault_core.passkeyGuidToBytes
+import uniffi.aliasvault_core.passkeyPickAlgorithm
/**
- * PasskeyAuthenticator
- * -------------------------
- * A WebAuthn "virtual authenticator" for Android credential provider.
- * Implements passkey creation (registration) and authentication (assertion) following
- * the WebAuthn Level 2 specification.
- *
- * This is a Kotlin port of the reference TypeScript implementation:
- * - Reference: apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts
- * - iOS: apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
- *
- * Key features:
- * - ES256 (ECDSA P-256) and RS256 (RSASSA-PKCS1-v1.5) key pair generation
- * - CBOR/COSE encoding for attestation objects
- * - Proper authenticator data with WebAuthn flags
- * - Self-attestation (packed format) or none attestation
- * - Consistent base64url handling
- * - Sign count always 0 for syncable passkeys
- * - BE/BS flags for backup-eligible and backed-up status
+ * The WebAuthn authenticator of the Android credential provider. Key generation, authenticator data, the
+ * attestation object, signatures and PRF all run in the Rust core (core/rust/src/passkey).
+ * Other platform implementations: PasskeyAuthenticator.swift (iOS), PasskeyAuthenticator.ts (browser extension).
*/
object PasskeyAuthenticator {
-
- /** AliasVault AAGUID: a11a5faa-9f32-4b8c-8c5d-2f7d13e8c942. */
- private val AAGUID = byteArrayOf(
- 0xa1.toByte(), 0x1a, 0x5f, 0xaa.toByte(), 0x9f.toByte(), 0x32, 0x4b, 0x8c.toByte(),
- 0x8c.toByte(), 0x5d, 0x2f, 0x7d, 0x13, 0xe8.toByte(), 0xc9.toByte(), 0x42,
- )
-
/** COSE algorithm identifier for ES256 (ECDSA P-256 with SHA-256). */
const val ALG_ES256 = -7
- /** COSE algorithm identifier for RS256 (RSASSA-PKCS1-v1.5 with SHA-256). */
- const val ALG_RS256 = -257
-
- /** RSA modulus size used when generating RS256 credentials. */
- private const val RSA_KEY_SIZE = 2048
-
/**
- * Algorithms supported by this authenticator, in our order of preference.
- * When an RP lists multiple, we honor the RP's order and pick the first match.
+ * The 16-byte credential id of a passkey GUID.
*/
- private val SUPPORTED_ALGORITHMS = listOf(ALG_ES256, ALG_RS256)
-
- // MARK: - Public API
+ @JvmStatic
+ fun guidToBytes(guid: String): ByteArray = passkeyGuidToBytes(guid)
/**
- * Pick a supported credential algorithm from the RP's pubKeyCredParams.
- * Honors the RP's preference order and returns the first algorithm we support.
- * Defaults to ES256 when the RP provides no params.
- *
- * @param params COSE algorithm identifiers from pubKeyCredParams, in RP order.
- * @return The chosen COSE algorithm identifier (-7 for ES256, -257 for RS256).
+ * The first algorithm in the RP's pubKeyCredParams order that the authenticator supports; ES256 when the RP lists none.
*/
@JvmStatic
fun pickSupportedAlgorithm(params: List<Int>): Int {
- if (params.isEmpty()) {
- return ALG_ES256
- }
- for (alg in params) {
- if (SUPPORTED_ALGORITHMS.contains(alg)) {
- return alg
- }
- }
- throw PasskeyError.UnsupportedAlgorithm(
- "No supported algorithm (ES256, RS256) in pubKeyCredParams",
- )
+ return passkeyPickAlgorithm(params.map { it.toLong() }).toInt()
}
/**
- * Create a new passkey (registration).
- * Returns credential data ready for Android to return to the RP, plus storage data.
+ * Create a new passkey (registration): the attestation object for the RP and the keys the vault stores.
*/
@JvmStatic
@Suppress("LongParameterList")
@@ -102,91 +45,25 @@ object PasskeyAuthenticator {
prfInputs: PrfInputs? = null,
algorithm: Int = ALG_ES256,
): PasskeyCreationResult {
- // 1. Generate key pair for the chosen algorithm
- val keyPair = generateKeyPair(algorithm)
-
- // 2. RP ID hash
- val md = MessageDigest.getInstance("SHA-256")
- val rpIdHash = md.digest(rpId.toByteArray(Charsets.UTF_8))
-
- // 3. Build flags
- var flags: Byte = 0x41 // UP (bit 0) + AT (bit 6)
- if (uvPerformed) {
- flags = (flags.toInt() or 0x04).toByte() // UV (bit 2)
- }
- flags = (flags.toInt() or 0x08).toByte() // BE (bit 3) - backup eligible
- flags = (flags.toInt() or 0x10).toByte() // BS (bit 4) - backup state
-
- // 4. Sign count (always 0 for syncable credentials)
- val signCount = byteArrayOf(0x00, 0x00, 0x00, 0x00)
-
- // 5. Build COSE public key
- val coseKey = if (algorithm == ALG_RS256) {
- buildCoseRsaRs256(keyPair.public as RSAPublicKey)
- } else {
- buildCoseEc2Es256(keyPair.public as ECPublicKey)
- }
-
- // 6. Build attested credential data
- val credIdLength = byteArrayOf(
- ((credentialId.size shr 8) and 0xFF).toByte(),
- (credentialId.size and 0xFF).toByte(),
- )
- val attestedCredData = AAGUID + credIdLength + credentialId + coseKey
-
- // 7. Build authenticator data
- val authenticatorData = rpIdHash + byteArrayOf(flags) + signCount + attestedCredData
-
- // 8. Build attestation object (none format)
- val attestationObject = buildAttestationObjectNone(authenticatorData)
-
- // 9. Generate PRF secret if requested
- var prfSecret: ByteArray? = null
- if (enablePrf) {
- val prfBytes = ByteArray(32)
- SecureRandom().nextBytes(prfBytes)
- prfSecret = prfBytes
- }
-
- // 10. Evaluate PRF values if requested during registration
- var prfResults: PrfResults? = null
- if (prfInputs != null && prfInputs.first != null && prfSecret != null) {
- val firstResult = evaluatePrf(prfSecret, prfInputs.first)
- val secondResult = prfInputs.second?.let { evaluatePrf(prfSecret, it) }
- prfResults = PrfResults(firstResult, secondResult)
- }
-
- // 11. Export keys for storage
- val publicKeyJWK: ByteArray
- val privateKeyData: ByteArray
- if (algorithm == ALG_RS256) {
- publicKeyJWK = exportRsaPublicKeyAsJWK(keyPair.public as RSAPublicKey)
- privateKeyData = exportRsaPrivateKeyAsJWK(keyPair.private as RSAPrivateCrtKey)
- } else {
- publicKeyJWK = exportPublicKeyAsJWK(keyPair.public as ECPublicKey)
- privateKeyData = exportPrivateKeyAsJWK(keyPair.private as ECPrivateKey, keyPair.public as ECPublicKey)
- }
- val publicKeyDER = keyPair.public.encoded // DER/SPKI format (EC or RSA)
-
+ val created = passkeyCreate(credentialId, rpId, algorithm.toLong(), uvPerformed, enablePrf, prfInputs?.toRust())
return PasskeyCreationResult(
credentialId = credentialId,
- attestationObject = attestationObject,
- authenticatorData = authenticatorData,
- publicKey = publicKeyJWK,
- publicKeyDER = publicKeyDER,
- privateKey = privateKeyData,
+ authenticatorData = created.authenticatorData,
+ attestationObject = created.attestationObject,
+ publicKey = created.publicKeyJwk.toByteArray(Charsets.UTF_8),
+ publicKeyDER = created.publicKeySpki,
+ privateKey = created.privateKeyJwk.toByteArray(Charsets.UTF_8),
rpId = rpId,
userId = userId,
userName = userName,
userDisplayName = userDisplayName,
- prfSecret = prfSecret,
- prfResults = prfResults,
+ prfSecret = created.prfSecret,
+ prfResults = created.prfResults?.let { PrfResults(it.first, it.second) },
)
}
/**
- * Create an assertion (authentication).
- * Returns assertion data ready for Android to return to the RP.
+ * Create an assertion (authentication) signed with the stored private key JWK.
*/
@JvmStatic
@Suppress("LongParameterList")
@@ -200,346 +77,17 @@ object PasskeyAuthenticator {
prfInputs: PrfInputs? = null,
prfSecret: ByteArray? = null,
): PasskeyAssertionResult {
- // 1. RP ID hash
- val md = MessageDigest.getInstance("SHA-256")
- val rpIdHash = md.digest(rpId.toByteArray(Charsets.UTF_8))
-
- // 2. Build flags
- var flags: Byte = 0x01 // UP (bit 0)
- if (uvPerformed) {
- flags = (flags.toInt() or 0x04).toByte() // UV (bit 2)
- }
- flags = (flags.toInt() or 0x08).toByte() // BE (bit 3)
- flags = (flags.toInt() or 0x10).toByte() // BS (bit 4)
-
- // 3. Sign count
- val signCount = byteArrayOf(0x00, 0x00, 0x00, 0x00)
-
- // 4. Build authenticator data
- val authenticatorData = rpIdHash + byteArrayOf(flags) + signCount
-
- // 5. Build data to sign: authenticatorData || clientDataHash
- val dataToSign = authenticatorData + clientDataHash
-
- // 6. Determine algorithm from the stored key, import it, and sign
- val jwk = JSONObject(String(privateKeyJWK, Charsets.UTF_8))
- val algorithm = if (jwk.optString("kty") == "RSA") ALG_RS256 else ALG_ES256
- val privateKey = importPrivateKeyFromJWK(privateKeyJWK)
- val signatureAlgorithm = if (algorithm == ALG_RS256) "SHA256withRSA" else "SHA256withECDSA"
- val signature = Signature.getInstance(signatureAlgorithm)
- signature.initSign(privateKey)
- signature.update(dataToSign)
-
- // 7. The signature is already in the form the RP expects:
- // ECDSA output is DER-encoded, RSA output is raw PKCS#1 v1.5. Both are what WebAuthn expects.
- val signatureBytes = signature.sign()
-
- // 8. Evaluate PRF if requested
- var prfResults: PrfResults? = null
- if (prfInputs != null && prfInputs.first != null && prfSecret != null) {
- val firstResult = evaluatePrf(prfSecret, prfInputs.first)
- val secondResult = prfInputs.second?.let { evaluatePrf(prfSecret, it) }
- prfResults = PrfResults(firstResult, secondResult)
- }
-
+ val assertion = passkeyGetAssertion(rpId, clientDataHash, String(privateKeyJWK, Charsets.UTF_8), uvPerformed, prfInputs?.toRust(), prfSecret)
return PasskeyAssertionResult(
credentialId = credentialId,
- authenticatorData = authenticatorData,
- signature = signatureBytes,
+ authenticatorData = assertion.authenticatorData,
+ signature = assertion.signature,
userHandle = userId,
- prfResults = prfResults,
- )
- }
-
- // MARK: - Key Management
-
- /**
- * Export public key as JWK format (JSON).
- */
- private fun exportPublicKeyAsJWK(publicKey: ECPublicKey): ByteArray {
- val w = publicKey.w
- val xBytes = w.affineX.toByteArray().dropLeadingZeros().padTo32Bytes()
- val yBytes = w.affineY.toByteArray().dropLeadingZeros().padTo32Bytes()
-
- val jwk = JSONObject().apply {
- put("kty", "EC")
- put("crv", "P-256")
- put("x", PasskeyHelper.bytesToBase64url(xBytes))
- put("y", PasskeyHelper.bytesToBase64url(yBytes))
- }
-
- return jwk.toString().toByteArray(Charsets.UTF_8)
- }
-
- /**
- * Export private key as JWK format (JSON).
- * Note: We need the KeyPair to properly export both public and private components.
- */
- private fun exportPrivateKeyAsJWK(privateKey: ECPrivateKey, publicKey: ECPublicKey): ByteArray {
- val w = publicKey.w
- val xBytes = w.affineX.toByteArray().dropLeadingZeros().padTo32Bytes()
- val yBytes = w.affineY.toByteArray().dropLeadingZeros().padTo32Bytes()
- val dBytes = privateKey.s.toByteArray().dropLeadingZeros().padTo32Bytes()
-
- val jwk = JSONObject().apply {
- put("kty", "EC")
- put("crv", "P-256")
- put("x", PasskeyHelper.bytesToBase64url(xBytes))
- put("y", PasskeyHelper.bytesToBase64url(yBytes))
- put("d", PasskeyHelper.bytesToBase64url(dBytes))
- }
-
- return jwk.toString().toByteArray(Charsets.UTF_8)
- }
-
- /**
- * Export an RSA public key as JWK format (JSON): {kty, n, e}.
- */
- private fun exportRsaPublicKeyAsJWK(publicKey: RSAPublicKey): ByteArray {
- val jwk = JSONObject().apply {
- put("kty", "RSA")
- put("n", PasskeyHelper.bytesToBase64url(publicKey.modulus.toUnsignedBytes()))
- put("e", PasskeyHelper.bytesToBase64url(publicKey.publicExponent.toUnsignedBytes()))
- }
-
- return jwk.toString().toByteArray(Charsets.UTF_8)
- }
-
- /**
- * Export an RSA private key as JWK format (JSON): {kty, n, e, d, p, q, dp, dq, qi}.
- */
- private fun exportRsaPrivateKeyAsJWK(privateKey: RSAPrivateCrtKey): ByteArray {
- val jwk = JSONObject().apply {
- put("kty", "RSA")
- put("n", PasskeyHelper.bytesToBase64url(privateKey.modulus.toUnsignedBytes()))
- put("e", PasskeyHelper.bytesToBase64url(privateKey.publicExponent.toUnsignedBytes()))
- put("d", PasskeyHelper.bytesToBase64url(privateKey.privateExponent.toUnsignedBytes()))
- put("p", PasskeyHelper.bytesToBase64url(privateKey.primeP.toUnsignedBytes()))
- put("q", PasskeyHelper.bytesToBase64url(privateKey.primeQ.toUnsignedBytes()))
- put("dp", PasskeyHelper.bytesToBase64url(privateKey.primeExponentP.toUnsignedBytes()))
- put("dq", PasskeyHelper.bytesToBase64url(privateKey.primeExponentQ.toUnsignedBytes()))
- put("qi", PasskeyHelper.bytesToBase64url(privateKey.crtCoefficient.toUnsignedBytes()))
- }
-
- return jwk.toString().toByteArray(Charsets.UTF_8)
- }
-
- /**
- * Import a private key from JWK format, dispatching on the key type ("kty").
- */
- private fun importPrivateKeyFromJWK(jwkData: ByteArray): java.security.PrivateKey {
- val jwkString = String(jwkData, Charsets.UTF_8)
- val jwk = JSONObject(jwkString)
- return if (jwk.optString("kty") == "RSA") {
- importRsaPrivateKeyFromJWK(jwk)
- } else {
- importEcPrivateKeyFromJWK(jwk)
- }
- }
-
- /**
- * Import an EC (P-256) private key from JWK format.
- * Uses ECPrivateKeySpec to avoid Android Keystore issues.
- */
- private fun importEcPrivateKeyFromJWK(jwk: JSONObject): java.security.PrivateKey {
- // Extract the d parameter (private key component)
- val dBase64url = jwk.optString("d")
- if (dBase64url.isEmpty()) {
- throw PasskeyError.InvalidJWK("Missing 'd' parameter in JWK")
- }
-
- // Decode base64url to bytes
- val dBytes = Helpers.base64urlDecode(dBase64url)
-
- // Convert to BigInteger (d parameter is the private key value)
- val d = java.math.BigInteger(1, dBytes)
-
- // Get P-256 curve parameters
- val ecSpec = java.security.spec.ECGenParameterSpec("secp256r1")
- val params = java.security.AlgorithmParameters.getInstance("EC")
- params.init(ecSpec)
- val ecParameterSpec = params.getParameterSpec(java.security.spec.ECParameterSpec::class.java)
-
- // Create ECPrivateKeySpec with the d value and curve parameters
- val privKeySpec = java.security.spec.ECPrivateKeySpec(d, ecParameterSpec)
-
- // Generate the private key
- val keyFactory = java.security.KeyFactory.getInstance("EC")
- return keyFactory.generatePrivate(privKeySpec) as ECPrivateKey
- }
-
- /**
- * Import an RSA private key from JWK format using the full CRT parameters.
- */
- private fun importRsaPrivateKeyFromJWK(jwk: JSONObject): java.security.PrivateKey {
- fun param(field: String): java.math.BigInteger {
- val b64 = jwk.optString(field)
- if (b64.isEmpty()) {
- throw PasskeyError.InvalidJWK("Missing '$field' parameter in RSA JWK")
- }
- return java.math.BigInteger(1, Helpers.base64urlDecode(b64))
- }
-
- val spec = java.security.spec.RSAPrivateCrtKeySpec(
- param("n"), // modulus
- param("e"), // public exponent
- param("d"), // private exponent
- param("p"), // prime p
- param("q"), // prime q
- param("dp"), // prime exponent p
- param("dq"), // prime exponent q
- param("qi"), // crt coefficient
+ prfResults = assertion.prfResults?.let { PrfResults(it.first, it.second) },
)
-
- val keyFactory = java.security.KeyFactory.getInstance("RSA")
- return keyFactory.generatePrivate(spec)
- }
-
- /**
- * Generate a key pair for the given COSE algorithm.
- */
- private fun generateKeyPair(algorithm: Int): java.security.KeyPair {
- return if (algorithm == ALG_RS256) {
- val generator = KeyPairGenerator.getInstance("RSA")
- generator.initialize(RSA_KEY_SIZE)
- generator.generateKeyPair()
- } else {
- val generator = KeyPairGenerator.getInstance("EC")
- generator.initialize(ECGenParameterSpec("secp256r1"))
- generator.generateKeyPair()
- }
- }
-
- // MARK: - CBOR Encoding
-
- /**
- * Build COSE EC2 public key for ES256.
- * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}.
- */
- private fun buildCoseEc2Es256(publicKey: ECPublicKey): ByteArray {
- val w = publicKey.w
- val xBytes = w.affineX.toByteArray().dropLeadingZeros().padTo32Bytes()
- val yBytes = w.affineY.toByteArray().dropLeadingZeros().padTo32Bytes()
-
- return byteArrayOf(
- 0xA5.toByte(), // map(5)
- 0x01, 0x02, // 1: 2 (kty: EC2)
- 0x03, 0x26, // 3: -7 (alg: ES256)
- 0x20, 0x01, // -1: 1 (crv: P-256)
- 0x21, 0x58, 0x20, // -2: bytes(32) for x
- ) + xBytes + byteArrayOf(
- 0x22, 0x58, 0x20, // -3: bytes(32) for y
- ) + yBytes
- }
-
- /**
- * Build COSE RSA public key for RS256 (RFC 8230).
- * CBOR map: {1: 3 (kty: RSA), 3: -257 (alg: RS256), -1: n (modulus), -2: e (exponent)}.
- */
- private fun buildCoseRsaRs256(publicKey: RSAPublicKey): ByteArray {
- val n = publicKey.modulus.toUnsignedBytes()
- val e = publicKey.publicExponent.toUnsignedBytes()
-
- return byteArrayOf(
- 0xA4.toByte(), // map(4)
- 0x01, 0x03, // 1: 3 (kty: RSA)
- 0x03, 0x39, 0x01, 0x00, // 3: -257 (alg: RS256)
- 0x20, // -1: modulus n
- ) + cborBytes(n) + byteArrayOf(
- 0x21, // -2: exponent e
- ) + cborBytes(e)
- }
-
- /**
- * Build attestation object with "none" format.
- * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}.
- */
- private fun buildAttestationObjectNone(authenticatorData: ByteArray): ByteArray {
- return byteArrayOf(
- 0xA3.toByte(), // map(3)
- ) +
- cborText("fmt") +
- cborText("none") +
- cborText("attStmt") +
- byteArrayOf(0xA0.toByte()) + // map(0) - empty attStmt
- cborText("authData") +
- cborBytes(authenticatorData)
- }
-
- /**
- * Encode a string as CBOR text.
- */
- private fun cborText(text: String): ByteArray {
- val bytes = text.toByteArray(Charsets.UTF_8)
- return when {
- bytes.size <= 23 -> byteArrayOf((0x60 or bytes.size).toByte()) + bytes
- bytes.size <= 0xFF -> byteArrayOf(0x78, bytes.size.toByte()) + bytes
- else -> byteArrayOf(
- 0x79,
- ((bytes.size shr 8) and 0xFF).toByte(),
- (bytes.size and 0xFF).toByte(),
- ) + bytes
- }
- }
-
- /**
- * Encode bytes as CBOR byte string.
- */
- private fun cborBytes(bytes: ByteArray): ByteArray {
- return when {
- bytes.size <= 23 -> byteArrayOf((0x40 or bytes.size).toByte()) + bytes
- bytes.size <= 0xFF -> byteArrayOf(0x58, bytes.size.toByte()) + bytes
- else -> byteArrayOf(
- 0x59,
- ((bytes.size shr 8) and 0xFF).toByte(),
- (bytes.size and 0xFF).toByte(),
- ) + bytes
- }
- }
-
- // MARK: - PRF Extension
-
- /**
- * Evaluate PRF (hmac-secret extension).
- * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt)).
- */
- private fun evaluatePrf(secret: ByteArray, salt: ByteArray): ByteArray {
- // Step 1: Domain separation - hash salt with "WebAuthn PRF\x00" prefix
- val prefix = "WebAuthn PRF\u0000".toByteArray(Charsets.UTF_8)
- val domainSeparatedSalt = prefix + salt
-
- val md = MessageDigest.getInstance("SHA-256")
- val hashedSalt = md.digest(domainSeparatedSalt)
-
- // Step 2: Compute HMAC-SHA256(prfSecret, hashedSalt)
- val mac = Mac.getInstance("HmacSHA256")
- val secretKey = SecretKeySpec(secret, "HmacSHA256")
- mac.init(secretKey)
- return mac.doFinal(hashedSalt)
}
- // MARK: - Helper Extensions
-
- private fun ByteArray.dropLeadingZeros(): ByteArray {
- var index = 0
- while (index < this.size - 1 && this[index] == 0.toByte()) {
- index++
- }
- return this.copyOfRange(index, this.size)
- }
-
- private fun ByteArray.padTo32Bytes(): ByteArray {
- if (this.size == 32) return this
- val padded = ByteArray(32)
- System.arraycopy(this, 0, padded, 32 - this.size, this.size)
- return padded
- }
-
- /**
- * Convert a (positive) BigInteger to its minimal unsigned big-endian byte representation.
- * BigInteger.toByteArray() is two's-complement and may carry a leading 0x00 sign byte.
- */
- private fun java.math.BigInteger.toUnsignedBytes(): ByteArray = this.toByteArray().dropLeadingZeros()
+ private fun PrfInputs.toRust(): PasskeyPrfInputs = PasskeyPrfInputs(first, second)
// MARK: - Supporting Types
@@ -724,39 +272,4 @@ object PasskeyAuthenticator {
return result
}
}
-
- /**
- * Base class for passkey-related errors.
- */
- sealed class PasskeyError(message: String) : Exception(message) {
- /**
- * Error indicating an invalid public key.
- */
- class InvalidPublicKey(message: String) : PasskeyError(message)
-
- /**
- * Error indicating an invalid private key.
- */
- class InvalidPrivateKey(message: String) : PasskeyError(message)
-
- /**
- * Error indicating an invalid JWK format.
- */
- class InvalidJWK(message: String) : PasskeyError(message)
-
- /**
- * Error indicating an invalid signature.
- */
- class InvalidSignature(message: String) : PasskeyError(message)
-
- /**
- * Error indicating CBOR encoding failure.
- */
- class CborEncodingFailed(message: String) : PasskeyError(message)
-
- /**
- * Error indicating none of the RP-requested algorithms are supported.
- */
- class UnsupportedAlgorithm(message: String) : PasskeyError(message)
- }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt
deleted file mode 100644
index 0e5553ca6..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt
+++ /dev/null
@@ -1,71 +0,0 @@
-package net.aliasvault.app.vaultstore.passkey
-
-/**
- * PasskeyHelper
- * -------------------------
- * Utility class for passkey-related operations, including GUID/base64url conversions.
- *
- * This is a Kotlin port of the reference TypeScript implementation:
- * - Reference: apps/browser-extension/src/utils/passkey/PasskeyHelper.ts
- * - iOS: apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyHelper.swift
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
- */
-object PasskeyHelper {
-
- /**
- * Convert GUID string to byte array.
- * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → ByteArray(16 bytes).
- */
- @JvmStatic
- fun guidToBytes(guid: String): ByteArray {
- // Remove dashes
- val hex = guid.replace("-", "")
-
- require(hex.length == 32) { "Invalid GUID format" }
-
- val bytes = ByteArray(16)
- for (i in 0..15) {
- bytes[i] = hex.substring(i * 2, i * 2 + 2).toInt(16).toByte()
- }
- return bytes
- }
-
- /**
- * Convert byte array to GUID string.
- * Example: ByteArray(16 bytes) → "3f2504e0-4f89-11d3-9a0c-0305e82c3301".
- */
- @JvmStatic
- fun bytesToGuid(bytes: ByteArray): String {
- require(bytes.size == 16) { "Invalid byte length for GUID" }
-
- val hex = bytes.joinToString("") { "%02x".format(it) }
-
- // Insert dashes in canonical format: 8-4-4-4-12
- return buildString {
- append(hex.substring(0, 8))
- append("-")
- append(hex.substring(8, 12))
- append("-")
- append(hex.substring(12, 16))
- append("-")
- append(hex.substring(16, 20))
- append("-")
- append(hex.substring(20))
- }
- }
-
- /**
- * Convert byte array to Base64URL encoding.
- * Base64URL uses - instead of + and _ instead of /, and omits padding.
- */
- @JvmStatic
- fun bytesToBase64url(bytes: ByteArray): String {
- val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
- return base64
- .replace('+', '-')
- .replace('/', '_')
- .trimEnd('=')
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
deleted file mode 100644
index 112d7e5c6..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
+++ /dev/null
@@ -1,89 +0,0 @@
-package net.aliasvault.app.vaultstore.queries
-
-/**
- * SQL query constants for the item reads the autofill service needs.
- * Every join and lookup is keyed by (ManifestId, Id) because the same id can exist in more than one manifest.
- */
-object ItemQueries {
- /**
- * Base SELECT for items with common fields.
- * Includes a LEFT JOIN to the item's logo row and scoped subqueries for HasPasskey/HasAttachment/HasTotp.
- */
- const val BASE_SELECT = """
- SELECT DISTINCT
- i.Id,
- i.ManifestId,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- l.Kind as LogoKind,
- l.Source as LogoSource,
- 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.ArchivedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
- """
-
- /**
- * Get all active items (not deleted, not in trash, not archived).
- */
- const val GET_ALL_ACTIVE = """
- $BASE_SELECT
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
- ORDER BY i.CreatedAt DESC
- """
-
- /**
- * Get field values for multiple items, matched on the whole (ManifestId, ItemId) key.
- * @param itemCount Number of items (one `(?, ?)` pair each, bound as manifestId, itemId, ...)
- * @return Query with placeholders
- */
- fun getFieldValuesForItems(itemCount: Int): String {
- val placeholders = Array(itemCount) { "(?, ?)" }.joinToString(", ")
- return """
- SELECT
- fv.ItemId,
- fv.ManifestId,
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fd.ManifestId = fv.ManifestId AND fd.Id = fv.FieldDefinitionId
- WHERE (fv.ManifestId, fv.ItemId) IN (VALUES $placeholders)
- AND fv.IsDeleted = 0
- ORDER BY fv.ItemId, fv.Weight, fv.ValueIndex
- """.trimIndent()
- }
-
- /**
- * Get an item's TOTP codes. Binds (itemId, manifestId).
- */
- const val GET_TOTP_CODES_FOR_ITEM = """
- SELECT Id, Name, SecretKey, Algorithm, Digits, Period, ItemId
- FROM TotpCodes
- WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0
- """
-
- /**
- * Get folder data for building folder paths, one tree per manifest.
- */
- const val GET_ALL_FOLDERS = """
- SELECT Id, ManifestId, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
- """
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt
deleted file mode 100644
index 9036e2928..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-package net.aliasvault.app.vaultstore.queries
-
-/**
- * SQL query constants for per-item usage statistics.
- */
-object ItemStatsQueries {
- /**
- * Create the stats row for an item on its first recorded use. Binds (manifestId, itemId, now, now).
- */
- const val INSERT_ROW = """
- INSERT OR IGNORE INTO ItemStats (
- ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,
- LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted
- )
- VALUES (?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)
- """
-
- /**
- * Record one use of an item, bumping the aggregate and the per-action pair. The column names come from
- * a closed set, never from caller input. IsDeleted is cleared because a use resurrects a row the pruner
- * tombstoned. Binds (now, now, now, manifestId, itemId).
- */
- fun forAction(lastColumn: String, countColumn: String): String {
- return """
- UPDATE ItemStats
- SET LastUsedAt = ?,
- UseCount = UseCount + 1,
- $lastColumn = ?,
- $countColumn = $countColumn + 1,
- UpdatedAt = ?,
- IsDeleted = 0
- WHERE ManifestId = ? AND Id = ?
- """.trimIndent()
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
deleted file mode 100644
index 8c6f6bfaa..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
+++ /dev/null
@@ -1,204 +0,0 @@
-package net.aliasvault.app.vaultstore.queries
-
-import net.aliasvault.app.vaultstore.models.FieldKey
-
-/**
- * SQL query constants for Passkey operations.
- */
-object PasskeyQueries {
- /**
- * Base SELECT for passkeys without item information.
- */
- const val BASE_SELECT = """
- SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.AdditionalData, p.CreatedAt, p.UpdatedAt, p.IsDeleted
- FROM Passkeys p
- """
-
- /**
- * Base SELECT for passkeys joined to their live (not trashed, not tombstoned) item.
- */
- const val BASE_SELECT_WITH_ITEM = """
- SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.AdditionalData, p.CreatedAt, p.UpdatedAt, p.IsDeleted,
- i.Name as ServiceName,
- i.CreatedAt as ItemCreatedAt,
- i.UpdatedAt as ItemUpdatedAt,
- (SELECT fv.Value FROM FieldValues fv
- WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LOGIN_USERNAME}' 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.LOGIN_EMAIL}' 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
- """
-
- /**
- * Get a passkey by its ID (which is also the WebAuthn credential ID), only while its item is live.
- * Searches every manifest deterministically.
- */
- const val GET_BY_ID = """
- $BASE_SELECT_WITH_ITEM
- WHERE p.Id = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC, p.ManifestId
- LIMIT 1
- """
-
- /**
- * Get all passkeys for an item. Binds (itemId, manifestId).
- */
- const val GET_BY_ITEM_ID = """
- $BASE_SELECT
- WHERE p.ItemId = ? AND p.ManifestId = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC
- """
-
- /**
- * Get all passkeys for a relying party (rpId) whose item is live.
- */
- const val GET_BY_RP_ID = """
- $BASE_SELECT_WITH_ITEM
- WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC, p.ManifestId
- """
-
- /**
- * Get every passkey whose item is live, with the item's display info.
- */
- const val GET_ALL_WITH_ITEMS = """
- $BASE_SELECT_WITH_ITEM
- WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC, p.ManifestId
- """
-
- /**
- * Insert a new passkey, stamped with the manifest of the item it hangs off (bound third, after the item id).
- */
- const val INSERT = """
- INSERT INTO Passkeys (Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey,
- PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """
-
- /**
- * Soft delete a passkey. Binds (now, id, manifestId).
- */
- const val SOFT_DELETE = """
- UPDATE Passkeys SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
- """
-
- /**
- * Get ALL active Login items that don't have a passkey yet (no URL filtering).
- * Used with RustItemMatcher for intelligent, cross-platform consistent filtering.
- */
- val GET_ALL_ITEMS_WITHOUT_PASSKEY = """
- SELECT i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
- GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
- fv_username.Value as Username,
- fv_email.Value as Email,
- fv_password.Value as Password
- FROM Items i
- LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id AND fv_url.ManifestId = i.ManifestId
- AND fv_url.FieldKey = ?
- AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id AND fv_username.ManifestId = i.ManifestId
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.ManifestId = i.ManifestId
- AND fv_email.FieldKey = ?
- AND fv_email.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id AND fv_password.ManifestId = i.ManifestId
- AND fv_password.FieldKey = ?
- AND fv_password.IsDeleted = 0
- WHERE i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- AND i.ArchivedAt IS NULL
- AND i.ItemType = 'Login'
- AND NOT EXISTS (
- SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0
- )
- GROUP BY i.ManifestId, i.Id
- ORDER BY i.UpdatedAt DESC
- """.trimIndent()
-
- /**
- * Create an Item record for passkey registration. Binds (id, name, itemType, logoId, folderId, now, now, 0, null, manifestId).
- */
- const val CREATE_ITEM = """
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt, ManifestId)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """
-
- /**
- * Insert a field value. Binds (id, itemId, fieldDefinitionId, fieldKey, value, weight, now, now, 0, manifestId).
- */
- const val INSERT_FIELD_VALUE = """
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6,
- (SELECT COALESCE(MAX(ValueIndex), -1) + 1 FROM FieldValues WHERE ItemId = ?2 AND ManifestId = ?10 AND FieldKey = ?4 AND IsDeleted = 0),
- ?7, ?8, ?9, ?10)
- """
-
- /**
- * Get the logo ID of an item. Binds (id, manifestId).
- */
- const val GET_LOGO_ID_FROM_ITEM = """
- SELECT LogoId FROM Items WHERE Id = ? AND ManifestId = ?
- """
-}
-
-/**
- * SQL query constants for the Logos rows the passkey flows read and write.
- * Mirrors core/client LogoQueries.ts.
- */
-object LogoQueries {
- /**
- * The id of the logo with this kind and key inside one manifest. Binds (manifestId, kind, source).
- */
- const val GET_ID_FOR_KEY = """
- SELECT Id FROM Logos
- WHERE ManifestId = ? AND Kind = ? AND Source = ? AND IsDeleted = 0
- LIMIT 1
- """
-
- /**
- * The best row to copy from when a manifest needs a logo it does not have but the vault does. Binds (kind, source).
- */
- const val GET_BEST_FOR_KEY = """
- SELECT FileData, MimeType, Name FROM Logos
- WHERE Kind = ? AND Source = ? AND IsDeleted = 0
- ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC
- LIMIT 1
- """
-
- /**
- * The kind and key of an item's logo, which always lives in the item's own manifest. Binds (id, manifestId).
- */
- const val GET_BY_ID = """
- SELECT Id, Kind, Source, Name FROM Logos
- WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0
- """
-
- /**
- * Insert or refresh a logo. Binds (id, kind, source, manifestId, fileData, mimeType, name, now, now).
- */
- const val UPSERT = """
- INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
- ON CONFLICT(ManifestId, Id) DO UPDATE SET
- FileData = excluded.FileData,
- MimeType = excluded.MimeType,
- Name = COALESCE(excluded.Name, Logos.Name),
- UpdatedAt = excluded.UpdatedAt,
- IsDeleted = 0
- """
-
- /**
- * Point an item at a logo. Binds (logoId, now, itemId, manifestId).
- */
- const val UPDATE_ITEM_LOGO_ID = """
- UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
- """
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt
deleted file mode 100644
index 57b9bf4a4..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt
+++ /dev/null
@@ -1,86 +0,0 @@
-package net.aliasvault.app.vaultstore.repositories
-
-import net.aliasvault.app.utils.DateHelpers
-import net.aliasvault.app.vaultstore.AppError
-import net.aliasvault.app.vaultstore.VaultDatabase
-import net.aliasvault.app.vaultstore.models.VaultMutationScope
-import java.util.UUID
-
-/**
- * The grouping key of a manifest-scoped row, for joining rows of one query to rows of another in memory.
- */
-fun scopedKey(manifestId: String, id: String): String {
- return "${manifestId.lowercase()}${id.lowercase()}"
-}
-
-/**
- * Base repository class with common database operations.
- */
-open class BaseRepository(
- /** The database component used for executing queries. */
- protected val database: VaultDatabase,
-) {
- /**
- * The manifest new rows outside any folder or item are stamped with: the personal manifest. Rows inside a
- * folder or item take that parent's manifest through the SQL instead. Throws when no manifest has been
- * recorded yet, since an unstamped row would make every later push of the vault fail.
- */
- protected fun writeManifestId(): String {
- return database.getPersonalManifestId() ?: throw AppError.ManifestNotRecorded()
- }
-
- // MARK: - Transaction Helpers
-
- /**
- * Execute a function within a transaction. The commit persists the vault and marks it dirty, so every
- * repository write reaches the next sync.
- * @param scope What the mutation touched, so the next sync can push only that scope
- * @param operation The function to execute within the transaction
- * @return The result of the function
- */
- fun <T> withTransaction(scope: String = VaultMutationScope.MAIN, operation: () -> T): T {
- database.beginTransaction()
- return try {
- val result = operation()
- database.commitTransaction(scope)
- result
- } catch (e: Exception) {
- database.rollbackTransaction()
- throw e
- }
- }
-
- // MARK: - Utility Methods
-
- /**
- * Generate a new id.
- * @return A new UUID string
- */
- fun generateId(): String {
- return UUID.randomUUID().toString()
- }
-
- /**
- * Get the current timestamp in the standard format.
- * @return Current timestamp string
- */
- fun now(): String {
- return DateHelpers.now()
- }
-
- // MARK: - Database Operation Helpers
-
- /**
- * Execute a SELECT query on the database.
- */
- protected fun executeQuery(query: String, params: Array<Any?>): List<Map<String, Any?>> {
- return database.query(query, params.toList())
- }
-
- /**
- * Execute an UPDATE, INSERT, or DELETE query on the database.
- */
- protected fun executeUpdate(query: String, params: Array<Any?>): Int {
- return database.execute(query, params.toList())
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
deleted file mode 100644
index 4ca736454..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
+++ /dev/null
@@ -1,113 +0,0 @@
-package net.aliasvault.app.vaultstore.repositories
-
-import android.util.Log
-import net.aliasvault.app.vaultstore.VaultDatabase
-import net.aliasvault.app.vaultstore.mappers.FieldMapper
-import net.aliasvault.app.vaultstore.mappers.FieldRow
-import net.aliasvault.app.vaultstore.mappers.ItemMapper
-import net.aliasvault.app.vaultstore.mappers.ItemRow
-import net.aliasvault.app.vaultstore.models.Item
-import net.aliasvault.app.vaultstore.models.TotpCode
-import net.aliasvault.app.vaultstore.queries.ItemQueries
-import net.aliasvault.app.vaultstore.utils.FolderUtils
-import java.util.UUID
-
-/**
- * Repository for the item reads the autofill service needs.
- * Other platform implementations: ItemRepository.ts (core/client), ItemRepository.swift (iOS).
- */
-class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
- companion object {
- private const val TAG = "ItemRepository"
- }
-
- // MARK: - Read Operations
-
- /**
- * Build folder paths for all folders, keyed by the folder's scoped key (manifest + id). The tree is walked
- * one manifest at a time: a parent link only ever resolves inside its own namespace.
- *
- * @return Map of scoped folder key to folder path array.
- */
- private fun buildFolderPaths(): Map<String, List<String>> {
- val folderPathMap = mutableMapOf<String, List<String>>()
-
- try {
- val folderResults = executeQuery(ItemQueries.GET_ALL_FOLDERS, emptyArray())
- if (folderResults.isEmpty()) {
- return folderPathMap
- }
-
- val foldersByManifest = mutableMapOf<String, MutableList<FolderUtils.Folder>>()
- for (row in folderResults) {
- try {
- val idString = row["Id"] as? String
- val manifestId = row["ManifestId"] as? String
- val name = row["Name"] as? String
- if (idString == null || manifestId == null || name == null) continue
- val parentFolderId = (row["ParentFolderId"] as? String)?.let { UUID.fromString(it) }
- foldersByManifest.getOrPut(manifestId) { mutableListOf() }.add(FolderUtils.Folder(UUID.fromString(idString), name, parentFolderId))
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing folder row", e)
- }
- }
-
- for ((manifestId, folders) in foldersByManifest) {
- for (folder in folders) {
- val path = FolderUtils.getFolderPath(folder.id, folders)
- if (path.isNotEmpty()) {
- folderPathMap[scopedKey(manifestId, folder.id.toString())] = path
- }
- }
- }
-
- return folderPathMap
- } catch (e: Exception) {
- // Folders table may not exist in older vault versions
- Log.e(TAG, "Error building folder paths", e)
- return folderPathMap
- }
- }
-
- /**
- * Fetch all active items (not deleted, not in trash, not archived) with their fields.
- *
- * @return List of Item objects.
- */
- fun getAll(): List<Item> {
- val itemRows = executeQuery(ItemQueries.GET_ALL_ACTIVE, emptyArray()).mapNotNull { ItemRow.fromRow(it) }
- if (itemRows.isEmpty()) {
- return emptyList()
- }
-
- // Fields are matched on the whole (ManifestId, Id) key, bound as one pair per item.
- val keyBindings = itemRows.flatMap { listOf<Any?>(it.manifestId, it.id.lowercase()) }.toTypedArray()
- val fieldRows = executeQuery(ItemQueries.getFieldValuesForItems(itemRows.size), keyBindings).mapNotNull { FieldRow.fromRow(it) }
- val fieldsByItem = FieldMapper.processFieldRows(fieldRows)
- val folderPaths = buildFolderPaths()
-
- return ItemMapper.mapRows(itemRows, fieldsByItem, folderPaths)
- }
-
- /**
- * Get the first non-deleted TOTP code for an item, or null when there is none.
- * Used by the autofill service to copy the current TOTP code to the clipboard
- * when the user selects a credential to fill.
- *
- * @param itemId The UUID of the item.
- * @param manifestId The manifest the item belongs to.
- * @return The TOTP code with its RFC 6238 parameters, or null.
- */
- fun getTotpForItem(itemId: String, manifestId: String): TotpCode? {
- val results = executeQuery("${ItemQueries.GET_TOTP_CODES_FOR_ITEM} LIMIT 1", arrayOf(itemId.lowercase(), manifestId))
- val row = results.firstOrNull() ?: return null
- val secretKey = row["SecretKey"] as? String ?: return null
-
- return TotpCode(
- secretKey = secretKey,
- algorithm = row["Algorithm"] as? String ?: TotpCode.DEFAULT_ALGORITHM,
- digits = (row["Digits"] as? Long)?.toInt() ?: TotpCode.DEFAULT_DIGITS,
- period = (row["Period"] as? Long)?.toInt() ?: TotpCode.DEFAULT_PERIOD,
- )
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt
deleted file mode 100644
index 9bb334712..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt
+++ /dev/null
@@ -1,45 +0,0 @@
-package net.aliasvault.app.vaultstore.repositories
-
-import net.aliasvault.app.vaultstore.VaultDatabase
-import net.aliasvault.app.vaultstore.models.VaultDataBucketCategory
-import net.aliasvault.app.vaultstore.queries.ItemStatsQueries
-
-/**
- * The actions whose use of an item is recorded, each with its own timestamp + counter pair.
- */
-enum class ItemUsageAction(
- /** The per-action timestamp column. */
- val lastColumn: String,
- /** The per-action counter column. */
- val countColumn: String,
-) {
- /** The item was filled into a form. */
- AUTOFILL("LastAutofilledAt", "AutofillCount"),
-
- /** A value of the item was copied. */
- COPY("LastCopiedAt", "CopyCount"),
-
- /** The item's passkey signed an assertion. */
- PASSKEY("LastPasskeyAuthAt", "PasskeyAuthCount"),
-}
-
-/**
- * Repository for per-item usage statistics.
- */
-class ItemStatsRepository(database: VaultDatabase) : BaseRepository(database) {
- /**
- * Record one use of an item, in its own transaction so the vault is persisted and marked dirty.
- * @param itemId The item that was used
- * @param manifestId The manifest the item belongs to
- * @param action What the user did with it
- */
- fun recordUsage(itemId: String, manifestId: String, action: ItemUsageAction) {
- // Usage statistics live in their own data bucket which should be pushed without a full manifest write.
- withTransaction(VaultDataBucketCategory.STATS) {
- val now = now()
- val id = itemId.lowercase()
- executeUpdate(ItemStatsQueries.INSERT_ROW, arrayOf(manifestId, id, now, now))
- executeUpdate(ItemStatsQueries.forAction(action.lastColumn, action.countColumn), arrayOf(now, now, now, manifestId, id))
- }
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
deleted file mode 100644
index 28e515522..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
+++ /dev/null
@@ -1,554 +0,0 @@
-package net.aliasvault.app.vaultstore.repositories
-
-import android.util.Log
-import net.aliasvault.app.autofill.utils.RustItemMatcher
-import net.aliasvault.app.utils.DateHelpers
-import net.aliasvault.app.vaultstore.VaultDatabase
-import net.aliasvault.app.vaultstore.mappers.ItemMapper
-import net.aliasvault.app.vaultstore.mappers.PasskeyMapper
-import net.aliasvault.app.vaultstore.mappers.PasskeyRow
-import net.aliasvault.app.vaultstore.mappers.PasskeyWithItem
-import net.aliasvault.app.vaultstore.mappers.PasskeyWithItemRow
-import net.aliasvault.app.vaultstore.models.FieldKey
-import net.aliasvault.app.vaultstore.models.Item
-import net.aliasvault.app.vaultstore.models.Passkey
-import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
-import net.aliasvault.app.vaultstore.queries.LogoQueries
-import net.aliasvault.app.vaultstore.queries.PasskeyQueries
-import uniffi.aliasvault_core.faviconSourceKey
-import uniffi.aliasvault_core.vaultCodecLogoIdFor
-import java.util.Date
-import java.util.UUID
-
-/**
- * Repository for Passkey operations on Items.
- * Other platform implementations: PasskeyRepository.ts (core/client), PasskeyRepository.swift (iOS).
- */
-class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
- companion object {
- private const val TAG = "PasskeyRepository"
- private const val LOGO_KIND_FAVICON = "favicon"
- private const val FAVICON_MIME_TYPE = "image/x-icon"
-
- /*
- * FieldValues.Weight of the two system fields a passkey item gets: the DefaultDisplayOrder of
- * login.url and login.username in core/models/src/vault/SystemFieldRegistry.ts.
- */
- private const val LOGIN_URL_WEIGHT = 5
- private const val LOGIN_USERNAME_WEIGHT = 15
- }
-
- /**
- * The identity of a logo row: its kind and the natural key within that kind.
- */
- private data class LogoRef(val kind: String, val source: String)
-
- // MARK: - Read Operations
-
- /**
- * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Item UUID).
- * @param credentialId The WebAuthn credential ID bytes
- * @return Passkey object or null if not found
- */
- fun getByCredentialId(credentialId: ByteArray): Passkey? {
- val credentialIdString = try {
- PasskeyHelper.bytesToGuid(credentialId)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to convert credentialId bytes to UUID string", e)
- return null
- }
-
- val results = executeQuery(PasskeyQueries.GET_BY_ID, arrayOf(credentialIdString.lowercase()))
- return results.firstOrNull()?.let { parsePasskeyRow(it) }
- }
-
- /**
- * Get all passkeys for an item.
- * @param itemId The UUID of the parent item
- * @param manifestId The manifest the item belongs to
- * @return List of Passkey objects
- */
- fun getByItemId(itemId: UUID, manifestId: String): List<Passkey> {
- val results = executeQuery(PasskeyQueries.GET_BY_ITEM_ID, arrayOf(itemId.toString().lowercase(), manifestId))
- return results.mapNotNull { parsePasskeyRow(it) }
- }
-
- /**
- * Get all passkeys for a specific relying party identifier (RP ID) whose item is live.
- * @param rpId The relying party identifier
- * @return List of Passkey objects
- */
- fun getByRpId(rpId: String): List<Passkey> {
- val results = executeQuery(PasskeyQueries.GET_BY_RP_ID, arrayOf(rpId))
- return results.mapNotNull { parsePasskeyRow(it) }
- }
-
- /**
- * Get a passkey by its ID, only while its item is live.
- * @param passkeyId The UUID of the passkey
- * @return Passkey object or null if not found
- */
- fun getById(passkeyId: UUID): Passkey? {
- val results = executeQuery(PasskeyQueries.GET_BY_ID, arrayOf(passkeyId.toString().lowercase()))
- return results.firstOrNull()?.let { parsePasskeyRow(it) }
- }
-
- // MARK: - Write Operations
-
- /**
- * Insert a new passkey, stamped with the manifest of its item, which the caller has already put on it.
- * @param passkey The passkey to insert
- */
- private fun insert(passkey: Passkey) {
- val manifestId = passkey.manifestId ?: error("Passkey has no manifest: ${passkey.id}")
- executeUpdate(
- PasskeyQueries.INSERT,
- arrayOf(
- passkey.id.toString().lowercase(),
- passkey.parentItemId.toString().lowercase(),
- manifestId,
- passkey.rpId,
- passkey.userHandle,
- String(passkey.publicKey, Charsets.UTF_8),
- String(passkey.privateKey, Charsets.UTF_8),
- passkey.prfKey,
- passkey.displayName,
- passkey.additionalData,
- DateHelpers.toStandardFormat(passkey.createdAt),
- DateHelpers.toStandardFormat(passkey.updatedAt),
- if (passkey.isDeleted) 1L else 0L,
- ),
- )
- }
-
- /**
- * Create a new item with an associated passkey, in the personal manifest.
- * @param url The item's login URL, which the favicon was fetched for
- * @param userName The username (optional)
- * @param displayName The display name
- * @param passkey The passkey to associate
- * @param logo The favicon bytes fetched for the url (optional)
- * @return The created Item
- */
- fun createItemWithPasskey(
- url: String,
- userName: String?,
- displayName: String,
- passkey: Passkey,
- logo: ByteArray? = null,
- ): Item {
- return withTransaction {
- val manifestId = writeManifestId()
- val itemId = passkey.parentItemId.toString().lowercase()
- val now = Date()
- val timestamp = DateHelpers.toStandardFormat(now)
-
- val logoId = resolveLogoId(manifestId, null, url, logo, timestamp)
-
- // Create the Item
- executeUpdate(
- PasskeyQueries.CREATE_ITEM,
- arrayOf(itemId, displayName, "Login", logoId, null, timestamp, timestamp, 0, null, manifestId),
- )
-
- // Insert URL and username field values
- if (url.isNotEmpty()) {
- insertFieldValue(itemId, manifestId, FieldKey.LOGIN_URL, url, LOGIN_URL_WEIGHT, timestamp)
- }
- if (userName != null) {
- insertFieldValue(itemId, manifestId, FieldKey.LOGIN_USERNAME, userName, LOGIN_USERNAME_WEIGHT, timestamp)
- }
-
- insert(passkey.copy(manifestId = manifestId))
-
- // Return a minimal Item object; the full item is loaded via getAllItems()
- Item(
- id = passkey.parentItemId,
- manifestId = manifestId,
- name = displayName,
- itemType = "Login",
- logo = logo,
- folderId = null,
- folderPath = null,
- fields = emptyList(),
- hasPasskey = true,
- hasAttachment = false,
- hasTotp = false,
- createdAt = now,
- updatedAt = now,
- )
- }
- }
-
- /**
- * Replace an existing passkey with a new one on the same item.
- *
- * @param oldPasskeyId The UUID of the passkey to replace.
- * @param newPasskey The new passkey.
- * @param displayName The updated display name.
- * @param url The login URL the favicon was fetched for.
- * @param logo The favicon bytes fetched for the url (optional).
- */
- fun replace(
- oldPasskeyId: UUID,
- newPasskey: Passkey,
- displayName: String,
- url: String,
- logo: ByteArray? = null,
- ) {
- withTransaction {
- val now = Date()
- val timestamp = DateHelpers.toStandardFormat(now)
-
- // Get the old passkey to find its item and manifest
- val oldPasskey = getById(oldPasskeyId) ?: error("Passkey not found: $oldPasskeyId")
- val manifestId = oldPasskey.manifestId ?: error("Passkey has no manifest: $oldPasskeyId")
- val itemId = oldPasskey.parentItemId.toString().lowercase()
-
- updateItemLogo(itemId, manifestId, url, logo, timestamp)
-
- // Soft delete the old passkey
- executeUpdate(PasskeyQueries.SOFT_DELETE, arrayOf(timestamp, oldPasskeyId.toString().lowercase(), manifestId))
-
- // Create the new passkey with the same item ID
- insert(
- newPasskey.copy(
- parentItemId = oldPasskey.parentItemId,
- manifestId = manifestId,
- displayName = displayName,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
- ),
- )
- }
- }
-
- /**
- * Add a passkey to an existing Item (merge passkey into existing credential).
- *
- * @param itemId The UUID of the existing Item to add the passkey to.
- * @param manifestId The manifest the item belongs to.
- * @param passkey The passkey to add (will have its parentItemId updated).
- * @param url The login URL the favicon was fetched for.
- * @param logo The favicon bytes fetched for the url (optional).
- */
- fun addPasskeyToExistingItem(
- itemId: UUID,
- manifestId: String,
- passkey: Passkey,
- url: String,
- logo: ByteArray? = null,
- ) {
- withTransaction {
- val now = Date()
- val timestamp = DateHelpers.toStandardFormat(now)
- val id = itemId.toString().lowercase()
-
- updateItemLogo(id, manifestId, url, logo, timestamp)
-
- insert(
- passkey.copy(
- parentItemId = itemId,
- manifestId = manifestId,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
- ),
- )
- }
- }
-
- // MARK: - Complex Query Operations
-
- /**
- * Get passkeys with item info for a specific rpId and optionally username.
- * Used for finding existing passkeys that might be replaced during registration.
- *
- * @param rpId The relying party identifier.
- * @param userName Optional username to filter by.
- * @param userId Optional user ID bytes to filter by.
- * @return List of PasskeyAndItem objects.
- */
- fun getWithItem(
- rpId: String,
- userName: String? = null,
- userId: ByteArray? = null,
- ): List<PasskeyWithItem> {
- if (!database.isOpen()) return emptyList()
-
- val rows = executeQuery(PasskeyQueries.GET_BY_RP_ID, arrayOf(rpId)).mapNotNull { PasskeyWithItemRow.fromRow(it) }
- return PasskeyMapper.mapRowsWithItem(rows).filter { entry ->
- // Filter by username or userId if provided
- val usernameMatches = userName == null || entry.username == userName
- val userIdMatches = userId == null || entry.passkey.userHandle == null || userId.contentEquals(entry.passkey.userHandle)
- usernameMatches && userIdMatches
- }
- }
-
- /**
- * Get ALL active Login items that don't have a passkey yet (no URL filtering).
- * Used with RustCredentialMatcher for intelligent, cross-platform consistent filtering.
- *
- * @return List of ItemWithCredentialInfo objects with all URLs.
- */
- fun getAllItemsWithoutPasskey(): List<ItemWithCredentialInfo> {
- if (!database.isOpen()) return emptyList()
-
- val results = mutableListOf<ItemWithCredentialInfo>()
- val rows = executeQuery(
- PasskeyQueries.GET_ALL_ITEMS_WITHOUT_PASSKEY,
- arrayOf(FieldKey.LOGIN_URL, FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL, FieldKey.LOGIN_PASSWORD),
- )
-
- for (row in rows) {
- try {
- val itemIdString = row["Id"] as? String
- val manifestId = row["ManifestId"] as? String
- if (itemIdString == null || manifestId == null) continue
- val itemId = UUID.fromString(itemIdString)
- val createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?: "") ?: ItemMapper.MIN_DATE
- val updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?: "") ?: ItemMapper.MIN_DATE
- val urls = (row["Urls"] as? String)?.split(",")?.filter { it.isNotEmpty() } ?: emptyList()
-
- results.add(
- ItemWithCredentialInfo(
- itemId = itemId,
- manifestId = manifestId,
- serviceName = row["Name"] as? String,
- urls = urls,
- username = row["Username"] as? String,
- email = row["Email"] as? String,
- hasPassword = !(row["Password"] as? String).isNullOrEmpty(),
- createdAt = createdAt,
- updatedAt = updatedAt,
- ),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing item row", e)
- }
- }
-
- return results
- }
-
- /**
- * Get Items that match an rpId but don't have a passkey yet.
- * Uses the Rust credential matcher for consistent cross-platform matching logic.
- *
- * @param rpId The relying party identifier to match against.
- * @param rpName The relying party name (used for title matching fallback).
- * @param userName Optional username to filter by.
- * @return List of ItemWithCredentialInfo objects representing Items without passkeys.
- */
- fun getItemsWithoutPasskeyForRpId(
- rpId: String,
- rpName: String? = null,
- userName: String? = null,
- ): List<ItemWithCredentialInfo> {
- // Get all items without passkeys
- val allItems = getAllItemsWithoutPasskey()
-
- // Use Rust item matcher for intelligent filtering
- var matchedItems = RustItemMatcher.filterItemsForPasskeyMerge(allItems, rpId, rpName)
-
- // Apply optional username filter
- if (userName != null) {
- matchedItems = matchedItems.filter { it.username == userName }
- }
-
- return matchedItems
- }
-
- /**
- * Get all passkeys with their associated items in a single query.
- * This is much more efficient than calling getByItemId() for each item.
- *
- * @return List of PasskeyAndItem objects.
- */
- fun getAllWithItems(): List<PasskeyAndItem> {
- if (!database.isOpen()) return emptyList()
-
- val results = mutableListOf<PasskeyAndItem>()
- for (row in executeQuery(PasskeyQueries.GET_ALL_WITH_ITEMS, emptyArray())) {
- try {
- val passkey = parsePasskeyRow(row)
- val manifestId = passkey?.manifestId
- if (passkey == null || manifestId == null) continue
- val itemCreatedAt = DateHelpers.parseDateString(row["ItemCreatedAt"] as? String) ?: ItemMapper.MIN_DATE
- val itemUpdatedAt = DateHelpers.parseDateString(row["ItemUpdatedAt"] as? String) ?: ItemMapper.MIN_DATE
-
- // Create a minimal Item object with the data we have
- val item = Item(
- id = passkey.parentItemId,
- manifestId = manifestId,
- name = row["ServiceName"] as? String,
- itemType = "Login",
- logo = null,
- folderId = null,
- folderPath = null,
- fields = emptyList(), // Not loading all fields for performance
- hasPasskey = true,
- hasAttachment = false,
- hasTotp = false,
- createdAt = itemCreatedAt,
- updatedAt = itemUpdatedAt,
- )
-
- results.add(PasskeyAndItem(passkey, item))
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing passkey with item row", e)
- }
- }
-
- return results
- }
-
- // MARK: - Helper Methods
-
- /**
- * Insert one system field value on an item.
- */
- @Suppress("LongParameterList") // One argument per column written
- private fun insertFieldValue(itemId: String, manifestId: String, fieldKey: String, value: String, weight: Int, timestamp: String) {
- executeUpdate(
- PasskeyQueries.INSERT_FIELD_VALUE,
- arrayOf(generateId(), itemId, null, fieldKey, value, weight, timestamp, timestamp, 0, manifestId),
- )
- }
-
- /**
- * Point the item at the logo the item-logo rules pick for its url and the fetched bytes, when that differs
- * from the logo it has. A null pick keeps the current logo, like the COALESCE in the TS item update.
- */
- private fun updateItemLogo(itemId: String, manifestId: String, url: String, logo: ByteArray?, timestamp: String) {
- val existingLogoId = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId, manifestId)).firstOrNull()?.get("LogoId") as? String
- val logoId = resolveLogoId(manifestId, existingLogoId, url, logo, timestamp) ?: return
- if (logoId != existingLogoId) {
- executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(logoId, timestamp, itemId, manifestId))
- }
- }
-
- /**
- * The logo an item should point at, following ItemRepository.ts resolveLogoId without an explicit selection:
- * a logo the user chose earlier (built-in or uploaded) is kept; a favicon the item already has for this
- * domain is kept; fresh bytes create or refresh this domain's favicon row in the item's manifest; otherwise
- * the favicon this domain already has anywhere in the vault is reused, or none at all.
- *
- * @return The logo id, or null when the item should keep what it has (update) or get none (create)
- */
- private fun resolveLogoId(scope: String, existingLogoId: String?, url: String, logo: ByteArray?, timestamp: String): String? {
- val existing = existingLogoId?.let { getLogoById(it, scope) }
- if (existing != null && existing.kind != LOGO_KIND_FAVICON) {
- return ensureInScope(scope, existing.kind, existing.source, timestamp)
- }
-
- // Without a domain there is no natural key to store a favicon under.
- val source = faviconSourceKey(url)
- if (source.isEmpty()) {
- return null
- }
-
- if (existing != null && existing.source == source) {
- return ensureInScope(scope, LOGO_KIND_FAVICON, source, timestamp)
- }
-
- if (logo != null && logo.isNotEmpty()) {
- return upsertLogo(scope, LOGO_KIND_FAVICON, source, logo, FAVICON_MIME_TYPE, null, timestamp)
- }
-
- return ensureInScope(scope, LOGO_KIND_FAVICON, source, timestamp)
- }
-
- /**
- * The kind and key of an item's logo in the item's manifest, or null when it no longer exists.
- */
- private fun getLogoById(logoId: String, manifestId: String): LogoRef? {
- val row = executeQuery(LogoQueries.GET_BY_ID, arrayOf(logoId, manifestId)).firstOrNull() ?: return null
- val source = row["Source"] as? String ?: return null
- return LogoRef(row["Kind"] as? String ?: LOGO_KIND_FAVICON, source)
- }
-
- /**
- * The id this logo has inside the manifest, copying it in from another manifest when it is not there yet.
- * Null when the vault holds no such logo at all.
- */
- private fun ensureInScope(manifestId: String, kind: String, source: String, timestamp: String): String? {
- val inScope = executeQuery(LogoQueries.GET_ID_FOR_KEY, arrayOf(manifestId, kind, source)).firstOrNull()?.get("Id") as? String
- if (inScope != null) {
- return inScope
- }
-
- val origin = executeQuery(LogoQueries.GET_BEST_FOR_KEY, arrayOf(kind, source)).firstOrNull() ?: return null
- return upsertLogo(manifestId, kind, source, origin["FileData"] as? ByteArray, origin["MimeType"] as? String, origin["Name"] as? String, timestamp)
- }
-
- /**
- * Insert or refresh the logo for a kind and key inside one manifest. The id is derived from (manifest, kind,
- * source) by the Rust core, like every other client does, so the same logo never produces two rows.
- */
- @Suppress("LongParameterList") // One argument per column written
- private fun upsertLogo(
- manifestId: String,
- kind: String,
- source: String,
- fileData: ByteArray?,
- mimeType: String?,
- name: String?,
- timestamp: String,
- ): String {
- val logoId = vaultCodecLogoIdFor(manifestId, kind, source)
- executeUpdate(LogoQueries.UPSERT, arrayOf(logoId, kind, source, manifestId, fileData, mimeType, name, timestamp, timestamp))
- return logoId
- }
-
- /**
- * Parse a passkey row from database query results.
- */
- private fun parsePasskeyRow(row: Map<String, Any?>): Passkey? {
- return PasskeyRow.fromRow(row)?.let { PasskeyMapper.mapRow(it) }
- }
-}
-
-// MARK: - Data Classes
-
-/**
- * Data class to hold passkey with its associated item.
- *
- * @property passkey The passkey.
- * @property item The item this passkey belongs to.
- */
-data class PasskeyAndItem(
- val passkey: Passkey,
- val item: Item,
-)
-
-/**
- * Data class to hold Item info for Items without passkeys.
- * Used for showing existing credentials that can have a passkey added.
- *
- * @property itemId The UUID of the item.
- * @property manifestId The manifest the item belongs to.
- * @property serviceName The service name (Item.Name).
- * @property urls All login URLs associated with this item.
- * @property username The username from field values.
- * @property email The email from field values, used as display fallback when there is no username.
- * @property hasPassword Whether the item has a password.
- * @property createdAt When the item was created.
- * @property updatedAt When the item was last updated.
- */
-data class ItemWithCredentialInfo(
- val itemId: UUID,
- val manifestId: String,
- val serviceName: String?,
- val urls: List<String>,
- val username: String?,
- val email: String? = null,
- val hasPassword: Boolean,
- val createdAt: Date,
- val updatedAt: Date,
-) {
- /** The account identifier to display: the username, or the email when no username is set. */
- val accountLabel: String?
- get() = username?.takeIf { it.isNotBlank() } ?: email?.takeIf { it.isNotBlank() }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/utils/FolderUtils.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/utils/FolderUtils.kt
deleted file mode 100644
index 8e7439914..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/utils/FolderUtils.kt
+++ /dev/null
@@ -1,53 +0,0 @@
-package net.aliasvault.app.vaultstore.utils
-
-import java.util.UUID
-
-/**
- * The folder path of an item, built from the flat folder list of one manifest.
- * Other platform implementations: FolderUtils.ts (core/client), FolderUtils.swift (iOS).
- */
-object FolderUtils {
- /**
- * Maximum allowed folder nesting depth (root is 0, folders at depth 4 cannot have subfolders).
- */
- const val MAX_FOLDER_DEPTH = 4
-
- /**
- * Folder model matching database structure.
- *
- * @property id The unique identifier of the folder.
- * @property name The name of the folder.
- * @property parentFolderId The ID of the parent folder (null for root folders).
- */
- data class Folder(
- val id: UUID,
- val name: String,
- val parentFolderId: UUID?,
- )
-
- /**
- * Get the full path of folder names from root to the specified folder.
- * @param folderId The folder ID.
- * @param folders Flat array of all folders.
- * @return Array of folder names from root to current folder, or empty array if not found.
- */
- fun getFolderPath(folderId: UUID?, folders: List<Folder>): List<String> {
- if (folderId == null) {
- return emptyList()
- }
-
- val path = mutableListOf<String>()
- var currentId: UUID? = folderId
- var iterations = 0
-
- // Build path by traversing up to root
- while (currentId != null && iterations < MAX_FOLDER_DEPTH + 1) {
- val folder = folders.find { it.id == currentId } ?: break
- path.add(0, folder.name) // Add to beginning of array
- currentId = folder.parentFolderId
- iterations++
- }
-
- return path
- }
-}
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index 8ffd478c2..49956dda3 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -3,11 +3,10 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 60;
+ objectVersion = 70;
objects = {
/* Begin PBXBuildFile section */
- A7D10C012F000000000F0004 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };
07A10A71081ED4937FFAA625 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };
1381C2F6D317F2404928BA59 /* libPods-VaultUI.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C32D89DCBA51D7C8CDE51DD2 /* libPods-VaultUI.a */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
@@ -21,6 +20,7 @@
835999B8CD9DA8BC5D467BA1 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };
905A3FBFD11ECE1AAC428868 /* RustCoreFramework.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
9E8B9B9318C79E9CBB868429 /* libPods-VaultStoreKit.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D17078F549B652835E3A4AFA /* libPods-VaultStoreKit.a */; };
+ A7D10C012F000000000F0004 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };
B00629AD90FABE8F65D64107 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };
B18059E884C0ABDD17F3DC3D /* ExpoModulesProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAC715A2D49A985799AEE119 /* ExpoModulesProvider.swift */; };
B2E3CEC9AABDA3497BFE65B7 /* libPods-VaultStoreKitTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9E9AD944E3A0F270C797F5DD /* libPods-VaultStoreKitTests.a */; };
@@ -58,21 +58,21 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
- A7D10C012F000000000F0005 /* PBXContainerItemProxy */ = {
+ 1F09A0CB86D87B7C44135D75 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 55118F9387BE1BFE21365CB8;
remoteInfo = RustCoreFramework;
};
- 1F09A0CB86D87B7C44135D75 /* PBXContainerItemProxy */ = {
+ 438C62A9BB3AAF42A6633996 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 55118F9387BE1BFE21365CB8;
remoteInfo = RustCoreFramework;
};
- 438C62A9BB3AAF42A6633996 /* PBXContainerItemProxy */ = {
+ A7D10C012F000000000F0005 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
@@ -262,7 +262,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {
+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -272,73 +272,12 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- CE77825E2EA1822400A75E6F /* VaultUtils */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUtils;
- sourceTree = "<group>";
- };
- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKit;
- sourceTree = "<group>";
- };
- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKitTests;
- sourceTree = "<group>";
- };
- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUI;
- sourceTree = "<group>";
- };
- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultModels;
- sourceTree = "<group>";
- };
- CEE909812DA548C7008D568F /* Autofill */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = Autofill;
- sourceTree = "<group>";
- };
+ CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };
+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };
+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };
+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };
+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };
+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -490,7 +429,7 @@
path = Generated;
sourceTree = "<group>";
};
- 6114AD0A31612EA499210371 /* */ = {
+ 6114AD0A31612EA499210371 = {
isa = PBXGroup;
children = (
8F8258CE46969A87661E0302 /* RustCore.swift */,
@@ -525,7 +464,7 @@
832341AE1AAA6A7D00B99B32 /* Libraries */,
D65327D7A22EEC0BE12398D9 /* Pods */,
83CBBA001A601CBA00E9B192 /* Products */,
- 6114AD0A31612EA499210371 /* */,
+ 6114AD0A31612EA499210371,
CE5212B62F0C061800F4C835 /* Recovered References */,
3AD00C41DD88E219A26C2E41 /* RustCoreFramework */,
);
@@ -1378,12 +1317,6 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
- A7D10C012F000000000F0006 /* PBXTargetDependency */ = {
- isa = PBXTargetDependency;
- name = RustCoreFramework;
- target = 55118F9387BE1BFE21365CB8 /* RustCoreFramework */;
- targetProxy = A7D10C012F000000000F0005 /* PBXContainerItemProxy */;
- };
174AAF666366E11F87CAB46E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = RustCoreFramework;
@@ -1396,6 +1329,12 @@
target = 55118F9387BE1BFE21365CB8 /* RustCoreFramework */;
targetProxy = DEAC25BDB7E709F0299B67EA /* PBXContainerItemProxy */;
};
+ A7D10C012F000000000F0006 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ name = RustCoreFramework;
+ target = 55118F9387BE1BFE21365CB8 /* RustCoreFramework */;
+ targetProxy = A7D10C012F000000000F0005 /* PBXContainerItemProxy */;
+ };
CE48FD662DBEA3B800E5E3D6 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = CEE481692DBE8AC800F4A367 /* VaultUI */;
@@ -1656,10 +1595,7 @@
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -1722,10 +1658,7 @@
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 50516948e..f220d38d7 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -73,7 +73,7 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
}
// Generate assertion
- let credentialId = try? PasskeyHelper.guidToBytes(passkey.id.uuidString)
+ let credentialId = try? PasskeyAuthenticator.guidToBytes(passkey.id.uuidString)
let assertion = try PasskeyAuthenticator.getAssertion(
credentialId: credentialId ?? Data(),
clientDataHash: clientDataHash,
@@ -457,12 +457,11 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// Step 3: Create passkey credentials
let itemId = UUID() // Item ID that will contain the passkey
let passkeyId = UUID() // Passkey credential ID
- let credentialId = try PasskeyHelper.guidToBytes(passkeyId.uuidString)
+ let credentialId = try PasskeyAuthenticator.guidToBytes(passkeyId.uuidString)
// Create the passkey using PasskeyAuthenticator
let passkeyResult = try PasskeyAuthenticator.createPasskey(
credentialId: credentialId,
- clientDataHash: clientDataHash,
rpId: rpId,
userId: userId,
userName: userName,
@@ -604,7 +603,7 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
prfInputs: PrfInputs? = nil
) throws {
// Generate assertion using PasskeyAuthenticator
- let credentialId = try? PasskeyHelper.guidToBytes(passkey.id.uuidString)
+ let credentialId = try? PasskeyAuthenticator.guidToBytes(passkey.id.uuidString)
let assertion = try PasskeyAuthenticator.getAssertion(
credentialId: credentialId ?? Data(),
diff --git a/apps/mobile-app/ios/VaultModels/VaultSql.swift b/apps/mobile-app/ios/VaultModels/VaultSql.swift
deleted file mode 100644
index 634aa57ad..000000000
--- a/apps/mobile-app/ios/VaultModels/VaultSql.swift
+++ /dev/null
@@ -1,3081 +0,0 @@
-// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/SqlConstants.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-// swiftlint:disable all
-
-import Foundation
-
-/// SQL statements for vault creation and migration.
-public struct VaultSql {
- /// Complete database schema SQL for creating a new vault with the latest schema.
- public static let completeSchema = """
- CREATE TABLE IF NOT EXISTS \"__EFMigrationsHistory\" (
- \"MigrationId\" TEXT NOT NULL CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY,
- \"ProductVersion\" TEXT NOT NULL
- );
-
- BEGIN TRANSACTION;
- CREATE TABLE \"Aliases\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,
- \"Gender\" VARCHAR NULL,
- \"FirstName\" VARCHAR NULL,
- \"LastName\" VARCHAR NULL,
- \"NickName\" VARCHAR NULL,
- \"BirthDate\" TEXT NOT NULL,
- \"AddressStreet\" VARCHAR NULL,
- \"AddressCity\" VARCHAR NULL,
- \"AddressState\" VARCHAR NULL,
- \"AddressZipCode\" VARCHAR NULL,
- \"AddressCountry\" VARCHAR NULL,
- \"Hobbies\" TEXT NULL,
- \"EmailPrefix\" TEXT NULL,
- \"PhoneMobile\" TEXT NULL,
- \"BankAccountIBAN\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- CREATE TABLE \"Services\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Services\" PRIMARY KEY,
- \"Name\" TEXT NULL,
- \"Url\" TEXT NULL,
- \"Logo\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- CREATE TABLE \"Credentials\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,
- \"AliasId\" TEXT NOT NULL,
- \"Notes\" TEXT NULL,
- \"Username\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"ServiceId\" TEXT NOT NULL,
- CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Attachment\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachment\" PRIMARY KEY,
- \"Filename\" TEXT NOT NULL,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachment_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Passwords\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passwords\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- CONSTRAINT \"FK_Passwords_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_Attachment_CredentialId\" ON \"Attachment\" (\"CredentialId\");
-
- CREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");
-
- CREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");
-
- CREATE INDEX \"IX_Passwords_CredentialId\" ON \"Passwords\" (\"CredentialId\");
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- ALTER TABLE \"Aliases\" RENAME COLUMN \"EmailPrefix\" TO \"Email\";
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- CREATE TABLE \"EncryptionKeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"IsPrimary\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- CREATE TABLE \"Settings\" (
- \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Aliases\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,
- \"BirthDate\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Email\" TEXT NULL,
- \"FirstName\" VARCHAR NULL,
- \"Gender\" VARCHAR NULL,
- \"LastName\" VARCHAR NULL,
- \"NickName\" VARCHAR NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"ef_temp_Aliases\" (\"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\")
- SELECT \"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\"
- FROM \"Aliases\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Aliases\";
-
- ALTER TABLE \"ef_temp_Aliases\" RENAME TO \"Aliases\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.10');
-
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Credentials\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,
- \"AliasId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Notes\" TEXT NULL,
- \"ServiceId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Username\" TEXT NULL,
- CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Credentials\" (\"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\")
- SELECT \"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\"
- FROM \"Credentials\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Credentials\";
-
- ALTER TABLE \"ef_temp_Credentials\" RENAME TO \"Credentials\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");
-
- CREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.10');
-
- BEGIN TRANSACTION;
- ALTER TABLE \"Settings\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Services\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Passwords\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"EncryptionKeys\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Credentials\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Attachment\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Aliases\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
- ALTER TABLE \"Attachment\" RENAME TO \"Attachments\";
-
- CREATE TABLE \"ef_temp_Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\")
- SELECT \"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\"
- FROM \"Attachments\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Attachments\";
-
- ALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.10');
-
- BEGIN TRANSACTION;
- CREATE TABLE \"TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.10');
-
- COMMIT;
-
- BEGIN TRANSACTION;
-
- PRAGMA foreign_keys = OFF;
-
- -- Clean up any existing temp tables first
- DROP TABLE IF EXISTS \"__EFMigrationsHistory_temp\";
- DROP TABLE IF EXISTS \"Aliases_temp\";
- DROP TABLE IF EXISTS \"Services_temp\";
- DROP TABLE IF EXISTS \"EncryptionKeys_temp\";
- DROP TABLE IF EXISTS \"Settings_temp\";
- DROP TABLE IF EXISTS \"Credentials_temp\";
- DROP TABLE IF EXISTS \"Attachments_temp\";
- DROP TABLE IF EXISTS \"Passwords_temp\";
- DROP TABLE IF EXISTS \"TotpCodes_temp\";
-
- -- Create backup tables for all data
- CREATE TABLE \"__EFMigrationsHistory_temp\" AS SELECT * FROM \"__EFMigrationsHistory\";
- CREATE TABLE \"Aliases_temp\" AS SELECT * FROM \"Aliases\";
- CREATE TABLE \"Services_temp\" AS SELECT * FROM \"Services\";
- CREATE TABLE \"EncryptionKeys_temp\" AS SELECT * FROM \"EncryptionKeys\";
- CREATE TABLE \"Settings_temp\" AS SELECT * FROM \"Settings\";
- CREATE TABLE \"Credentials_temp\" AS SELECT * FROM \"Credentials\";
- CREATE TABLE \"Attachments_temp\" AS SELECT * FROM \"Attachments\";
- CREATE TABLE \"Passwords_temp\" AS SELECT * FROM \"Passwords\";
- CREATE TABLE \"TotpCodes_temp\" AS SELECT * FROM \"TotpCodes\";
-
- -- Delete orphaned records that do not have a valid FK to the credential object
- DELETE FROM \"Attachments_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"Passwords_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"TotpCodes_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
-
- -- Delete orphaned credentials that do not have valid FKs to alias or service objects
- DELETE FROM \"Credentials_temp\" WHERE \"AliasId\" NOT IN (SELECT \"Id\" FROM \"Aliases_temp\");
- DELETE FROM \"Credentials_temp\" WHERE \"ServiceId\" NOT IN (SELECT \"Id\" FROM \"Services_temp\");
-
- -- After cleaning credentials, clean dependent tables again in case we removed credentials
- DELETE FROM \"Attachments_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"Passwords_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"TotpCodes_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
-
- -- Drop all existing tables
- DROP TABLE \"TotpCodes\";
- DROP TABLE \"Passwords\";
- DROP TABLE \"Attachments\";
- DROP TABLE \"Credentials\";
- DROP TABLE \"Settings\";
- DROP TABLE \"EncryptionKeys\";
- DROP TABLE \"Services\";
- DROP TABLE \"Aliases\";
- DROP TABLE \"__EFMigrationsHistory\";
-
- -- Recreate tables with proper constraints (no dependencies first)
- CREATE TABLE \"__EFMigrationsHistory\" (
- \"MigrationId\" TEXT NOT NULL CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY,
- \"ProductVersion\" TEXT NOT NULL
- );
-
- CREATE TABLE \"Aliases\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,
- \"BirthDate\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Email\" TEXT NULL,
- \"FirstName\" VARCHAR NULL,
- \"Gender\" VARCHAR NULL,
- \"LastName\" VARCHAR NULL,
- \"NickName\" VARCHAR NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"Services\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Services\" PRIMARY KEY,
- \"Name\" TEXT NULL,
- \"Url\" TEXT NULL,
- \"Logo\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"EncryptionKeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"IsPrimary\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"Settings\" (
- \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- -- Tables with foreign keys
- CREATE TABLE \"Credentials\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,
- \"AliasId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Notes\" TEXT NULL,
- \"ServiceId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Username\" TEXT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Passwords\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passwords\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_Passwords_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
-
- -- Restore data from temp tables
- INSERT INTO \"__EFMigrationsHistory\" SELECT * FROM \"__EFMigrationsHistory_temp\";
- INSERT INTO \"Aliases\" SELECT * FROM \"Aliases_temp\";
- INSERT INTO \"Services\" SELECT * FROM \"Services_temp\";
- INSERT INTO \"EncryptionKeys\" SELECT * FROM \"EncryptionKeys_temp\";
- INSERT INTO \"Settings\" SELECT * FROM \"Settings_temp\";
- INSERT INTO \"Credentials\" SELECT * FROM \"Credentials_temp\";
- INSERT INTO \"Attachments\" SELECT * FROM \"Attachments_temp\";
- INSERT INTO \"Passwords\" SELECT * FROM \"Passwords_temp\";
- INSERT INTO \"TotpCodes\" SELECT * FROM \"TotpCodes_temp\";
-
- -- =====================================================================================
- -- Date Format Normalization Migration
- -- =====================================================================================
- -- This migration normalizes ALL date fields to the standard format: 'yyyy-MM-dd HH:mm:ss.fff'
- -- Previously the different clients used different date formats which complicate date parsing.
- -- From version 0.24.0 onwards, all new dates are stored in this standard format.
-
- -- Update Aliases table (CreatedAt, UpdatedAt, BirthDate)
- UPDATE \"Aliases\" SET \"CreatedAt\" =
- CASE
- -- Already in correct format (yyyy-MM-dd HH:mm:ss.fff) - no change
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
-
- -- ISO 8601 with milliseconds (yyyy-MM-ddTHH:mm:ss.fffZ) -> Replace T with space, remove Z and everything after .fff
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
-
- -- Without milliseconds (yyyy-MM-dd HH:mm:ss or yyyy-MM-ddTHH:mm:ssZ) -> Add .000
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
-
- -- Fallback: if none match, keep as-is (edge case)
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Aliases\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- BirthDate: Always set time to 00:00:00 (no milliseconds for birth dates)
- UPDATE \"Aliases\" SET \"BirthDate\" =
- CASE
- -- If empty or already '0001-01-01 00:00:00', keep as-is
- WHEN \"BirthDate\" = '' OR \"BirthDate\" = '0001-01-01 00:00:00'
- THEN \"BirthDate\"
-
- -- If already in correct format (yyyy-MM-dd 00:00:00), keep as-is
- WHEN \"BirthDate\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] 00:00:00'
- THEN \"BirthDate\"
-
- -- Extract date part and set time to 00:00:00
- WHEN \"BirthDate\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'
- THEN substr(\"BirthDate\", 1, 10) || ' 00:00:00'
-
- -- Fallback
- ELSE \"BirthDate\"
- END;
-
- -- Update Services table (CreatedAt, UpdatedAt)
- UPDATE \"Services\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Services\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update EncryptionKeys table (CreatedAt, UpdatedAt)
- UPDATE \"EncryptionKeys\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"EncryptionKeys\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Settings table (CreatedAt, UpdatedAt)
- UPDATE \"Settings\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Settings\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Credentials table (CreatedAt, UpdatedAt)
- UPDATE \"Credentials\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Credentials\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Attachments table (CreatedAt, UpdatedAt)
- UPDATE \"Attachments\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Attachments\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Passwords table (CreatedAt, UpdatedAt)
- UPDATE \"Passwords\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Passwords\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update TotpCodes table (CreatedAt, UpdatedAt)
- UPDATE \"TotpCodes\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"TotpCodes\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- =====================================================================================
- -- End of Date Format Normalization Migration
- -- =====================================================================================
-
- -- Recreate indexes
- CREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");
- CREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");
- CREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");
- CREATE INDEX \"IX_Passwords_CredentialId\" ON \"Passwords\" (\"CredentialId\");
- CREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");
-
- -- Clean up temp tables
- DROP TABLE \"__EFMigrationsHistory_temp\";
- DROP TABLE \"Aliases_temp\";
- DROP TABLE \"Services_temp\";
- DROP TABLE \"EncryptionKeys_temp\";
- DROP TABLE \"Settings_temp\";
- DROP TABLE \"Credentials_temp\";
- DROP TABLE \"Attachments_temp\";
- DROP TABLE \"Passwords_temp\";
- DROP TABLE \"TotpCodes_temp\";
-
- PRAGMA foreign_keys = ON;
-
-
- CREATE TABLE \"Passkeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passkeys\" PRIMARY KEY,
- \"RpId\" TEXT COLLATE NOCASE NOT NULL,
- \"UserHandle\" BLOB NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PrfKey\" BLOB NULL,
- \"DisplayName\" TEXT NOT NULL,
- \"AdditionalData\" BLOB NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Passkeys_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_Passkeys_CredentialId\" ON \"Passkeys\" (\"CredentialId\");
-
- CREATE INDEX \"IX_Passkeys_RpId\" ON \"Passkeys\" (\"RpId\");
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.10');
-
- COMMIT;
-
- PRAGMA foreign_keys = OFF;
-
- BEGIN TRANSACTION;
- ALTER TABLE \"TotpCodes\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_TotpCodes_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_TotpCodes_ItemId\" ON \"TotpCodes\" (\"ItemId\");
-
- ALTER TABLE \"Passkeys\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_Passkeys_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_Passkeys_ItemId\" ON \"Passkeys\" (\"ItemId\");
-
- ALTER TABLE \"Attachments\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_Attachments_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_Attachments_ItemId\" ON \"Attachments\" (\"ItemId\");
-
- CREATE TABLE \"FieldDefinitions\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldDefinitions\" PRIMARY KEY,
- \"FieldType\" TEXT NOT NULL,
- \"Label\" TEXT NOT NULL,
- \"IsMultiValue\" INTEGER NOT NULL,
- \"IsHidden\" INTEGER NOT NULL,
- \"EnableHistory\" INTEGER NOT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"ApplicableToTypes\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Folders\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Folders\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"ParentFolderId\" TEXT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Folders_Folders_ParentFolderId\" FOREIGN KEY (\"ParentFolderId\") REFERENCES \"Folders\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Logos\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Logos\" PRIMARY KEY,
- \"Source\" TEXT NOT NULL,
- \"FileData\" BLOB NULL,
- \"MimeType\" TEXT NULL,
- \"FetchedAt\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Tags\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Tags\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"Color\" TEXT NULL,
- \"DisplayOrder\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Items\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Items\" PRIMARY KEY,
- \"Name\" TEXT NULL,
- \"ItemType\" TEXT NOT NULL,
- \"LogoId\" TEXT NULL,
- \"DeletedAt\" TEXT NULL,
- \"FolderId\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Items_Folders_FolderId\" FOREIGN KEY (\"FolderId\") REFERENCES \"Folders\" (\"Id\") ON DELETE SET NULL,
- CONSTRAINT \"FK_Items_Logos_LogoId\" FOREIGN KEY (\"LogoId\") REFERENCES \"Logos\" (\"Id\") ON DELETE SET NULL
- );
-
- CREATE TABLE \"FieldHistories\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldHistories\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT NULL,
- \"FieldKey\" TEXT NULL,
- \"ValueSnapshot\" TEXT NOT NULL,
- \"ChangedAt\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_FieldHistories_FieldDefinitions_FieldDefinitionId\" FOREIGN KEY (\"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldHistories_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"FieldValues\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldValues\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT NULL,
- \"FieldKey\" TEXT NULL,
- \"Value\" TEXT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_FieldValues_FieldDefinitions_FieldDefinitionId\" FOREIGN KEY (\"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldValues_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"ItemTags\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_ItemTags\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"TagId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_ItemTags_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_ItemTags_Tags_TagId\" FOREIGN KEY (\"TagId\") REFERENCES \"Tags\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_FieldHistories_FieldDefinitionId\" ON \"FieldHistories\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldHistories_ItemId\" ON \"FieldHistories\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_FieldDefinitionId\" ON \"FieldValues\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldValues_FieldKey\" ON \"FieldValues\" (\"FieldKey\");
-
- CREATE INDEX \"IX_FieldValues_ItemId\" ON \"FieldValues\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldDefinitionId_Weight\" ON \"FieldValues\" (\"ItemId\", \"FieldDefinitionId\", \"Weight\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldKey\" ON \"FieldValues\" (\"ItemId\", \"FieldKey\");
-
- CREATE INDEX \"IX_Folders_ParentFolderId\" ON \"Folders\" (\"ParentFolderId\");
-
- CREATE INDEX \"IX_Items_FolderId\" ON \"Items\" (\"FolderId\");
-
- CREATE INDEX \"IX_Items_LogoId\" ON \"Items\" (\"LogoId\");
-
- CREATE INDEX \"IX_ItemTags_ItemId\" ON \"ItemTags\" (\"ItemId\");
-
- CREATE UNIQUE INDEX \"IX_ItemTags_ItemId_TagId\" ON \"ItemTags\" (\"ItemId\", \"TagId\");
-
- CREATE INDEX \"IX_ItemTags_TagId\" ON \"ItemTags\" (\"TagId\");
-
- CREATE UNIQUE INDEX \"IX_Logos_Source\" ON \"Logos\" (\"Source\");
-
- CREATE INDEX \"IX_Tags_Name\" ON \"Tags\" (\"Name\");
-
-
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- c.Id,
- s.Name AS Name,
- CASE
- WHEN a.Id IS NOT NULL AND (
- (a.FirstName IS NOT NULL AND a.FirstName != '') OR
- (a.LastName IS NOT NULL AND a.LastName != '') OR
- (a.Gender IS NOT NULL AND a.Gender != '') OR
- (a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%')
- ) THEN 'Alias'
- ELSE 'Login'
- END AS ItemType,
- NULL AS LogoId,
- NULL AS FolderId,
- c.CreatedAt,
- c.UpdatedAt,
- c.IsDeleted
- FROM Credentials c
- LEFT JOIN Services s ON s.Id = c.ServiceId
- LEFT JOIN Aliases a ON a.Id = c.AliasId;
-
-
-
- INSERT INTO Logos (Id, Source, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- -- Extract and normalize hostname: remove protocol, path, lowercase, and www. prefix
- REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) AS Source,
- s.Logo AS FileData,
- 'image/png' AS MimeType,
- NULL AS FetchedAt,
- MIN(s.CreatedAt) AS CreatedAt,
- MAX(s.UpdatedAt) AS UpdatedAt,
- 0 AS IsDeleted
- FROM Services s
- WHERE s.Logo IS NOT NULL AND s.Url IS NOT NULL AND s.Url != ''
- GROUP BY REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- );
-
-
-
- UPDATE Items
- SET LogoId = (
- SELECT l.Id FROM Logos l
- INNER JOIN Services s ON REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) = l.Source
- INNER JOIN Credentials c ON c.ServiceId = s.Id
- WHERE c.Id = Items.Id
- LIMIT 1
- )
- WHERE EXISTS (
- SELECT 1 FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE c.Id = Items.Id AND s.Logo IS NOT NULL
- );
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.url' AS FieldKey,
- s.Url AS Value,
- 0 AS Weight,
- s.UpdatedAt AS CreatedAt,
- s.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE s.Url IS NOT NULL AND s.Url != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.username' AS FieldKey,
- c.Username AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Username IS NOT NULL AND c.Username != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'notes.content' AS FieldKey,
- c.Notes AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Notes IS NOT NULL AND c.Notes != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- p.CredentialId AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.password' AS FieldKey,
- p.Value AS Value,
- 0 AS Weight,
- p.UpdatedAt AS CreatedAt,
- p.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Passwords p
- INNER JOIN (
- SELECT CredentialId, MAX(UpdatedAt) AS MaxUpdated, MAX(Id) AS MaxId
- FROM Passwords
- WHERE IsDeleted = 0
- GROUP BY CredentialId
- ) pm ON p.CredentialId = pm.CredentialId AND p.UpdatedAt = pm.MaxUpdated AND p.Id = pm.MaxId
- WHERE p.IsDeleted = 0;
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.email' AS FieldKey,
- a.Email AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Email IS NOT NULL AND a.Email != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.first_name' AS FieldKey,
- a.FirstName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.FirstName IS NOT NULL AND a.FirstName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.last_name' AS FieldKey,
- a.LastName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.LastName IS NOT NULL AND a.LastName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.gender' AS FieldKey,
- a.Gender AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Gender IS NOT NULL AND a.Gender != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.birthdate' AS FieldKey,
- SUBSTR(a.BirthDate, 1, 10) AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%';
-
-
- DROP TABLE \"Passwords\";
-
- DROP TABLE \"Credentials\";
-
- DROP TABLE \"Aliases\";
-
- DROP TABLE \"Services\";
-
- COMMIT;
-
- PRAGMA foreign_keys = ON;
-
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\")
- SELECT \"Id\", \"Blob\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\"
- FROM \"Attachments\";
-
- CREATE TABLE \"ef_temp_Passkeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passkeys\" PRIMARY KEY,
- \"AdditionalData\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"DisplayName\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"PrfKey\" BLOB NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"RpId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"UserHandle\" BLOB NOT NULL,
- CONSTRAINT \"FK_Passkeys_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Passkeys\" (\"Id\", \"AdditionalData\", \"CreatedAt\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\")
- SELECT \"Id\", \"AdditionalData\", \"CreatedAt\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\"
- FROM \"Passkeys\";
-
- CREATE TABLE \"ef_temp_TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_TotpCodes_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_TotpCodes\" (\"Id\", \"CreatedAt\", \"IsDeleted\", \"ItemId\", \"Name\", \"SecretKey\", \"UpdatedAt\")
- SELECT \"Id\", \"CreatedAt\", \"IsDeleted\", \"ItemId\", \"Name\", \"SecretKey\", \"UpdatedAt\"
- FROM \"TotpCodes\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Attachments\";
-
- ALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";
-
- DROP TABLE \"Passkeys\";
-
- ALTER TABLE \"ef_temp_Passkeys\" RENAME TO \"Passkeys\";
-
- DROP TABLE \"TotpCodes\";
-
- ALTER TABLE \"ef_temp_TotpCodes\" RENAME TO \"TotpCodes\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Attachments_ItemId\" ON \"Attachments\" (\"ItemId\");
-
- CREATE INDEX \"IX_Passkeys_ItemId\" ON \"Passkeys\" (\"ItemId\");
-
- CREATE INDEX \"IX_Passkeys_RpId\" ON \"Passkeys\" (\"RpId\");
-
- CREATE INDEX \"IX_TotpCodes_ItemId\" ON \"TotpCodes\" (\"ItemId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.10');
-
- BEGIN TRANSACTION;
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.10');
-
- COMMIT;
-
- PRAGMA foreign_keys = OFF;
-
- BEGIN TRANSACTION;
- DROP INDEX \"IX_TotpCodes_ItemId\";
-
- DROP INDEX \"IX_Tags_Name\";
-
- DROP INDEX \"IX_Passkeys_ItemId\";
-
- DROP INDEX \"IX_Logos_Source\";
-
- DROP INDEX \"IX_ItemTags_ItemId_TagId\";
-
- DROP INDEX \"IX_Items_FolderId\";
-
- DROP INDEX \"IX_Items_LogoId\";
-
- DROP INDEX \"IX_Attachments_ItemId\";
-
- ALTER TABLE \"TotpCodes\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"TotpCodes\" ADD \"Algorithm\" TEXT NOT NULL DEFAULT 'SHA1';
-
- ALTER TABLE \"TotpCodes\" ADD \"Digits\" INTEGER NOT NULL DEFAULT 6;
-
- ALTER TABLE \"TotpCodes\" ADD \"Period\" INTEGER NOT NULL DEFAULT 30;
-
- ALTER TABLE \"Tags\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Settings\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Passkeys\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Passkeys\" ADD \"CredentialId\" BLOB NULL;
-
- ALTER TABLE \"Logos\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Logos\" ADD \"Kind\" TEXT NOT NULL DEFAULT 'favicon';
-
- ALTER TABLE \"Logos\" ADD \"Name\" TEXT NULL;
-
- ALTER TABLE \"ItemTags\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Items\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Items\" ADD \"ArchivedAt\" TEXT NULL;
-
- ALTER TABLE \"Folders\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"FieldValues\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"FieldValues\" ADD \"IsDisabled\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"FieldValues\" ADD \"ValueIndex\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"FieldHistories\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"FieldDefinitions\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"EncryptionKeys\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Attachments\" ADD \"ManifestId\" TEXT COLLATE NOCASE NOT NULL DEFAULT '';
-
- ALTER TABLE \"Logos\" ADD \"FileDataHash\" TEXT NULL;
-
- ALTER TABLE \"Attachments\" ADD \"BlobHash\" TEXT NULL;
-
- CREATE TABLE \"CodecOverflows\" (
- \"Id\" TEXT COLLATE NOCASE NOT NULL CONSTRAINT \"PK_CodecOverflows\" PRIMARY KEY,
- \"Data\" TEXT NOT NULL
- );
-
- CREATE TABLE \"ItemStats\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"LastUsedAt\" TEXT NULL,
- \"UseCount\" INTEGER NOT NULL,
- \"LastAutofilledAt\" TEXT NULL,
- \"AutofillCount\" INTEGER NOT NULL,
- \"LastCopiedAt\" TEXT NULL,
- \"CopyCount\" INTEGER NOT NULL,
- \"LastPasskeyAuthAt\" TEXT NULL,
- \"PasskeyAuthCount\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"PK_ItemStats\" PRIMARY KEY (\"ManifestId\", \"Id\")
- );
-
- CREATE TABLE \"Manifests\" (
- \"Id\" TEXT COLLATE NOCASE NOT NULL CONSTRAINT \"PK_Manifests\" PRIMARY KEY,
- \"Name\" TEXT NULL
- );
-
- CREATE INDEX \"IX_TotpCodes_ManifestId_ItemId\" ON \"TotpCodes\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_Tags_ManifestId_Name\" ON \"Tags\" (\"ManifestId\", \"Name\");
-
- CREATE INDEX \"IX_Passkeys_ManifestId_ItemId\" ON \"Passkeys\" (\"ManifestId\", \"ItemId\");
-
- CREATE UNIQUE INDEX \"IX_Logos_ManifestId_Kind_Source\" ON \"Logos\" (\"ManifestId\", \"Kind\", \"Source\");
-
- CREATE INDEX \"IX_ItemTags_ManifestId_TagId\" ON \"ItemTags\" (\"ManifestId\", \"TagId\");
-
- CREATE INDEX \"IX_Items_ManifestId_FolderId\" ON \"Items\" (\"ManifestId\", \"FolderId\");
-
- CREATE INDEX \"IX_Items_ManifestId_LogoId\" ON \"Items\" (\"ManifestId\", \"LogoId\");
-
- CREATE INDEX \"IX_Folders_ManifestId_ParentFolderId\" ON \"Folders\" (\"ManifestId\", \"ParentFolderId\");
-
- CREATE INDEX \"IX_FieldValues_ManifestId_FieldDefinitionId\" ON \"FieldValues\" (\"ManifestId\", \"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldValues_ManifestId_ItemId\" ON \"FieldValues\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_FieldHistories_ManifestId_FieldDefinitionId\" ON \"FieldHistories\" (\"ManifestId\", \"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldHistories_ManifestId_ItemId\" ON \"FieldHistories\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_EncryptionKeys_ManifestId_IsPrimary\" ON \"EncryptionKeys\" (\"ManifestId\", \"IsPrimary\");
-
- CREATE INDEX \"IX_Attachments_ManifestId_ItemId\" ON \"Attachments\" (\"ManifestId\", \"ItemId\");
-
- CREATE TABLE \"ef_temp_Attachments\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"Blob\" BLOB NULL,
- \"BlobHash\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_Attachments\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_Attachments_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Attachments\" (\"ManifestId\", \"Id\", \"Blob\", \"BlobHash\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"Blob\", \"BlobHash\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\"
- FROM \"Attachments\";
-
- CREATE TABLE \"ef_temp_FieldHistories\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"ChangedAt\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT COLLATE NOCASE NULL,
- \"FieldKey\" TEXT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"ValueSnapshot\" TEXT NOT NULL,
- CONSTRAINT \"PK_FieldHistories\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_FieldHistories_FieldDefinitions_ManifestId_FieldDefinitionId\" FOREIGN KEY (\"ManifestId\", \"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"ManifestId\", \"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldHistories_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_FieldHistories\" (\"ManifestId\", \"Id\", \"ChangedAt\", \"CreatedAt\", \"FieldDefinitionId\", \"FieldKey\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\", \"ValueSnapshot\")
- SELECT \"ManifestId\", \"Id\", \"ChangedAt\", \"CreatedAt\", \"FieldDefinitionId\", \"FieldKey\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\", \"ValueSnapshot\"
- FROM \"FieldHistories\";
-
- CREATE TABLE \"ef_temp_FieldValues\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT COLLATE NOCASE NULL,
- \"FieldKey\" TEXT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"IsDisabled\" INTEGER NOT NULL DEFAULT 0,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Value\" TEXT NULL,
- \"ValueIndex\" INTEGER NOT NULL DEFAULT 0,
- \"Weight\" INTEGER NOT NULL,
- CONSTRAINT \"PK_FieldValues\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_FieldValues_FieldDefinitions_ManifestId_FieldDefinitionId\" FOREIGN KEY (\"ManifestId\", \"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"ManifestId\", \"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldValues_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_FieldValues\" (\"ManifestId\", \"Id\", \"CreatedAt\", \"FieldDefinitionId\", \"FieldKey\", \"IsDeleted\", \"IsDisabled\", \"ItemId\", \"UpdatedAt\", \"Value\", \"ValueIndex\", \"Weight\")
- SELECT \"ManifestId\", \"Id\", \"CreatedAt\", \"FieldDefinitionId\", \"FieldKey\", \"IsDeleted\", \"IsDisabled\", \"ItemId\", \"UpdatedAt\", \"Value\", \"ValueIndex\", \"Weight\"
- FROM \"FieldValues\";
-
- CREATE TABLE \"ef_temp_Folders\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"Name\" TEXT NOT NULL,
- \"ParentFolderId\" TEXT COLLATE NOCASE NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Weight\" INTEGER NOT NULL,
- CONSTRAINT \"PK_Folders\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_Folders_Folders_ManifestId_ParentFolderId\" FOREIGN KEY (\"ManifestId\", \"ParentFolderId\") REFERENCES \"Folders\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Folders\" (\"ManifestId\", \"Id\", \"CreatedAt\", \"IsDeleted\", \"Name\", \"ParentFolderId\", \"UpdatedAt\", \"Weight\")
- SELECT \"ManifestId\", \"Id\", \"CreatedAt\", \"IsDeleted\", \"Name\", \"ParentFolderId\", \"UpdatedAt\", \"Weight\"
- FROM \"Folders\";
-
- CREATE TABLE \"ef_temp_Items\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"ArchivedAt\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"DeletedAt\" TEXT NULL,
- \"FolderId\" TEXT COLLATE NOCASE NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemType\" TEXT NOT NULL,
- \"LogoId\" TEXT COLLATE NOCASE NULL,
- \"Name\" TEXT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_Items\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_Items_Folders_ManifestId_FolderId\" FOREIGN KEY (\"ManifestId\", \"FolderId\") REFERENCES \"Folders\" (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_Items_Logos_ManifestId_LogoId\" FOREIGN KEY (\"ManifestId\", \"LogoId\") REFERENCES \"Logos\" (\"ManifestId\", \"Id\")
- );
-
- INSERT INTO \"ef_temp_Items\" (\"ManifestId\", \"Id\", \"ArchivedAt\", \"CreatedAt\", \"DeletedAt\", \"FolderId\", \"IsDeleted\", \"ItemType\", \"LogoId\", \"Name\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"ArchivedAt\", \"CreatedAt\", \"DeletedAt\", \"FolderId\", \"IsDeleted\", \"ItemType\", \"LogoId\", \"Name\", \"UpdatedAt\"
- FROM \"Items\";
-
- CREATE TABLE \"ef_temp_ItemTags\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"TagId\" TEXT COLLATE NOCASE NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_ItemTags\" PRIMARY KEY (\"ManifestId\", \"ItemId\", \"TagId\"),
- CONSTRAINT \"FK_ItemTags_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_ItemTags_Tags_ManifestId_TagId\" FOREIGN KEY (\"ManifestId\", \"TagId\") REFERENCES \"Tags\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_ItemTags\" (\"ManifestId\", \"ItemId\", \"TagId\", \"CreatedAt\", \"IsDeleted\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"ItemId\", \"TagId\", \"CreatedAt\", \"IsDeleted\", \"UpdatedAt\"
- FROM \"ItemTags\";
-
- CREATE TABLE \"ef_temp_Passkeys\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"AdditionalData\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"CredentialId\" BLOB NULL,
- \"DisplayName\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"PrfKey\" BLOB NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"RpId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"UserHandle\" BLOB NOT NULL,
- CONSTRAINT \"PK_Passkeys\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_Passkeys_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Passkeys\" (\"ManifestId\", \"Id\", \"AdditionalData\", \"CreatedAt\", \"CredentialId\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\")
- SELECT \"ManifestId\", \"Id\", \"AdditionalData\", \"CreatedAt\", \"CredentialId\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\"
- FROM \"Passkeys\";
-
- CREATE TABLE \"ef_temp_TotpCodes\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"Algorithm\" TEXT NOT NULL DEFAULT 'SHA1',
- \"CreatedAt\" TEXT NOT NULL,
- \"Digits\" INTEGER NOT NULL DEFAULT 6,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT COLLATE NOCASE NOT NULL,
- \"Name\" TEXT NOT NULL,
- \"Period\" INTEGER NOT NULL DEFAULT 30,
- \"SecretKey\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY (\"ManifestId\", \"Id\"),
- CONSTRAINT \"FK_TotpCodes_Items_ManifestId_ItemId\" FOREIGN KEY (\"ManifestId\", \"ItemId\") REFERENCES \"Items\" (\"ManifestId\", \"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_TotpCodes\" (\"ManifestId\", \"Id\", \"Algorithm\", \"CreatedAt\", \"Digits\", \"IsDeleted\", \"ItemId\", \"Name\", \"Period\", \"SecretKey\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"Algorithm\", \"CreatedAt\", \"Digits\", \"IsDeleted\", \"ItemId\", \"Name\", \"Period\", \"SecretKey\", \"UpdatedAt\"
- FROM \"TotpCodes\";
-
- CREATE TABLE \"ef_temp_Tags\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"Color\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"DisplayOrder\" INTEGER NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"Name\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_Tags\" PRIMARY KEY (\"ManifestId\", \"Id\")
- );
-
- INSERT INTO \"ef_temp_Tags\" (\"ManifestId\", \"Id\", \"Color\", \"CreatedAt\", \"DisplayOrder\", \"IsDeleted\", \"Name\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"Color\", \"CreatedAt\", \"DisplayOrder\", \"IsDeleted\", \"Name\", \"UpdatedAt\"
- FROM \"Tags\";
-
- CREATE TABLE \"ef_temp_Settings\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Key\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Value\" TEXT NULL,
- CONSTRAINT \"PK_Settings\" PRIMARY KEY (\"ManifestId\", \"Key\")
- );
-
- INSERT INTO \"ef_temp_Settings\" (\"ManifestId\", \"Key\", \"CreatedAt\", \"IsDeleted\", \"UpdatedAt\", \"Value\")
- SELECT \"ManifestId\", \"Key\", \"CreatedAt\", \"IsDeleted\", \"UpdatedAt\", \"Value\"
- FROM \"Settings\";
-
- CREATE TABLE \"ef_temp_Logos\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"FetchedAt\" TEXT NULL,
- \"FileData\" BLOB NULL,
- \"FileDataHash\" TEXT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"Kind\" TEXT NOT NULL DEFAULT 'favicon',
- \"MimeType\" TEXT NULL,
- \"Name\" TEXT NULL,
- \"Source\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_Logos\" PRIMARY KEY (\"ManifestId\", \"Id\")
- );
-
- INSERT INTO \"ef_temp_Logos\" (\"ManifestId\", \"Id\", \"CreatedAt\", \"FetchedAt\", \"FileData\", \"FileDataHash\", \"IsDeleted\", \"Kind\", \"MimeType\", \"Name\", \"Source\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"CreatedAt\", \"FetchedAt\", \"FileData\", \"FileDataHash\", \"IsDeleted\", \"Kind\", \"MimeType\", \"Name\", \"Source\", \"UpdatedAt\"
- FROM \"Logos\";
-
- CREATE TABLE \"ef_temp_FieldDefinitions\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"ApplicableToTypes\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"EnableHistory\" INTEGER NOT NULL,
- \"FieldType\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"IsHidden\" INTEGER NOT NULL,
- \"IsMultiValue\" INTEGER NOT NULL,
- \"Label\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Weight\" INTEGER NOT NULL,
- CONSTRAINT \"PK_FieldDefinitions\" PRIMARY KEY (\"ManifestId\", \"Id\")
- );
-
- INSERT INTO \"ef_temp_FieldDefinitions\" (\"ManifestId\", \"Id\", \"ApplicableToTypes\", \"CreatedAt\", \"EnableHistory\", \"FieldType\", \"IsDeleted\", \"IsHidden\", \"IsMultiValue\", \"Label\", \"UpdatedAt\", \"Weight\")
- SELECT \"ManifestId\", \"Id\", \"ApplicableToTypes\", \"CreatedAt\", \"EnableHistory\", \"FieldType\", \"IsDeleted\", \"IsHidden\", \"IsMultiValue\", \"Label\", \"UpdatedAt\", \"Weight\"
- FROM \"FieldDefinitions\";
-
- CREATE TABLE \"ef_temp_EncryptionKeys\" (
- \"ManifestId\" TEXT COLLATE NOCASE NOT NULL,
- \"Id\" TEXT COLLATE NOCASE NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"IsPrimary\" INTEGER NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY (\"ManifestId\", \"Id\")
- );
-
- INSERT INTO \"ef_temp_EncryptionKeys\" (\"ManifestId\", \"Id\", \"CreatedAt\", \"IsDeleted\", \"IsPrimary\", \"PrivateKey\", \"PublicKey\", \"UpdatedAt\")
- SELECT \"ManifestId\", \"Id\", \"CreatedAt\", \"IsDeleted\", \"IsPrimary\", \"PrivateKey\", \"PublicKey\", \"UpdatedAt\"
- FROM \"EncryptionKeys\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Attachments\";
-
- ALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";
-
- DROP TABLE \"FieldHistories\";
-
- ALTER TABLE \"ef_temp_FieldHistories\" RENAME TO \"FieldHistories\";
-
- DROP TABLE \"FieldValues\";
-
- ALTER TABLE \"ef_temp_FieldValues\" RENAME TO \"FieldValues\";
-
- DROP TABLE \"Folders\";
-
- ALTER TABLE \"ef_temp_Folders\" RENAME TO \"Folders\";
-
- DROP TABLE \"Items\";
-
- ALTER TABLE \"ef_temp_Items\" RENAME TO \"Items\";
-
- DROP TABLE \"ItemTags\";
-
- ALTER TABLE \"ef_temp_ItemTags\" RENAME TO \"ItemTags\";
-
- DROP TABLE \"Passkeys\";
-
- ALTER TABLE \"ef_temp_Passkeys\" RENAME TO \"Passkeys\";
-
- DROP TABLE \"TotpCodes\";
-
- ALTER TABLE \"ef_temp_TotpCodes\" RENAME TO \"TotpCodes\";
-
- DROP TABLE \"Tags\";
-
- ALTER TABLE \"ef_temp_Tags\" RENAME TO \"Tags\";
-
- DROP TABLE \"Settings\";
-
- ALTER TABLE \"ef_temp_Settings\" RENAME TO \"Settings\";
-
- DROP TABLE \"Logos\";
-
- ALTER TABLE \"ef_temp_Logos\" RENAME TO \"Logos\";
-
- DROP TABLE \"FieldDefinitions\";
-
- ALTER TABLE \"ef_temp_FieldDefinitions\" RENAME TO \"FieldDefinitions\";
-
- DROP TABLE \"EncryptionKeys\";
-
- ALTER TABLE \"ef_temp_EncryptionKeys\" RENAME TO \"EncryptionKeys\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Attachments_ManifestId_ItemId\" ON \"Attachments\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_FieldHistories_FieldDefinitionId\" ON \"FieldHistories\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldHistories_ItemId\" ON \"FieldHistories\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldHistories_ManifestId_FieldDefinitionId\" ON \"FieldHistories\" (\"ManifestId\", \"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldHistories_ManifestId_ItemId\" ON \"FieldHistories\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_FieldDefinitionId\" ON \"FieldValues\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldValues_FieldKey\" ON \"FieldValues\" (\"FieldKey\");
-
- CREATE INDEX \"IX_FieldValues_ItemId\" ON \"FieldValues\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldDefinitionId_Weight\" ON \"FieldValues\" (\"ItemId\", \"FieldDefinitionId\", \"Weight\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldKey\" ON \"FieldValues\" (\"ItemId\", \"FieldKey\");
-
- CREATE INDEX \"IX_FieldValues_ManifestId_FieldDefinitionId\" ON \"FieldValues\" (\"ManifestId\", \"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldValues_ManifestId_ItemId\" ON \"FieldValues\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_Folders_ManifestId_ParentFolderId\" ON \"Folders\" (\"ManifestId\", \"ParentFolderId\");
-
- CREATE INDEX \"IX_Folders_ParentFolderId\" ON \"Folders\" (\"ParentFolderId\");
-
- CREATE INDEX \"IX_Items_ManifestId_FolderId\" ON \"Items\" (\"ManifestId\", \"FolderId\");
-
- CREATE INDEX \"IX_Items_ManifestId_LogoId\" ON \"Items\" (\"ManifestId\", \"LogoId\");
-
- CREATE INDEX \"IX_ItemTags_ItemId\" ON \"ItemTags\" (\"ItemId\");
-
- CREATE INDEX \"IX_ItemTags_ManifestId_TagId\" ON \"ItemTags\" (\"ManifestId\", \"TagId\");
-
- CREATE INDEX \"IX_ItemTags_TagId\" ON \"ItemTags\" (\"TagId\");
-
- CREATE INDEX \"IX_Passkeys_ManifestId_ItemId\" ON \"Passkeys\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_Passkeys_RpId\" ON \"Passkeys\" (\"RpId\");
-
- CREATE INDEX \"IX_TotpCodes_ManifestId_ItemId\" ON \"TotpCodes\" (\"ManifestId\", \"ItemId\");
-
- CREATE INDEX \"IX_Tags_ManifestId_Name\" ON \"Tags\" (\"ManifestId\", \"Name\");
-
- CREATE UNIQUE INDEX \"IX_Logos_ManifestId_Kind_Source\" ON \"Logos\" (\"ManifestId\", \"Kind\", \"Source\");
-
- CREATE INDEX \"IX_EncryptionKeys_ManifestId_IsPrimary\" ON \"EncryptionKeys\" (\"ManifestId\", \"IsPrimary\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20260918090000_2.1.0-ManifestScopedStorage', '10.0.10');
-
- BEGIN TRANSACTION;
- CREATE TRIGGER IF NOT EXISTS \"TR_Items_ClearTombstoneBeforeReturn\"
- BEFORE UPDATE OF \"ManifestId\" ON \"Items\"
- FOR EACH ROW WHEN OLD.\"ManifestId\" <> NEW.\"ManifestId\"
- AND EXISTS (SELECT 1 FROM \"Items\" WHERE \"ManifestId\" = NEW.\"ManifestId\" AND \"Id\" = NEW.\"Id\" AND \"IsDeleted\" = 1)
- BEGIN
- DELETE FROM \"FieldValues\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"FieldHistories\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"ItemTags\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"Attachments\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"Passkeys\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"TotpCodes\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"ItemStats\" WHERE \"Id\" = NEW.\"Id\" AND \"ManifestId\" = NEW.\"ManifestId\";
- DELETE FROM \"Items\" WHERE \"ManifestId\" = NEW.\"ManifestId\" AND \"Id\" = NEW.\"Id\" AND \"IsDeleted\" = 1;
- END;
-
- CREATE TRIGGER IF NOT EXISTS \"TR_Items_ResyncChildManifestIds\"
- AFTER UPDATE OF \"ManifestId\" ON \"Items\"
- FOR EACH ROW WHEN OLD.\"ManifestId\" <> NEW.\"ManifestId\"
- BEGIN
- INSERT INTO \"Tags\" (\"ManifestId\", \"Id\", \"Name\", \"Color\", \"DisplayOrder\", \"CreatedAt\", \"UpdatedAt\", \"IsDeleted\")
- SELECT NEW.\"ManifestId\", \"Id\", \"Name\", \"Color\", \"DisplayOrder\", \"CreatedAt\", NEW.\"UpdatedAt\", \"IsDeleted\" FROM \"Tags\"
- WHERE \"ManifestId\" = OLD.\"ManifestId\" AND \"Id\" IN (SELECT \"TagId\" FROM \"ItemTags\" WHERE \"ManifestId\" = OLD.\"ManifestId\" AND \"ItemId\" = NEW.\"Id\")
- ON CONFLICT (\"ManifestId\", \"Id\") DO UPDATE SET \"Name\" = excluded.\"Name\", \"Color\" = excluded.\"Color\", \"DisplayOrder\" = excluded.\"DisplayOrder\", \"UpdatedAt\" = excluded.\"UpdatedAt\", \"IsDeleted\" = 0 WHERE \"IsDeleted\" = 1 AND excluded.\"IsDeleted\" = 0;
- INSERT INTO \"FieldDefinitions\" (\"ManifestId\", \"Id\", \"FieldType\", \"Label\", \"IsMultiValue\", \"IsHidden\", \"EnableHistory\", \"Weight\", \"ApplicableToTypes\", \"CreatedAt\", \"UpdatedAt\", \"IsDeleted\")
- SELECT NEW.\"ManifestId\", \"Id\", \"FieldType\", \"Label\", \"IsMultiValue\", \"IsHidden\", \"EnableHistory\", \"Weight\", \"ApplicableToTypes\", \"CreatedAt\", NEW.\"UpdatedAt\", \"IsDeleted\" FROM \"FieldDefinitions\"
- WHERE \"ManifestId\" = OLD.\"ManifestId\" AND \"Id\" IN (SELECT \"FieldDefinitionId\" FROM \"FieldValues\" WHERE \"ManifestId\" = OLD.\"ManifestId\" AND \"ItemId\" = NEW.\"Id\" UNION SELECT \"FieldDefinitionId\" FROM \"FieldHistories\" WHERE \"ManifestId\" = OLD.\"ManifestId\" AND \"ItemId\" = NEW.\"Id\")
- ON CONFLICT (\"ManifestId\", \"Id\") DO UPDATE SET \"FieldType\" = excluded.\"FieldType\", \"Label\" = excluded.\"Label\", \"IsMultiValue\" = excluded.\"IsMultiValue\", \"IsHidden\" = excluded.\"IsHidden\", \"EnableHistory\" = excluded.\"EnableHistory\", \"Weight\" = excluded.\"Weight\", \"ApplicableToTypes\" = excluded.\"ApplicableToTypes\", \"UpdatedAt\" = excluded.\"UpdatedAt\", \"IsDeleted\" = 0 WHERE \"IsDeleted\" = 1 AND excluded.\"IsDeleted\" = 0;
- UPDATE \"FieldValues\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"FieldHistories\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"ItemTags\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"Attachments\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"Passkeys\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"TotpCodes\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"ItemId\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- UPDATE \"ItemStats\" SET \"ManifestId\" = NEW.\"ManifestId\" WHERE \"Id\" = NEW.\"Id\" AND \"ManifestId\" = OLD.\"ManifestId\";
- INSERT OR IGNORE INTO \"Items\" (\"ManifestId\", \"Id\", \"ItemType\", \"CreatedAt\", \"UpdatedAt\", \"IsDeleted\")
- SELECT OLD.\"ManifestId\", OLD.\"Id\", OLD.\"ItemType\", OLD.\"CreatedAt\", NEW.\"UpdatedAt\", 1 WHERE OLD.\"IsDeleted\" = 0;
- END;
-
- COMMIT;
-
- PRAGMA foreign_keys = ON;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20260918090100_2.1.1-ItemChildManifestTrigger', '10.0.10');
- """
-
- /// Migration SQL scripts indexed by migration number.
- /// Key is the source migration number (migration FROM this version).
- public static let migrations: [Int: String] = [
- 1: """
- BEGIN TRANSACTION;
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');
-
- COMMIT;
- """,
- 2: """
- BEGIN TRANSACTION;
- ALTER TABLE \"Aliases\" RENAME COLUMN \"EmailPrefix\" TO \"Email\";
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');
-
- COMMIT;
- """,
- 3: """
- BEGIN TRANSACTION;
- CREATE TABLE \"EncryptionKeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"IsPrimary\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');
-
- COMMIT;
- """,
- 4: """
- BEGIN TRANSACTION;
- CREATE TABLE \"Settings\" (
- \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');
-
- COMMIT;
- """,
- 5: """
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Aliases\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,
- \"BirthDate\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Email\" TEXT NULL,
- \"FirstName\" VARCHAR NULL,
- \"Gender\" VARCHAR NULL,
- \"LastName\" VARCHAR NULL,
- \"NickName\" VARCHAR NULL,
- \"UpdatedAt\" TEXT NOT NULL
- );
-
- INSERT INTO \"ef_temp_Aliases\" (\"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\")
- SELECT \"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\"
- FROM \"Aliases\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Aliases\";
-
- ALTER TABLE \"ef_temp_Aliases\" RENAME TO \"Aliases\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');
- """,
- 6: """
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Credentials\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,
- \"AliasId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Notes\" TEXT NULL,
- \"ServiceId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Username\" TEXT NULL,
- CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Credentials\" (\"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\")
- SELECT \"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\"
- FROM \"Credentials\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Credentials\";
-
- ALTER TABLE \"ef_temp_Credentials\" RENAME TO \"Credentials\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");
-
- CREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');
- """,
- 7: """
- BEGIN TRANSACTION;
- ALTER TABLE \"Settings\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Services\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Passwords\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"EncryptionKeys\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Credentials\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Attachment\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- ALTER TABLE \"Aliases\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');
-
- COMMIT;
- """,
- 8: """
- BEGIN TRANSACTION;
- ALTER TABLE \"Attachment\" RENAME TO \"Attachments\";
-
- CREATE TABLE \"ef_temp_Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\")
- SELECT \"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\"
- FROM \"Attachments\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Attachments\";
-
- ALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');
- """,
- 9: """
- BEGIN TRANSACTION;
- CREATE TABLE \"TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');
-
- COMMIT;
- """,
- 10: """
- BEGIN TRANSACTION;
-
- PRAGMA foreign_keys = OFF;
-
- -- Clean up any existing temp tables first
- DROP TABLE IF EXISTS \"__EFMigrationsHistory_temp\";
- DROP TABLE IF EXISTS \"Aliases_temp\";
- DROP TABLE IF EXISTS \"Services_temp\";
- DROP TABLE IF EXISTS \"EncryptionKeys_temp\";
- DROP TABLE IF EXISTS \"Settings_temp\";
- DROP TABLE IF EXISTS \"Credentials_temp\";
- DROP TABLE IF EXISTS \"Attachments_temp\";
- DROP TABLE IF EXISTS \"Passwords_temp\";
- DROP TABLE IF EXISTS \"TotpCodes_temp\";
-
- -- Create backup tables for all data
- CREATE TABLE \"__EFMigrationsHistory_temp\" AS SELECT * FROM \"__EFMigrationsHistory\";
- CREATE TABLE \"Aliases_temp\" AS SELECT * FROM \"Aliases\";
- CREATE TABLE \"Services_temp\" AS SELECT * FROM \"Services\";
- CREATE TABLE \"EncryptionKeys_temp\" AS SELECT * FROM \"EncryptionKeys\";
- CREATE TABLE \"Settings_temp\" AS SELECT * FROM \"Settings\";
- CREATE TABLE \"Credentials_temp\" AS SELECT * FROM \"Credentials\";
- CREATE TABLE \"Attachments_temp\" AS SELECT * FROM \"Attachments\";
- CREATE TABLE \"Passwords_temp\" AS SELECT * FROM \"Passwords\";
- CREATE TABLE \"TotpCodes_temp\" AS SELECT * FROM \"TotpCodes\";
-
- -- Delete orphaned records that do not have a valid FK to the credential object
- DELETE FROM \"Attachments_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"Passwords_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"TotpCodes_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
-
- -- Delete orphaned credentials that do not have valid FKs to alias or service objects
- DELETE FROM \"Credentials_temp\" WHERE \"AliasId\" NOT IN (SELECT \"Id\" FROM \"Aliases_temp\");
- DELETE FROM \"Credentials_temp\" WHERE \"ServiceId\" NOT IN (SELECT \"Id\" FROM \"Services_temp\");
-
- -- After cleaning credentials, clean dependent tables again in case we removed credentials
- DELETE FROM \"Attachments_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"Passwords_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
- DELETE FROM \"TotpCodes_temp\" WHERE \"CredentialId\" NOT IN (SELECT \"Id\" FROM \"Credentials_temp\");
-
- -- Drop all existing tables
- DROP TABLE \"TotpCodes\";
- DROP TABLE \"Passwords\";
- DROP TABLE \"Attachments\";
- DROP TABLE \"Credentials\";
- DROP TABLE \"Settings\";
- DROP TABLE \"EncryptionKeys\";
- DROP TABLE \"Services\";
- DROP TABLE \"Aliases\";
- DROP TABLE \"__EFMigrationsHistory\";
-
- -- Recreate tables with proper constraints (no dependencies first)
- CREATE TABLE \"__EFMigrationsHistory\" (
- \"MigrationId\" TEXT NOT NULL CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY,
- \"ProductVersion\" TEXT NOT NULL
- );
-
- CREATE TABLE \"Aliases\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,
- \"BirthDate\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Email\" TEXT NULL,
- \"FirstName\" VARCHAR NULL,
- \"Gender\" VARCHAR NULL,
- \"LastName\" VARCHAR NULL,
- \"NickName\" VARCHAR NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"Services\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Services\" PRIMARY KEY,
- \"Name\" TEXT NULL,
- \"Url\" TEXT NULL,
- \"Logo\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"EncryptionKeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"IsPrimary\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- CREATE TABLE \"Settings\" (
- \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0
- );
-
- -- Tables with foreign keys
- CREATE TABLE \"Credentials\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,
- \"AliasId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Notes\" TEXT NULL,
- \"ServiceId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"Username\" TEXT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Passwords\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passwords\" PRIMARY KEY,
- \"Value\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_Passwords_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
-
- -- Restore data from temp tables
- INSERT INTO \"__EFMigrationsHistory\" SELECT * FROM \"__EFMigrationsHistory_temp\";
- INSERT INTO \"Aliases\" SELECT * FROM \"Aliases_temp\";
- INSERT INTO \"Services\" SELECT * FROM \"Services_temp\";
- INSERT INTO \"EncryptionKeys\" SELECT * FROM \"EncryptionKeys_temp\";
- INSERT INTO \"Settings\" SELECT * FROM \"Settings_temp\";
- INSERT INTO \"Credentials\" SELECT * FROM \"Credentials_temp\";
- INSERT INTO \"Attachments\" SELECT * FROM \"Attachments_temp\";
- INSERT INTO \"Passwords\" SELECT * FROM \"Passwords_temp\";
- INSERT INTO \"TotpCodes\" SELECT * FROM \"TotpCodes_temp\";
-
- -- =====================================================================================
- -- Date Format Normalization Migration
- -- =====================================================================================
- -- This migration normalizes ALL date fields to the standard format: 'yyyy-MM-dd HH:mm:ss.fff'
- -- Previously the different clients used different date formats which complicate date parsing.
- -- From version 0.24.0 onwards, all new dates are stored in this standard format.
-
- -- Update Aliases table (CreatedAt, UpdatedAt, BirthDate)
- UPDATE \"Aliases\" SET \"CreatedAt\" =
- CASE
- -- Already in correct format (yyyy-MM-dd HH:mm:ss.fff) - no change
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
-
- -- ISO 8601 with milliseconds (yyyy-MM-ddTHH:mm:ss.fffZ) -> Replace T with space, remove Z and everything after .fff
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
-
- -- Without milliseconds (yyyy-MM-dd HH:mm:ss or yyyy-MM-ddTHH:mm:ssZ) -> Add .000
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
-
- -- Fallback: if none match, keep as-is (edge case)
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Aliases\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- BirthDate: Always set time to 00:00:00 (no milliseconds for birth dates)
- UPDATE \"Aliases\" SET \"BirthDate\" =
- CASE
- -- If empty or already '0001-01-01 00:00:00', keep as-is
- WHEN \"BirthDate\" = '' OR \"BirthDate\" = '0001-01-01 00:00:00'
- THEN \"BirthDate\"
-
- -- If already in correct format (yyyy-MM-dd 00:00:00), keep as-is
- WHEN \"BirthDate\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] 00:00:00'
- THEN \"BirthDate\"
-
- -- Extract date part and set time to 00:00:00
- WHEN \"BirthDate\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'
- THEN substr(\"BirthDate\", 1, 10) || ' 00:00:00'
-
- -- Fallback
- ELSE \"BirthDate\"
- END;
-
- -- Update Services table (CreatedAt, UpdatedAt)
- UPDATE \"Services\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Services\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update EncryptionKeys table (CreatedAt, UpdatedAt)
- UPDATE \"EncryptionKeys\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"EncryptionKeys\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Settings table (CreatedAt, UpdatedAt)
- UPDATE \"Settings\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Settings\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Credentials table (CreatedAt, UpdatedAt)
- UPDATE \"Credentials\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Credentials\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Attachments table (CreatedAt, UpdatedAt)
- UPDATE \"Attachments\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Attachments\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update Passwords table (CreatedAt, UpdatedAt)
- UPDATE \"Passwords\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"Passwords\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- Update TotpCodes table (CreatedAt, UpdatedAt)
- UPDATE \"TotpCodes\" SET \"CreatedAt\" =
- CASE
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"CreatedAt\"
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(\"CreatedAt\", 12, 12)
- WHEN \"CreatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"CreatedAt\", 1, 10) || ' ' || substr(replace(\"CreatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"CreatedAt\"
- END;
-
- UPDATE \"TotpCodes\" SET \"UpdatedAt\" =
- CASE
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN \"UpdatedAt\"
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(\"UpdatedAt\", 12, 12)
- WHEN \"UpdatedAt\" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr(\"UpdatedAt\", 1, 10) || ' ' || substr(replace(\"UpdatedAt\", 'T', ' '), 12, 8) || '.000'
- ELSE \"UpdatedAt\"
- END;
-
- -- =====================================================================================
- -- End of Date Format Normalization Migration
- -- =====================================================================================
-
- -- Recreate indexes
- CREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");
- CREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");
- CREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");
- CREATE INDEX \"IX_Passwords_CredentialId\" ON \"Passwords\" (\"CredentialId\");
- CREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");
-
- -- Clean up temp tables
- DROP TABLE \"__EFMigrationsHistory_temp\";
- DROP TABLE \"Aliases_temp\";
- DROP TABLE \"Services_temp\";
- DROP TABLE \"EncryptionKeys_temp\";
- DROP TABLE \"Settings_temp\";
- DROP TABLE \"Credentials_temp\";
- DROP TABLE \"Attachments_temp\";
- DROP TABLE \"Passwords_temp\";
- DROP TABLE \"TotpCodes_temp\";
-
- PRAGMA foreign_keys = ON;
-
-
- CREATE TABLE \"Passkeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passkeys\" PRIMARY KEY,
- \"RpId\" TEXT COLLATE NOCASE NOT NULL,
- \"UserHandle\" BLOB NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PrfKey\" BLOB NULL,
- \"DisplayName\" TEXT NOT NULL,
- \"AdditionalData\" BLOB NULL,
- \"CredentialId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Passkeys_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_Passkeys_CredentialId\" ON \"Passkeys\" (\"CredentialId\");
-
- CREATE INDEX \"IX_Passkeys_RpId\" ON \"Passkeys\" (\"RpId\");
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20251014122838_1.6.0-AddPasskeys', '9.0.4');
-
- COMMIT;
- """,
- 11: """
- PRAGMA foreign_keys = OFF;
-
- BEGIN TRANSACTION;
- ALTER TABLE \"TotpCodes\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_TotpCodes_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_TotpCodes_ItemId\" ON \"TotpCodes\" (\"ItemId\");
-
- ALTER TABLE \"Passkeys\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_Passkeys_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_Passkeys_ItemId\" ON \"Passkeys\" (\"ItemId\");
-
- ALTER TABLE \"Attachments\" RENAME COLUMN \"CredentialId\" TO \"ItemId\";
-
- DROP INDEX IF EXISTS \"IX_Attachments_CredentialId\";
-
- CREATE INDEX IF NOT EXISTS \"IX_Attachments_ItemId\" ON \"Attachments\" (\"ItemId\");
-
- CREATE TABLE \"FieldDefinitions\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldDefinitions\" PRIMARY KEY,
- \"FieldType\" TEXT NOT NULL,
- \"Label\" TEXT NOT NULL,
- \"IsMultiValue\" INTEGER NOT NULL,
- \"IsHidden\" INTEGER NOT NULL,
- \"EnableHistory\" INTEGER NOT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"ApplicableToTypes\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Folders\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Folders\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"ParentFolderId\" TEXT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Folders_Folders_ParentFolderId\" FOREIGN KEY (\"ParentFolderId\") REFERENCES \"Folders\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"Logos\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Logos\" PRIMARY KEY,
- \"Source\" TEXT NOT NULL,
- \"FileData\" BLOB NULL,
- \"MimeType\" TEXT NULL,
- \"FetchedAt\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Tags\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Tags\" PRIMARY KEY,
- \"Name\" TEXT NOT NULL,
- \"Color\" TEXT NULL,
- \"DisplayOrder\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL
- );
-
- CREATE TABLE \"Items\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Items\" PRIMARY KEY,
- \"Name\" TEXT NULL,
- \"ItemType\" TEXT NOT NULL,
- \"LogoId\" TEXT NULL,
- \"DeletedAt\" TEXT NULL,
- \"FolderId\" TEXT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_Items_Folders_FolderId\" FOREIGN KEY (\"FolderId\") REFERENCES \"Folders\" (\"Id\") ON DELETE SET NULL,
- CONSTRAINT \"FK_Items_Logos_LogoId\" FOREIGN KEY (\"LogoId\") REFERENCES \"Logos\" (\"Id\") ON DELETE SET NULL
- );
-
- CREATE TABLE \"FieldHistories\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldHistories\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT NULL,
- \"FieldKey\" TEXT NULL,
- \"ValueSnapshot\" TEXT NOT NULL,
- \"ChangedAt\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_FieldHistories_FieldDefinitions_FieldDefinitionId\" FOREIGN KEY (\"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldHistories_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"FieldValues\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_FieldValues\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"FieldDefinitionId\" TEXT NULL,
- \"FieldKey\" TEXT NULL,
- \"Value\" TEXT NULL,
- \"Weight\" INTEGER NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_FieldValues_FieldDefinitions_FieldDefinitionId\" FOREIGN KEY (\"FieldDefinitionId\") REFERENCES \"FieldDefinitions\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_FieldValues_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE TABLE \"ItemTags\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_ItemTags\" PRIMARY KEY,
- \"ItemId\" TEXT NOT NULL,
- \"TagId\" TEXT NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- CONSTRAINT \"FK_ItemTags_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE,
- CONSTRAINT \"FK_ItemTags_Tags_TagId\" FOREIGN KEY (\"TagId\") REFERENCES \"Tags\" (\"Id\") ON DELETE CASCADE
- );
-
- CREATE INDEX \"IX_FieldHistories_FieldDefinitionId\" ON \"FieldHistories\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldHistories_ItemId\" ON \"FieldHistories\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_FieldDefinitionId\" ON \"FieldValues\" (\"FieldDefinitionId\");
-
- CREATE INDEX \"IX_FieldValues_FieldKey\" ON \"FieldValues\" (\"FieldKey\");
-
- CREATE INDEX \"IX_FieldValues_ItemId\" ON \"FieldValues\" (\"ItemId\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldDefinitionId_Weight\" ON \"FieldValues\" (\"ItemId\", \"FieldDefinitionId\", \"Weight\");
-
- CREATE INDEX \"IX_FieldValues_ItemId_FieldKey\" ON \"FieldValues\" (\"ItemId\", \"FieldKey\");
-
- CREATE INDEX \"IX_Folders_ParentFolderId\" ON \"Folders\" (\"ParentFolderId\");
-
- CREATE INDEX \"IX_Items_FolderId\" ON \"Items\" (\"FolderId\");
-
- CREATE INDEX \"IX_Items_LogoId\" ON \"Items\" (\"LogoId\");
-
- CREATE INDEX \"IX_ItemTags_ItemId\" ON \"ItemTags\" (\"ItemId\");
-
- CREATE UNIQUE INDEX \"IX_ItemTags_ItemId_TagId\" ON \"ItemTags\" (\"ItemId\", \"TagId\");
-
- CREATE INDEX \"IX_ItemTags_TagId\" ON \"ItemTags\" (\"TagId\");
-
- CREATE UNIQUE INDEX \"IX_Logos_Source\" ON \"Logos\" (\"Source\");
-
- CREATE INDEX \"IX_Tags_Name\" ON \"Tags\" (\"Name\");
-
-
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- c.Id,
- s.Name AS Name,
- CASE
- WHEN a.Id IS NOT NULL AND (
- (a.FirstName IS NOT NULL AND a.FirstName != '') OR
- (a.LastName IS NOT NULL AND a.LastName != '') OR
- (a.Gender IS NOT NULL AND a.Gender != '') OR
- (a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%')
- ) THEN 'Alias'
- ELSE 'Login'
- END AS ItemType,
- NULL AS LogoId,
- NULL AS FolderId,
- c.CreatedAt,
- c.UpdatedAt,
- c.IsDeleted
- FROM Credentials c
- LEFT JOIN Services s ON s.Id = c.ServiceId
- LEFT JOIN Aliases a ON a.Id = c.AliasId;
-
-
-
- INSERT INTO Logos (Id, Source, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- -- Extract and normalize hostname: remove protocol, path, lowercase, and www. prefix
- REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) AS Source,
- s.Logo AS FileData,
- 'image/png' AS MimeType,
- NULL AS FetchedAt,
- MIN(s.CreatedAt) AS CreatedAt,
- MAX(s.UpdatedAt) AS UpdatedAt,
- 0 AS IsDeleted
- FROM Services s
- WHERE s.Logo IS NOT NULL AND s.Url IS NOT NULL AND s.Url != ''
- GROUP BY REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- );
-
-
-
- UPDATE Items
- SET LogoId = (
- SELECT l.Id FROM Logos l
- INNER JOIN Services s ON REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) = l.Source
- INNER JOIN Credentials c ON c.ServiceId = s.Id
- WHERE c.Id = Items.Id
- LIMIT 1
- )
- WHERE EXISTS (
- SELECT 1 FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE c.Id = Items.Id AND s.Logo IS NOT NULL
- );
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.url' AS FieldKey,
- s.Url AS Value,
- 0 AS Weight,
- s.UpdatedAt AS CreatedAt,
- s.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE s.Url IS NOT NULL AND s.Url != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.username' AS FieldKey,
- c.Username AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Username IS NOT NULL AND c.Username != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'notes.content' AS FieldKey,
- c.Notes AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Notes IS NOT NULL AND c.Notes != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- p.CredentialId AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.password' AS FieldKey,
- p.Value AS Value,
- 0 AS Weight,
- p.UpdatedAt AS CreatedAt,
- p.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Passwords p
- INNER JOIN (
- SELECT CredentialId, MAX(UpdatedAt) AS MaxUpdated, MAX(Id) AS MaxId
- FROM Passwords
- WHERE IsDeleted = 0
- GROUP BY CredentialId
- ) pm ON p.CredentialId = pm.CredentialId AND p.UpdatedAt = pm.MaxUpdated AND p.Id = pm.MaxId
- WHERE p.IsDeleted = 0;
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.email' AS FieldKey,
- a.Email AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Email IS NOT NULL AND a.Email != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.first_name' AS FieldKey,
- a.FirstName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.FirstName IS NOT NULL AND a.FirstName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.last_name' AS FieldKey,
- a.LastName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.LastName IS NOT NULL AND a.LastName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.gender' AS FieldKey,
- a.Gender AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Gender IS NOT NULL AND a.Gender != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.birthdate' AS FieldKey,
- SUBSTR(a.BirthDate, 1, 10) AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%';
-
-
- DROP TABLE \"Passwords\";
-
- DROP TABLE \"Credentials\";
-
- DROP TABLE \"Aliases\";
-
- DROP TABLE \"Services\";
-
- COMMIT;
-
- PRAGMA foreign_keys = ON;
-
- BEGIN TRANSACTION;
- CREATE TABLE \"ef_temp_Attachments\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,
- \"Blob\" BLOB NOT NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"Filename\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_Attachments_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\")
- SELECT \"Id\", \"Blob\", \"CreatedAt\", \"Filename\", \"IsDeleted\", \"ItemId\", \"UpdatedAt\"
- FROM \"Attachments\";
-
- CREATE TABLE \"ef_temp_Passkeys\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passkeys\" PRIMARY KEY,
- \"AdditionalData\" BLOB NULL,
- \"CreatedAt\" TEXT NOT NULL,
- \"DisplayName\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"PrfKey\" BLOB NULL,
- \"PrivateKey\" TEXT NOT NULL,
- \"PublicKey\" TEXT NOT NULL,
- \"RpId\" TEXT COLLATE NOCASE NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- \"UserHandle\" BLOB NOT NULL,
- CONSTRAINT \"FK_Passkeys_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_Passkeys\" (\"Id\", \"AdditionalData\", \"CreatedAt\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\")
- SELECT \"Id\", \"AdditionalData\", \"CreatedAt\", \"DisplayName\", \"IsDeleted\", \"ItemId\", \"PrfKey\", \"PrivateKey\", \"PublicKey\", \"RpId\", \"UpdatedAt\", \"UserHandle\"
- FROM \"Passkeys\";
-
- CREATE TABLE \"ef_temp_TotpCodes\" (
- \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,
- \"CreatedAt\" TEXT NOT NULL,
- \"IsDeleted\" INTEGER NOT NULL,
- \"ItemId\" TEXT NOT NULL,
- \"Name\" TEXT NOT NULL,
- \"SecretKey\" TEXT NOT NULL,
- \"UpdatedAt\" TEXT NOT NULL,
- CONSTRAINT \"FK_TotpCodes_Items_ItemId\" FOREIGN KEY (\"ItemId\") REFERENCES \"Items\" (\"Id\") ON DELETE CASCADE
- );
-
- INSERT INTO \"ef_temp_TotpCodes\" (\"Id\", \"CreatedAt\", \"IsDeleted\", \"ItemId\", \"Name\", \"SecretKey\", \"UpdatedAt\")
- SELECT \"Id\", \"CreatedAt\", \"IsDeleted\", \"ItemId\", \"Name\", \"SecretKey\", \"UpdatedAt\"
- FROM \"TotpCodes\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 0;
-
- BEGIN TRANSACTION;
- DROP TABLE \"Attachments\";
-
- ALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";
-
- DROP TABLE \"Passkeys\";
-
- ALTER TABLE \"ef_temp_Passkeys\" RENAME TO \"Passkeys\";
-
- DROP TABLE \"TotpCodes\";
-
- ALTER TABLE \"ef_temp_TotpCodes\" RENAME TO \"TotpCodes\";
-
- COMMIT;
-
- PRAGMA foreign_keys = 1;
-
- BEGIN TRANSACTION;
- CREATE INDEX \"IX_Attachments_ItemId\" ON \"Attachments\" (\"ItemId\");
-
- CREATE INDEX \"IX_Passkeys_ItemId\" ON \"Passkeys\" (\"ItemId\");
-
- CREATE INDEX \"IX_Passkeys_RpId\" ON \"Passkeys\" (\"RpId\");
-
- CREATE INDEX \"IX_TotpCodes_ItemId\" ON \"TotpCodes\" (\"ItemId\");
-
- COMMIT;
-
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '9.0.4');
- """,
- 12: """
- BEGIN TRANSACTION;
- INSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")
- VALUES ('20260130221620_2.0.0-MajorVersionBump', '9.0.4');
-
- COMMIT;
- """
- ]
-
- /// Get migration SQL for upgrading from a specific revision.
- public static func getMigrationSql(fromRevision: Int) -> String? {
- return migrations[fromRevision]
- }
-}
-
-// swiftlint:enable all
diff --git a/apps/mobile-app/ios/VaultModels/VaultVersions.swift b/apps/mobile-app/ios/VaultModels/VaultVersions.swift
deleted file mode 100644
index 254cb41e9..000000000
--- a/apps/mobile-app/ios/VaultModels/VaultVersions.swift
+++ /dev/null
@@ -1,149 +0,0 @@
-// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/VaultVersions.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-// swiftlint:disable all
-
-import Foundation
-
-/// Vault database version information.
-public struct VaultVersion {
- /// The migration revision number.
- public let revision: Int
-
- /// The internal migration version number that equals the AliasClientDb database version (e.g., "1.5.0").
- public let version: String
-
- /// Description of changes in this version.
- public let description: String
-
- /// The AliasVault release that this vault version was introduced in (e.g., "0.14.0").
- public let releaseVersion: String
-
- /// The last AliasVault release version that the vault was compatible with before requiring this migration.
- public let compatibleUpToVersion: String
-}
-
-/// Registry of all vault versions.
-public struct VaultVersions {
- /// All vault migrations/versions in chronological order.
- public static let all: [VaultVersion] = [
- VaultVersion(
- revision: 1,
- version: "1.0.0",
- description: "Initial Migration",
- releaseVersion: "0.1.0",
- compatibleUpToVersion: "0.0.0"
- ),
- VaultVersion(
- revision: 2,
- version: "1.0.1",
- description: "Empty Test Migration",
- releaseVersion: "0.2.0",
- compatibleUpToVersion: "0.1.0"
- ),
- VaultVersion(
- revision: 3,
- version: "1.0.2",
- description: "Change Email Column",
- releaseVersion: "0.3.0",
- compatibleUpToVersion: "0.2.0"
- ),
- VaultVersion(
- revision: 4,
- version: "1.1.0",
- description: "Add Pki Tables",
- releaseVersion: "0.4.0",
- compatibleUpToVersion: "0.3.0"
- ),
- VaultVersion(
- revision: 5,
- version: "1.2.0",
- description: "Add Settings Table",
- releaseVersion: "0.4.0",
- compatibleUpToVersion: "0.3.0"
- ),
- VaultVersion(
- revision: 6,
- version: "1.3.0",
- description: "Update Identity Structure",
- releaseVersion: "0.5.0",
- compatibleUpToVersion: "0.4.0"
- ),
- VaultVersion(
- revision: 7,
- version: "1.3.1",
- description: "Make Username Optional",
- releaseVersion: "0.5.0",
- compatibleUpToVersion: "0.4.0"
- ),
- VaultVersion(
- revision: 8,
- version: "1.4.0",
- description: "Add Sync Support",
- releaseVersion: "0.6.0",
- compatibleUpToVersion: "0.5.0"
- ),
- VaultVersion(
- revision: 9,
- version: "1.4.1",
- description: "Rename Attachments Plural",
- releaseVersion: "0.6.0",
- compatibleUpToVersion: "0.13.0"
- ),
- VaultVersion(
- revision: 10,
- version: "1.5.0",
- description: "Add 2FA Tokens to credentials",
- releaseVersion: "0.14.0",
- compatibleUpToVersion: "0.23.0"
- ),
- VaultVersion(
- revision: 11,
- version: "1.6.0",
- description: "Add Passkey support",
- releaseVersion: "0.24.0",
- compatibleUpToVersion: "0.25.0"
- ),
- VaultVersion(
- revision: 12,
- version: "1.7.0",
- description: "Update to Field-Based Data Model",
- releaseVersion: "0.26.0",
- compatibleUpToVersion: "0.25.0"
- ),
- VaultVersion(
- revision: 13,
- version: "2.0.0",
- description: "Update to Field-Based Data Model",
- releaseVersion: "0.26.1",
- compatibleUpToVersion: "0.25.0"
- )
- ]
-
- /// Get the latest vault version.
- public static var latest: VaultVersion {
- return all.last!
- }
-
- /// Get the latest vault version string (e.g., "1.7.0").
- public static var latestVersion: String {
- return latest.version
- }
-
- /// Get the latest vault revision number.
- public static var latestRevision: Int {
- return latest.revision
- }
-
- /// Find a vault version by revision number.
- public static func findByRevision(_ revision: Int) -> VaultVersion? {
- return all.first { $0.revision == revision }
- }
-
- /// Find a vault version by version string.
- public static func findByVersion(_ version: String) -> VaultVersion? {
- return all.first { $0.version == version }
- }
-}
-
-// swiftlint:enable all
diff --git a/apps/mobile-app/ios/VaultStoreKit/CredentialIdentityStore.swift b/apps/mobile-app/ios/VaultStoreKit/CredentialIdentityStore.swift
index 398f39c0e..eb0c4a808 100644
--- a/apps/mobile-app/ios/VaultStoreKit/CredentialIdentityStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/CredentialIdentityStore.swift
@@ -121,7 +121,7 @@ public class CredentialIdentityStore {
let userName = passkey.userName ?? credential.identifier
// Convert passkey.Id to bytes for credentialID
- let credentialId = try? PasskeyHelper.guidToBytes(passkey.id.uuidString)
+ let credentialId = try? PasskeyAuthenticator.guidToBytes(passkey.id.uuidString)
// For passkeys, we use the rpId from the passkey itself, not the service URL
// This is because passkeys are tied to the RP ID, which may differ from the service URL
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift
deleted file mode 100644
index 430972519..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift
+++ /dev/null
@@ -1,64 +0,0 @@
-import Foundation
-import VaultModels
-import VaultUtils
-
-/// The grouping key of a manifest-scoped row (same id can exist in several manifests by design).
-internal func scopedKey(manifestId: String, id: String) -> String {
- return manifestId + id
-}
-
-/// Base repository class with common database operations.
-public class BaseRepository {
- /// The database client used for executing queries.
- internal let client: DatabaseClient
-
- /// Initialize the repository with a database client.
- /// - Parameter client: The database client to use
- public init(client: DatabaseClient) {
- self.client = client
- }
-
- /// The manifest new rows outside any folder or item are stamped with: the personal manifest. Rows inside a
- /// folder or item take that parent's manifest through the SQL instead. An unrecorded manifest is an error,
- /// never the empty (unstamped) scope, which every later push would reject.
- public func writeManifestId() throws -> String {
- guard let manifestId = client.personalManifestId(), !manifestId.isEmpty else {
- throw AppError.manifestNotRecorded
- }
- return manifestId
- }
-
- // MARK: - Transaction Helpers
-
- /// Execute a function within a transaction.
- /// Automatically handles begin, commit, and rollback.
- /// - Parameters:
- /// - scope: What the mutation touched, so the next sync can push only that scope
- /// - operation: The function to execute within the transaction
- /// - Returns: The result of the function
- public func withTransaction<T>(scope: String = VaultMutationScope.main, _ operation: () throws -> T) throws -> T {
- try client.beginTransaction()
- do {
- let result = try operation()
- try client.commitTransaction(scope: scope)
- return result
- } catch {
- try? client.rollbackTransaction()
- throw error
- }
- }
-
- // MARK: - Utility Methods
-
- /// Generate a new id.
- /// - Returns: A new UUID string
- public func generateId() -> String {
- return UUID().uuidString.lowercased()
- }
-
- /// Get the current timestamp in the standard format.
- /// - Returns: Current timestamp string
- public func now() -> String {
- return DateHelpers.now()
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift
deleted file mode 100644
index eb784775a..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift
+++ /dev/null
@@ -1,36 +0,0 @@
-import Foundation
-
-/// A query parameter: nil, String, Int, Int64, Double, Bool, Data, or a base64 string behind `av-base64-to-blob:`.
-public typealias SqliteBindValue = Any?
-
-/// Protocol for core database operations needed by repositories.
-/// Abstracts the SQLite database connection to allow for testing and flexibility.
-public protocol DatabaseClient: AnyObject {
- /// Execute a SELECT query and return results as an array of dictionaries.
- /// - Parameters:
- /// - query: The SQL query to execute
- /// - params: The parameters to bind to the query
- /// - Returns: Array of dictionaries representing the result rows
- func executeQuery(_ query: String, params: [SqliteBindValue]) throws -> [[String: Any]]
-
- /// Execute an UPDATE, INSERT, or DELETE query.
- /// - Parameters:
- /// - query: The SQL query to execute
- /// - params: The parameters to bind to the query
- /// - Returns: Number of rows affected
- @discardableResult
- func executeUpdate(_ query: String, params: [SqliteBindValue]) throws -> Int
-
- /// Begin a database transaction.
- func beginTransaction() throws
-
- /// Commit a database transaction.
- /// - Parameter scope: What the mutation touched, so the next sync can push only that scope
- func commitTransaction(scope: String) throws
-
- /// Rollback a database transaction.
- func rollbackTransaction() throws
-
- /// The id of the user's personal manifest, or nil before the first pull recorded one.
- func personalManifestId() -> String?
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift
deleted file mode 100644
index 0c53e298a..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift
+++ /dev/null
@@ -1,217 +0,0 @@
-import Foundation
-import VaultModels
-
-/// Raw field row from database query.
-public struct FieldRow {
- public let itemId: String
- public let manifestId: String
- public let fieldKey: String?
- public let fieldDefinitionId: String?
- public let customLabel: String?
- public let customFieldType: String?
- public let customIsHidden: Int64?
- public let customEnableHistory: Int64?
- public let value: String
- public let displayOrder: Int
-
- public init(
- itemId: String,
- manifestId: String,
- fieldKey: String?,
- fieldDefinitionId: String?,
- customLabel: String?,
- customFieldType: String?,
- customIsHidden: Int64?,
- customEnableHistory: Int64?,
- value: String,
- displayOrder: Int
- ) {
- self.itemId = itemId
- self.manifestId = manifestId
- self.fieldKey = fieldKey
- self.fieldDefinitionId = fieldDefinitionId
- self.customLabel = customLabel
- self.customFieldType = customFieldType
- self.customIsHidden = customIsHidden
- self.customEnableHistory = customEnableHistory
- self.value = value
- self.displayOrder = displayOrder
- }
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let itemId = row["ItemId"] as? String, let manifestId = row["ManifestId"] as? String else { return nil }
-
- self.itemId = itemId
- self.manifestId = manifestId
- self.fieldKey = row["FieldKey"] as? String
- self.fieldDefinitionId = row["FieldDefinitionId"] as? String
- self.customLabel = row["CustomLabel"] as? String
- self.customFieldType = row["CustomFieldType"] as? String
- self.customIsHidden = row["CustomIsHidden"] as? Int64
- self.customEnableHistory = row["CustomEnableHistory"] as? Int64
- self.value = row["Value"] as? String ?? ""
- self.displayOrder = Int(row["DisplayOrder"] as? Int64 ?? 0)
- }
-}
-
-/// Intermediate field representation before grouping.
-public struct ProcessedField {
- public let itemId: String
- public let manifestId: String
- public let fieldKey: String
- public let label: String
- public let fieldType: String
- public let isHidden: Bool
- public let value: String
- public let displayOrder: Int
- public let isCustomField: Bool
- public let enableHistory: Bool
-}
-
-/// Mapper class for processing database field rows into ItemField objects.
-/// Handles both system fields (with FieldKey) and custom fields (with FieldDefinitionId).
-/// Other platform implementations: FieldMapper.ts (core/client), FieldMapper.kt (Android).
-public struct FieldMapper {
- /// Process raw field rows from database into a map of scoped item key (see `scopedKey`) -> [ItemField].
- /// Handles system vs custom fields. Multi-value fields (like URLs) create separate ItemField entries
- /// with the same fieldKey but different values, allowing Item.getFieldValues() to return all values.
- /// - Parameter rows: Raw field rows from database
- /// - Returns: Dictionary of scoped item key to array of ItemField objects
- public static func processFieldRows(_ rows: [FieldRow]) -> [String: [ItemField]] {
- // First, convert rows to processed fields with proper metadata
- let processedFields = rows.map { processFieldRow($0) }
-
- // Group fields by item key, keeping separate entries for multi-value fields
- var fieldsByItem: [String: [ItemField]] = [:]
-
- for field in processedFields {
- // Create an ItemField for each row (including duplicates for multi-value fields)
- let itemField = ItemField(
- fieldKey: field.fieldKey,
- label: field.label,
- fieldType: field.fieldType,
- value: field.value,
- isHidden: field.isHidden,
- displayOrder: field.displayOrder,
- isCustomField: field.isCustomField,
- enableHistory: field.enableHistory
- )
- fieldsByItem[scopedKey(manifestId: field.manifestId, id: field.itemId), default: []].append(itemField)
- }
-
- return fieldsByItem
- }
-
- /// Process a single field row to extract proper metadata.
- /// System fields use FieldKey and get metadata from SystemFieldRegistry.
- /// Custom fields use FieldDefinitionId and get metadata from the row.
- /// - Parameter row: Raw field row
- /// - Returns: Processed field with proper metadata
- private static func processFieldRow(_ row: FieldRow) -> ProcessedField {
- if let fieldKey = row.fieldKey, !fieldKey.isEmpty {
- // System field: has FieldKey, get metadata from field metadata resolver
- let metadata = resolveFieldMetadata(
- fieldKey: fieldKey,
- customLabel: nil,
- customFieldType: nil,
- customIsHidden: false,
- customEnableHistory: false,
- isCustomField: false
- )
- return ProcessedField(
- itemId: row.itemId,
- manifestId: row.manifestId,
- fieldKey: fieldKey,
- label: metadata.label,
- fieldType: metadata.fieldType,
- isHidden: metadata.isHidden,
- value: row.value,
- displayOrder: row.displayOrder,
- isCustomField: false,
- enableHistory: metadata.enableHistory
- )
- } else {
- // Custom field: has FieldDefinitionId, get metadata from FieldDefinitions
- let fieldKey = row.fieldDefinitionId ?? ""
- return ProcessedField(
- itemId: row.itemId,
- manifestId: row.manifestId,
- fieldKey: fieldKey,
- label: row.customLabel ?? "",
- fieldType: row.customFieldType ?? FieldType.text,
- isHidden: row.customIsHidden == 1,
- value: row.value,
- displayOrder: row.displayOrder,
- isCustomField: true,
- enableHistory: row.customEnableHistory == 1
- )
- }
- }
-
- // MARK: - Field Metadata Resolution
-
- /// Helper struct to hold resolved field metadata.
- private struct FieldMetadata {
- let label: String
- let fieldType: String
- let isHidden: Bool
- let enableHistory: Bool
- }
-
- /// Resolve field metadata for system fields and custom fields.
- private static func resolveFieldMetadata(
- fieldKey: String,
- customLabel: String?,
- customFieldType: String?,
- customIsHidden: Bool,
- customEnableHistory: Bool,
- isCustomField: Bool
- ) -> FieldMetadata {
- if isCustomField {
- return FieldMetadata(
- label: customLabel ?? fieldKey,
- fieldType: customFieldType ?? FieldType.text,
- isHidden: customIsHidden,
- enableHistory: customEnableHistory
- )
- }
-
- // System field metadata based on FieldKey constants
- switch fieldKey {
- case FieldKey.loginUsername:
- return FieldMetadata(label: "Username", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.loginPassword:
- return FieldMetadata(label: "Password", fieldType: FieldType.password, isHidden: true, enableHistory: true)
- case FieldKey.loginEmail:
- return FieldMetadata(label: "Email", fieldType: FieldType.email, isHidden: false, enableHistory: false)
- case FieldKey.loginUrl:
- return FieldMetadata(label: "URL", fieldType: FieldType.uRL, isHidden: false, enableHistory: false)
- case FieldKey.cardNumber:
- return FieldMetadata(label: "Card Number", fieldType: FieldType.text, isHidden: true, enableHistory: false)
- case FieldKey.cardCardholderName:
- return FieldMetadata(label: "Cardholder Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.cardExpiryMonth:
- return FieldMetadata(label: "Expiry Month", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.cardExpiryYear:
- return FieldMetadata(label: "Expiry Year", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.cardCvv:
- return FieldMetadata(label: "CVV", fieldType: FieldType.password, isHidden: true, enableHistory: false)
- case FieldKey.cardPin:
- return FieldMetadata(label: "PIN", fieldType: FieldType.password, isHidden: true, enableHistory: false)
- case FieldKey.aliasFirstName:
- return FieldMetadata(label: "First Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.aliasLastName:
- return FieldMetadata(label: "Last Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.aliasGender:
- return FieldMetadata(label: "Gender", fieldType: FieldType.text, isHidden: false, enableHistory: false)
- case FieldKey.aliasBirthdate:
- return FieldMetadata(label: "Birth Date", fieldType: FieldType.date, isHidden: false, enableHistory: false)
- case FieldKey.notesContent:
- return FieldMetadata(label: "Notes", fieldType: FieldType.textArea, isHidden: false, enableHistory: false)
- default:
- // Unknown system field - use field key as label
- return FieldMetadata(label: fieldKey, fieldType: FieldType.text, isHidden: false, enableHistory: false)
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift
deleted file mode 100644
index 7c1099e3c..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift
+++ /dev/null
@@ -1,105 +0,0 @@
-import Foundation
-import VaultModels
-import VaultUtils
-
-/// Raw item row from database query.
-public struct ItemRow {
- public let id: String
- public let manifestId: String
- public let name: String?
- public let itemType: String
- public let folderId: String?
- public let logo: Data?
- public let hasPasskey: Bool
- public let hasAttachment: Bool
- public let hasTotp: Bool
- public let createdAt: String
- public let updatedAt: String
- public let deletedAt: String?
- public let archivedAt: String?
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let id = row["Id"] as? String,
- let manifestId = row["ManifestId"] as? String,
- let itemType = row["ItemType"] as? String,
- let createdAt = row["CreatedAt"] as? String,
- let updatedAt = row["UpdatedAt"] as? String else {
- return nil
- }
-
- self.id = id
- self.manifestId = manifestId
- self.name = row["Name"] as? String
- self.itemType = itemType
- self.folderId = row["FolderId"] as? String
-
- // A built-in logo carries no bytes: it is drawn from the shared catalog, keyed by its Source.
- if row["LogoKind"] as? String == "builtin", let source = row["LogoSource"] as? String {
- self.logo = BuiltinLogos.svg(for: source)?.data(using: .utf8)
- } else if let logoBase64 = row["Logo"] as? String {
- // BLOB columns arrive as base64 text
- self.logo = Data(base64Encoded: logoBase64, options: .ignoreUnknownCharacters)
- } else {
- self.logo = nil
- }
-
- self.hasPasskey = (row["HasPasskey"] as? Int64 ?? 0) == 1
- self.hasAttachment = (row["HasAttachment"] as? Int64 ?? 0) == 1
- self.hasTotp = (row["HasTotp"] as? Int64 ?? 0) == 1
- self.createdAt = createdAt
- self.updatedAt = updatedAt
- self.deletedAt = row["DeletedAt"] as? String
- self.archivedAt = row["ArchivedAt"] as? String
- }
-
- /// The key this item's child rows and folder path are grouped under (see `scopedKey`).
- internal var scopedItemKey: String {
- return scopedKey(manifestId: manifestId, id: id)
- }
-}
-
-/// Mapper class for converting database rows to Item objects.
-public struct ItemMapper {
- /// Map a single database row to an Item object.
- /// - Parameters:
- /// - row: Raw item row from database
- /// - fields: Processed fields for this item
- /// - folderPath: Computed folder path array (optional)
- /// - Returns: Item object
- public static func mapRow(_ row: ItemRow, fields: [ItemField] = [], folderPath: [String]? = nil) -> Item? {
- guard let createdAt = DateHelpers.parseDateString(row.createdAt), let updatedAt = DateHelpers.parseDateString(row.updatedAt) else {
- return nil
- }
-
- return Item(
- id: UUID(uuidString: row.id) ?? UUID(),
- manifestId: row.manifestId,
- name: row.name,
- itemType: row.itemType,
- logo: row.logo,
- folderId: row.folderId.flatMap { UUID(uuidString: $0) },
- folderPath: folderPath,
- fields: fields,
- hasPasskey: row.hasPasskey,
- hasAttachment: row.hasAttachment,
- hasTotp: row.hasTotp,
- createdAt: createdAt,
- updatedAt: updatedAt
- )
- }
-
- /// Map multiple database rows to Item objects with their fields.
- /// - Parameters:
- /// - rows: Raw item rows from database
- /// - fieldsByItem: Dictionary of scoped item key to array of fields
- /// - folderPathsByFolderKey: Dictionary of scoped folder key to folder path array (optional)
- /// - Returns: Array of Item objects
- public static func mapRows(_ rows: [ItemRow], fieldsByItem: [String: [ItemField]], folderPathsByFolderKey: [String: [String]] = [:]) -> [Item] {
- return rows.compactMap { row in
- let fields = fieldsByItem[row.scopedItemKey] ?? []
- let folderPath = row.folderId.flatMap { folderPathsByFolderKey[scopedKey(manifestId: row.manifestId, id: $0.lowercased())] }
- return mapRow(row, fields: fields, folderPath: folderPath)
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift
deleted file mode 100644
index 36f40d2e9..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift
+++ /dev/null
@@ -1,177 +0,0 @@
-import Foundation
-import VaultModels
-import VaultUtils
-
-/// Row structure for passkey database results.
-public struct PasskeyRow {
- public let id: String
- public let itemId: String
- public let manifestId: String
- public let rpId: String
- public let userHandle: Data?
- public let publicKey: String
- public let privateKey: String
- public let prfKey: Data?
- public let displayName: String
- public let additionalData: Data?
- public let createdAt: String
- public let updatedAt: String
- public let isDeleted: Int64
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let id = row["Id"] as? String,
- let itemId = row["ItemId"] as? String,
- let manifestId = row["ManifestId"] as? String,
- let rpId = row["RpId"] as? String,
- let publicKey = row["PublicKey"] as? String,
- let privateKey = row["PrivateKey"] as? String,
- let displayName = row["DisplayName"] as? String,
- let createdAt = row["CreatedAt"] as? String,
- let updatedAt = row["UpdatedAt"] as? String,
- let isDeleted = row["IsDeleted"] as? Int64 else {
- return nil
- }
-
- self.id = id
- self.itemId = itemId
- self.manifestId = manifestId
- self.rpId = rpId
- self.publicKey = publicKey
- self.privateKey = privateKey
- self.displayName = displayName
- self.createdAt = createdAt
- self.updatedAt = updatedAt
- self.isDeleted = isDeleted
-
- // Handle optional blob fields
- if let userHandleBase64 = row["UserHandle"] as? String {
- self.userHandle = Data(base64Encoded: userHandleBase64, options: .ignoreUnknownCharacters)
- } else {
- self.userHandle = nil
- }
-
- if let prfKeyBase64 = row["PrfKey"] as? String {
- self.prfKey = Data(base64Encoded: prfKeyBase64, options: .ignoreUnknownCharacters)
- } else {
- self.prfKey = nil
- }
-
- if let additionalDataBase64 = row["AdditionalData"] as? String {
- self.additionalData = Data(base64Encoded: additionalDataBase64, options: .ignoreUnknownCharacters)
- } else {
- self.additionalData = nil
- }
- }
-}
-
-/// Row structure for passkey with item info (joined query).
-public struct PasskeyWithItemRow {
- public let passkeyRow: PasskeyRow
- public let serviceName: String?
- public let username: String?
- public let email: String?
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let passkeyRow = PasskeyRow(from: row) else {
- return nil
- }
-
- self.passkeyRow = passkeyRow
- self.serviceName = row["ServiceName"] as? String
- self.username = row["Username"] as? String
- self.email = row["Email"] as? String
- }
-}
-
-/// Result type for passkey with item info.
-public struct PasskeyWithItem {
- public let passkey: Passkey
- public let serviceName: String?
- public let username: String?
- public let email: String?
-
- public init(passkey: Passkey, serviceName: String?, username: String?, email: String? = nil) {
- self.passkey = passkey
- self.serviceName = serviceName
- self.username = username
- self.email = email
- }
-}
-
-/// Mapper for converting database rows to Passkey model objects.
-public struct PasskeyMapper {
- /// Map a single passkey row to a Passkey object.
- /// - Parameter row: The passkey row from the database
- /// - Returns: Passkey object or nil if mapping fails
- public static func mapRow(_ row: PasskeyRow) -> Passkey? {
- // Parse UUIDs
- guard let id = UUID(uuidString: row.id),
- let parentItemId = UUID(uuidString: row.itemId) else {
- print("PasskeyMapper: Invalid UUID - id=\(row.id), itemId=\(row.itemId)")
- return nil
- }
-
- // Parse dates
- guard let createdAt = DateHelpers.parseDateString(row.createdAt),
- let updatedAt = DateHelpers.parseDateString(row.updatedAt) else {
- print("PasskeyMapper: Invalid date - created=\(row.createdAt), updated=\(row.updatedAt)")
- return nil
- }
-
- // Parse keys - stored as UTF-8 strings
- guard let publicKeyData = row.publicKey.data(using: .utf8),
- let privateKeyData = row.privateKey.data(using: .utf8) else {
- print("PasskeyMapper: Invalid key data")
- return nil
- }
-
- return Passkey(
- id: id,
- parentItemId: parentItemId,
- rpId: row.rpId,
- userHandle: row.userHandle,
- userName: nil, // userName not stored in DB, derived from parent credential
- publicKey: publicKeyData,
- privateKey: privateKeyData,
- prfKey: row.prfKey,
- displayName: row.displayName,
- createdAt: createdAt,
- updatedAt: updatedAt,
- isDeleted: row.isDeleted == 1,
- manifestId: row.manifestId,
- additionalData: row.additionalData
- )
- }
-
- /// Map multiple passkey rows to Passkey objects.
- /// - Parameter rows: Array of passkey rows
- /// - Returns: Array of Passkey objects
- public static func mapRows(_ rows: [PasskeyRow]) -> [Passkey] {
- return rows.compactMap { mapRow($0) }
- }
-
- /// Map a passkey with item info row to PasskeyWithItem.
- /// - Parameter row: The joined row from the database
- /// - Returns: PasskeyWithItem or nil if mapping fails
- public static func mapRowWithItem(_ row: PasskeyWithItemRow) -> PasskeyWithItem? {
- guard let passkey = mapRow(row.passkeyRow) else {
- return nil
- }
-
- return PasskeyWithItem(
- passkey: passkey,
- serviceName: row.serviceName,
- username: row.username,
- email: row.email
- )
- }
-
- /// Map multiple joined rows to PasskeyWithItem objects.
- /// - Parameter rows: Array of joined rows
- /// - Returns: Array of PasskeyWithItem objects
- public static func mapRowsWithItem(_ rows: [PasskeyWithItemRow]) -> [PasskeyWithItem] {
- return rows.compactMap { mapRowWithItem($0) }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift
deleted file mode 100644
index 2ca68d41f..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift
+++ /dev/null
@@ -1,93 +0,0 @@
-import Foundation
-
-/// SQL query constants for Item operations.
-public struct ItemQueries {
- /// Base SELECT for items with common fields.
- /// Includes LEFT JOIN to Logos and subqueries for HasPasskey/HasAttachment/HasTotp.
- public static let baseSelect = """
- SELECT DISTINCT
- i.Id,
- i.ManifestId,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- l.Kind as LogoKind,
- l.Source as LogoSource,
- 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.ArchivedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
- """
-
- /// Get all active items (not deleted, not in trash, not archived). This is what autofill reads.
- public static let getAllActive = """
- \(baseSelect)
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
- ORDER BY i.CreatedAt DESC
- """
-
- /// Get field values for multiple items, matched on the whole item key.
- /// - Parameter itemCount: Number of items (for placeholder generation)
- /// - Returns: Query with one (?, ?) placeholder pair per item, bound as [manifestId, itemId, ...]
- public static func getFieldValuesForItems(_ itemCount: Int) -> String {
- let placeholders = Array(repeating: "(?, ?)", count: itemCount).joined(separator: ", ")
- return """
- SELECT
- fv.ItemId,
- fv.ManifestId,
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fd.ManifestId = fv.ManifestId AND fd.Id = fv.FieldDefinitionId
- WHERE (fv.ManifestId, fv.ItemId) IN (VALUES \(placeholders))
- AND fv.IsDeleted = 0
- ORDER BY fv.ItemId, fv.Weight, fv.ValueIndex
- """
- }
-
- /// All live folders, for building folder paths one manifest's tree at a time.
- public static let getAllFolders = """
- SELECT Id, ManifestId, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
- """
-
- /// Insert a new item, bound as [id, name, itemType, logoId, folderId, now, now, 0, manifestId].
- public static let insertItem = """
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """
-}
-
-/// SQL query constants for FieldValue operations.
-public struct FieldValueQueries {
- /// Insert a new field value, bound as [id, itemId, fieldDefinitionId, fieldKey, value, weight, now, now, 0, manifestId].
- public static let insert = """
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6,
- (SELECT COALESCE(MAX(ValueIndex), -1) + 1 FROM FieldValues WHERE ItemId = ?2 AND ManifestId = ?10 AND FieldKey = ?4 AND IsDeleted = 0),
- ?7, ?8, ?9, ?10)
- """
-
- /// The Weight a system field's values are written with: the field's DefaultDisplayOrder from
- /// core/models `SystemFieldRegistry.ts`, which is what the TypeScript writers store.
- public static func defaultWeight(forFieldKey fieldKey: String) -> Int {
- switch fieldKey {
- case "login.url":
- return 5
- case "login.username":
- return 15
- default:
- return 0
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift
deleted file mode 100644
index 375839b19..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift
+++ /dev/null
@@ -1,33 +0,0 @@
-import Foundation
-
-/// SQL query constants for per-item usage statistics.
-public struct ItemStatsQueries {
- /// Create the stats row for an item on its first recorded use, bound as [manifestId, itemId, now, now].
- public static let insertRow = """
- INSERT OR IGNORE INTO ItemStats (
- ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,
- LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted
- )
- VALUES (?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)
- """
-
- /// Record one use of an item, bumping the aggregate and the per-action pair. The column names come from
- /// the closed set in `ItemUsageAction`, never from caller input. `IsDeleted` is cleared because a use
- /// resurrects a row the pruner tombstoned.
- /// - Parameters:
- /// - lastColumn: The per-action timestamp column
- /// - countColumn: The per-action counter column
- /// - Returns: The UPDATE statement, bound as [now, now, now, manifestId, itemId]
- public static func forAction(lastColumn: String, countColumn: String) -> String {
- return """
- UPDATE ItemStats
- SET LastUsedAt = ?,
- UseCount = UseCount + 1,
- \(lastColumn) = ?,
- \(countColumn) = \(countColumn) + 1,
- UpdatedAt = ?,
- IsDeleted = 0
- WHERE ManifestId = ? AND Id = ?
- """
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
deleted file mode 100644
index b6d0c1b15..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
+++ /dev/null
@@ -1,180 +0,0 @@
-import Foundation
-
-/// SQL query constants for Passkey operations.
-public struct PasskeyQueries {
- /// The passkey columns every SELECT projects.
- private static let columns = """
- p.Id,
- p.ItemId,
- p.ManifestId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.PrfKey,
- p.DisplayName,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted
- """
-
- /// Base SELECT for passkeys without item information.
- public static let baseSelect = """
- SELECT
- \(columns)
- FROM Passkeys p
- """
-
- /// Base SELECT for passkeys joined with their item, which must be live (not deleted, not in trash).
- public static let baseSelectWithItemCheck = """
- SELECT
- \(columns)
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- """
-
- /// Get a passkey by its ID (credential ID) across every manifest deterministically.
- public static let getById = """
- \(baseSelectWithItemCheck)
- WHERE p.Id = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC, p.ManifestId
- LIMIT 1
- """
-
- /// Get one passkey inside one manifest, bound as [passkeyId, manifestId].
- public static let getByIdInManifest = """
- \(baseSelectWithItemCheck)
- WHERE p.Id = ? AND p.ManifestId = ? AND p.IsDeleted = 0
- """
-
- /// Get all passkeys for one item, bound as [itemId, manifestId].
- public static let getByItemId = """
- \(baseSelect)
- WHERE p.ItemId = ? AND p.ManifestId = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC
- """
-
- /// Get all passkeys for a relying party (rpId).
- public static let getByRpId = """
- \(baseSelectWithItemCheck)
- WHERE p.RpId = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC, p.ManifestId
- """
-
- /// Get passkeys with item info for a specific rpId.
- public static let getWithItemByRpId = """
- SELECT
- \(columns),
- i.Name as ServiceName,
- (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.username' 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 = 'login.email' 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
- WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC, p.ManifestId
- """
-
- /// Insert a new passkey, stamped with the manifest of the item it hangs off (bound third, after the item id).
- public static let insert = """
- INSERT INTO Passkeys (Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """
-
- /// Soft delete a passkey, bound as [now, passkeyId, manifestId].
- public static let softDelete = """
- UPDATE Passkeys
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ? AND ManifestId = ?
- """
-
- /// Update passkey display name, bound as [displayName, now, passkeyId, manifestId].
- public static let updateDisplayName = """
- UPDATE Passkeys
- SET DisplayName = ?,
- UpdatedAt = ?
- WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0
- """
-
- /// Get all active Login items that don't have a passkey yet (no URL filtering).
- /// Used with Rust credential matcher for intelligent filtering.
- /// Returns items with their URLs aggregated using GROUP_CONCAT for multi-URL support.
- public static let getAllItemsWithoutPasskey = """
- SELECT i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
- GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
- fv_username.Value as Username,
- fv_email.Value as Email,
- fv_password.Value as Password
- FROM Items i
- LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id AND fv_url.ManifestId = i.ManifestId
- AND fv_url.FieldKey = 'login.url'
- AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id AND fv_username.ManifestId = i.ManifestId
- AND fv_username.FieldKey = 'login.username'
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.ManifestId = i.ManifestId
- AND fv_email.FieldKey = 'login.email'
- AND fv_email.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id AND fv_password.ManifestId = i.ManifestId
- AND fv_password.FieldKey = 'login.password'
- AND fv_password.IsDeleted = 0
- WHERE i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- AND i.ArchivedAt IS NULL
- AND i.ItemType = 'Login'
- AND NOT EXISTS (
- SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0
- )
- GROUP BY i.ManifestId, i.Id
- ORDER BY i.UpdatedAt DESC
- """
-}
-
-/// SQL query constants for Logo operations used during passkey/item creation.
-/// Mirrors core/client `LogoQueries.ts`.
-public struct LogoQueries {
- /// The logo of a given kind and key within one manifest, bound as [manifestId, kind, source].
- public static let getIdForKey = """
- SELECT Id FROM Logos
- WHERE ManifestId = ? AND Kind = ? AND Source = ? AND IsDeleted = 0
- LIMIT 1
- """
-
- /// The best row to copy from when a manifest needs a logo it does not have but the vault does, bound as [kind, source].
- public static let getBestForKey = """
- SELECT FileData, MimeType, Name FROM Logos
- WHERE Kind = ? AND Source = ? AND IsDeleted = 0
- ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC
- LIMIT 1
- """
-
- /// The kind and key of an item's logo, bound as [logoId, item manifest]; it always lives in the item's own manifest.
- public static let getById = """
- SELECT Id, Kind, Source, Name FROM Logos
- WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0
- """
-
- /// Insert or update a logo, bound as [id, kind, source, manifestId, fileData, mimeType, name, now, now].
- public static let upsert = """
- INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
- ON CONFLICT(ManifestId, Id) DO UPDATE SET
- FileData = excluded.FileData,
- MimeType = excluded.MimeType,
- Name = COALESCE(excluded.Name, Logos.Name),
- UpdatedAt = excluded.UpdatedAt,
- IsDeleted = 0
- """
-
- /// Get the logo ID of one item, bound as [itemId, manifestId].
- public static let getLogoIdFromItem = """
- SELECT LogoId FROM Items WHERE Id = ? AND ManifestId = ?
- """
-
- /// Point an item at a logo, bound as [logoId, now, itemId, manifestId].
- public static let updateItemLogoId = """
- UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
- """
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
deleted file mode 100644
index ac10bb734..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
+++ /dev/null
@@ -1,79 +0,0 @@
-import Foundation
-import VaultModels
-
-/// Repository for reading items and appending field values.
-/// Other platform implementations: ItemRepository.ts (core/client), ItemRepository.kt (Android).
-public class ItemRepository: BaseRepository {
-
- // MARK: - Read Operations
-
- /// Build folder paths for all folders, keyed by scoped folder key (see `scopedKey`).
- /// The tree is walked per manifest: a parent link only ever resolves inside its own namespace.
- /// - Returns: Dictionary of scoped folder key to folder path array
- private func buildFolderPaths() throws -> [String: [String]] {
- var folderPathMap: [String: [String]] = [:]
-
- let folderResults: [[String: Any]]
- do {
- folderResults = try client.executeQuery(ItemQueries.getAllFolders, params: [])
- } catch {
- // Folders table may not exist in older vault versions
- return folderPathMap
- }
-
- var foldersByManifest: [String: [FolderUtils.Folder]] = [:]
- for row in folderResults {
- guard let manifestId = row["ManifestId"] as? String, let idString = row["Id"] as? String, let id = UUID(uuidString: idString), let name = row["Name"] as? String else {
- continue
- }
- let parentFolderId = (row["ParentFolderId"] as? String).flatMap { UUID(uuidString: $0) }
- foldersByManifest[manifestId, default: []].append(FolderUtils.Folder(id: id, name: name, parentFolderId: parentFolderId))
- }
-
- for (manifestId, folders) in foldersByManifest {
- for folder in folders {
- let path = FolderUtils.getFolderPath(folderId: folder.id, folders: folders)
- if !path.isEmpty {
- folderPathMap[scopedKey(manifestId: manifestId, id: folder.id.uuidString.lowercased())] = path
- }
- }
- }
-
- return folderPathMap
- }
-
- /// Fetch all active items (not deleted, not in trash, not archived) with their fields.
- /// - Returns: Array of Item objects
- public func getAll() throws -> [Item] {
- let itemRows = try client.executeQuery(ItemQueries.getAllActive, params: []).compactMap { ItemRow(from: $0) }
- if itemRows.isEmpty {
- return []
- }
-
- // Fields are matched on the whole (ManifestId, Id) key, bound as one pair per item.
- let keyParams = itemRows.flatMap { [$0.manifestId as SqliteBindValue, $0.id as SqliteBindValue] }
- let fieldRows = try client.executeQuery(ItemQueries.getFieldValuesForItems(itemRows.count), params: keyParams).compactMap { FieldRow(from: $0) }
- let fieldsByItem = FieldMapper.processFieldRows(fieldRows)
- let folderPaths = try buildFolderPaths()
-
- return ItemMapper.mapRows(itemRows, fieldsByItem: fieldsByItem, folderPathsByFolderKey: folderPaths)
- }
-
- // MARK: - Write Operations
-
- /// Append a single value to a multi-value field on an existing item without touching other field rows.
- /// - Parameters:
- /// - itemId: The id of the item to append the value to (lowercase string)
- /// - fieldKey: The system FieldKey to append under (e.g. `FieldKey.loginUrl`)
- /// - value: The value to append
- /// - manifestId: The manifest the item belongs to
- /// - Returns: The number of rows inserted
- @discardableResult
- public func appendFieldValue(itemId: String, manifestId: String, fieldKey: String, value: String) throws -> Int {
- return try withTransaction {
- let now = self.now()
- let weight = FieldValueQueries.defaultWeight(forFieldKey: fieldKey)
- return try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, manifestId])
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift
deleted file mode 100644
index 1bc363443..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift
+++ /dev/null
@@ -1,43 +0,0 @@
-import Foundation
-import VaultModels
-
-/// The actions whose use of an item is recorded. Each maps to its own timestamp + counter pair alongside the
-/// aggregate `LastUsedAt` / `UseCount`.
-public enum ItemUsageAction {
- /// A credential filled into a form.
- case autofill
- /// A value copied to the clipboard.
- case copy
- /// A passkey assertion.
- case passkey
-
- /// The column pair this action bumps. Closed set: nothing here is ever built from caller input.
- internal var columns: (last: String, count: String) {
- switch self {
- case .autofill:
- return ("LastAutofilledAt", "AutofillCount")
- case .copy:
- return ("LastCopiedAt", "CopyCount")
- case .passkey:
- return ("LastPasskeyAuthAt", "PasskeyAuthCount")
- }
- }
-}
-
-/// Repository for per-item usage statistics.
-public class ItemStatsRepository: BaseRepository {
- /// Record one use of an item. Runs in its own transaction so the vault is persisted and marked dirty.
- /// - Parameters:
- /// - itemId: The item that was used
- /// - manifestId: The manifest the item belongs to
- /// - action: What the user did with it
- public func recordUsage(itemId: String, manifestId: String, action: ItemUsageAction) throws {
- // Usage statistics live in their own data bucket which should be pushed without a full manifest write.
- try withTransaction(scope: VaultDataBucketCategory.stats) {
- let now = self.now()
- let columns = action.columns
- try client.executeUpdate(ItemStatsQueries.insertRow, params: [manifestId, itemId, now, now])
- try client.executeUpdate(ItemStatsQueries.forAction(lastColumn: columns.last, countColumn: columns.count), params: [now, now, now, manifestId, itemId])
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
deleted file mode 100644
index 7ae79a4d7..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
+++ /dev/null
@@ -1,337 +0,0 @@
-import Foundation
-import RustCoreFramework
-import VaultModels
-import VaultUtils
-
-/// Repository for Passkey CRUD operations.
-/// Handles fetching, creating, updating, and deleting passkeys.
-/// Other platform implementations: PasskeyRepository.ts (core/client), PasskeyRepository.kt (Android).
-public class PasskeyRepository: BaseRepository {
-
- // MARK: - Read Operations
-
- /// Get a passkey by its credential ID.
- /// - Parameter credentialId: The passkey credential ID (UUID string)
- /// - Returns: Passkey object or nil if not found
- public func getById(_ credentialId: String) throws -> Passkey? {
- let results = try client.executeQuery(PasskeyQueries.getById, params: [credentialId])
- guard let row = results.first.flatMap({ PasskeyRow(from: $0) }) else {
- return nil
- }
- return PasskeyMapper.mapRow(row)
- }
-
- /// Get a passkey by its ID inside one manifest.
- /// - Parameters:
- /// - passkeyId: The passkey ID (UUID string)
- /// - manifestId: The manifest the passkey belongs to
- /// - Returns: Passkey object or nil if not found
- public func getById(_ passkeyId: String, manifestId: String) throws -> Passkey? {
- let results = try client.executeQuery(PasskeyQueries.getByIdInManifest, params: [passkeyId, manifestId])
- guard let row = results.first.flatMap({ PasskeyRow(from: $0) }) else {
- return nil
- }
- return PasskeyMapper.mapRow(row)
- }
-
- /// Get all passkeys for an item.
- /// - Parameters:
- /// - itemId: The item ID (UUID string)
- /// - manifestId: The manifest the item belongs to
- /// - Returns: Array of Passkey objects
- public func getByItemId(_ itemId: String, manifestId: String) throws -> [Passkey] {
- let results = try client.executeQuery(PasskeyQueries.getByItemId, params: [itemId, manifestId])
- return PasskeyMapper.mapRows(results.compactMap { PasskeyRow(from: $0) })
- }
-
- /// Get all passkeys for a relying party (rpId).
- /// - Parameter rpId: The relying party identifier (domain)
- /// - Returns: Array of Passkey objects
- public func getByRpId(_ rpId: String) throws -> [Passkey] {
- let results = try client.executeQuery(PasskeyQueries.getByRpId, params: [rpId])
- return PasskeyMapper.mapRows(results.compactMap { PasskeyRow(from: $0) })
- }
-
- /// Get passkeys with item info for a specific rpId.
- /// - Parameters:
- /// - rpId: The relying party identifier (domain)
- /// - userName: Optional username to filter by
- /// - userId: Optional user handle to filter by
- /// - Returns: Array of PasskeyWithItem objects
- public func getWithItem(forRpId rpId: String, userName: String? = nil, userId: Data? = nil) throws -> [PasskeyWithItem] {
- let results = try client.executeQuery(PasskeyQueries.getWithItemByRpId, params: [rpId])
- let rows = results.compactMap { PasskeyWithItemRow(from: $0) }
- var mappedResults = PasskeyMapper.mapRowsWithItem(rows)
-
- // Apply optional filters
- if let userName = userName {
- mappedResults = mappedResults.filter { $0.username == userName }
- }
- if let userId = userId {
- mappedResults = mappedResults.filter { $0.passkey.userHandle == userId }
- }
-
- return mappedResults
- }
-
- /// Get all Login items that don't have a passkey yet (no URL filtering).
- /// Used with RustItemMatcher for intelligent, cross-platform consistent filtering.
- /// - Returns: Array of ItemWithCredentialInfoData objects with all URLs
- public func getAllItemsWithoutPasskey() throws -> [ItemWithCredentialInfoData] {
- let results = try client.executeQuery(PasskeyQueries.getAllItemsWithoutPasskey, params: [])
-
- return results.compactMap { row -> ItemWithCredentialInfoData? in
- let urls = (row["Urls"] as? String)?.components(separatedBy: ",").filter { !$0.isEmpty } ?? []
- return mapItemWithCredentialInfo(row, urls: urls)
- }
- }
-
- /// Map one row of the without-passkey queries.
- private func mapItemWithCredentialInfo(_ row: [String: Any], urls: [String]) -> ItemWithCredentialInfoData? {
- guard let idString = row["Id"] as? String, let itemId = UUID(uuidString: idString), let manifestId = row["ManifestId"] as? String else {
- return nil
- }
-
- let password = row["Password"] as? String
- return ItemWithCredentialInfoData(
- itemId: itemId,
- serviceName: row["Name"] as? String,
- urls: urls,
- username: row["Username"] as? String,
- email: row["Email"] as? String,
- hasPassword: !(password ?? "").isEmpty,
- createdAt: DateHelpers.parseDateString(row["CreatedAt"] as? String ?? "") ?? Date.distantPast,
- updatedAt: DateHelpers.parseDateString(row["UpdatedAt"] as? String ?? "") ?? Date.distantPast,
- manifestId: manifestId
- )
- }
-
- // MARK: - Write Operations
-
- /// Soft delete a passkey.
- /// - Parameters:
- /// - passkeyId: The ID of the passkey to delete
- /// - manifestId: The manifest the passkey belongs to
- /// - Returns: Number of rows affected
- @discardableResult
- public func delete(_ passkeyId: String, manifestId: String) throws -> Int {
- return try withTransaction {
- try client.executeUpdate(PasskeyQueries.softDelete, params: [self.now(), passkeyId, manifestId])
- }
- }
-
- /// Update a passkey's display name.
- /// - Parameters:
- /// - passkeyId: The ID of the passkey to update
- /// - manifestId: The manifest the passkey belongs to
- /// - displayName: The new display name
- /// - Returns: Number of rows affected
- @discardableResult
- public func updateDisplayName(_ passkeyId: String, manifestId: String, displayName: String) throws -> Int {
- return try withTransaction {
- try client.executeUpdate(PasskeyQueries.updateDisplayName, params: [displayName, self.now(), passkeyId, manifestId])
- }
- }
-
- /// Replace an existing passkey with a new one, optionally refreshing the item's logo.
- /// Soft deletes the old passkey and creates a new one linked to the same item, in the same manifest.
- /// - Parameters:
- /// - oldPasskeyId: The ID of the passkey to replace
- /// - manifestId: The manifest the old passkey and its item belong to
- /// - newPasskey: The new passkey to create
- /// - displayName: The display name for the new passkey
- /// - logo: Optional favicon bytes fetched for the passkey's rpId
- /// - Returns: The ID of the new passkey
- @discardableResult
- public func replace(oldPasskeyId: String, manifestId: String, with newPasskey: Passkey, displayName: String, logo: Data? = nil) throws -> String {
- return try withTransaction {
- let now = self.now()
- let itemId = newPasskey.parentItemId.uuidString.lowercased()
-
- if let logo = logo {
- try refreshItemLogo(itemId: itemId, manifestId: manifestId, rpId: newPasskey.rpId, logo: logo, now: now)
- }
-
- try client.executeUpdate(PasskeyQueries.softDelete, params: [now, oldPasskeyId, manifestId])
- return try insertPasskey(newPasskey, itemId: itemId, manifestId: manifestId, displayName: displayName, now: now)
- }
- }
-
- // MARK: - Item + Passkey Creation
-
- /// Create an item with a passkey (for passkey registration).
- /// This creates an Item record with field values and links the passkey to it.
- /// - Parameters:
- /// - rpId: The relying party identifier (domain)
- /// - userName: Optional username
- /// - displayName: Display name for the item
- /// - passkey: The passkey to create
- /// - logo: Optional favicon bytes fetched for the rpId
- /// - Returns: The created item ID
- @discardableResult
- public func createItemWithPasskey(rpId: String, userName: String?, displayName: String, passkey: Passkey, logo: Data? = nil) throws -> String {
- return try withTransaction {
- let itemId = passkey.parentItemId.uuidString.lowercased()
- let now = self.now()
-
- // An item outside any folder lands in the write manifest, which is the scope its logo has to live in too.
- let scope = try writeManifestId()
- let logoId = try resolveLogoId(existingLogoId: nil, manifestId: scope, rpId: rpId, logo: logo, now: now)
-
- try client.executeUpdate(ItemQueries.insertItem, params: [itemId, displayName as SqliteBindValue, ItemType.login, logoId as SqliteBindValue, nil, now, now, 0, scope])
-
- try insertSystemField(itemId: itemId, fieldKey: FieldKey.loginUrl, value: "https://\(rpId)", manifestId: scope, now: now)
- if let userName = userName, !userName.isEmpty {
- try insertSystemField(itemId: itemId, fieldKey: FieldKey.loginUsername, value: userName, manifestId: scope, now: now)
- }
-
- _ = try insertPasskey(passkey, itemId: itemId, manifestId: scope, displayName: passkey.displayName, now: now)
- return itemId
- }
- }
-
- /// Add a passkey to an existing Item (merge passkey into existing credential).
- /// - Parameters:
- /// - itemId: The UUID of the existing Item to add the passkey to
- /// - manifestId: The manifest the item belongs to
- /// - passkey: The passkey to add
- /// - logo: Optional favicon bytes fetched for the passkey's rpId
- /// - Returns: The ID of the created passkey
- @discardableResult
- public func addPasskeyToExistingItem(itemId: UUID, manifestId: String, passkey: Passkey, logo: Data? = nil) throws -> String {
- return try withTransaction {
- let itemIdString = itemId.uuidString.lowercased()
- let now = self.now()
- if let logo = logo {
- try refreshItemLogo(itemId: itemIdString, manifestId: manifestId, rpId: passkey.rpId, logo: logo, now: now)
- }
-
- return try insertPasskey(passkey, itemId: itemIdString, manifestId: manifestId, displayName: passkey.displayName, now: now)
- }
- }
-
- // MARK: - Row Helpers
-
- /// Base64 text the query bridge binds as a BLOB, or nil.
- private func blobParam(_ data: Data?) -> SqliteBindValue {
- return data.map { "av-base64-to-blob:\($0.base64EncodedString())" }
- }
-
- /// Insert one system field value for an item.
- private func insertSystemField(itemId: String, fieldKey: String, value: String, manifestId: String, now: String) throws {
- let weight = FieldValueQueries.defaultWeight(forFieldKey: fieldKey)
- try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, manifestId])
- }
-
- /// Insert a passkey row linked to an item, stamped with the item's manifest.
- /// - Returns: The passkey ID
- private func insertPasskey(_ passkey: Passkey, itemId: String, manifestId: String, displayName: String, now: String) throws -> String {
- let passkeyId = passkey.id.uuidString.lowercased()
- guard let publicKeyString = String(data: passkey.publicKey, encoding: .utf8), let privateKeyString = String(data: passkey.privateKey, encoding: .utf8) else {
- throw PasskeyRepositoryError.invalidKeyData
- }
-
- try client.executeUpdate(PasskeyQueries.insert, params: [
- passkeyId,
- itemId,
- manifestId,
- passkey.rpId,
- blobParam(passkey.userHandle),
- publicKeyString,
- privateKeyString,
- blobParam(passkey.prfKey),
- displayName,
- blobParam(passkey.additionalData),
- now,
- now,
- 0
- ])
-
- return passkeyId
- }
-
- // MARK: - Logo Helpers
-
- /// The natural key a logo row is addressed by, and the manifest it lives in.
- private struct LogoKey {
- let manifestId: String
- let kind: String
- let source: String
- }
-
- /// The image bytes and metadata written into a logo row.
- private struct LogoImage {
- let data: Data?
- let mimeType: String?
- let name: String?
- }
-
- /// The kind and key of an item's logo in the item's manifest, or nil when it no longer exists.
- private func getLogo(byId logoId: String, manifestId: String) throws -> (kind: String, source: String)? {
- guard let row = try client.executeQuery(LogoQueries.getById, params: [logoId, manifestId]).first, let kind = row["Kind"] as? String, let source = row["Source"] as? String else {
- return nil
- }
- return (kind, source)
- }
-
- /// Point an item at the favicon fetched for `rpId`, following the item-logo write rules in core/client
- /// `ItemRepository.resolveLogoId`.
- private func refreshItemLogo(itemId: String, manifestId: String, rpId: String, logo: Data, now: String) throws {
- let rows = try client.executeQuery(LogoQueries.getLogoIdFromItem, params: [itemId, manifestId])
- let existingLogoId = rows.first?["LogoId"] as? String
-
- guard let logoId = try resolveLogoId(existingLogoId: existingLogoId, manifestId: manifestId, rpId: rpId, logo: logo, now: now), logoId != existingLogoId else {
- return
- }
- try client.executeUpdate(LogoQueries.updateItemLogoId, params: [logoId, now, itemId, manifestId])
- }
-
- /// The logo id an item should carry after a favicon was fetched for `rpId` (core/client `ItemRepository.resolveLogoId`):
- /// a built-in or uploaded logo the user chose is kept, a favicon already on file for this domain is reused, fresh
- /// bytes go under the domain's own row, and without a derivable domain the logo is left as it is.
- private func resolveLogoId(existingLogoId: String?, manifestId: String, rpId: String, logo: Data?, now: String) throws -> String? {
- let existing = try existingLogoId.flatMap { try getLogo(byId: $0, manifestId: manifestId) }
- if let existing = existing, existing.kind != "favicon" {
- return try ensureInScope(LogoKey(manifestId: manifestId, kind: existing.kind, source: existing.source), now: now)
- }
-
- // The same URL string the item's login.url field is written with, which is what the TypeScript side derives the favicon target from.
- let source = RustCoreFramework.faviconSourceKey(url: "https://\(rpId)")
- if source.isEmpty {
- return existingLogoId
- }
-
- let key = LogoKey(manifestId: manifestId, kind: "favicon", source: source)
- if let existing = existing, existing.source == source {
- return try ensureInScope(key, now: now)
- }
- if let logo = logo, !logo.isEmpty {
- return try getOrCreateLogo(key, image: LogoImage(data: logo, mimeType: "image/x-icon", name: nil), now: now)
- }
- return try ensureInScope(key, now: now)
- }
-
- /// Get or create the logo for a key inside one manifest, refreshing its image data.
- /// The row's stamp and the id derived for it come from the same manifest.
- private func getOrCreateLogo(_ key: LogoKey, image: LogoImage, now: String) throws -> String {
- let logoId = RustCoreFramework.vaultCodecLogoIdFor(manifestId: key.manifestId, kind: key.kind, source: key.source)
- let params: [SqliteBindValue] = [logoId, key.kind, key.source, key.manifestId, blobParam(image.data), image.mimeType, image.name, now, now]
- try client.executeUpdate(LogoQueries.upsert, params: params)
- return logoId
- }
-
- /// The id this logo has inside the key's manifest, copying it in from another manifest when it is not there yet.
- /// - Returns: The logo id inside this manifest, or nil when the vault holds no such logo at all
- private func ensureInScope(_ key: LogoKey, now: String) throws -> String? {
- let inScope = try client.executeQuery(LogoQueries.getIdForKey, params: [key.manifestId, key.kind, key.source])
- if let logoId = inScope.first?["Id"] as? String {
- return logoId
- }
-
- guard let origin = try client.executeQuery(LogoQueries.getBestForKey, params: [key.kind, key.source]).first else {
- return nil
- }
- let data = (origin["FileData"] as? String).flatMap { Data(base64Encoded: $0) }
- return try getOrCreateLogo(key, image: LogoImage(data: data, mimeType: origin["MimeType"] as? String, name: origin["Name"] as? String), now: now)
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift
deleted file mode 100644
index 0b88e2e54..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift
+++ /dev/null
@@ -1,46 +0,0 @@
-import Foundation
-
-/// Data class to hold Item info for Items without passkeys (internal VaultStoreKit type).
-/// Used for showing existing credentials that can have a passkey added.
-/// Note: VaultUI has its own ItemWithCredentialInfo type for UI usage.
-public struct ItemWithCredentialInfoData {
- /// The item id.
- public let itemId: UUID
- /// The item name.
- public let serviceName: String?
- /// All URLs associated with this item (supports multi-value URL fields)
- public let urls: [String]
- /// The login.username value, if any.
- public let username: String?
- /// The login.email value, if any.
- public let email: String?
- /// Whether the item has a non-empty password.
- public let hasPassword: Bool
- /// When the item was created.
- public let createdAt: Date
- /// When the item was last updated.
- public let updatedAt: Date
- /// The manifest the item lives in.
- public let manifestId: String
-
- /// Create an entry from the mapped row values.
- public init(itemId: UUID, serviceName: String?, urls: [String], username: String?, email: String? = nil, hasPassword: Bool, createdAt: Date, updatedAt: Date, manifestId: String) {
- self.itemId = itemId
- self.serviceName = serviceName
- self.urls = urls
- self.username = username
- self.email = email
- self.hasPassword = hasPassword
- self.createdAt = createdAt
- self.updatedAt = updatedAt
- self.manifestId = manifestId
- }
-}
-
-/// Errors that can occur in PasskeyRepository operations.
-public enum PasskeyRepositoryError: Error {
- /// The passkey's public or private key is not valid UTF-8 JWK text.
- case invalidKeyData
- /// No live passkey with the given id exists.
- case passkeyNotFound
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
deleted file mode 100644
index 683fce450..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
+++ /dev/null
@@ -1,49 +0,0 @@
-import Foundation
-import VaultModels
-
-/// Repository for reading TOTP codes from the vault database.
-public class TotpRepository: BaseRepository {
- /// An item's TOTP codes, scoped by manifest as well as item (core/client `TotpCodeQueries.GET_BY_ITEM_ID`).
- private static let getByItemId = """
- SELECT Id, Name, SecretKey, Algorithm, Digits, Period, ItemId
- FROM TotpCodes
- WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0
- """
-
- /// Get all TOTP codes for a specific item.
- /// - Parameters:
- /// - itemId: The UUID of the item
- /// - manifestId: The manifest the item belongs to
- /// - Returns: Array of TotpCode objects for the item
- public func getTotpCodesForItem(_ itemId: UUID, manifestId: String) throws -> [TotpCode] {
- let results = try client.executeQuery(Self.getByItemId, params: [itemId.uuidString.lowercased(), manifestId])
- return results.compactMap { row -> TotpCode? in
- guard let idString = row["Id"] as? String, let id = UUID(uuidString: idString), let name = row["Name"] as? String, let secretKey = row["SecretKey"] as? String else {
- return nil
- }
- guard let rowItemId = row["ItemId"] as? String, let itemIdParsed = UUID(uuidString: rowItemId) else {
- return nil
- }
-
- return TotpCode(
- id: id,
- name: name,
- secretKey: secretKey,
- algorithm: row["Algorithm"] as? String ?? TotpCode.defaultAlgorithm,
- digits: Int(row["Digits"] as? Int64 ?? Int64(TotpCode.defaultDigits)),
- period: Int(row["Period"] as? Int64 ?? Int64(TotpCode.defaultPeriod)),
- itemId: itemIdParsed,
- isDeleted: false
- )
- }
- }
-
- /// Get the first TOTP code for a specific item (convenience method).
- /// - Parameters:
- /// - itemId: The UUID of the item
- /// - manifestId: The manifest the item belongs to
- /// - Returns: Optional TotpCode if one exists
- public func getFirstTotpCodeForItem(_ itemId: UUID, manifestId: String) throws -> TotpCode? {
- return try getTotpCodesForItem(itemId, manifestId: manifestId).first
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
index 4dcdd2dbb..9264f1af5 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
@@ -1,79 +1,34 @@
import Foundation
-import CryptoKit
-import Security
+import RustCoreFramework
/**
- * PasskeyAuthenticator
- * -------------------------
- * A WebAuthn "virtual authenticator" for iOS credential provider extension.
- * Implements passkey creation (registration) and authentication (assertion) following
- * the WebAuthn Level 2 specification.
- *
- * This is a Swift port of the reference TypeScript implementation:
- * - Reference: apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts
- * - Android: apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
- *
- * Key features:
- * - ES256 (ECDSA P-256) and RS256 (RSASSA-PKCS1-v1.5) key pair generation
- * - CBOR/COSE encoding for attestation objects
- * - Proper authenticator data with WebAuthn flags
- * - Self-attestation (packed format) or none attestation
- * - Consistent base64url handling
- * - Sign count always 0 for syncable passkeys
- * - BE/BS flags for backup-eligible and backed-up status
+ * The WebAuthn authenticator of the iOS credential provider extension. Key generation, authenticator data,
+ * the attestation object, signatures and PRF all run in the Rust core (core/rust/src/passkey).
+ * Other platform implementations: PasskeyAuthenticator.kt (Android), PasskeyAuthenticator.ts (browser extension).
*/
public class PasskeyAuthenticator {
-
- /// AliasVault AAGUID: a11a5faa-9f32-4b8c-8c5d-2f7d13e8c942
- private static let aaguid: [UInt8] = [
- 0xa1, 0x1a, 0x5f, 0xaa, 0x9f, 0x32, 0x4b, 0x8c,
- 0x8c, 0x5d, 0x2f, 0x7d, 0x13, 0xe8, 0xc9, 0x42
- ]
-
/// COSE algorithm identifier for ES256 (ECDSA P-256 with SHA-256).
public static let algES256 = -7
- /// COSE algorithm identifier for RS256 (RSASSA-PKCS1-v1.5 with SHA-256).
- public static let algRS256 = -257
+ /// The 16-byte credential id of a passkey GUID.
+ public static func guidToBytes(_ guid: String) throws -> Data {
+ return try passkeyGuidToBytes(guid: guid)
+ }
- /// Algorithms supported by this authenticator, in our order of preference.
- private static let supportedAlgorithms = [algES256, algRS256]
+ /// The lowercase GUID text of a 16-byte credential id.
+ public static func bytesToGuid(_ bytes: Data) throws -> String {
+ return try passkeyBytesToGuid(bytes: bytes)
+ }
- /**
- * Pick a supported credential algorithm from the RP's requested algorithms.
- * Honors the RP's preference order and returns the first algorithm we support.
- * Defaults to ES256 when the RP provides no algorithms.
- *
- * - Parameter algs: COSE algorithm identifiers from the RP (e.g. ASCOSEAlgorithmIdentifier rawValues)
- * - Returns: The chosen COSE algorithm identifier (-7 for ES256, -257 for RS256)
- */
+ /// The first algorithm in the RP's preference order that the authenticator supports; ES256 when the RP lists none.
public static func pickSupportedAlgorithm(_ algs: [Int]) throws -> Int {
- if algs.isEmpty {
- return algES256
- }
- for alg in algs where supportedAlgorithms.contains(alg) {
- return alg
- }
- throw PasskeyError.unsupportedAlgorithm
+ return Int(try passkeyPickAlgorithm(requested: algs.map(Int64.init)))
}
- // MARK: - Public API
-
- /**
- * Create a new passkey (registration)
- * Returns credential data ready for iOS to return to the RP, plus storage data
- *
- * - Note: This method intentionally has more than 5 parameters to match WebAuthn spec requirements.
- * SwiftLint: function_parameter_count is disabled for this method as parameters directly map
- * to WebAuthn credential creation parameters and cannot be reasonably grouped.
- */
+ /// Create a new passkey (registration): the attestation object for the RP and the keys the vault stores.
// swiftlint:disable:next function_parameter_count
public static func createPasskey(
credentialId: Data,
- clientDataHash: Data,
rpId: String,
userId: Data?,
userName: String?,
@@ -83,103 +38,29 @@ public class PasskeyAuthenticator {
prfInputs: PrfInputs? = nil,
algorithm: Int = algES256
) throws -> PasskeyCreationResult {
-
- // 1. Generate key pair, build COSE key, and export JWKs for the chosen algorithm
- let coseKey: Data
- let publicKeyData: Data
- let privateKeyData: Data
- if algorithm == algRS256 {
- let rsaKey = try generateRsaKey()
- coseKey = try buildCoseRsaRs256(privateKey: rsaKey)
- publicKeyData = try exportRsaPublicKeyAsJWK(privateKey: rsaKey)
- privateKeyData = try exportRsaPrivateKeyAsJWK(privateKey: rsaKey)
- } else {
- let privateKey = P256.Signing.PrivateKey()
- let publicKey = privateKey.publicKey
- coseKey = try buildCoseEc2Es256(publicKey: publicKey)
- publicKeyData = try exportPublicKeyAsJWK(publicKey: publicKey)
- privateKeyData = try exportPrivateKeyAsJWK(privateKey: privateKey)
- }
-
- // 2. RP ID hash
- let rpIdHash = Data(SHA256.hash(data: rpId.data(using: .utf8)!))
-
- // 3. Build flags
- var flags: UInt8 = 0x41 // UP (bit 0) + AT (bit 6)
- if uvPerformed {
- flags |= 0x04 // UV (bit 2)
- }
- flags |= 0x08 // BE (bit 3) - backup eligible
- flags |= 0x10 // BS (bit 4) - backup state
-
- // 4. Sign count (always 0 for syncable credentials)
- let signCount = Data([0x00, 0x00, 0x00, 0x00])
-
- // 5. Build attested credential data
- let credIdLength = Data([
- UInt8((credentialId.count >> 8) & 0xFF),
- UInt8(credentialId.count & 0xFF)
- ])
- var attestedCredData = Data(aaguid)
- attestedCredData.append(credIdLength)
- attestedCredData.append(credentialId)
- attestedCredData.append(coseKey)
-
- // 6. Build authenticator data
- var authenticatorData = Data()
- authenticatorData.append(rpIdHash)
- authenticatorData.append(Data([flags]))
- authenticatorData.append(signCount)
- authenticatorData.append(attestedCredData)
-
- // 7. Build attestation object (none format)
- let attestationObject = try buildAttestationObjectNone(authenticatorData: authenticatorData)
-
- // 8. Generate PRF secret if requested
- var prfSecret: Data?
- if enablePrf {
- var prfBytes = Data(count: 32)
- let result = prfBytes.withUnsafeMutableBytes { bytes in
- SecRandomCopyBytes(kSecRandomDefault, 32, bytes.baseAddress!)
- }
- if result == errSecSuccess {
- prfSecret = prfBytes
- }
- }
-
- // 9. Evaluate PRF values if requested during registration (some authenticators try this during registration already)
- var prfResults: PrfResults?
- if let inputs = prfInputs, let firstSalt = inputs.first, let secret = prfSecret {
- var firstResult = try evaluatePrf(secret: secret, salt: firstSalt)
- var secondResult: Data?
- if let secondSalt = inputs.second {
- secondResult = try evaluatePrf(secret: secret, salt: secondSalt)
- }
- prfResults = PrfResults(first: firstResult, second: secondResult)
- }
-
+ let created = try passkeyCreate(
+ credentialId: credentialId,
+ rpId: rpId,
+ algorithm: Int64(algorithm),
+ uvPerformed: uvPerformed,
+ enablePrf: enablePrf,
+ prfInputs: prfInputs.map { PasskeyPrfInputs(first: $0.first, second: $0.second) }
+ )
return PasskeyCreationResult(
credentialId: credentialId,
- attestationObject: attestationObject,
- publicKey: publicKeyData,
- privateKey: privateKeyData,
+ attestationObject: created.attestationObject,
+ publicKey: Data(created.publicKeyJwk.utf8),
+ privateKey: Data(created.privateKeyJwk.utf8),
rpId: rpId,
userId: userId,
userName: userName,
userDisplayName: userDisplayName,
- prfSecret: prfSecret,
- prfResults: prfResults
+ prfSecret: created.prfSecret,
+ prfResults: created.prfResults.map { PrfResults(first: $0.first, second: $0.second) }
)
}
- /**
- * Create an assertion (authentication)
- * Returns assertion data ready for iOS to return to the RP
- *
- * - Note: This method intentionally has more than 5 parameters to match WebAuthn spec requirements.
- * SwiftLint: function_parameter_count is disabled for this method as parameters directly map
- * to WebAuthn assertion parameters and cannot be reasonably grouped.
- */
+ /// Create an assertion (authentication) signed with the stored private key JWK.
// swiftlint:disable:next function_parameter_count
public static func getAssertion(
credentialId: Data,
@@ -191,698 +72,82 @@ public class PasskeyAuthenticator {
prfInputs: PrfInputs? = nil,
prfSecret: Data? = nil
) throws -> PasskeyAssertionResult {
-
- // 1. RP ID hash
- let rpIdHash = Data(SHA256.hash(data: rpId.data(using: .utf8)!))
-
- // 2. Build flags
- var flags: UInt8 = 0x01 // UP (bit 0)
- if uvPerformed {
- flags |= 0x04 // UV (bit 2)
- }
- flags |= 0x08 // BE (bit 3)
- flags |= 0x10 // BS (bit 4)
-
- // 3. Sign count
- let signCount = Data([0x00, 0x00, 0x00, 0x00])
-
- // 4. Build authenticator data
- var authenticatorData = Data()
- authenticatorData.append(rpIdHash)
- authenticatorData.append(Data([flags]))
- authenticatorData.append(signCount)
-
- // 5. Build data to sign: authenticatorData || clientDataHash
- var dataToSign = Data()
- dataToSign.append(authenticatorData)
- dataToSign.append(clientDataHash)
-
- // 6. Determine algorithm from the stored key, import it, and sign.
- // The signature is returned in the form the RP expects:
- // DER-encoded for ES256, raw PKCS#1 v1.5 for RS256.
- let signatureData: Data
- if jwkKeyType(jwkData: privateKeyJWK) == "RSA" {
- signatureData = try signRsa(jwkData: privateKeyJWK, dataToSign: dataToSign)
- } else {
- let privateKey = try importPrivateKeyFromJWK(jwkData: privateKeyJWK)
- let signature = try privateKey.signature(for: dataToSign)
- signatureData = try convertRawSignatureToDER(signature: signature)
- }
-
- // 8. Evaluate PRF if requested
- var prfResults: PrfResults?
- if let inputs = prfInputs, let firstSalt = inputs.first, let secret = prfSecret {
- var firstResult = try evaluatePrf(secret: secret, salt: firstSalt)
-
- var secondResult: Data?
- if let secondSalt = inputs.second {
- secondResult = try evaluatePrf(secret: secret, salt: secondSalt)
- }
- prfResults = PrfResults(first: firstResult, second: secondResult)
- }
-
+ let assertion = try passkeyGetAssertion(
+ rpId: rpId,
+ clientDataHash: clientDataHash,
+ privateKeyJwk: String(decoding: privateKeyJWK, as: UTF8.self),
+ uvPerformed: uvPerformed,
+ prfInputs: prfInputs.map { PasskeyPrfInputs(first: $0.first, second: $0.second) },
+ prfSecret: prfSecret
+ )
return PasskeyAssertionResult(
credentialId: credentialId,
- authenticatorData: authenticatorData,
- signature: signatureData,
+ authenticatorData: assertion.authenticatorData,
+ signature: assertion.signature,
userHandle: userId,
- prfResults: prfResults
+ prfResults: assertion.prfResults.map { PrfResults(first: $0.first, second: $0.second) }
)
}
-
- // MARK: - Key Management
-
- /**
- * Export public key as JWK format (JSON)
- */
- private static func exportPublicKeyAsJWK(publicKey: P256.Signing.PublicKey) throws -> Data {
- let rawRepresentation = publicKey.rawRepresentation
-
- // CryptoKit's rawRepresentation is 64 bytes (x || y) without the 0x04 prefix
- guard rawRepresentation.count == 64 else {
- print("PasskeyAuthenticator: exportPublicKeyAsJWK - Expected 64 bytes but got \(rawRepresentation.count)")
- throw PasskeyError.invalidPublicKey
- }
-
- // Get bytes and normalize: accept 64 (x||y) or 65 (0x04||x||y)
- var bytes = [UInt8](publicKey.rawRepresentation)
- if bytes.count == 65, bytes[0] == 0x04 { bytes.removeFirst() }
- guard bytes.count == 64 else { throw PasskeyError.invalidPublicKey }
-
- // Safe slicing without Data.subdata
- let xBytes = Data(bytes[0..<32])
- let yBytes = Data(bytes[32..<64])
-
- let jwk: [String: Any] = [
- "kty": "EC",
- "crv": "P-256",
- "x": xBytes.base64URLEncodedString(),
- "y": yBytes.base64URLEncodedString()
- ]
-
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Export private key as JWK format (JSON)
- */
- private static func exportPrivateKeyAsJWK(privateKey: P256.Signing.PrivateKey) throws -> Data {
- let rawRepresentation = privateKey.rawRepresentation
- let publicKey = privateKey.publicKey
-
- // Get bytes and normalize: accept 64 (x||y) or 65 (0x04||x||y)
- var bytes = [UInt8](publicKey.rawRepresentation)
- if bytes.count == 65, bytes[0] == 0x04 { bytes.removeFirst() }
- guard bytes.count == 64 else { throw PasskeyError.invalidPublicKey }
-
- // Safe slicing without Data.subdata
- let xBytes = Data(bytes[0..<32])
- let yBytes = Data(bytes[32..<64])
-
- let dBytes = rawRepresentation
-
- let jwk: [String: Any] = [
- "kty": "EC",
- "crv": "P-256",
- "x": xBytes.base64URLEncodedString(),
- "y": yBytes.base64URLEncodedString(),
- "d": dBytes.base64URLEncodedString()
- ]
-
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Import private key from JWK format
- */
- private static func importPrivateKeyFromJWK(jwkData: Data) throws -> P256.Signing.PrivateKey {
- guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
- let dBase64url = jwk["d"] as? String else {
- throw PasskeyError.invalidJWK
- }
-
- let dBytes = try Data(base64URLEncoded: dBase64url)
- return try P256.Signing.PrivateKey(rawRepresentation: dBytes)
- }
-
- /**
- * Read the "kty" field of a JWK ("EC" or "RSA"). Defaults to "EC".
- */
- private static func jwkKeyType(jwkData: Data) -> String {
- guard let jwk = try? JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
- let kty = jwk["kty"] as? String else {
- return "EC"
- }
- return kty
- }
-
- // MARK: - CBOR Encoding
-
- /**
- * Build COSE EC2 public key for ES256
- * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}
- */
- private static func buildCoseEc2Es256(publicKey: P256.Signing.PublicKey) throws -> Data {
- let rawRepresentation = publicKey.rawRepresentation
-
- // CryptoKit's rawRepresentation is 64 bytes (x || y) without the 0x04 prefix
- // Unlike X9.63 format which is 65 bytes (0x04 || x || y)
- guard rawRepresentation.count == 64 else {
- print("PasskeyAuthenticator: ERROR - Expected 64 bytes but got \(rawRepresentation.count)")
- throw PasskeyError.invalidPublicKey
- }
-
- // Get bytes and normalize: accept 64 (x||y) or 65 (0x04||x||y)
- var bytes = [UInt8](publicKey.rawRepresentation)
- if bytes.count == 65, bytes[0] == 0x04 { bytes.removeFirst() }
- guard bytes.count == 64 else { throw PasskeyError.invalidPublicKey }
-
- // Safe slicing without Data.subdata
- let xBytes = bytes[0..<32]
- let yBytes = bytes[32..<64]
-
- // Build CBOR map manually
- var cbor = Data()
- cbor.append(0xA5) // map(5)
-
- // 1: 2 (kty: EC2)
- cbor.append(0x01) // key 1
- cbor.append(0x02) // value 2
-
- // 3: -7 (alg: ES256)
- cbor.append(0x03) // key 3
- cbor.append(0x26) // value -7
-
- // -1: 1 (crv: P-256)
- cbor.append(0x20) // key -1
- cbor.append(0x01) // value 1
-
- // -2: x (x coordinate)
- cbor.append(0x21) // key -2
- cbor.append(0x58) // bytes(32)
- cbor.append(0x20) // length 32
- cbor.append(contentsOf: xBytes)
-
- // -3: y (y coordinate)
- cbor.append(0x22) // key -3
- cbor.append(0x58) // bytes(32)
- cbor.append(0x20) // length 32
- cbor.append(contentsOf: yBytes)
-
- return cbor
- }
-
- /**
- * Build COSE RSA public key for RS256 (RFC 8230)
- * CBOR map: {1: 3 (kty: RSA), 3: -257 (alg: RS256), -1: n (modulus), -2: e (exponent)}
- */
- private static func buildCoseRsaRs256(privateKey: SecKey) throws -> Data {
- // swiftlint:disable:next identifier_name - n/e are the standard RSA modulus/exponent names (RFC 8230)
- let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
-
- var cbor = Data()
- cbor.append(0xA4) // map(4)
-
- // 1: 3 (kty: RSA)
- cbor.append(0x01)
- cbor.append(0x03)
-
- // 3: -257 (alg: RS256), encoded as negative int with 2-byte argument
- cbor.append(0x03)
- cbor.append(contentsOf: [0x39, 0x01, 0x00])
-
- // -1: n (modulus)
- cbor.append(0x20)
- cbor.append(cborBytes(n))
-
- // -2: e (exponent)
- cbor.append(0x21)
- cbor.append(cborBytes(e))
-
- return cbor
- }
-
- /**
- * Build attestation object with "none" format
- * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}
- */
- private static func buildAttestationObjectNone(authenticatorData: Data) throws -> Data {
- var cbor = Data()
- cbor.append(0xA3) // map(3)
-
- // "fmt": "none"
- cbor.append(contentsOf: cborText("fmt"))
- cbor.append(contentsOf: cborText("none"))
-
- // "attStmt": {}
- cbor.append(contentsOf: cborText("attStmt"))
- cbor.append(0xA0) // map(0)
-
- // "authData": <bytes>
- cbor.append(contentsOf: cborText("authData"))
- cbor.append(contentsOf: cborBytes(authenticatorData))
-
- return cbor
- }
-
- /**
- * Encode a string as CBOR text
- */
- private static func cborText(_ text: String) -> Data {
- guard let bytes = text.data(using: .utf8) else {
- return Data()
- }
-
- var cbor = Data()
- if bytes.count <= 23 {
- cbor.append(0x60 | UInt8(bytes.count)) // text(n)
- cbor.append(bytes)
- } else if bytes.count <= 0xFF {
- cbor.append(0x78) // text(uint8)
- cbor.append(UInt8(bytes.count))
- cbor.append(bytes)
- } else {
- cbor.append(0x79) // text(uint16)
- cbor.append(UInt8((bytes.count >> 8) & 0xFF))
- cbor.append(UInt8(bytes.count & 0xFF))
- cbor.append(bytes)
- }
-
- return cbor
- }
-
- /**
- * Encode bytes as CBOR byte string
- */
- private static func cborBytes(_ bytes: Data) -> Data {
- var cbor = Data()
- if bytes.count <= 23 {
- cbor.append(0x40 | UInt8(bytes.count)) // bytes(n)
- cbor.append(bytes)
- } else if bytes.count <= 0xFF {
- cbor.append(0x58) // bytes(uint8)
- cbor.append(UInt8(bytes.count))
- cbor.append(bytes)
- } else {
- cbor.append(0x59) // bytes(uint16)
- cbor.append(UInt8((bytes.count >> 8) & 0xFF))
- cbor.append(UInt8(bytes.count & 0xFF))
- cbor.append(bytes)
- }
-
- return cbor
- }
-
- // MARK: - Signature Conversion
-
- /**
- * Convert P256.Signing.ECDSASignature to DER format
- * WebAuthn requires DER encoding, but CryptoKit gives us raw r||s
- */
- private static func convertRawSignatureToDER(signature: P256.Signing.ECDSASignature) throws -> Data {
- let rawSig = signature.rawRepresentation
-
- guard rawSig.count == 64 else {
- throw PasskeyError.invalidSignature
- }
-
- // Convert SubSequence to Data to avoid indexing issues
- let rVal = Data(rawSig[0..<32])
- let sVal = Data(rawSig[32..<64])
-
- let rDER = derInteger(rVal)
- let sDER = derInteger(sVal)
-
- var derSig = Data()
- derSig.append(0x30) // SEQUENCE
- derSig.append(UInt8(rDER.count + sDER.count))
- derSig.append(rDER)
- derSig.append(sDER)
-
- return derSig
- }
-
- /**
- * Encode a positive big integer as DER INTEGER
- */
- private static func derInteger(_ bytes: Data) -> Data {
- // Trim leading zeros, but keep at least 1 byte
- var startIndex = 0
- while startIndex < bytes.count - 1 && bytes[startIndex] == 0x00 {
- startIndex += 1
- }
- var trimmed = bytes.suffix(from: startIndex)
-
- // If MSB is set, prepend 0x00 to keep it positive
- var value = trimmed
- if !trimmed.isEmpty && (trimmed[trimmed.startIndex] & 0x80) != 0 {
- value = Data([0x00]) + trimmed
- }
-
- var der = Data()
- der.append(0x02) // INTEGER
- der.append(derLength(value.count))
- der.append(value)
-
- return der
- }
-
- // MARK: - ASN.1 DER
-
- /**
- * Encode a DER length (definite form), supporting multi-byte lengths.
- */
- private static func derLength(_ length: Int) -> Data {
- if length < 0x80 {
- return Data([UInt8(length)])
- }
- var lenBytes: [UInt8] = []
- var value = length
- while value > 0 {
- lenBytes.insert(UInt8(value & 0xFF), at: 0)
- value >>= 8
- }
- return Data([UInt8(0x80 | lenBytes.count)] + lenBytes)
- }
-
- /**
- * Wrap pre-encoded DER elements in a SEQUENCE.
- */
- private static func derSequence(_ elements: [Data]) -> Data {
- var body = Data()
- for element in elements {
- body.append(element)
- }
- var result = Data()
- result.append(0x30) // SEQUENCE
- result.append(derLength(body.count))
- result.append(body)
- return result
- }
-
- /**
- * Parse a DER SEQUENCE of INTEGERs, returning each integer's content as
- * an unsigned big-endian minimal byte string (leading sign byte stripped).
- */
- private static func parseDerIntegerSequence(_ der: Data) throws -> [Data] {
- var index = der.startIndex
-
- func readByte() throws -> UInt8 {
- guard index < der.endIndex else { throw PasskeyError.invalidJWK }
- let byte = der[index]
- index = der.index(after: index)
- return byte
- }
-
- func readLength() throws -> Int {
- let first = try readByte()
- if first < 0x80 {
- return Int(first)
- }
- let count = Int(first & 0x7F)
- guard count > 0 && count <= 8 else { throw PasskeyError.invalidJWK }
- var length = 0
- for _ in 0..<count {
- length = (length << 8) | Int(try readByte())
- }
- return length
- }
-
- guard try readByte() == 0x30 else { throw PasskeyError.invalidJWK } // SEQUENCE
- let seqLength = try readLength()
- guard let seqEnd = der.index(index, offsetBy: seqLength, limitedBy: der.endIndex) else {
- throw PasskeyError.invalidJWK
- }
-
- var integers: [Data] = []
- while index < seqEnd {
- guard try readByte() == 0x02 else { throw PasskeyError.invalidJWK } // INTEGER
- let length = try readLength()
- guard let contentEnd = der.index(index, offsetBy: length, limitedBy: seqEnd) else {
- throw PasskeyError.invalidJWK
- }
- var content = Data(der[index..<contentEnd])
- index = contentEnd
- // Strip leading zero bytes to get unsigned minimal representation
- while content.count > 1 && content.first == 0x00 {
- content = content.dropFirst()
- }
- integers.append(Data(content))
- }
- return integers
- }
-
- // MARK: - PRF Extension
-
- /**
- * Evaluate PRF (hmac-secret extension)
- * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt))
- */
- private static func evaluatePrf(secret: Data, salt: Data) throws -> Data {
- // Step 1: Domain separation - hash salt with "WebAuthn PRF\x00" prefix
- let prefix = "WebAuthn PRF\0".data(using: .utf8)!
- var domainSeparatedSalt = Data()
- domainSeparatedSalt.append(prefix)
- domainSeparatedSalt.append(salt)
-
- let hashedSalt = Data(SHA256.hash(data: domainSeparatedSalt))
-
- // Step 2: Compute HMAC-SHA256(prfSecret, hashedSalt)
- let key = SymmetricKey(data: secret)
- let hmac = HMAC<SHA256>.authenticationCode(for: hashedSalt, using: key)
-
- return Data(hmac)
- }
-}
-
-// MARK: - RSA Key Management (RS256)
-
-/*
- * RSA helpers live in an extension to keep the main type body within SwiftLint's
- * type_body_length limit. Same-file `private` access keeps them callable from the class.
- */
-extension PasskeyAuthenticator {
-
- /**
- * Generate an RSA-2048 key pair (returns the private SecKey).
- */
- private static func generateRsaKey() throws -> SecKey {
- let attributes: [String: Any] = [
- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
- kSecAttrKeySizeInBits as String: 2048
- ]
- var error: Unmanaged<CFError>?
- guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
- throw PasskeyError.keyGenerationFailed
- }
- return key
- }
-
- /**
- * Extract (modulus, exponent) from an RSA private key's public component.
- * SecKeyCopyExternalRepresentation of an RSA public key is PKCS#1
- * RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }.
- */
- private static func rsaModulusAndExponent(privateKey: SecKey) throws -> (n: Data, e: Data) {
- guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
- throw PasskeyError.invalidPublicKey
- }
- var error: Unmanaged<CFError>?
- guard let der = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else {
- throw PasskeyError.invalidPublicKey
- }
- let ints = try parseDerIntegerSequence(der)
- guard ints.count == 2 else { throw PasskeyError.invalidPublicKey }
- return (ints[0], ints[1])
- }
-
- /**
- * Export RSA public key as JWK: {kty: "RSA", n, e}.
- */
- private static func exportRsaPublicKeyAsJWK(privateKey: SecKey) throws -> Data {
- // swiftlint:disable:next identifier_name - n/e are the standard RSA modulus/exponent names (RFC 8230)
- let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
- let jwk: [String: Any] = [
- "kty": "RSA",
- "n": n.base64URLEncodedString(),
- "e": e.base64URLEncodedString()
- ]
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Export RSA private key as JWK: {kty: "RSA", n, e, d, p, q, dp, dq, qi}.
- * SecKeyCopyExternalRepresentation of an RSA private key is PKCS#1
- * RSAPrivateKey ::= SEQUENCE { version, modulus, publicExponent, privateExponent,
- * prime1, prime2, exponent1, exponent2, coefficient } (9 INTEGERs).
- */
- private static func exportRsaPrivateKeyAsJWK(privateKey: SecKey) throws -> Data {
- var error: Unmanaged<CFError>?
- guard let der = SecKeyCopyExternalRepresentation(privateKey, &error) as Data? else {
- throw PasskeyError.invalidPrivateKey
- }
- let ints = try parseDerIntegerSequence(der)
- guard ints.count >= 9 else { throw PasskeyError.invalidPrivateKey }
- let jwk: [String: Any] = [
- "kty": "RSA",
- "n": ints[1].base64URLEncodedString(),
- "e": ints[2].base64URLEncodedString(),
- "d": ints[3].base64URLEncodedString(),
- "p": ints[4].base64URLEncodedString(),
- "q": ints[5].base64URLEncodedString(),
- "dp": ints[6].base64URLEncodedString(),
- "dq": ints[7].base64URLEncodedString(),
- "qi": ints[8].base64URLEncodedString()
- ]
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Import an RSA private key from JWK and sign data with RS256
- * (RSASSA-PKCS1-v1.5 over SHA-256). The ".message" variant hashes the
- * input internally, matching how P256.signature(for:) hashes its input.
- */
- private static func signRsa(jwkData: Data, dataToSign: Data) throws -> Data {
- let key = try importRsaPrivateKeyFromJWK(jwkData: jwkData)
- var error: Unmanaged<CFError>?
- guard let sig = SecKeyCreateSignature(
- key,
- .rsaSignatureMessagePKCS1v15SHA256,
- dataToSign as CFData,
- &error
- ) as Data? else {
- throw PasskeyError.invalidSignature
- }
- return sig
- }
-
- /**
- * Build a PKCS#1 RSAPrivateKey from a JWK and import it as a SecKey.
- */
- private static func importRsaPrivateKeyFromJWK(jwkData: Data) throws -> SecKey {
- guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
- let nB64 = jwk["n"] as? String,
- let eB64 = jwk["e"] as? String,
- let dB64 = jwk["d"] as? String,
- let pB64 = jwk["p"] as? String,
- let qB64 = jwk["q"] as? String,
- let dpB64 = jwk["dp"] as? String,
- let dqB64 = jwk["dq"] as? String,
- let qiB64 = jwk["qi"] as? String else {
- throw PasskeyError.invalidJWK
- }
-
- // swiftlint:disable identifier_name - n/e/d/p/q/dp/dq/qi are the standard RSA/JWK component names (RFC 7518)
- let n = try Data(base64URLEncoded: nB64)
- let e = try Data(base64URLEncoded: eB64)
- let d = try Data(base64URLEncoded: dB64)
- let p = try Data(base64URLEncoded: pB64)
- let q = try Data(base64URLEncoded: qB64)
- let dp = try Data(base64URLEncoded: dpB64)
- let dq = try Data(base64URLEncoded: dqB64)
- let qi = try Data(base64URLEncoded: qiB64)
- // swiftlint:enable identifier_name
-
- // PKCS#1 RSAPrivateKey DER (version 0, two-prime)
- let der = derSequence([
- derInteger(Data([0x00])), // version
- derInteger(n),
- derInteger(e),
- derInteger(d),
- derInteger(p),
- derInteger(q),
- derInteger(dp),
- derInteger(dq),
- derInteger(qi)
- ])
-
- let attributes: [String: Any] = [
- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
- kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
- kSecAttrKeySizeInBits as String: n.count * 8
- ]
- var error: Unmanaged<CFError>?
- guard let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, &error) else {
- throw PasskeyError.invalidPrivateKey
- }
- return key
- }
}
// MARK: - Supporting Types
+/// A new passkey: what the RP receives, and the JWK keys and PRF secret the vault stores.
public struct PasskeyCreationResult {
+ /// The credential id.
public let credentialId: Data
+ /// The CBOR attestation object for the RP.
public let attestationObject: Data
- public let publicKey: Data // JWK format
- public let privateKey: Data // JWK format
+ /// The public key as JWK JSON.
+ public let publicKey: Data
+ /// The private key as JWK JSON.
+ public let privateKey: Data
+ /// The relying party id.
public let rpId: String
+ /// The RP's user handle.
public let userId: Data?
+ /// The RP's user name.
public let userName: String?
+ /// The RP's user display name.
public let userDisplayName: String?
+ /// The PRF secret, when PRF was enabled.
public let prfSecret: Data?
+ /// The PRF outputs for salts requested at registration.
public let prfResults: PrfResults?
}
+/// A signed assertion for the RP.
public struct PasskeyAssertionResult {
+ /// The credential id.
public let credentialId: Data
+ /// The authenticator data that was signed.
public let authenticatorData: Data
+ /// The signature over authenticator data and client data hash.
public let signature: Data
+ /// The RP's user handle.
public let userHandle: Data?
+ /// The PRF outputs for the requested salts.
public let prfResults: PrfResults?
}
+/// The salts of a PRF extension request.
public struct PrfInputs {
+ /// The first salt.
public let first: Data?
+ /// The optional second salt.
public let second: Data?
+ /// Create PRF inputs from the request's salts.
public init(first: Data? = nil, second: Data? = nil) {
self.first = first
self.second = second
}
}
+/// The PRF outputs for the requested salts.
public struct PrfResults {
+ /// The output for the first salt.
public let first: Data
+ /// The output for the second salt, if one was given.
public let second: Data?
}
-
-public enum PasskeyError: Error {
- case invalidPublicKey
- case invalidPrivateKey
- case invalidJWK
- case invalidSignature
- case cborEncodingFailed
- case keyGenerationFailed
- case unsupportedAlgorithm
-}
-
-// MARK: - Data Extension for Base64URL
-
-extension Data {
- func base64URLEncodedString() -> String {
- let base64 = self.base64EncodedString()
- return base64
- .replacingOccurrences(of: "+", with: "-")
- .replacingOccurrences(of: "/", with: "_")
- .replacingOccurrences(of: "=", with: "")
- }
-
- init(base64URLEncoded string: String) throws {
- var base64 = string
- .replacingOccurrences(of: "-", with: "+")
- .replacingOccurrences(of: "_", with: "/")
-
- // Add padding if needed
- let remainder = base64.count % 4
- if remainder > 0 {
- base64.append(String(repeating: "=", count: 4 - remainder))
- }
-
- guard let data = Data(base64Encoded: base64) else {
- throw PasskeyError.invalidJWK
- }
-
- self = data
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyHelper.swift b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyHelper.swift
deleted file mode 100644
index 418e23b82..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyHelper.swift
+++ /dev/null
@@ -1,75 +0,0 @@
-import Foundation
-
-/**
- * PasskeyHelper
- * -------------------------
- * Utility class for passkey-related operations, including GUID/base64url conversions.
- *
- * This is a Swift port of the reference TypeScript implementation:
- * - Reference: apps/browser-extension/src/utils/passkey/PasskeyHelper.ts
- * - Android: apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Method names, parameters, and behavior should remain consistent.
- */
-public class PasskeyHelper {
-
- /**
- * Convert GUID string to byte array
- * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → Data(16 bytes)
- */
- public static func guidToBytes(_ guid: String) throws -> Data {
- // Remove dashes
- let hex = guid.replacingOccurrences(of: "-", with: "")
-
- guard hex.count == 32 else {
- throw PasskeyHelperError.invalidGuidFormat
- }
-
- var bytes = Data()
- var index = hex.startIndex
-
- for _ in 0..<16 {
- let nextIndex = hex.index(index, offsetBy: 2)
- let byteString = String(hex[index..<nextIndex])
-
- guard let byte = UInt8(byteString, radix: 16) else {
- throw PasskeyHelperError.invalidGuidFormat
- }
-
- bytes.append(byte)
- index = nextIndex
- }
-
- return bytes
- }
-
- /**
- * Convert byte array to GUID string.
- * Example: Data(16 bytes) → "3f2504e0-4f89-11d3-9a0c-0305e82c3301"
- */
- public static func bytesToGuid(_ bytes: Data) throws -> String {
- guard bytes.count == 16 else {
- throw PasskeyHelperError.invalidByteLength
- }
-
- let hex = bytes.map { String(format: "%02x", $0) }.joined()
-
- // Insert dashes in canonical format: 8-4-4-4-12
- let parts = [
- String(hex.prefix(8)),
- String(hex.dropFirst(8).prefix(4)),
- String(hex.dropFirst(12).prefix(4)),
- String(hex.dropFirst(16).prefix(4)),
- String(hex.dropFirst(20))
- ]
-
- return parts.joined(separator: "-")
- }
-
-}
-
-public enum PasskeyHelperError: Error {
- case invalidGuidFormat
- case invalidByteLength
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
index a5d0e5a66..5158c9617 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
@@ -319,10 +319,7 @@ public final class VaultSyncEngine {
/// Open a fresh staging database in memory with the current client schema.
private func openStaging() throws {
closeStaging()
- let opened = try SqliteMemoryDatabase.withSchema(schemaSql: VaultSql.completeSchema)
- // The schema script ends by turning foreign keys on; the engine inserts rows in codec order, not FK order.
- try opened.executeBatch(sql: "PRAGMA foreign_keys = OFF")
- staging = opened
+ staging = try SqliteMemoryDatabase.withLatestSchema()
}
private func closeStaging() {
diff --git a/apps/mobile-app/ios/VaultStoreKit/Utils/FolderUtils.swift b/apps/mobile-app/ios/VaultStoreKit/Utils/FolderUtils.swift
deleted file mode 100644
index ea58d386b..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Utils/FolderUtils.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-import Foundation
-
-/// The folder path of an item, built from the flat folder list of one manifest.
-/// Other platform implementations: FolderUtils.ts (core/client), FolderUtils.kt (Android).
-public enum FolderUtils {
- /// Maximum allowed folder nesting depth (root is 0, folders at depth 4 cannot have subfolders).
- public static let maxFolderDepth = 4
-
- /// Simplified folder model for utility functions.
- public struct Folder {
- public let id: UUID
- public let name: String
- public let parentFolderId: UUID?
-
- public init(id: UUID, name: String, parentFolderId: UUID?) {
- self.id = id
- self.name = name
- self.parentFolderId = parentFolderId
- }
- }
-
- /// Get the full path of folder names from root to the specified folder.
- /// - Parameters:
- /// - folderId: The folder ID.
- /// - folders: Flat array of all folders.
- /// - Returns: Array of folder names from root to current folder, or empty array if not found.
- public static func getFolderPath(folderId: UUID?, folders: [Folder]) -> [String] {
- guard let folderId = folderId else {
- return []
- }
-
- var path: [String] = []
- var currentId: UUID? = folderId
- var iterations = 0
-
- // Build path by traversing up to root
- while let id = currentId, iterations < maxFolderDepth + 1 {
- guard let folder = folders.first(where: { $0.id == id }) else {
- break
- }
- path.insert(folder.name, at: 0) // Add to beginning of array
- currentId = folder.parentFolderId
- iterations += 1
- }
-
- return path
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift b/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift
deleted file mode 100644
index c55780e6e..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift
+++ /dev/null
@@ -1,105 +0,0 @@
-import Foundation
-import RustCoreFramework
-
-/// Wrapper for the Rust item matcher using UniFFI bindings.
-/// Used in VaultStoreKit for passkey registration to find mergeable items.
-public enum RustItemMatcher {
-
- /// Matching mode for item filtering.
- public enum MatchingMode: String {
- case `default` = "default"
- case urlExact = "urlExact"
- case urlSubdomain = "urlSubdomain"
- }
-
- /// Filter items based on rpId using the Rust core item matcher.
- /// Used during passkey registration to find existing items that can have a passkey merged into them.
- ///
- /// - Parameters:
- /// - items: List of items to filter (without passkeys)
- /// - rpId: The relying party identifier (domain) to match against
- /// - matchingMode: The matching mode to use (default: urlSubdomain)
- /// - Returns: List of item IDs that match the rpId
- public static func filterItems(
- _ items: [ItemWithCredentialInfoData],
- rpId: String,
- matchingMode: MatchingMode = .urlSubdomain
- ) -> [UUID] {
- // Early return for empty rpId or items
- if rpId.isEmpty || items.isEmpty {
- return []
- }
-
- do {
- // Convert items to the format expected by Rust
- let rustCredentials = items.map { item -> [String: Any?] in
- return [
- "id": item.itemId.uuidString.lowercased(),
- "itemName": item.serviceName as Any?,
- "itemUrls": item.urls,
- "username": item.username as Any?
- ]
- }
-
- // Prepare input JSON for Rust
- // Use https:// prefix for the rpId to match URL format
- let input: [String: Any] = [
- "credentials": rustCredentials,
- "currentUrl": "https://\(rpId)",
- "pageTitle": "",
- "matchingMode": matchingMode.rawValue
- ]
-
- let inputData = try JSONSerialization.data(withJSONObject: input, options: [])
- guard let inputJson = String(data: inputData, encoding: .utf8) else {
- print("[RustItemMatcher] Failed to create input JSON")
- return []
- }
-
- // Call Rust via UniFFI
- let outputJson = try filterCredentialsJson(inputJson: inputJson)
-
- // Parse output
- guard let outputData = outputJson.data(using: .utf8),
- let output = try JSONSerialization.jsonObject(with: outputData) as? [String: Any],
- let matchedIds = output["matchedIds"] as? [String] else {
- print("[RustItemMatcher] Failed to parse output JSON")
- return []
- }
-
- // If no matches found, return empty array
- if matchedIds.isEmpty {
- return []
- }
-
- // Convert matched IDs back to UUIDs, maintaining order
- return matchedIds.compactMap { UUID(uuidString: $0) }
-
- } catch {
- print("[RustItemMatcher] Error filtering items: \(error)")
- // Return empty array on error
- return []
- }
- }
-
- /// Filter items and return the full ItemWithCredentialInfoData objects.
- /// Convenience method that returns filtered items instead of just IDs.
- ///
- /// - Parameters:
- /// - items: List of items to filter (without passkeys)
- /// - rpId: The relying party identifier (domain) to match against
- /// - matchingMode: The matching mode to use (default: urlSubdomain)
- /// - Returns: List of items that match the rpId, in priority order
- public static func filterItemsWithData(
- _ items: [ItemWithCredentialInfoData],
- rpId: String,
- matchingMode: MatchingMode = .urlSubdomain
- ) -> [ItemWithCredentialInfoData] {
- let matchedIds = filterItems(items, rpId: rpId, matchingMode: matchingMode)
-
- // Map matched IDs back to items, maintaining Rust's priority order
- return matchedIds.compactMap { matchedId in
- items.first { $0.itemId == matchedId }
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
deleted file mode 100644
index b7f121a1f..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
+++ /dev/null
@@ -1,30 +0,0 @@
-import Foundation
-
-/// Extension to make VaultStore conform to DatabaseClient protocol.
-/// This allows VaultStore to be used with the repository pattern.
-extension VaultStore: DatabaseClient {
- /// The id of the user's personal manifest, or nil before the first pull recorded one.
- public func personalManifestId() -> String? {
- return getPersonalManifestId()
- }
-
- /// The ItemRepository instance for this VaultStore.
- public var itemRepository: ItemRepository {
- return ItemRepository(client: self)
- }
-
- /// The PasskeyRepository instance for this VaultStore.
- public var passkeyRepository: PasskeyRepository {
- return PasskeyRepository(client: self)
- }
-
- /// The TotpRepository instance for this VaultStore.
- public var totpRepository: TotpRepository {
- return TotpRepository(client: self)
- }
-
- /// The ItemStatsRepository instance for this VaultStore.
- public var itemStatsRepository: ItemStatsRepository {
- return ItemStatsRepository(client: self)
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
index 00431377d..e707e3452 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
@@ -1,173 +1,183 @@
import Foundation
+import RustCoreFramework
import VaultModels
import VaultUtils
+/// A passkey with the name and account of the item it belongs to.
+public struct PasskeyWithItem {
+ /// The passkey.
+ public let passkey: Passkey
+ /// The item name.
+ public let serviceName: String?
+ /// The item's login.username value, if any.
+ public let username: String?
+ /// The item's login.email value, if any.
+ public let email: String?
+}
+
+/// A Login item without a passkey that a new passkey could be added to.
+public struct ItemWithCredentialInfoData {
+ /// The item id.
+ public let itemId: UUID
+ /// The item name.
+ public let serviceName: String?
+ /// All login.url values of the item.
+ public let urls: [String]
+ /// The login.username value, if any.
+ public let username: String?
+ /// The login.email value, if any.
+ public let email: String?
+ /// Whether the item has a non-empty password.
+ public let hasPassword: Bool
+ /// When the item was created.
+ public let createdAt: Date
+ /// When the item was last updated.
+ public let updatedAt: Date
+ /// The manifest the item lives in.
+ public let manifestId: String
+}
+
/**
* VaultStore+Passkey
- * Extension to VaultStore for passkey operations.
- * Delegates to PasskeyRepository for database operations.
+ * Passkey reads and writes, run by the Rust core on the open vault database.
+ * Other platform implementations: VaultPasskey.kt (Android).
*/
extension VaultStore {
// MARK: - Passkey Queries (Public API)
- /**
- * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Credential UUID)
- */
+ /// Get a passkey by its WebAuthn credential ID (not the parent item id), in any manifest.
public func getPasskey(byCredentialId credentialId: Data) throws -> Passkey? {
- // Convert credentialId bytes to a UUID string for lookup
- guard let credentialIdString = try? PasskeyHelper.bytesToGuid(credentialId) else {
+ guard let credentialIdString = try? PasskeyAuthenticator.bytesToGuid(credentialId) else {
print("VaultStore+Passkey: Failed to convert credentialId bytes to UUID string")
return nil
}
- return try passkeyRepository.getById(credentialIdString)
+ return try requireDatabase().getPasskeyById(passkeyId: credentialIdString).flatMap { Self.passkey(from: $0.passkey) }
}
- /**
- * Get all passkeys for an item.
- */
+ /// Get all passkeys for an item.
public func getPasskeys(forItemId itemId: UUID, manifestId: String) throws -> [Passkey] {
- return try passkeyRepository.getByItemId(itemId.uuidString.lowercased(), manifestId: manifestId)
+ return try requireDatabase().getPasskeysForItem(itemId: itemId.uuidString.lowercased(), manifestId: manifestId).compactMap(Self.passkey(from:))
}
- /**
- * Get all passkeys for a specific relying party identifier (RP ID)
- */
- public func getPasskeys(forRpId rpId: String) throws -> [Passkey] {
- return try passkeyRepository.getByRpId(rpId)
- }
-
- /**
- * Get passkeys with item info for a specific rpId and optionally username
- * Used for finding existing passkeys that might be replaced during registration
- */
+ /// Get passkeys with item info for an rpId, narrowed to an account when a user name or handle is given.
+ /// Used for finding existing passkeys that might be replaced during registration.
public func getPasskeysWithCredentialInfo(forRpId rpId: String, userName: String? = nil, userId: Data? = nil) throws -> [PasskeyWithItem] {
- return try passkeyRepository.getWithItem(forRpId: rpId, userName: userName, userId: userId)
+ return try requireDatabase().getPasskeysForRpId(rpId: rpId, userName: userName, userHandle: userId).compactMap { row in
+ Self.passkey(from: row.passkey).map { PasskeyWithItem(passkey: $0, serviceName: row.serviceName, username: row.username, email: row.email) }
+ }
}
- /**
- * Get Items that match an rpId but don't have a passkey yet.
- * Used for finding existing credentials that could have a passkey added to them.
- * Uses the Rust credential matcher for consistent cross-platform matching logic.
- */
+ /// Get the Login items without a passkey that match an rpId, best match first, which a new passkey could be added to.
public func getItemsWithoutPasskey(forRpId rpId: String, userName: String? = nil) throws -> [ItemWithCredentialInfoData] {
- // Get all items without passkeys
- let allItems = try passkeyRepository.getAllItemsWithoutPasskey()
-
- // Use Rust item matcher for intelligent filtering
- var matchedItems = RustItemMatcher.filterItemsWithData(allItems, rpId: rpId)
-
- // Apply optional username filter
- if let userName = userName {
- matchedItems = matchedItems.filter { $0.username == userName }
+ return try requireDatabase().getItemsWithoutPasskeyForRpId(rpId: rpId, rpName: nil, userName: userName).compactMap { row in
+ guard let itemId = UUID(uuidString: row.itemId) else { return nil }
+ return ItemWithCredentialInfoData(
+ itemId: itemId,
+ serviceName: row.serviceName,
+ urls: row.urls,
+ username: row.username,
+ email: row.email,
+ hasPassword: row.hasPassword,
+ createdAt: Self.date(row.createdAtMs),
+ updatedAt: Self.date(row.updatedAtMs),
+ manifestId: row.manifestId
+ )
}
-
- return matchedItems
}
// MARK: - Passkey Storage (Public API)
- /**
- * Create an item with a passkey (for passkey registration)
- * This creates an Item record with field values and links the passkey to it
- */
+ /// Create a Login item in the personal manifest holding a new passkey (passkey registration).
@discardableResult
- public func createItemWithPasskey(
- rpId: String,
- userName: String?,
- displayName: String,
- passkey: Passkey,
- logo: Data? = nil
- ) throws -> UUID {
- let itemIdString = try passkeyRepository.createItemWithPasskey(
- rpId: rpId,
- userName: userName,
- displayName: displayName,
- passkey: passkey,
- logo: logo
- )
-
- // Return the created item ID
- guard let itemId = UUID(uuidString: itemIdString) else {
- throw VaultStoreError.databaseError("Invalid item ID returned")
+ public func createItemWithPasskey(rpId: String, userName: String?, displayName: String, passkey: Passkey, logo: Data? = nil) throws -> UUID {
+ guard let manifestId = getPersonalManifestId(), !manifestId.isEmpty else {
+ throw AppError.manifestNotRecorded
}
-
- return itemId
+ try withTransaction {
+ try requireDatabase().createItemWithPasskey(
+ manifestId: manifestId,
+ itemId: passkey.parentItemId.uuidString.lowercased(),
+ itemName: displayName,
+ url: "https://\(rpId)",
+ userName: userName,
+ passkey: try Self.newPasskey(from: passkey, displayName: passkey.displayName),
+ logo: logo
+ )
+ }
+ return passkey.parentItemId
}
- /**
- * Replace an existing passkey with a new one
- * This deletes the old passkey and creates a new one with the same item, in the same manifest
- */
+ /// Replace an existing passkey with a new one on the same item, in the same manifest.
public func replacePasskey(oldPasskeyId: UUID, manifestId: String, newPasskey: Passkey, displayName: String, logo: Data? = nil) throws {
- // Get the old passkey to find its item
- guard let oldPasskey = try passkeyRepository.getById(oldPasskeyId.uuidString.lowercased(), manifestId: manifestId) else {
- throw VaultStoreError.passkeyNotFound
+ try withTransaction {
+ _ = try requireDatabase().replacePasskey(
+ oldPasskeyId: oldPasskeyId.uuidString.lowercased(),
+ manifestId: manifestId,
+ passkey: try Self.newPasskey(from: newPasskey, displayName: displayName),
+ url: "https://\(newPasskey.rpId)",
+ logo: logo
+ )
}
+ }
- // Create the new passkey with the same item ID, in the same manifest
- let updatedPasskey = Passkey(
- id: newPasskey.id,
- parentItemId: oldPasskey.parentItemId,
- rpId: newPasskey.rpId,
- userHandle: newPasskey.userHandle,
- userName: newPasskey.userName,
- publicKey: newPasskey.publicKey,
- privateKey: newPasskey.privateKey,
- prfKey: newPasskey.prfKey,
- displayName: displayName,
- createdAt: Date(),
- updatedAt: Date(),
- isDeleted: false,
- manifestId: manifestId
- )
+ /// Add a passkey to an existing item (merge the passkey into an existing credential).
+ public func addPasskeyToExistingItem(itemId: UUID, manifestId: String, passkey: Passkey, logo: Data? = nil) throws {
+ try withTransaction {
+ try requireDatabase().addPasskeyToItem(
+ itemId: itemId.uuidString.lowercased(),
+ manifestId: manifestId,
+ passkey: try Self.newPasskey(from: passkey, displayName: passkey.displayName),
+ url: "https://\(passkey.rpId)",
+ logo: logo
+ )
+ }
+ }
+
+ // MARK: - Mapping
- // Replace the passkey (handles logo update in same transaction)
- try passkeyRepository.replace(
- oldPasskeyId: oldPasskeyId.uuidString.lowercased(),
- manifestId: manifestId,
- with: updatedPasskey,
- displayName: displayName,
- logo: logo
+ /// A stored passkey as the model the authenticator works with.
+ internal static func passkey(from row: VaultPasskey) -> Passkey? {
+ guard let id = UUID(uuidString: row.id), let parentItemId = UUID(uuidString: row.itemId) else {
+ return nil
+ }
+ return Passkey(
+ id: id,
+ parentItemId: parentItemId,
+ rpId: row.rpId,
+ userHandle: row.userHandle,
+ userName: nil,
+ publicKey: Data(row.publicKey.utf8),
+ privateKey: Data(row.privateKey.utf8),
+ prfKey: row.prfKey,
+ displayName: row.displayName,
+ createdAt: date(row.createdAtMs),
+ updatedAt: date(row.updatedAtMs),
+ isDeleted: false,
+ manifestId: row.manifestId,
+ additionalData: row.additionalData
)
}
- /**
- * Add a passkey to an existing Item (merge passkey into existing credential).
- * @param itemId The UUID of the existing Item to add the passkey to.
- * @param manifestId The manifest the item belongs to.
- * @param passkey The passkey to add.
- * @param logo Optional logo to update/add.
- */
- public func addPasskeyToExistingItem(
- itemId: UUID,
- manifestId: String,
- passkey: Passkey,
- logo: Data? = nil
- ) throws {
- // Create the passkey with the existing item ID, in that item's manifest
- let passkeyWithItemId = Passkey(
- id: passkey.id,
- parentItemId: itemId,
+ /// A passkey to write, its keys as the JWK text they are stored as.
+ private static func newPasskey(from passkey: Passkey, displayName: String) throws -> NewPasskey {
+ guard let publicKey = String(data: passkey.publicKey, encoding: .utf8), let privateKey = String(data: passkey.privateKey, encoding: .utf8) else {
+ throw VaultStoreError.databaseError("Passkey keys are not valid JWK text")
+ }
+ return NewPasskey(
+ id: passkey.id.uuidString.lowercased(),
rpId: passkey.rpId,
userHandle: passkey.userHandle,
- userName: passkey.userName,
- publicKey: passkey.publicKey,
- privateKey: passkey.privateKey,
+ publicKey: publicKey,
+ privateKey: privateKey,
prfKey: passkey.prfKey,
- displayName: passkey.displayName,
- createdAt: Date(),
- updatedAt: Date(),
- isDeleted: false,
- manifestId: manifestId
+ displayName: displayName
)
+ }
- try passkeyRepository.addPasskeyToExistingItem(
- itemId: itemId,
- manifestId: manifestId,
- passkey: passkeyWithItemId,
- logo: logo
- )
+ /// A Unix-milliseconds timestamp from the Rust core as a Date.
+ internal static func date(_ milliseconds: Int64) -> Date {
+ return Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index 7d5026a21..fc291b84a 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -3,9 +3,12 @@ import RustCoreFramework
import VaultModels
import VaultUtils
+/// A query parameter: nil, String, Int, Int64, Double, Bool, Data, SqlValue, or a base64 string behind `av-base64-to-blob:`.
+public typealias SqliteBindValue = Any?
+
/// Extension for the VaultStore class to handle query management
extension VaultStore {
- // MARK: - Core Database Operations (DatabaseClient Protocol)
+ // MARK: - Core Database Operations
/// Prefix repositories put in front of base64 text to bind it as a BLOB.
private static let blobParamPrefix = "av-base64-to-blob:"
@@ -130,32 +133,83 @@ extension VaultStore {
}
}
- // MARK: - Items (Using Repository Pattern)
+ /// Run `operation` in a transaction whose commit persists the vault and marks it dirty for `scope`.
+ internal func withTransaction<T>(scope: String = VaultMutationScope.main, _ operation: () throws -> T) throws -> T {
+ try beginTransaction()
+ do {
+ let result = try operation()
+ try commitTransaction(scope: scope)
+ return result
+ } catch {
+ try? rollbackTransaction()
+ throw error
+ }
+ }
- /// Get all active items from the database using the field-based model.
- /// Delegates to ItemRepository for the actual query logic.
+ // MARK: - Items
+
+ /// Get all active items (not deleted, trashed or archived) with their fields and folder paths, newest first.
public func getAllItems() throws -> [Item] {
- return try itemRepository.getAll()
+ return try requireDatabase().getAllActiveItems().compactMap(Self.item(from:))
}
- /// Append a URL to an existing credential's `login.url` multi-value field
- /// without disturbing existing URLs on the credential. Caller is responsible
- /// for kicking off `mutateVault(using:)` afterwards to push the change.
+ /// Append a URL to an existing credential's `login.url` values without touching its other URLs. The caller
+ /// starts `mutateVault(using:)` afterwards to push the change.
/// - Parameters:
/// - itemId: The UUID of the credential to append to
/// - manifestId: The manifest the credential belongs to
/// - url: The URL or app package identifier to add
public func appendUrl(toItemId itemId: UUID, manifestId: String, url: String) throws {
- try itemRepository.appendFieldValue(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, fieldKey: FieldKey.loginUrl, value: url)
+ try withTransaction {
+ _ = try requireDatabase().appendFieldValue(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, fieldKey: FieldKey.loginUrl, value: url)
+ }
}
- /// Record one use of an item in its ItemStats row. Runs in a transaction, so the vault is persisted and marked dirty.
+ /// Record one use of an item in its ItemStats row, in its own transaction so the vault is persisted and marked dirty.
/// - Parameters:
/// - itemId: The item that was used
/// - manifestId: The manifest the item belongs to
/// - action: What the user did with it
public func recordItemUsage(itemId: UUID, manifestId: String, action: ItemUsageAction) throws {
- try itemStatsRepository.recordUsage(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, action: action)
+ // Usage statistics live in their own data bucket, pushed without a full manifest write.
+ try withTransaction(scope: VaultDataBucketCategory.stats) {
+ _ = try requireDatabase().recordItemUse(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, action: action)
+ }
+ }
+
+ /// An item from the Rust core as the model the autofill layer works with.
+ private static func item(from row: VaultItem) -> Item? {
+ guard let id = UUID(uuidString: row.id) else { return nil }
+
+ // A built-in logo carries no bytes: it is drawn from the shared catalog, keyed by its Source.
+ let logo = row.logoKind == "builtin" ? row.logoSource.flatMap { BuiltinLogos.svg(for: $0)?.data(using: .utf8) } : row.logo
+ let fields = row.fields.map {
+ ItemField(
+ fieldKey: $0.fieldKey,
+ label: $0.label,
+ fieldType: $0.fieldType,
+ value: $0.value,
+ isHidden: $0.isHidden,
+ displayOrder: Int($0.displayOrder),
+ isCustomField: $0.isCustomField,
+ enableHistory: $0.enableHistory
+ )
+ }
+ return Item(
+ id: id,
+ manifestId: row.manifestId,
+ name: row.name,
+ itemType: row.itemType,
+ logo: logo,
+ folderId: row.folderId.flatMap { UUID(uuidString: $0) },
+ folderPath: row.folderPath.isEmpty ? nil : row.folderPath,
+ fields: fields,
+ hasPasskey: row.hasPasskey,
+ hasAttachment: row.hasAttachment,
+ hasTotp: row.hasTotp,
+ createdAt: date(row.createdAtMs),
+ updatedAt: date(row.updatedAtMs)
+ )
}
// MARK: - Autofill Credentials
@@ -192,6 +246,9 @@ extension VaultStore {
/// - Returns: Optional TotpCode if one exists
/// - Throws: Database errors
public func getFirstTotpCode(forItemId itemId: UUID, manifestId: String) throws -> TotpCode? {
- return try totpRepository.getFirstTotpCodeForItem(itemId, manifestId: manifestId)
+ guard let row = try requireDatabase().getTotpCodesForItem(itemId: itemId.uuidString.lowercased(), manifestId: manifestId).first, let id = UUID(uuidString: row.id) else {
+ return nil
+ }
+ return TotpCode(id: id, name: row.name, secretKey: row.secretKey, algorithm: row.algorithm, digits: Int(row.digits), period: Int(row.period), itemId: itemId, isDeleted: false)
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKitTests/PasskeyAuthenticatorTests.swift b/apps/mobile-app/ios/VaultStoreKitTests/PasskeyAuthenticatorTests.swift
deleted file mode 100644
index c9faf3068..000000000
--- a/apps/mobile-app/ios/VaultStoreKitTests/PasskeyAuthenticatorTests.swift
+++ /dev/null
@@ -1,182 +0,0 @@
-import XCTest
-@testable import VaultStoreKit
-
-final class PasskeyAuthenticatorTests: XCTestCase {
-
- override func setUp() {
- super.setUp()
- }
-
- override func tearDown() {
- super.tearDown()
- }
-
- /**
- * Test that PasskeyAuthenticator can successfully create a passkey
- * This validates the entire flow including key generation, CBOR encoding, and JWK export
- */
- func testCreatePasskey() throws {
- print("PasskeyAuthenticatorTests: Starting passkey creation test")
-
- // Test data
- let rpId = "example.com"
- let userName = "[email protected]"
- let userDisplayName = "Test User"
- let userId = Data("test-user-id".utf8)
- let clientDataHash = Data(repeating: 0xAB, count: 32) // Mock 32-byte hash
- let credentialId = Data(repeating: 0x12, count: 16) // Mock 16-byte credential ID
-
- print("PasskeyAuthenticatorTests: Test parameters:")
- print(" - rpId: \(rpId)")
- print(" - userName: \(userName ?? "nil")")
- print(" - userId: \(userId.base64EncodedString())")
- print(" - clientDataHash: \(clientDataHash.count) bytes")
- print(" - credentialId: \(credentialId.count) bytes")
-
- // Attempt to create the passkey
- let result: PasskeyCreationResult
- do {
- result = try PasskeyAuthenticator.createPasskey(
- credentialId: credentialId,
- clientDataHash: clientDataHash,
- rpId: rpId,
- userId: userId,
- userName: userName,
- userDisplayName: userDisplayName,
- uvPerformed: true,
- enablePrf: false
- )
- print("PasskeyAuthenticatorTests: ✅ Passkey created successfully")
- } catch {
- XCTFail("Failed to create passkey: \(error)")
- return
- }
-
- // Validate the result
- print("PasskeyAuthenticatorTests: Validating result...")
-
- // Check credential ID
- XCTAssertEqual(result.credentialId, credentialId, "Credential ID should match input")
- print(" ✅ Credential ID matches")
-
- // Check attestation object exists and has reasonable size
- XCTAssertGreaterThan(result.attestationObject.count, 50, "Attestation object should be at least 50 bytes")
- print(" ✅ Attestation object size: \(result.attestationObject.count) bytes")
-
- // Check public key JWK
- XCTAssertGreaterThan(result.publicKey.count, 0, "Public key JWK should not be empty")
- print(" ✅ Public key JWK size: \(result.publicKey.count) bytes")
-
- // Validate public key JWK structure
- if let publicKeyJson = try? JSONSerialization.jsonObject(with: result.publicKey) as? [String: Any] {
- XCTAssertEqual(publicKeyJson["kty"] as? String, "EC", "Key type should be EC")
- XCTAssertEqual(publicKeyJson["crv"] as? String, "P-256", "Curve should be P-256")
- XCTAssertNotNil(publicKeyJson["x"], "Public key should have x coordinate")
- XCTAssertNotNil(publicKeyJson["y"], "Public key should have y coordinate")
- print(" ✅ Public key JWK structure is valid")
- } else {
- XCTFail("Public key should be valid JSON")
- }
-
- // Check private key JWK
- XCTAssertGreaterThan(result.privateKey.count, 0, "Private key JWK should not be empty")
- print(" ✅ Private key JWK size: \(result.privateKey.count) bytes")
-
- // Validate private key JWK structure
- if let privateKeyJson = try? JSONSerialization.jsonObject(with: result.privateKey) as? [String: Any] {
- XCTAssertEqual(privateKeyJson["kty"] as? String, "EC", "Key type should be EC")
- XCTAssertEqual(privateKeyJson["crv"] as? String, "P-256", "Curve should be P-256")
- XCTAssertNotNil(privateKeyJson["x"], "Private key should have x coordinate")
- XCTAssertNotNil(privateKeyJson["y"], "Private key should have y coordinate")
- XCTAssertNotNil(privateKeyJson["d"], "Private key should have d value")
- print(" ✅ Private key JWK structure is valid")
- } else {
- XCTFail("Private key should be valid JSON")
- }
-
- // Check RP ID
- XCTAssertEqual(result.rpId, rpId, "RP ID should match input")
- print(" ✅ RP ID matches")
-
- // Check user ID
- XCTAssertEqual(result.userId, userId, "User ID should match input")
- print(" ✅ User ID matches")
-
- // Check user name
- XCTAssertEqual(result.userName, userName, "User name should match input")
- print(" ✅ User name matches")
-
- // Check user display name
- XCTAssertEqual(result.userDisplayName, userDisplayName, "User display name should match input")
- print(" ✅ User display name matches")
-
- // Check PRF secret (should be nil since enablePrf = false)
- XCTAssertNil(result.prfSecret, "PRF secret should be nil when not enabled")
- print(" ✅ PRF secret is nil (as expected)")
-
- print("PasskeyAuthenticatorTests: ✅ All validations passed!")
- }
-
- /**
- * Test passkey creation with PRF extension enabled
- */
- func testCreatePasskeyWithPrf() throws {
- print("PasskeyAuthenticatorTests: Starting passkey creation test with PRF")
-
- let rpId = "example.com"
- let clientDataHash = Data(repeating: 0xAB, count: 32)
- let credentialId = Data(repeating: 0x12, count: 16)
-
- let result = try PasskeyAuthenticator.createPasskey(
- credentialId: credentialId,
- clientDataHash: clientDataHash,
- rpId: rpId,
- userId: nil,
- userName: nil,
- userDisplayName: nil,
- uvPerformed: true,
- enablePrf: true
- )
-
- // Check PRF secret exists
- XCTAssertNotNil(result.prfSecret, "PRF secret should exist when enabled")
- XCTAssertEqual(result.prfSecret?.count, 32, "PRF secret should be 32 bytes")
- print(" ✅ PRF secret generated: \(result.prfSecret!.count) bytes")
-
- print("PasskeyAuthenticatorTests: ✅ PRF test passed!")
- }
-
- /**
- * Test passkey creation with minimal parameters
- */
- func testCreatePasskeyMinimal() throws {
- print("PasskeyAuthenticatorTests: Starting minimal passkey creation test")
-
- let rpId = "example.com"
- let clientDataHash = Data(repeating: 0xAB, count: 32)
- let credentialId = Data(repeating: 0x12, count: 16)
-
- let result = try PasskeyAuthenticator.createPasskey(
- credentialId: credentialId,
- clientDataHash: clientDataHash,
- rpId: rpId,
- userId: nil,
- userName: nil,
- userDisplayName: nil,
- uvPerformed: false,
- enablePrf: false
- )
-
- XCTAssertEqual(result.credentialId, credentialId)
- XCTAssertGreaterThan(result.attestationObject.count, 0)
- XCTAssertGreaterThan(result.publicKey.count, 0)
- XCTAssertGreaterThan(result.privateKey.count, 0)
- XCTAssertEqual(result.rpId, rpId)
- XCTAssertNil(result.userId)
- XCTAssertNil(result.userName)
- XCTAssertNil(result.userDisplayName)
- XCTAssertNil(result.prfSecret)
-
- print("PasskeyAuthenticatorTests: ✅ Minimal test passed!")
- }
-}
diff --git a/apps/mobile-app/ios/VaultUtils/DateHelpers.swift b/apps/mobile-app/ios/VaultUtils/DateHelpers.swift
deleted file mode 100644
index fe0e358c6..000000000
--- a/apps/mobile-app/ios/VaultUtils/DateHelpers.swift
+++ /dev/null
@@ -1,73 +0,0 @@
-import Foundation
-
-/**
- * DateHelpers
- * -------------------------
- * Centralized utility for formatting Date values consistently across the client application.
- * All dates are stored in UTC with the format: "yyyy-MM-dd HH:mm:ss.fff" (23 characters).
- * This format ensures:
- * - SQLite native support for date functions
- * - No timezone ambiguity (all dates are UTC)
- * - Consistent precision with milliseconds for accurate sorting/comparison
- * - Readable space separator instead of 'T'
- * - Lexicographic sorting works correctly
- * Other platform implementations: DateHelpers.ts (core/client), DateHelpers.kt (Android).
- */
-public class DateHelpers {
- /// Date formatter for a given pattern.
- private static func makeFormatter(_ pattern: String) -> DateFormatter {
- let formatter = DateFormatter()
- formatter.dateFormat = pattern
- formatter.locale = Locale(identifier: "en_US_POSIX")
- formatter.timeZone = TimeZone(secondsFromGMT: 0)
- return formatter
- }
-
- private static let standardFormatter = makeFormatter("yyyy-MM-dd HH:mm:ss.SSS")
- private static let withoutMillisFormatter = makeFormatter("yyyy-MM-dd HH:mm:ss")
- private static let isoFormatter: ISO8601DateFormatter = {
- let formatter = ISO8601DateFormatter()
- formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
- formatter.timeZone = TimeZone(secondsFromGMT: 0)
- return formatter
- }()
-
- /// Format a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
- public static func toStandardFormat(_ date: Date) -> String {
- return standardFormatter.string(from: date)
- }
-
- /// Format the current UTC time to the standard format string.
- public static func now() -> String {
- return toStandardFormat(Date())
- }
-
- /// Parse a date string to a Date object for use in queries.
- /// Supports multiple formats:
- /// - "yyyy-MM-dd HH:mm:ss.SSS" (standard format with milliseconds)
- /// - "yyyy-MM-dd HH:mm:ss" (standard format without milliseconds)
- /// - ISO8601 with fractional seconds and timezone
- public static func parseDateString(_ dateString: String) -> Date? {
- let cleanedDateString = dateString.trimmingCharacters(in: .whitespacesAndNewlines)
-
- // If ends with 'Z' or contains timezone, attempt ISO8601 parsing
- if cleanedDateString.contains("Z") || cleanedDateString.contains("+") || cleanedDateString.contains("-") {
- if let isoDate = isoFormatter.date(from: cleanedDateString) {
- return isoDate
- }
- }
-
- // Try parsing with milliseconds
- if let dateWithMillis = standardFormatter.date(from: cleanedDateString) {
- return dateWithMillis
- }
-
- // Try parsing without milliseconds
- if let dateWithoutMillis = withoutMillisFormatter.date(from: cleanedDateString) {
- return dateWithoutMillis
- }
-
- // If parsing still fails, return nil
- return nil
- }
-}
diff --git a/core/client/src/database/mappers/FieldMapper.ts b/core/client/src/database/mappers/FieldMapper.ts
index 4d2ab8b18..faba3bee4 100644
--- a/core/client/src/database/mappers/FieldMapper.ts
+++ b/core/client/src/database/mappers/FieldMapper.ts
@@ -40,7 +40,6 @@ export type ProcessedField = {
/**
* Mapper class for processing database field rows into ItemField objects.
* Handles both system fields (with FieldKey) and custom fields (with FieldDefinitionId).
- * Other platform implementations: FieldMapper.swift (iOS), FieldMapper.kt (Android).
*/
export class FieldMapper {
/**
diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.ts
index e305dc768..c951961f3 100644
--- a/core/client/src/database/repositories/ItemRepository.ts
+++ b/core/client/src/database/repositories/ItemRepository.ts
@@ -38,7 +38,6 @@ type StoredFieldValue = {
/**
* Repository for Item CRUD operations.
* Handles items, field values, field definitions, and field history.
- * Other platform implementations: ItemRepository.swift (iOS), ItemRepository.kt (Android), reads only.
*/
export class ItemRepository extends BaseRepository {
/**
diff --git a/core/client/src/database/repositories/PasskeyRepository.ts b/core/client/src/database/repositories/PasskeyRepository.ts
index 6f71fb513..9d926bb8e 100644
--- a/core/client/src/database/repositories/PasskeyRepository.ts
+++ b/core/client/src/database/repositories/PasskeyRepository.ts
@@ -8,7 +8,6 @@ import type { Passkey } from '@aliasvault/models/vault';
/**
* Repository for Passkey CRUD operations.
- * Other platform implementations: PasskeyRepository.swift (iOS), PasskeyRepository.kt (Android), which also write items.
*/
export class PasskeyRepository extends BaseRepository {
/**
diff --git a/core/client/src/items/FolderUtils.ts b/core/client/src/items/FolderUtils.ts
index 0828d4844..89fddce2b 100644
--- a/core/client/src/items/FolderUtils.ts
+++ b/core/client/src/items/FolderUtils.ts
@@ -6,7 +6,6 @@ import type { Folder, FolderRef } from '../database/repositories/FolderRepositor
* Maximum allowed folder nesting depth.
* Structure: Root (0) > Level 1 (1) > Level 2 (2) > Level 3 (3) > Level 4 (4)
* Folders at depth 4 cannot have subfolders.
- * Other platform implementations: FolderUtils.swift (iOS), FolderUtils.kt (Android).
*/
export const MAX_FOLDER_DEPTH = 4;
diff --git a/core/client/src/rust/WasmPasskey.ts b/core/client/src/rust/WasmPasskey.ts
new file mode 100644
index 000000000..1ca73eb76
--- /dev/null
+++ b/core/client/src/rust/WasmPasskey.ts
@@ -0,0 +1,92 @@
+/*
+ * The Rust passkey authenticator (core/rust/src/passkey) for hosts that run the core as WebAssembly. It is kept off
+ * IRustCore because only the browser extension acts as an authenticator; the mobile apps call it natively.
+ */
+import * as core from '../../wasm/aliasvault_core.js';
+
+import { rustCore } from './RustCore';
+
+/**
+ * The PRF salts of a request.
+ */
+export type PasskeyPrfInputs = {
+ first: Uint8Array;
+ second?: Uint8Array;
+};
+
+/**
+ * The PRF outputs for the requested salts.
+ */
+export type PasskeyPrfResults = {
+ first: Uint8Array;
+ second: Uint8Array | null;
+};
+
+/**
+ * A new passkey: what the relying party receives, and the keys and PRF secret the vault stores.
+ */
+export type PasskeyCreation = {
+ attestationObject: Uint8Array;
+ authenticatorData: Uint8Array;
+ publicKeyJwk: string;
+ publicKeySpki: Uint8Array;
+ privateKeyJwk: string;
+ prfSecret: Uint8Array | null;
+ prfResults: PasskeyPrfResults | null;
+};
+
+/**
+ * A signed assertion for the relying party.
+ */
+export type PasskeyAssertion = {
+ authenticatorData: Uint8Array;
+ signature: Uint8Array;
+ prfResults: PasskeyPrfResults | null;
+};
+
+/**
+ * The first algorithm (COSE id) in the relying party's order that the authenticator supports; ES256 for an empty list.
+ * @param requested - The relying party's algorithms, in its order of preference
+ * @returns The chosen algorithm
+ */
+export async function passkeyPickAlgorithm(requested: number[]): Promise<number> {
+ await rustCore().init();
+ return core.passkeyPickAlgorithm(Int32Array.from(requested));
+}
+
+/**
+ * Create a passkey. With `selfAttestationClientDataHash` the attestation is "packed" self-attestation, otherwise "none".
+ * @param options - The credential id, relying party, algorithm and requested extensions
+ * @returns The new passkey
+ */
+export async function passkeyCreate(options: {
+ credentialId: Uint8Array;
+ rpId: string;
+ algorithm: number;
+ uvPerformed: boolean;
+ enablePrf: boolean;
+ prfInputs?: PasskeyPrfInputs;
+ selfAttestationClientDataHash?: Uint8Array;
+}): Promise<PasskeyCreation> {
+ await rustCore().init();
+ const { credentialId, rpId, algorithm, uvPerformed, enablePrf, prfInputs, selfAttestationClientDataHash } = options;
+ return core.passkeyCreate(credentialId, rpId, algorithm, uvPerformed, enablePrf, prfInputs?.first, prfInputs?.second, selfAttestationClientDataHash) as PasskeyCreation;
+}
+
+/**
+ * Sign an assertion over `authenticatorData || clientDataHash` with a stored private key JWK.
+ * @param options - The relying party, client data hash, stored key and PRF request
+ * @returns The signed assertion
+ */
+export async function passkeyGetAssertion(options: {
+ rpId: string;
+ clientDataHash: Uint8Array;
+ privateKeyJwk: string;
+ uvPerformed: boolean;
+ prfInputs?: PasskeyPrfInputs;
+ prfSecret?: Uint8Array;
+}): Promise<PasskeyAssertion> {
+ await rustCore().init();
+ const { rpId, clientDataHash, privateKeyJwk, uvPerformed, prfInputs, prfSecret } = options;
+ return core.passkeyGetAssertion(rpId, clientDataHash, privateKeyJwk, uvPerformed, prfInputs?.first, prfInputs?.second, prfSecret) as PasskeyAssertion;
+}
diff --git a/core/client/src/utilities/DateHelpers.ts b/core/client/src/utilities/DateHelpers.ts
index e4713a833..8bf911e47 100644
--- a/core/client/src/utilities/DateHelpers.ts
+++ b/core/client/src/utilities/DateHelpers.ts
@@ -11,7 +11,6 @@
/**
* Formats a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.fff" (23 characters).
- * Other platform implementations: DateHelpers.swift (iOS), DateHelpers.kt (Android).
* @param date - The Date to format
* @returns Formatted date-time string in format "yyyy-MM-dd HH:mm:ss.fff"
*/
diff --git a/core/models/scripts/lib/vault-table-registry-emit.cjs b/core/models/scripts/lib/vault-table-registry-emit.cjs
index 8f5a40841..bdcb8a987 100644
--- a/core/models/scripts/lib/vault-table-registry-emit.cjs
+++ b/core/models/scripts/lib/vault-table-registry-emit.cjs
@@ -118,7 +118,7 @@ function emitRust(registry) {
//! ${TS_SOURCE_REL} by ${GENERATOR_REL}.
//! Edit the TypeScript source and run 'core/models/build.sh' to regenerate.
-use super::{BlobColumn, TableConfig};
+use super::{BlobColumn, SystemField, TableConfig};
/// All tables that need LWW merge, in registry order. Order matters: a merge inserts rows
/// in this order, so child tables must be listed after the table they reference (Items first).
@@ -160,6 +160,11 @@ pub static PERSONAL_TABLES: &[&str] = &[${registry.VAULT_PERSONAL_TABLES.map((t)
/// adding two different things) and is not derived.
pub static MULTI_VALUE_FIELD_KEYS: &[&str] = ${rustStrSlice(registry.MULTI_VALUE_FIELD_KEYS)};
+/// The system fields and their metadata, from SystemFieldRegistry, in registry order.
+pub static SYSTEM_FIELDS: &[SystemField] = &[
+${Object.values(registry.SystemFieldRegistry).map((f) => ` SystemField { key: "${f.FieldKey}", field_type: "${f.FieldType}", is_hidden: ${f.IsHidden}, is_multi_value: ${f.IsMultiValue}, enable_history: ${f.EnableHistory}, default_display_order: ${f.DefaultDisplayOrder} },`).join('\n')}
+];
+
/// System field keys whose field holds one value. A key in neither list is a field this build does
/// not know (a newer writer's), whose rows the codec leaves as it found them.
pub static SINGLE_VALUE_FIELD_KEYS: &[&str] = ${rustStrSlice(registry.SINGLE_VALUE_FIELD_KEYS)};
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lock
index 8ec53f38d..11d96f4b2 100644
--- a/core/rust/Cargo.lock
+++ b/core/rust/Cargo.lock
@@ -61,6 +61,7 @@ dependencies = [
"js-sys",
"mail-parser",
"num-bigint",
+ "p256",
"rand 0.10.3",
"rand_core 0.6.4",
"rsa",
@@ -161,6 +162,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "base16ct"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
[[package]]
name = "base64"
version = "0.22.1"
@@ -388,6 +395,18 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "crypto-bigint"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
+dependencies = [
+ "generic-array",
+ "rand_core 0.6.4",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -458,6 +477,20 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "ecdsa"
+version = "0.16.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
+dependencies = [
+ "der",
+ "digest",
+ "elliptic-curve",
+ "rfc6979",
+ "signature",
+ "spki",
+]
+
[[package]]
name = "ed25519"
version = "2.2.3"
@@ -482,6 +515,25 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "elliptic-curve"
+version = "0.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
+dependencies = [
+ "base16ct",
+ "crypto-bigint",
+ "digest",
+ "ff",
+ "generic-array",
+ "group",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "sec1",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "encoding_rs"
version = "0.8.42"
@@ -530,6 +582,16 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+[[package]]
+name = "ff"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
+dependencies = [
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "fiat-crypto"
version = "0.2.9"
@@ -599,6 +661,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
+ "zeroize",
]
[[package]]
@@ -655,6 +718,17 @@ dependencies = [
"scroll",
]
+[[package]]
+name = "group"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
+dependencies = [
+ "ff",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -915,6 +989,18 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+[[package]]
+name = "p256"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
+dependencies = [
+ "ecdsa",
+ "elliptic-curve",
+ "primeorder",
+ "sha2",
+]
+
[[package]]
name = "password-hash"
version = "0.5.0"
@@ -1001,6 +1087,15 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "primeorder"
+version = "0.13.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
+dependencies = [
+ "elliptic-curve",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1071,6 +1166,16 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+[[package]]
+name = "rfc6979"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
+dependencies = [
+ "hmac",
+ "subtle",
+]
+
[[package]]
name = "rsa"
version = "0.9.10"
@@ -1085,6 +1190,7 @@ dependencies = [
"pkcs1",
"pkcs8",
"rand_core 0.6.4",
+ "sha2",
"signature",
"spki",
"subtle",
@@ -1176,6 +1282,20 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "sec1"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
+dependencies = [
+ "base16ct",
+ "der",
+ "generic-array",
+ "pkcs8",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "semver"
version = "1.0.28"
diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.toml
index 36acd12ff..d174b807e 100644
--- a/core/rust/Cargo.toml
+++ b/core/rust/Cargo.toml
@@ -60,7 +60,9 @@ sha1 = "0.10"
# AES-256-GCM (vault blobs, key wrapping) and RSA-OAEP-SHA256 (manifest key grants)
aes-gcm = "0.10"
-rsa = "0.9"
+rsa = { version = "0.9", features = ["sha2"] }
+# ECDSA P-256 (ES256 passkeys)
+p256 = { version = "0.13", default-features = false, features = ["alloc", "ecdsa", "pkcs8", "std"] }
rand_core06 = { package = "rand_core", version = "0.6", features = ["getrandom"] }
# Wipes key material from memory on drop
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 83f112470..a7d27c7a7 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -8,6 +8,7 @@ use crate::crypto::srp::{SrpEphemeral, SrpError, SrpSession};
use crate::common::error::{json_call, VaultError};
use crate::sqlite_host::{MemoryDatabase, SqlResult, SqlValue};
use crate::vault_codec::{self, CanonicalizeInput};
+use crate::vault_items;
/// Get the list of table names that take part in a vault sync.
#[uniffi::export]
@@ -375,10 +376,10 @@ impl SqliteMemoryDatabase {
Ok(std::sync::Arc::new(Self { inner: MemoryDatabase::from_bytes(&bytes)? }))
}
- /// Open an empty database and run a schema script on it.
+ /// Open an empty database on the latest vault schema, foreign keys off.
#[uniffi::constructor]
- pub fn with_schema(schema_sql: String) -> Result<std::sync::Arc<Self>, VaultError> {
- Ok(std::sync::Arc::new(Self { inner: MemoryDatabase::with_schema(&schema_sql)? }))
+ pub fn with_latest_schema() -> Result<std::sync::Arc<Self>, VaultError> {
+ Ok(std::sync::Arc::new(Self { inner: MemoryDatabase::with_latest_schema()? }))
}
/// Run a SQL script without parameters.
@@ -414,3 +415,127 @@ impl SqliteMemoryDatabase {
}
}
+
+/// Item, passkey and usage-statistics operations on the open vault. Writes open no transaction of their own:
+/// the host wraps each call in the transaction whose commit persists the vault.
+#[uniffi::export]
+impl SqliteMemoryDatabase {
+ /// Every active item (not deleted, trashed or archived) with its fields and folder path, newest first.
+ pub fn get_all_active_items(&self) -> Result<Vec<vault_items::VaultItem>, VaultError> {
+ self.inner.with_connection(vault_items::get_all_active_items)
+ }
+
+ /// The live TOTP codes of one item.
+ pub fn get_totp_codes_for_item(&self, item_id: String, manifest_id: String) -> Result<Vec<vault_items::VaultTotpCode>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_totp_codes_for_item(conn, &item_id, &manifest_id))
+ }
+
+ /// Append one value to a system field of an item and return the rows inserted.
+ pub fn append_field_value(&self, item_id: String, manifest_id: String, field_key: String, value: String) -> Result<u64, VaultError> {
+ self.inner.with_connection(|conn| vault_items::append_field_value(conn, &item_id, &manifest_id, &field_key, &value))
+ }
+
+ /// The passkey with this credential id in any manifest.
+ pub fn get_passkey_by_id(&self, passkey_id: String) -> Result<Option<vault_items::VaultPasskeyWithItem>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_passkey_by_id(conn, &passkey_id))
+ }
+
+ /// The passkey with this id inside one manifest.
+ pub fn get_passkey_in_manifest(&self, passkey_id: String, manifest_id: String) -> Result<Option<vault_items::VaultPasskeyWithItem>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_passkey_in_manifest(conn, &passkey_id, &manifest_id))
+ }
+
+ /// The passkeys of one item, newest first.
+ pub fn get_passkeys_for_item(&self, item_id: String, manifest_id: String) -> Result<Vec<vault_items::VaultPasskey>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_passkeys_for_item(conn, &item_id, &manifest_id))
+ }
+
+ /// The passkeys for a relying party, narrowed to an account when a user name or handle is given.
+ pub fn get_passkeys_for_rp_id(&self, rp_id: String, user_name: Option<String>, user_handle: Option<Vec<u8>>) -> Result<Vec<vault_items::VaultPasskeyWithItem>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_passkeys_for_rp_id(conn, &rp_id, user_name.as_deref(), user_handle.as_deref()))
+ }
+
+ /// Every passkey whose item is live.
+ pub fn get_all_passkeys_with_items(&self) -> Result<Vec<vault_items::VaultPasskeyWithItem>, VaultError> {
+ self.inner.with_connection(vault_items::get_all_passkeys_with_items)
+ }
+
+ /// The Login items without a passkey that match a relying party, best match first.
+ pub fn get_items_without_passkey_for_rp_id(&self, rp_id: String, rp_name: Option<String>, user_name: Option<String>) -> Result<Vec<vault_items::PasskeyMergeCandidate>, VaultError> {
+ self.inner.with_connection(|conn| vault_items::get_items_without_passkey_for_rp_id(conn, &rp_id, rp_name.as_deref(), user_name.as_deref()))
+ }
+
+ /// Create a Login item in a manifest that holds a new passkey, with its URL, username and favicon.
+ #[allow(clippy::too_many_arguments)]
+ pub fn create_item_with_passkey(
+ &self,
+ manifest_id: String,
+ item_id: String,
+ item_name: String,
+ url: String,
+ user_name: Option<String>,
+ passkey: vault_items::NewPasskey,
+ logo: Option<Vec<u8>>,
+ ) -> Result<(), VaultError> {
+ self.inner.with_connection(|conn| vault_items::create_item_with_passkey(conn, &manifest_id, &item_id, &item_name, &url, user_name.as_deref(), &passkey, logo.as_deref()))
+ }
+
+ /// Add a new passkey to an existing item, refreshing its favicon for `url`.
+ pub fn add_passkey_to_item(&self, item_id: String, manifest_id: String, passkey: vault_items::NewPasskey, url: String, logo: Option<Vec<u8>>) -> Result<(), VaultError> {
+ self.inner.with_connection(|conn| vault_items::add_passkey_to_item(conn, &item_id, &manifest_id, &passkey, &url, logo.as_deref()))
+ }
+
+ /// Replace a passkey with a new one on the same item and return the item id.
+ pub fn replace_passkey(&self, old_passkey_id: String, manifest_id: String, passkey: vault_items::NewPasskey, url: String, logo: Option<Vec<u8>>) -> Result<String, VaultError> {
+ self.inner.with_connection(|conn| vault_items::replace_passkey(conn, &old_passkey_id, &manifest_id, &passkey, &url, logo.as_deref()))
+ }
+
+ /// Record one use of an item; false when the item does not exist.
+ pub fn record_item_use(&self, item_id: String, manifest_id: String, action: vault_items::ItemUsageAction) -> Result<bool, VaultError> {
+ self.inner.with_connection(|conn| vault_items::record_item_use(conn, &item_id, &manifest_id, action))
+ }
+}
+
+/// The first passkey algorithm (COSE id) in the relying party's order that the authenticator supports; ES256 for an empty list.
+#[uniffi::export]
+pub fn passkey_pick_algorithm(requested: Vec<i64>) -> Result<i64, VaultError> {
+ crate::passkey::pick_algorithm(&requested)
+}
+
+/// Create a passkey: a fresh key pair, the "none" attestation object, and a PRF secret when `enable_prf` is set.
+#[uniffi::export]
+pub fn passkey_create(
+ credential_id: Vec<u8>,
+ rp_id: String,
+ algorithm: i64,
+ uv_performed: bool,
+ enable_prf: bool,
+ prf_inputs: Option<crate::passkey::PasskeyPrfInputs>,
+) -> Result<crate::passkey::PasskeyCreation, VaultError> {
+ crate::passkey::create_passkey(&credential_id, &rp_id, algorithm, uv_performed, enable_prf, prf_inputs.as_ref(), None)
+}
+
+/// Sign a passkey assertion with a stored private key JWK.
+#[uniffi::export]
+pub fn passkey_get_assertion(
+ rp_id: String,
+ client_data_hash: Vec<u8>,
+ private_key_jwk: String,
+ uv_performed: bool,
+ prf_inputs: Option<crate::passkey::PasskeyPrfInputs>,
+ prf_secret: Option<Vec<u8>>,
+) -> Result<crate::passkey::PasskeyAssertion, VaultError> {
+ crate::passkey::get_assertion(&rp_id, &client_data_hash, &private_key_jwk, uv_performed, prf_inputs.as_ref(), prf_secret.as_deref())
+}
+
+/// The 16 bytes of a passkey credential id from its GUID text.
+#[uniffi::export]
+pub fn passkey_guid_to_bytes(guid: String) -> Result<Vec<u8>, VaultError> {
+ crate::passkey::guid_to_bytes(&guid)
+}
+
+/// The lowercase GUID text of a 16-byte passkey credential id.
+#[uniffi::export]
+pub fn passkey_bytes_to_guid(bytes: Vec<u8>) -> Result<String, VaultError> {
+ crate::passkey::bytes_to_guid(&bytes)
+}
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index eadf4c024..1d99a3434 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -478,3 +478,74 @@ mod sqlite_js {
rows.into()
}
}
+
+/// Passkey authenticator bindings for the browser extension. Results are plain objects with Uint8Array bytes.
+mod passkey_js {
+ use js_sys::{Object, Reflect, Uint8Array};
+ use wasm_bindgen::prelude::*;
+
+ use super::js_err;
+ use crate::passkey::{self, PasskeyPrfInputs, PasskeyPrfResults};
+
+ /// The first algorithm (COSE id) in the relying party's order that the authenticator supports; ES256 for an empty list.
+ #[wasm_bindgen(js_name = passkeyPickAlgorithm)]
+ pub fn pick_algorithm(requested: Vec<i32>) -> Result<i32, JsValue> {
+ let requested: Vec<i64> = requested.into_iter().map(i64::from).collect();
+ passkey::pick_algorithm(&requested).map(|alg| alg as i32).map_err(js_err)
+ }
+
+ /// Create a passkey: `{ attestationObject, authenticatorData, publicKeyJwk, publicKeySpki, privateKeyJwk, prfSecret, prfResults }`.
+ /// With `selfAttestationClientDataHash` the attestation is "packed" self-attestation, otherwise "none".
+ #[wasm_bindgen(js_name = passkeyCreate)]
+ #[allow(clippy::too_many_arguments)]
+ pub fn create(
+ credential_id: &[u8],
+ rp_id: &str,
+ algorithm: i32,
+ uv_performed: bool,
+ enable_prf: bool,
+ prf_first: Option<Vec<u8>>,
+ prf_second: Option<Vec<u8>>,
+ self_attestation_client_data_hash: Option<Vec<u8>>,
+ ) -> Result<JsValue, JsValue> {
+ let inputs = PasskeyPrfInputs { first: prf_first, second: prf_second };
+ let created = passkey::create_passkey(credential_id, rp_id, i64::from(algorithm), uv_performed, enable_prf, Some(&inputs), self_attestation_client_data_hash.as_deref()).map_err(js_err)?;
+ let object = Object::new();
+ set(&object, "attestationObject", bytes(&created.attestation_object));
+ set(&object, "authenticatorData", bytes(&created.authenticator_data));
+ set(&object, "publicKeyJwk", JsValue::from_str(&created.public_key_jwk));
+ set(&object, "publicKeySpki", bytes(&created.public_key_spki));
+ set(&object, "privateKeyJwk", JsValue::from_str(&created.private_key_jwk));
+ set(&object, "prfSecret", created.prf_secret.as_deref().map_or(JsValue::NULL, bytes));
+ set(&object, "prfResults", prf_results(created.prf_results.as_ref()));
+ Ok(object.into())
+ }
+
+ /// Sign an assertion: `{ authenticatorData, signature, prfResults }`.
+ #[wasm_bindgen(js_name = passkeyGetAssertion)]
+ pub fn get_assertion(rp_id: &str, client_data_hash: &[u8], private_key_jwk: &str, uv_performed: bool, prf_first: Option<Vec<u8>>, prf_second: Option<Vec<u8>>, prf_secret: Option<Vec<u8>>) -> Result<JsValue, JsValue> {
+ let inputs = PasskeyPrfInputs { first: prf_first, second: prf_second };
+ let assertion = passkey::get_assertion(rp_id, client_data_hash, private_key_jwk, uv_performed, Some(&inputs), prf_secret.as_deref()).map_err(js_err)?;
+ let object = Object::new();
+ set(&object, "authenticatorData", bytes(&assertion.authenticator_data));
+ set(&object, "signature", bytes(&assertion.signature));
+ set(&object, "prfResults", prf_results(assertion.prf_results.as_ref()));
+ Ok(object.into())
+ }
+
+ fn prf_results(results: Option<&PasskeyPrfResults>) -> JsValue {
+ let Some(results) = results else { return JsValue::NULL };
+ let object = Object::new();
+ set(&object, "first", bytes(&results.first));
+ set(&object, "second", results.second.as_deref().map_or(JsValue::NULL, bytes));
+ object.into()
+ }
+
+ fn bytes(value: &[u8]) -> JsValue {
+ Uint8Array::from(value).into()
+ }
+
+ fn set(object: &Object, key: &str, value: JsValue) {
+ let _ = Reflect::set(object, &JsValue::from_str(key), &value);
+ }
+}
diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rs
index 79c1aea86..86a082f1f 100644
--- a/core/rust/src/crypto/rsa_oaep.rs
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -26,11 +26,14 @@ impl fmt::Debug for RsaKeyPair {
}
}
-/// The JWK fields WebCrypto emits for an RSA-OAEP-256 key. Optional members are absent on a public key.
+/// The JWK fields WebCrypto emits for an RSA-OAEP-256 key.
#[derive(Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
struct RsaJwk {
+ #[serde(default)]
key_ops: Vec<String>,
+ #[serde(default)]
ext: bool,
+ #[serde(default)]
alg: String,
kty: String,
n: String,
@@ -110,7 +113,7 @@ fn public_from_jwk(jwk: &str) -> VaultResult<RsaPublicKey> {
RsaPublicKey::new(field(&parsed.n)?, field(&parsed.e)?).map_err(|e| VaultError::General(format!("Invalid RSA public key: {}", e)))
}
-fn private_from_jwk(jwk: &str) -> VaultResult<RsaPrivateKey> {
+pub(crate) fn private_from_jwk(jwk: &str) -> VaultResult<RsaPrivateKey> {
let parsed = parse_jwk(jwk)?;
let d = parsed.d.as_deref().ok_or_else(|| VaultError::General("JWK is not a private key".to_string()))?;
let p = parsed.p.as_deref().ok_or_else(|| VaultError::General("JWK private key is missing p".to_string()))?;
diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rs
index cf359be54..17574c963 100644
--- a/core/rust/src/lib.rs
+++ b/core/rust/src/lib.rs
@@ -31,6 +31,8 @@ pub mod identity_generator;
pub mod crypto;
pub mod vault_sync;
pub mod sqlite_host;
+pub mod vault_items;
+pub mod passkey;
pub use common::error::VaultError;
diff --git a/core/rust/src/passkey/cbor.rs b/core/rust/src/passkey/cbor.rs
new file mode 100644
index 000000000..b96aa41d9
--- /dev/null
+++ b/core/rust/src/passkey/cbor.rs
@@ -0,0 +1,58 @@
+//! CBOR encodings the authenticator emits (RFC 8949): definite-length maps, small integers, text and byte strings.
+
+/// The head of a data item: major type plus its argument, in the shortest form.
+fn head(major: u8, argument: u64) -> Vec<u8> {
+ let major = major << 5;
+ match argument {
+ 0..=23 => vec![major | argument as u8],
+ 24..=0xff => vec![major | 24, argument as u8],
+ 0x100..=0xffff => {
+ let mut out = vec![major | 25];
+ out.extend_from_slice(&(argument as u16).to_be_bytes());
+ out
+ }
+ 0x1_0000..=0xffff_ffff => {
+ let mut out = vec![major | 26];
+ out.extend_from_slice(&(argument as u32).to_be_bytes());
+ out
+ }
+ _ => {
+ let mut out = vec![major | 27];
+ out.extend_from_slice(&argument.to_be_bytes());
+ out
+ }
+ }
+}
+
+/// An integer.
+pub(super) fn int(value: i64) -> Vec<u8> {
+ if value >= 0 {
+ head(0, value as u64)
+ } else {
+ head(1, (-1 - value) as u64)
+ }
+}
+
+/// A byte string.
+pub(super) fn bytes(value: &[u8]) -> Vec<u8> {
+ let mut out = head(2, value.len() as u64);
+ out.extend_from_slice(value);
+ out
+}
+
+/// A text string.
+pub(super) fn text(value: &str) -> Vec<u8> {
+ let mut out = head(3, value.len() as u64);
+ out.extend_from_slice(value.as_bytes());
+ out
+}
+
+/// A map of already-encoded keys and values, in the given order.
+pub(super) fn map(entries: &[(Vec<u8>, Vec<u8>)]) -> Vec<u8> {
+ let mut out = head(5, entries.len() as u64);
+ for (key, value) in entries {
+ out.extend_from_slice(key);
+ out.extend_from_slice(value);
+ }
+ out
+}
diff --git a/core/rust/src/passkey/keys.rs b/core/rust/src/passkey/keys.rs
new file mode 100644
index 000000000..c96f708ec
--- /dev/null
+++ b/core/rust/src/passkey/keys.rs
@@ -0,0 +1,151 @@
+//! Passkey key pairs: generation, the JWK text they are stored as, their COSE public key, and signing.
+
+use p256::ecdsa::signature::Signer;
+use p256::ecdsa::{Signature, SigningKey};
+use p256::pkcs8::EncodePublicKey;
+use rsa::traits::{PrivateKeyParts, PublicKeyParts};
+use rsa::{BigUint, Pkcs1v15Sign, RsaPrivateKey};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
+
+use super::cbor;
+use super::{ALG_ES256, ALG_RS256};
+use crate::common::encoding::{base64url_decode, base64url_encode};
+use crate::common::error::{VaultError, VaultResult};
+use crate::crypto::rsa_oaep::private_from_jwk;
+
+const RSA_MODULUS_BITS: usize = 2048;
+
+/// A new key pair: its JWKs and its COSE public key.
+pub(super) struct GeneratedKey {
+ pub public_key_jwk: String,
+ /// The public key as DER SubjectPublicKeyInfo.
+ pub public_key_spki: Vec<u8>,
+ pub private_key_jwk: String,
+ pub cose_public_key: Vec<u8>,
+}
+
+/// The JWK of a passkey key, EC or RSA. Unknown members (WebCrypto's `alg`, `ext`, `key_ops`) are ignored on read.
+#[derive(Default, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
+struct PasskeyJwk {
+ #[serde(default)]
+ kty: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ crv: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ x: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ y: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ n: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ e: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ d: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ p: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ q: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dp: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dq: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ qi: Option<String>,
+}
+
+/// Generate a key pair for a COSE algorithm the authenticator supports.
+pub(super) fn generate(algorithm: i64) -> VaultResult<GeneratedKey> {
+ match algorithm {
+ ALG_ES256 => generate_es256(),
+ ALG_RS256 => generate_rs256(),
+ other => Err(VaultError::General(format!("Unsupported passkey algorithm {other}"))),
+ }
+}
+
+/// Sign `data` with a stored private key: a DER ECDSA signature for an EC key, a PKCS#1 v1.5 signature for an RSA key.
+pub(super) fn sign(private_key_jwk: &str, data: &[u8]) -> VaultResult<Vec<u8>> {
+ let jwk: PasskeyJwk = serde_json::from_str(private_key_jwk).map_err(|e| VaultError::General(format!("Invalid passkey JWK: {e}")))?;
+ match jwk.kty.as_str() {
+ "RSA" => {
+ let key = private_from_jwk(private_key_jwk)?;
+ let digest = Sha256::digest(data);
+ key.sign(Pkcs1v15Sign::new::<Sha256>(), &digest).map_err(|e| VaultError::General(format!("RS256 signing failed: {e}")))
+ }
+ // A JWK without kty is an EC key, as the authenticators have always read it.
+ "EC" | "" => {
+ let d = jwk.d.as_deref().ok_or_else(|| VaultError::General("Passkey JWK has no private key".to_string()))?;
+ let key = signing_key_from_scalar(&Zeroizing::new(base64url_decode(d)?))?;
+ let signature: Signature = key.sign(data);
+ Ok(signature.to_der().as_bytes().to_vec())
+ }
+ other => Err(VaultError::General(format!("Unsupported passkey key type \"{other}\""))),
+ }
+}
+
+fn generate_es256() -> VaultResult<GeneratedKey> {
+ let key = SigningKey::random(&mut rand_core06::OsRng);
+ let point = key.verifying_key().to_encoded_point(false);
+ let (x, y) = (point.x().ok_or_else(invalid_point)?.to_vec(), point.y().ok_or_else(invalid_point)?.to_vec());
+ let d = Zeroizing::new(key.to_bytes().to_vec());
+
+ let mut public = PasskeyJwk::default();
+ public.kty = "EC".into();
+ public.crv = Some("P-256".into());
+ public.x = Some(base64url_encode(&x));
+ public.y = Some(base64url_encode(&y));
+ let mut private = public.clone();
+ private.d = Some(base64url_encode(&d));
+
+ // COSE_Key EC2 (RFC 9053): {1: 2 (kty EC2), 3: -7 (alg ES256), -1: 1 (crv P-256), -2: x, -3: y}
+ let cose_public_key = cbor::map(&[(cbor::int(1), cbor::int(2)), (cbor::int(3), cbor::int(ALG_ES256)), (cbor::int(-1), cbor::int(1)), (cbor::int(-2), cbor::bytes(&x)), (cbor::int(-3), cbor::bytes(&y))]);
+ let public_key_spki = p256::PublicKey::from(key.verifying_key()).to_public_key_der().map_err(|e| VaultError::General(format!("P-256 SPKI encoding failed: {e}")))?.into_vec();
+ Ok(GeneratedKey { public_key_jwk: to_json(&public)?, public_key_spki, private_key_jwk: to_json(&private)?, cose_public_key })
+}
+
+fn generate_rs256() -> VaultResult<GeneratedKey> {
+ let key = RsaPrivateKey::new(&mut rand_core06::OsRng, RSA_MODULUS_BITS).map_err(|e| VaultError::General(format!("RSA key generation failed: {e}")))?;
+ let primes = key.primes();
+ let qinv = key.qinv().and_then(|qinv| qinv.to_biguint()).ok_or_else(|| VaultError::General("RSA key has no CRT coefficient".to_string()))?;
+ let (n, e) = (key.n().to_bytes_be(), key.e().to_bytes_be());
+
+ let mut public = PasskeyJwk::default();
+ public.kty = "RSA".into();
+ public.n = Some(base64url_encode(&n));
+ public.e = Some(base64url_encode(&e));
+ let mut private = public.clone();
+ private.d = Some(encode(key.d()));
+ private.p = Some(encode(&primes[0]));
+ private.q = Some(encode(&primes[1]));
+ private.dp = key.dp().map(encode);
+ private.dq = key.dq().map(encode);
+ private.qi = Some(encode(&qinv));
+
+ // COSE_Key RSA (RFC 8230): {1: 3 (kty RSA), 3: -257 (alg RS256), -1: n, -2: e}
+ let cose_public_key = cbor::map(&[(cbor::int(1), cbor::int(3)), (cbor::int(3), cbor::int(ALG_RS256)), (cbor::int(-1), cbor::bytes(&n)), (cbor::int(-2), cbor::bytes(&e))]);
+ let public_key_spki = key.to_public_key().to_public_key_der().map_err(|e| VaultError::General(format!("RSA SPKI encoding failed: {e}")))?.into_vec();
+ Ok(GeneratedKey { public_key_jwk: to_json(&public)?, public_key_spki, private_key_jwk: to_json(&private)?, cose_public_key })
+}
+
+/// The P-256 signing key of a private scalar, left-padded to 32 bytes: some stored JWKs dropped leading zero bytes.
+fn signing_key_from_scalar(d: &[u8]) -> VaultResult<SigningKey> {
+ if d.len() > 32 {
+ return Err(VaultError::General("Invalid P-256 private key".to_string()));
+ }
+ let mut padded = Zeroizing::new([0u8; 32]);
+ padded[32 - d.len()..].copy_from_slice(d);
+ SigningKey::from_bytes(padded.as_slice().into()).map_err(|_| VaultError::General("Invalid P-256 private key".to_string()))
+}
+
+fn encode(value: &BigUint) -> String {
+ base64url_encode(&Zeroizing::new(value.to_bytes_be()))
+}
+
+fn to_json(jwk: &PasskeyJwk) -> VaultResult<String> {
+ serde_json::to_string(jwk).map_err(VaultError::from)
+}
+
+fn invalid_point() -> VaultError {
+ VaultError::General("Invalid P-256 public key".to_string())
+}
diff --git a/core/rust/src/passkey/mod.rs b/core/rust/src/passkey/mod.rs
new file mode 100644
index 000000000..13375c82f
--- /dev/null
+++ b/core/rust/src/passkey/mod.rs
@@ -0,0 +1,170 @@
+//! The WebAuthn authenticator for key generation, authenticator data, the attestation
+//! object, assertion signatures and the PRF extension.
+
+mod cbor;
+mod keys;
+
+#[cfg(test)]
+mod tests;
+
+use hmac::{Hmac, Mac};
+use sha2::{Digest, Sha256};
+
+use crate::common::encoding::format_uuid;
+use crate::common::error::{VaultError, VaultResult};
+
+/// COSE algorithm identifier of ES256 (ECDSA P-256 with SHA-256).
+pub const ALG_ES256: i64 = -7;
+
+/// COSE algorithm identifier of RS256 (RSASSA-PKCS1-v1.5 with SHA-256).
+pub const ALG_RS256: i64 = -257;
+
+/// The algorithms this authenticator supports, in its own order of preference.
+const SUPPORTED_ALGORITHMS: [i64; 2] = [ALG_ES256, ALG_RS256];
+
+/// AliasVault's AAGUID: a11a5faa-9f32-4b8c-8c5d-2f7d13e8c942.
+const AAGUID: [u8; 16] = [0xa1, 0x1a, 0x5f, 0xaa, 0x9f, 0x32, 0x4b, 0x8c, 0x8c, 0x5d, 0x2f, 0x7d, 0x13, 0xe8, 0xc9, 0x42];
+
+const FLAG_UP: u8 = 0x01;
+const FLAG_UV: u8 = 0x04;
+const FLAG_BE: u8 = 0x08;
+const FLAG_BS: u8 = 0x10;
+const FLAG_AT: u8 = 0x40;
+
+/// The salts of a PRF extension request.
+#[derive(Debug, Clone, Default, PartialEq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+pub struct PasskeyPrfInputs {
+ pub first: Option<Vec<u8>>,
+ pub second: Option<Vec<u8>>,
+}
+
+/// The PRF outputs for the requested salts.
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+pub struct PasskeyPrfResults {
+ pub first: Vec<u8>,
+ pub second: Option<Vec<u8>>,
+}
+
+/// A new passkey: what the relying party receives, and the keys and PRF secret the vault stores.
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+pub struct PasskeyCreation {
+ pub attestation_object: Vec<u8>,
+ pub authenticator_data: Vec<u8>,
+ pub public_key_jwk: String,
+ /// The public key as DER SubjectPublicKeyInfo.
+ pub public_key_spki: Vec<u8>,
+ pub private_key_jwk: String,
+ pub prf_secret: Option<Vec<u8>>,
+ pub prf_results: Option<PasskeyPrfResults>,
+}
+
+/// A signed assertion for the relying party.
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+pub struct PasskeyAssertion {
+ pub authenticator_data: Vec<u8>,
+ pub signature: Vec<u8>,
+ pub prf_results: Option<PasskeyPrfResults>,
+}
+
+/// The first algorithm in the relying party's preference order that this authenticator supports; ES256 when it lists none.
+pub fn pick_algorithm(requested: &[i64]) -> VaultResult<i64> {
+ if requested.is_empty() {
+ return Ok(ALG_ES256);
+ }
+ requested.iter().copied().find(|alg| SUPPORTED_ALGORITHMS.contains(alg)).ok_or_else(|| VaultError::General("No supported algorithm (ES256, RS256) in pubKeyCredParams".to_string()))
+}
+
+/// Create a passkey for `rp_id`: a fresh key pair, the attestation object, and a PRF secret when `enable_prf` is set.
+/// With `self_attestation_client_data_hash` the attestation is "packed" self-attestation over that hash, otherwise "none".
+pub fn create_passkey(
+ credential_id: &[u8],
+ rp_id: &str,
+ algorithm: i64,
+ uv_performed: bool,
+ enable_prf: bool,
+ prf_inputs: Option<&PasskeyPrfInputs>,
+ self_attestation_client_data_hash: Option<&[u8]>,
+) -> VaultResult<PasskeyCreation> {
+ let credential_id_length = u16::try_from(credential_id.len()).map_err(|_| VaultError::General("Credential id is too long".to_string()))?;
+ let key = keys::generate(algorithm)?;
+
+ let mut authenticator_data = authenticator_data(rp_id, FLAG_AT, uv_performed);
+ authenticator_data.extend_from_slice(&AAGUID);
+ authenticator_data.extend_from_slice(&credential_id_length.to_be_bytes());
+ authenticator_data.extend_from_slice(credential_id);
+ authenticator_data.extend_from_slice(&key.cose_public_key);
+
+ let (fmt, statement) = match self_attestation_client_data_hash {
+ Some(client_data_hash) => {
+ let signature = keys::sign(&key.private_key_jwk, &[authenticator_data.as_slice(), client_data_hash].concat())?;
+ ("packed", cbor::map(&[(cbor::text("alg"), cbor::int(algorithm)), (cbor::text("sig"), cbor::bytes(&signature))]))
+ }
+ None => ("none", cbor::map(&[])),
+ };
+ let attestation_object = cbor::map(&[(cbor::text("fmt"), cbor::text(fmt)), (cbor::text("attStmt"), statement), (cbor::text("authData"), cbor::bytes(&authenticator_data))]);
+
+ let prf_secret = enable_prf.then(|| {
+ let mut secret = vec![0u8; 32];
+ crate::common::rng::fill_random(&mut secret);
+ secret
+ });
+ let prf_results = prf(prf_secret.as_deref(), prf_inputs);
+
+ Ok(PasskeyCreation { attestation_object, authenticator_data, public_key_jwk: key.public_key_jwk, public_key_spki: key.public_key_spki, private_key_jwk: key.private_key_jwk, prf_secret, prf_results })
+}
+
+/// Sign an assertion for `rp_id` over `authenticator_data || client_data_hash` with a stored private key.
+pub fn get_assertion(rp_id: &str, client_data_hash: &[u8], private_key_jwk: &str, uv_performed: bool, prf_inputs: Option<&PasskeyPrfInputs>, prf_secret: Option<&[u8]>) -> VaultResult<PasskeyAssertion> {
+ let authenticator_data = authenticator_data(rp_id, 0, uv_performed);
+ let mut signed = authenticator_data.clone();
+ signed.extend_from_slice(client_data_hash);
+ let signature = keys::sign(private_key_jwk, &signed)?;
+ Ok(PasskeyAssertion { authenticator_data, signature, prf_results: prf(prf_secret, prf_inputs) })
+}
+
+/// The 16 bytes of a credential id from its GUID text.
+pub fn guid_to_bytes(guid: &str) -> VaultResult<Vec<u8>> {
+ let hex: String = guid.chars().filter(|c| *c != '-').collect();
+ match crate::common::encoding::hex_decode(&hex) {
+ Some(bytes) if bytes.len() == 16 => Ok(bytes),
+ _ => Err(VaultError::General(format!("Invalid GUID \"{guid}\""))),
+ }
+}
+
+/// The lowercase GUID text of a 16-byte credential id.
+pub fn bytes_to_guid(bytes: &[u8]) -> VaultResult<String> {
+ let bytes: [u8; 16] = bytes.try_into().map_err(|_| VaultError::General(format!("A credential id GUID is 16 bytes, not {}", bytes.len())))?;
+ Ok(format_uuid(&bytes))
+}
+
+/// The authenticator data header: SHA-256(rpId), flags, and a zero sign count.
+fn authenticator_data(rp_id: &str, extra_flags: u8, uv_performed: bool) -> Vec<u8> {
+ let mut flags = FLAG_UP | FLAG_BE | FLAG_BS | extra_flags;
+ if uv_performed {
+ flags |= FLAG_UV;
+ }
+ let mut data = Sha256::digest(rp_id.as_bytes()).to_vec();
+ data.push(flags);
+ data.extend_from_slice(&[0, 0, 0, 0]);
+ data
+}
+
+/// The PRF outputs for the requested salts, or None without both a secret and a first salt.
+fn prf(secret: Option<&[u8]>, inputs: Option<&PasskeyPrfInputs>) -> Option<PasskeyPrfResults> {
+ let (secret, inputs) = (secret?, inputs?);
+ Some(PasskeyPrfResults { first: evaluate_prf(secret, inputs.first.as_deref()?), second: inputs.second.as_deref().map(|salt| evaluate_prf(secret, salt)) })
+}
+
+/// HMAC-SHA256(secret, SHA-256("WebAuthn PRF" || 0x00 || salt)), the WebAuthn PRF extension over hmac-secret.
+fn evaluate_prf(secret: &[u8], salt: &[u8]) -> Vec<u8> {
+ let mut hasher = Sha256::new();
+ hasher.update(b"WebAuthn PRF\0");
+ hasher.update(salt);
+ let mut mac = Hmac::<Sha256>::new_from_slice(secret).expect("HMAC takes a key of any length");
+ mac.update(&hasher.finalize());
+ mac.finalize().into_bytes().to_vec()
+}
diff --git a/core/rust/src/passkey/tests.rs b/core/rust/src/passkey/tests.rs
new file mode 100644
index 000000000..58d9b3ba1
--- /dev/null
+++ b/core/rust/src/passkey/tests.rs
@@ -0,0 +1,149 @@
+use p256::ecdsa::signature::Verifier;
+use p256::ecdsa::{Signature, VerifyingKey};
+use p256::EncodedPoint;
+use rsa::{BigUint, Pkcs1v15Sign, RsaPublicKey};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+
+use super::*;
+use crate::common::encoding::{base64url_decode, base64url_encode, hex_decode, hex_encode_lower};
+
+const CREDENTIAL_ID: [u8; 16] = [0x3f, 0x25, 0x04, 0xe0, 0x4f, 0x89, 0x11, 0xd3, 0x9a, 0x0c, 0x03, 0x05, 0xe8, 0x2c, 0x33, 0x01];
+const CLIENT_DATA_HASH: [u8; 32] = [7; 32];
+
+/// SHA-256("example.com"), computed outside this crate.
+const EXAMPLE_COM_HASH: &str = "a379a6f6eeafb9a55e378c118034e2751e682fab9f2d30ab13d2125586ce1947";
+
+fn jwk_field(jwk: &str, name: &str) -> Vec<u8> {
+ let value: Value = serde_json::from_str(jwk).unwrap();
+ base64url_decode(value[name].as_str().unwrap()).unwrap()
+}
+
+fn es256_verifying_key(public_jwk: &str) -> VerifyingKey {
+ let point = EncodedPoint::from_affine_coordinates(jwk_field(public_jwk, "x").as_slice().into(), jwk_field(public_jwk, "y").as_slice().into(), false);
+ VerifyingKey::from_encoded_point(&point).unwrap()
+}
+
+fn signed_bytes(authenticator_data: &[u8]) -> Vec<u8> {
+ [authenticator_data, &CLIENT_DATA_HASH].concat()
+}
+
+#[test]
+fn es256_registration_builds_the_attestation_object_around_the_cose_key() {
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_ES256, true, false, None, None).unwrap();
+
+ let auth = &created.authenticator_data;
+ assert_eq!(hex_encode_lower(&auth[..32]), EXAMPLE_COM_HASH);
+ assert_eq!(auth[32], 0x5d, "UP, UV, BE, BS and AT");
+ assert_eq!(&auth[33..37], &[0, 0, 0, 0]);
+ assert_eq!(&auth[37..53], &AAGUID);
+ assert_eq!(&auth[53..55], &[0, 16]);
+ assert_eq!(&auth[55..71], &CREDENTIAL_ID);
+ let cose = &auth[71..];
+ assert_eq!(&cose[..10], &[0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]);
+ assert_eq!(&cose[10..42], jwk_field(&created.public_key_jwk, "x").as_slice());
+ assert_eq!(&cose[42..45], &[0x22, 0x58, 0x20]);
+ assert_eq!(&cose[45..], jwk_field(&created.public_key_jwk, "y").as_slice());
+
+ let mut expected = hex_decode("a363666d74646e6f6e656761747453746d74a068617574684461746158").unwrap();
+ expected.push(auth.len() as u8);
+ assert_eq!(&created.attestation_object[..expected.len()], expected.as_slice());
+ assert_eq!(&created.attestation_object[expected.len()..], auth.as_slice());
+ assert!(created.prf_secret.is_none());
+}
+
+#[test]
+fn es256_assertion_verifies_against_the_registered_public_key() {
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_ES256, false, false, None, None).unwrap();
+ let assertion = get_assertion("example.com", &CLIENT_DATA_HASH, &created.private_key_jwk, false, None, None).unwrap();
+
+ assert_eq!(assertion.authenticator_data.len(), 37);
+ assert_eq!(assertion.authenticator_data[32], 0x19, "UP, BE and BS");
+ let signature = Signature::from_der(&assertion.signature).unwrap();
+ let spki_key = <VerifyingKey as p256::pkcs8::DecodePublicKey>::from_public_key_der(&created.public_key_spki).unwrap();
+ assert_eq!(spki_key, es256_verifying_key(&created.public_key_jwk));
+ es256_verifying_key(&created.public_key_jwk).verify(&signed_bytes(&assertion.authenticator_data), &signature).unwrap();
+}
+
+#[test]
+fn rs256_registration_and_assertion_round_trip() {
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_RS256, false, false, None, None).unwrap();
+ let n = jwk_field(&created.public_key_jwk, "n");
+ let e = jwk_field(&created.public_key_jwk, "e");
+ let cose = &created.authenticator_data[71..];
+ assert_eq!(&cose[..9], &[0xa4, 0x01, 0x03, 0x03, 0x39, 0x01, 0x00, 0x20, 0x59]);
+ assert_eq!(&cose[9..11], &(n.len() as u16).to_be_bytes());
+
+ let assertion = get_assertion("example.com", &CLIENT_DATA_HASH, &created.private_key_jwk, true, None, None).unwrap();
+ let public = RsaPublicKey::new(BigUint::from_bytes_be(&n), BigUint::from_bytes_be(&e)).unwrap();
+ assert_eq!(<RsaPublicKey as rsa::pkcs8::DecodePublicKey>::from_public_key_der(&created.public_key_spki).unwrap(), public);
+ let digest = Sha256::digest(signed_bytes(&assertion.authenticator_data));
+ public.verify(Pkcs1v15Sign::new::<Sha256>(), &digest, &assertion.signature).unwrap();
+}
+
+#[test]
+fn stored_ec_keys_with_a_short_scalar_or_webcrypto_members_still_sign() {
+ // d = 1 encoded without its leading zero bytes, as some stored keys are; its public key is the generator.
+ let short = format!("{{\"kty\":\"EC\",\"crv\":\"P-256\",\"d\":\"{}\",\"ext\":true,\"key_ops\":[\"sign\"]}}", base64url_encode(&[1]));
+ let assertion = get_assertion("example.com", &CLIENT_DATA_HASH, &short, false, None, None).unwrap();
+
+ let generator = VerifyingKey::from_encoded_point(&p256::AffinePoint::GENERATOR.into()).unwrap();
+ generator.verify(&signed_bytes(&assertion.authenticator_data), &Signature::from_der(&assertion.signature).unwrap()).unwrap();
+}
+
+#[test]
+fn prf_matches_an_independently_computed_vector() {
+ let secret: Vec<u8> = (0..32).collect();
+ let inputs = PasskeyPrfInputs { first: Some(b"salt".to_vec()), second: Some(b"salt".to_vec()) };
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_ES256, false, false, None, None).unwrap();
+ let assertion = get_assertion("example.com", &CLIENT_DATA_HASH, &created.private_key_jwk, false, Some(&inputs), Some(&secret)).unwrap();
+
+ let results = assertion.prf_results.unwrap();
+ assert_eq!(hex_encode_lower(&results.first), "5ac88c3a9e94582e742c998c65aca73e2f834f06f16a4eb6958fda74cfabb286");
+ assert_eq!(results.second.as_deref(), Some(results.first.as_slice()));
+}
+
+#[test]
+fn registration_with_prf_creates_a_secret_and_evaluates_requested_salts() {
+ let inputs = PasskeyPrfInputs { first: Some(vec![1, 2, 3]), second: None };
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_ES256, false, true, Some(&inputs), None).unwrap();
+
+ assert_eq!(created.prf_secret.as_ref().map(Vec::len), Some(32));
+ let results = created.prf_results.unwrap();
+ assert_eq!(results.first.len(), 32);
+ assert!(results.second.is_none());
+}
+
+#[test]
+fn algorithm_choice_follows_the_relying_party_order() {
+ assert_eq!(pick_algorithm(&[]).unwrap(), ALG_ES256);
+ assert_eq!(pick_algorithm(&[-8, ALG_RS256, ALG_ES256]).unwrap(), ALG_RS256);
+ assert!(pick_algorithm(&[-8, -35]).is_err());
+}
+
+#[test]
+fn credential_id_guids_round_trip() {
+ let guid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
+ assert_eq!(guid_to_bytes(guid).unwrap(), CREDENTIAL_ID);
+ assert_eq!(guid_to_bytes(&guid.to_uppercase()).unwrap(), CREDENTIAL_ID);
+ assert_eq!(bytes_to_guid(&CREDENTIAL_ID).unwrap(), guid);
+ assert!(guid_to_bytes("not-a-guid").is_err());
+ assert!(bytes_to_guid(&[0; 15]).is_err());
+}
+
+#[test]
+fn packed_self_attestation_signs_auth_data_and_client_data_hash() {
+ let created = create_passkey(&CREDENTIAL_ID, "example.com", ALG_ES256, false, false, None, Some(&CLIENT_DATA_HASH)).unwrap();
+ let object = &created.attestation_object;
+
+ // {"fmt": "packed", "attStmt": {"alg": -7, "sig": <der>}, "authData": ...}
+ let header = hex_decode("a363666d74667061636b65646761747453746d74a263616c672663736967").unwrap();
+ assert_eq!(&object[..header.len()], header.as_slice());
+ let (length_header, signature_length) = match object[header.len()] {
+ 0x58 => (2, object[header.len() + 1] as usize),
+ short => (1, (short - 0x40) as usize),
+ };
+ let start = header.len() + length_header;
+ let signature = Signature::from_der(&object[start..start + signature_length]).unwrap();
+ es256_verifying_key(&created.public_key_jwk).verify(&signed_bytes(&created.authenticator_data), &signature).unwrap();
+}
diff --git a/core/rust/src/sqlite_host/.gitignore b/core/rust/src/sqlite_host/.gitignore
new file mode 100644
index 000000000..aecee65aa
--- /dev/null
+++ b/core/rust/src/sqlite_host/.gitignore
@@ -0,0 +1 @@
+!*.sql
diff --git a/core/rust/src/sqlite_host/mod.rs b/core/rust/src/sqlite_host/mod.rs
index 137f0ad79..38f7ce7e8 100644
--- a/core/rust/src/sqlite_host/mod.rs
+++ b/core/rust/src/sqlite_host/mod.rs
@@ -20,6 +20,9 @@ const VACUUM_MIN_FREE_PAGES: i64 = 64;
/// A VACUUM runs when the freelist holds at least this fraction (1/n) of the database's pages.
const VACUUM_FREE_PAGE_RATIO: i64 = 10;
+/// The complete client vault schema, generated from `core/vault/src/sql/SqlConstants.ts` by `core/vault/build.sh`.
+pub const VAULT_SCHEMA_SQL: &str = include_str!("vault_schema.sql");
+
/// One parameterized SQL statement, as the bindings and the sync engine hand it to a host.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SqlStatement {
@@ -72,6 +75,13 @@ impl MemoryDatabase {
Ok(Self { conn: Mutex::new(conn) })
}
+ /// Open an empty database on the latest vault schema, foreign keys off so rows can be inserted in any order.
+ pub fn with_latest_schema() -> VaultResult<Self> {
+ let db = Self::with_schema(VAULT_SCHEMA_SQL)?;
+ db.execute_batch("PRAGMA foreign_keys = OFF")?;
+ Ok(db)
+ }
+
/// Run a SQL script (several statements, no parameters).
pub fn execute_batch(&self, sql: &str) -> VaultResult<()> {
self.lock().execute_batch(sql).map_err(sql_error)
@@ -120,6 +130,11 @@ impl MemoryDatabase {
Ok(conn.serialize(MAIN_DB).map_err(sql_error)?.to_vec())
}
+ /// Run `f` on the connection, holding the lock for the whole call.
+ pub fn with_connection<R>(&self, f: impl FnOnce(&Connection) -> VaultResult<R>) -> VaultResult<R> {
+ f(&self.lock())
+ }
+
fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
self.conn.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
@@ -153,7 +168,7 @@ pub fn deserialize_into(conn: &mut Connection, bytes: &[u8]) -> VaultResult<()>
conn.deserialize_read_exact(MAIN_DB, bytes, bytes.len(), false).map_err(sql_error)
}
-fn sql_error(error: rusqlite::Error) -> VaultError {
+pub(crate) fn sql_error(error: rusqlite::Error) -> VaultError {
VaultError::General(error.to_string())
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt b/core/rust/src/sqlite_host/vault_schema.sql
similarity index 59%
rename from apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt
rename to core/rust/src/sqlite_host/vault_schema.sql
index 7fda5c0ff..bf7bd37ce 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt
+++ b/core/rust/src/sqlite_host/vault_schema.sql
@@ -1,18 +1,5 @@
-// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/SqlConstants.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-@file:Suppress("all")
-
-package net.aliasvault.app.vaultstore.models
-
-/**
- * SQL statements for vault creation and migration.
- */
-object VaultSql {
- /**
- * Complete database schema SQL for creating a new vault with the latest schema.
- */
- val completeSchema = """
+-- <auto-generated />
+-- Generated from core/vault/src/sql/SqlConstants.ts by core/vault/scripts/generate-vault-sql.cjs. Do not edit manually.
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
"MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
"ProductVersion" TEXT NOT NULL
@@ -1838,1250 +1825,3 @@ PRAGMA foreign_keys = ON;
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20260918090100_2.1.1-ItemChildManifestTrigger', '10.0.10');
- """.trimIndent()
-
- /**
- * Migration SQL scripts indexed by migration number.
- * Key is the source migration number (migration FROM this version).
- */
- val migrations: Map<Int, String> = mapOf(
- 1 to """
-BEGIN TRANSACTION;
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 2 to """
-BEGIN TRANSACTION;
-ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 3 to """
-BEGIN TRANSACTION;
-CREATE TABLE "EncryptionKeys" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,
- "PublicKey" TEXT NOT NULL,
- "PrivateKey" TEXT NOT NULL,
- "IsPrimary" INTEGER NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL
-);
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 4 to """
-BEGIN TRANSACTION;
-CREATE TABLE "Settings" (
- "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,
- "Value" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL
-);
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 5 to """
-BEGIN TRANSACTION;
-CREATE TABLE "ef_temp_Aliases" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,
- "BirthDate" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "Email" TEXT NULL,
- "FirstName" VARCHAR NULL,
- "Gender" VARCHAR NULL,
- "LastName" VARCHAR NULL,
- "NickName" VARCHAR NULL,
- "UpdatedAt" TEXT NOT NULL
-);
-
-INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")
-SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"
-FROM "Aliases";
-
-COMMIT;
-
-PRAGMA foreign_keys = 0;
-
-BEGIN TRANSACTION;
-DROP TABLE "Aliases";
-
-ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";
-
-COMMIT;
-
-PRAGMA foreign_keys = 1;
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');
- """.trimIndent(),
- 6 to """
-BEGIN TRANSACTION;
-CREATE TABLE "ef_temp_Credentials" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,
- "AliasId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "Notes" TEXT NULL,
- "ServiceId" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "Username" TEXT NULL,
- CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,
- CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE
-);
-
-INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")
-SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"
-FROM "Credentials";
-
-COMMIT;
-
-PRAGMA foreign_keys = 0;
-
-BEGIN TRANSACTION;
-DROP TABLE "Credentials";
-
-ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";
-
-COMMIT;
-
-PRAGMA foreign_keys = 1;
-
-BEGIN TRANSACTION;
-CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");
-
-CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");
-
-COMMIT;
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');
- """.trimIndent(),
- 7 to """
-BEGIN TRANSACTION;
-ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 8 to """
-BEGIN TRANSACTION;
-ALTER TABLE "Attachment" RENAME TO "Attachments";
-
-CREATE TABLE "ef_temp_Attachments" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,
- "Blob" BLOB NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "CredentialId" TEXT NOT NULL,
- "Filename" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")
-SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"
-FROM "Attachments";
-
-COMMIT;
-
-PRAGMA foreign_keys = 0;
-
-BEGIN TRANSACTION;
-DROP TABLE "Attachments";
-
-ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";
-
-COMMIT;
-
-PRAGMA foreign_keys = 1;
-
-BEGIN TRANSACTION;
-CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");
-
-COMMIT;
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');
- """.trimIndent(),
- 9 to """
-BEGIN TRANSACTION;
-CREATE TABLE "TotpCodes" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,
- "Name" TEXT NOT NULL,
- "SecretKey" TEXT NOT NULL,
- "CredentialId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 10 to """
-BEGIN TRANSACTION;
-
-PRAGMA foreign_keys = OFF;
-
--- Clean up any existing temp tables first
-DROP TABLE IF EXISTS "__EFMigrationsHistory_temp";
-DROP TABLE IF EXISTS "Aliases_temp";
-DROP TABLE IF EXISTS "Services_temp";
-DROP TABLE IF EXISTS "EncryptionKeys_temp";
-DROP TABLE IF EXISTS "Settings_temp";
-DROP TABLE IF EXISTS "Credentials_temp";
-DROP TABLE IF EXISTS "Attachments_temp";
-DROP TABLE IF EXISTS "Passwords_temp";
-DROP TABLE IF EXISTS "TotpCodes_temp";
-
--- Create backup tables for all data
-CREATE TABLE "__EFMigrationsHistory_temp" AS SELECT * FROM "__EFMigrationsHistory";
-CREATE TABLE "Aliases_temp" AS SELECT * FROM "Aliases";
-CREATE TABLE "Services_temp" AS SELECT * FROM "Services";
-CREATE TABLE "EncryptionKeys_temp" AS SELECT * FROM "EncryptionKeys";
-CREATE TABLE "Settings_temp" AS SELECT * FROM "Settings";
-CREATE TABLE "Credentials_temp" AS SELECT * FROM "Credentials";
-CREATE TABLE "Attachments_temp" AS SELECT * FROM "Attachments";
-CREATE TABLE "Passwords_temp" AS SELECT * FROM "Passwords";
-CREATE TABLE "TotpCodes_temp" AS SELECT * FROM "TotpCodes";
-
--- Delete orphaned records that do not have a valid FK to the credential object
-DELETE FROM "Attachments_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-DELETE FROM "Passwords_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-DELETE FROM "TotpCodes_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-
--- Delete orphaned credentials that do not have valid FKs to alias or service objects
-DELETE FROM "Credentials_temp" WHERE "AliasId" NOT IN (SELECT "Id" FROM "Aliases_temp");
-DELETE FROM "Credentials_temp" WHERE "ServiceId" NOT IN (SELECT "Id" FROM "Services_temp");
-
--- After cleaning credentials, clean dependent tables again in case we removed credentials
-DELETE FROM "Attachments_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-DELETE FROM "Passwords_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-DELETE FROM "TotpCodes_temp" WHERE "CredentialId" NOT IN (SELECT "Id" FROM "Credentials_temp");
-
--- Drop all existing tables
-DROP TABLE "TotpCodes";
-DROP TABLE "Passwords";
-DROP TABLE "Attachments";
-DROP TABLE "Credentials";
-DROP TABLE "Settings";
-DROP TABLE "EncryptionKeys";
-DROP TABLE "Services";
-DROP TABLE "Aliases";
-DROP TABLE "__EFMigrationsHistory";
-
--- Recreate tables with proper constraints (no dependencies first)
-CREATE TABLE "__EFMigrationsHistory" (
- "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
- "ProductVersion" TEXT NOT NULL
-);
-
-CREATE TABLE "Aliases" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,
- "BirthDate" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "Email" TEXT NULL,
- "FirstName" VARCHAR NULL,
- "Gender" VARCHAR NULL,
- "LastName" VARCHAR NULL,
- "NickName" VARCHAR NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0
-);
-
-CREATE TABLE "Services" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Services" PRIMARY KEY,
- "Name" TEXT NULL,
- "Url" TEXT NULL,
- "Logo" BLOB NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0
-);
-
-CREATE TABLE "EncryptionKeys" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,
- "PublicKey" TEXT NOT NULL,
- "PrivateKey" TEXT NOT NULL,
- "IsPrimary" INTEGER NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0
-);
-
-CREATE TABLE "Settings" (
- "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,
- "Value" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0
-);
-
--- Tables with foreign keys
-CREATE TABLE "Credentials" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,
- "AliasId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "Notes" TEXT NULL,
- "ServiceId" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "Username" TEXT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,
- CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "Attachments" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,
- "Blob" BLOB NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "CredentialId" TEXT NOT NULL,
- "Filename" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0,
- "UpdatedAt" TEXT NOT NULL,
- CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "Passwords" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Passwords" PRIMARY KEY,
- "Value" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "CredentialId" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT "FK_Passwords_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "TotpCodes" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,
- "Name" TEXT NOT NULL,
- "SecretKey" TEXT NOT NULL,
- "CredentialId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL DEFAULT 0,
- CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-
--- Restore data from temp tables
-INSERT INTO "__EFMigrationsHistory" SELECT * FROM "__EFMigrationsHistory_temp";
-INSERT INTO "Aliases" SELECT * FROM "Aliases_temp";
-INSERT INTO "Services" SELECT * FROM "Services_temp";
-INSERT INTO "EncryptionKeys" SELECT * FROM "EncryptionKeys_temp";
-INSERT INTO "Settings" SELECT * FROM "Settings_temp";
-INSERT INTO "Credentials" SELECT * FROM "Credentials_temp";
-INSERT INTO "Attachments" SELECT * FROM "Attachments_temp";
-INSERT INTO "Passwords" SELECT * FROM "Passwords_temp";
-INSERT INTO "TotpCodes" SELECT * FROM "TotpCodes_temp";
-
--- =====================================================================================
--- Date Format Normalization Migration
--- =====================================================================================
--- This migration normalizes ALL date fields to the standard format: 'yyyy-MM-dd HH:mm:ss.fff'
--- Previously the different clients used different date formats which complicate date parsing.
--- From version 0.24.0 onwards, all new dates are stored in this standard format.
-
--- Update Aliases table (CreatedAt, UpdatedAt, BirthDate)
-UPDATE "Aliases" SET "CreatedAt" =
- CASE
- -- Already in correct format (yyyy-MM-dd HH:mm:ss.fff) - no change
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
-
- -- ISO 8601 with milliseconds (yyyy-MM-ddTHH:mm:ss.fffZ) -> Replace T with space, remove Z and everything after .fff
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
-
- -- Without milliseconds (yyyy-MM-dd HH:mm:ss or yyyy-MM-ddTHH:mm:ssZ) -> Add .000
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
-
- -- Fallback: if none match, keep as-is (edge case)
- ELSE "CreatedAt"
- END;
-
-UPDATE "Aliases" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- BirthDate: Always set time to 00:00:00 (no milliseconds for birth dates)
-UPDATE "Aliases" SET "BirthDate" =
- CASE
- -- If empty or already '0001-01-01 00:00:00', keep as-is
- WHEN "BirthDate" = '' OR "BirthDate" = '0001-01-01 00:00:00'
- THEN "BirthDate"
-
- -- If already in correct format (yyyy-MM-dd 00:00:00), keep as-is
- WHEN "BirthDate" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] 00:00:00'
- THEN "BirthDate"
-
- -- Extract date part and set time to 00:00:00
- WHEN "BirthDate" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'
- THEN substr("BirthDate", 1, 10) || ' 00:00:00'
-
- -- Fallback
- ELSE "BirthDate"
- END;
-
--- Update Services table (CreatedAt, UpdatedAt)
-UPDATE "Services" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "Services" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update EncryptionKeys table (CreatedAt, UpdatedAt)
-UPDATE "EncryptionKeys" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "EncryptionKeys" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update Settings table (CreatedAt, UpdatedAt)
-UPDATE "Settings" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "Settings" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update Credentials table (CreatedAt, UpdatedAt)
-UPDATE "Credentials" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "Credentials" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update Attachments table (CreatedAt, UpdatedAt)
-UPDATE "Attachments" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "Attachments" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update Passwords table (CreatedAt, UpdatedAt)
-UPDATE "Passwords" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "Passwords" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- Update TotpCodes table (CreatedAt, UpdatedAt)
-UPDATE "TotpCodes" SET "CreatedAt" =
- CASE
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "CreatedAt"
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr("CreatedAt", 12, 12)
- WHEN "CreatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("CreatedAt", 1, 10) || ' ' || substr(replace("CreatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "CreatedAt"
- END;
-
-UPDATE "TotpCodes" SET "UpdatedAt" =
- CASE
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]'
- THEN "UpdatedAt"
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr("UpdatedAt", 12, 12)
- WHEN "UpdatedAt" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]*'
- THEN substr("UpdatedAt", 1, 10) || ' ' || substr(replace("UpdatedAt", 'T', ' '), 12, 8) || '.000'
- ELSE "UpdatedAt"
- END;
-
--- =====================================================================================
--- End of Date Format Normalization Migration
--- =====================================================================================
-
--- Recreate indexes
-CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");
-CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");
-CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");
-CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");
-CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");
-
--- Clean up temp tables
-DROP TABLE "__EFMigrationsHistory_temp";
-DROP TABLE "Aliases_temp";
-DROP TABLE "Services_temp";
-DROP TABLE "EncryptionKeys_temp";
-DROP TABLE "Settings_temp";
-DROP TABLE "Credentials_temp";
-DROP TABLE "Attachments_temp";
-DROP TABLE "Passwords_temp";
-DROP TABLE "TotpCodes_temp";
-
-PRAGMA foreign_keys = ON;
-
-
-CREATE TABLE "Passkeys" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Passkeys" PRIMARY KEY,
- "RpId" TEXT COLLATE NOCASE NOT NULL,
- "UserHandle" BLOB NOT NULL,
- "PublicKey" TEXT NOT NULL,
- "PrivateKey" TEXT NOT NULL,
- "PrfKey" BLOB NULL,
- "DisplayName" TEXT NOT NULL,
- "AdditionalData" BLOB NULL,
- "CredentialId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_Passkeys_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE
-);
-
-CREATE INDEX "IX_Passkeys_CredentialId" ON "Passkeys" ("CredentialId");
-
-CREATE INDEX "IX_Passkeys_RpId" ON "Passkeys" ("RpId");
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20251014122838_1.6.0-AddPasskeys', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- 11 to """
-PRAGMA foreign_keys = OFF;
-
-BEGIN TRANSACTION;
-ALTER TABLE "TotpCodes" RENAME COLUMN "CredentialId" TO "ItemId";
-
-DROP INDEX IF EXISTS "IX_TotpCodes_CredentialId";
-
-CREATE INDEX IF NOT EXISTS "IX_TotpCodes_ItemId" ON "TotpCodes" ("ItemId");
-
-ALTER TABLE "Passkeys" RENAME COLUMN "CredentialId" TO "ItemId";
-
-DROP INDEX IF EXISTS "IX_Passkeys_CredentialId";
-
-CREATE INDEX IF NOT EXISTS "IX_Passkeys_ItemId" ON "Passkeys" ("ItemId");
-
-ALTER TABLE "Attachments" RENAME COLUMN "CredentialId" TO "ItemId";
-
-DROP INDEX IF EXISTS "IX_Attachments_CredentialId";
-
-CREATE INDEX IF NOT EXISTS "IX_Attachments_ItemId" ON "Attachments" ("ItemId");
-
-CREATE TABLE "FieldDefinitions" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_FieldDefinitions" PRIMARY KEY,
- "FieldType" TEXT NOT NULL,
- "Label" TEXT NOT NULL,
- "IsMultiValue" INTEGER NOT NULL,
- "IsHidden" INTEGER NOT NULL,
- "EnableHistory" INTEGER NOT NULL,
- "Weight" INTEGER NOT NULL,
- "ApplicableToTypes" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL
-);
-
-CREATE TABLE "Folders" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Folders" PRIMARY KEY,
- "Name" TEXT NOT NULL,
- "ParentFolderId" TEXT NULL,
- "Weight" INTEGER NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_Folders_Folders_ParentFolderId" FOREIGN KEY ("ParentFolderId") REFERENCES "Folders" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "Logos" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Logos" PRIMARY KEY,
- "Source" TEXT NOT NULL,
- "FileData" BLOB NULL,
- "MimeType" TEXT NULL,
- "FetchedAt" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL
-);
-
-CREATE TABLE "Tags" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Tags" PRIMARY KEY,
- "Name" TEXT NOT NULL,
- "Color" TEXT NULL,
- "DisplayOrder" INTEGER NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL
-);
-
-CREATE TABLE "Items" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Items" PRIMARY KEY,
- "Name" TEXT NULL,
- "ItemType" TEXT NOT NULL,
- "LogoId" TEXT NULL,
- "DeletedAt" TEXT NULL,
- "FolderId" TEXT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_Items_Folders_FolderId" FOREIGN KEY ("FolderId") REFERENCES "Folders" ("Id") ON DELETE SET NULL,
- CONSTRAINT "FK_Items_Logos_LogoId" FOREIGN KEY ("LogoId") REFERENCES "Logos" ("Id") ON DELETE SET NULL
-);
-
-CREATE TABLE "FieldHistories" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_FieldHistories" PRIMARY KEY,
- "ItemId" TEXT NOT NULL,
- "FieldDefinitionId" TEXT NULL,
- "FieldKey" TEXT NULL,
- "ValueSnapshot" TEXT NOT NULL,
- "ChangedAt" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_FieldHistories_FieldDefinitions_FieldDefinitionId" FOREIGN KEY ("FieldDefinitionId") REFERENCES "FieldDefinitions" ("Id") ON DELETE CASCADE,
- CONSTRAINT "FK_FieldHistories_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "FieldValues" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_FieldValues" PRIMARY KEY,
- "ItemId" TEXT NOT NULL,
- "FieldDefinitionId" TEXT NULL,
- "FieldKey" TEXT NULL,
- "Value" TEXT NULL,
- "Weight" INTEGER NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_FieldValues_FieldDefinitions_FieldDefinitionId" FOREIGN KEY ("FieldDefinitionId") REFERENCES "FieldDefinitions" ("Id") ON DELETE CASCADE,
- CONSTRAINT "FK_FieldValues_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE
-);
-
-CREATE TABLE "ItemTags" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_ItemTags" PRIMARY KEY,
- "ItemId" TEXT NOT NULL,
- "TagId" TEXT NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- CONSTRAINT "FK_ItemTags_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE,
- CONSTRAINT "FK_ItemTags_Tags_TagId" FOREIGN KEY ("TagId") REFERENCES "Tags" ("Id") ON DELETE CASCADE
-);
-
-CREATE INDEX "IX_FieldHistories_FieldDefinitionId" ON "FieldHistories" ("FieldDefinitionId");
-
-CREATE INDEX "IX_FieldHistories_ItemId" ON "FieldHistories" ("ItemId");
-
-CREATE INDEX "IX_FieldValues_FieldDefinitionId" ON "FieldValues" ("FieldDefinitionId");
-
-CREATE INDEX "IX_FieldValues_FieldKey" ON "FieldValues" ("FieldKey");
-
-CREATE INDEX "IX_FieldValues_ItemId" ON "FieldValues" ("ItemId");
-
-CREATE INDEX "IX_FieldValues_ItemId_FieldDefinitionId_Weight" ON "FieldValues" ("ItemId", "FieldDefinitionId", "Weight");
-
-CREATE INDEX "IX_FieldValues_ItemId_FieldKey" ON "FieldValues" ("ItemId", "FieldKey");
-
-CREATE INDEX "IX_Folders_ParentFolderId" ON "Folders" ("ParentFolderId");
-
-CREATE INDEX "IX_Items_FolderId" ON "Items" ("FolderId");
-
-CREATE INDEX "IX_Items_LogoId" ON "Items" ("LogoId");
-
-CREATE INDEX "IX_ItemTags_ItemId" ON "ItemTags" ("ItemId");
-
-CREATE UNIQUE INDEX "IX_ItemTags_ItemId_TagId" ON "ItemTags" ("ItemId", "TagId");
-
-CREATE INDEX "IX_ItemTags_TagId" ON "ItemTags" ("TagId");
-
-CREATE UNIQUE INDEX "IX_Logos_Source" ON "Logos" ("Source");
-
-CREATE INDEX "IX_Tags_Name" ON "Tags" ("Name");
-
-
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- c.Id,
- s.Name AS Name,
- CASE
- WHEN a.Id IS NOT NULL AND (
- (a.FirstName IS NOT NULL AND a.FirstName != '') OR
- (a.LastName IS NOT NULL AND a.LastName != '') OR
- (a.Gender IS NOT NULL AND a.Gender != '') OR
- (a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%')
- ) THEN 'Alias'
- ELSE 'Login'
- END AS ItemType,
- NULL AS LogoId,
- NULL AS FolderId,
- c.CreatedAt,
- c.UpdatedAt,
- c.IsDeleted
- FROM Credentials c
- LEFT JOIN Services s ON s.Id = c.ServiceId
- LEFT JOIN Aliases a ON a.Id = c.AliasId;
-
-
-
- INSERT INTO Logos (Id, Source, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- -- Extract and normalize hostname: remove protocol, path, lowercase, and www. prefix
- REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) AS Source,
- s.Logo AS FileData,
- 'image/png' AS MimeType,
- NULL AS FetchedAt,
- MIN(s.CreatedAt) AS CreatedAt,
- MAX(s.UpdatedAt) AS UpdatedAt,
- 0 AS IsDeleted
- FROM Services s
- WHERE s.Logo IS NOT NULL AND s.Url IS NOT NULL AND s.Url != ''
- GROUP BY REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- );
-
-
-
- UPDATE Items
- SET LogoId = (
- SELECT l.Id FROM Logos l
- INNER JOIN Services s ON REPLACE(
- LOWER(
- SUBSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END,
- 1,
- CASE
- WHEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') > 0
- THEN INSTR(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END, '/') - 1
- ELSE LENGTH(
- CASE
- WHEN s.Url LIKE 'https://%' THEN SUBSTR(s.Url, 9)
- WHEN s.Url LIKE 'http://%' THEN SUBSTR(s.Url, 8)
- ELSE s.Url
- END)
- END
- )
- ),
- 'www.', ''
- ) = l.Source
- INNER JOIN Credentials c ON c.ServiceId = s.Id
- WHERE c.Id = Items.Id
- LIMIT 1
- )
- WHERE EXISTS (
- SELECT 1 FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE c.Id = Items.Id AND s.Logo IS NOT NULL
- );
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.url' AS FieldKey,
- s.Url AS Value,
- 0 AS Weight,
- s.UpdatedAt AS CreatedAt,
- s.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Services s ON s.Id = c.ServiceId
- WHERE s.Url IS NOT NULL AND s.Url != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.username' AS FieldKey,
- c.Username AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Username IS NOT NULL AND c.Username != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'notes.content' AS FieldKey,
- c.Notes AS Value,
- 0 AS Weight,
- c.UpdatedAt AS CreatedAt,
- c.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- WHERE c.Notes IS NOT NULL AND c.Notes != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- p.CredentialId AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.password' AS FieldKey,
- p.Value AS Value,
- 0 AS Weight,
- p.UpdatedAt AS CreatedAt,
- p.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Passwords p
- INNER JOIN (
- SELECT CredentialId, MAX(UpdatedAt) AS MaxUpdated, MAX(Id) AS MaxId
- FROM Passwords
- WHERE IsDeleted = 0
- GROUP BY CredentialId
- ) pm ON p.CredentialId = pm.CredentialId AND p.UpdatedAt = pm.MaxUpdated AND p.Id = pm.MaxId
- WHERE p.IsDeleted = 0;
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'login.email' AS FieldKey,
- a.Email AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Email IS NOT NULL AND a.Email != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.first_name' AS FieldKey,
- a.FirstName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.FirstName IS NOT NULL AND a.FirstName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.last_name' AS FieldKey,
- a.LastName AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.LastName IS NOT NULL AND a.LastName != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.gender' AS FieldKey,
- a.Gender AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.Gender IS NOT NULL AND a.Gender != '';
-
-
-
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT
- UPPER(SUBSTR(hex(randomblob(4)), 1, 8) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(2)), 1, 4) || '-' ||
- SUBSTR(hex(randomblob(6)), 1, 12)) AS Id,
- c.Id AS ItemId,
- NULL AS FieldDefinitionId,
- 'alias.birthdate' AS FieldKey,
- SUBSTR(a.BirthDate, 1, 10) AS Value,
- 0 AS Weight,
- a.UpdatedAt AS CreatedAt,
- a.UpdatedAt AS UpdatedAt,
- 0 AS IsDeleted
- FROM Credentials c
- INNER JOIN Aliases a ON a.Id = c.AliasId
- WHERE a.BirthDate IS NOT NULL AND a.BirthDate != '' AND a.BirthDate NOT LIKE '0001-%';
-
-
-DROP TABLE "Passwords";
-
-DROP TABLE "Credentials";
-
-DROP TABLE "Aliases";
-
-DROP TABLE "Services";
-
-COMMIT;
-
-PRAGMA foreign_keys = ON;
-
-BEGIN TRANSACTION;
-CREATE TABLE "ef_temp_Attachments" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,
- "Blob" BLOB NOT NULL,
- "CreatedAt" TEXT NOT NULL,
- "Filename" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- "ItemId" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- CONSTRAINT "FK_Attachments_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE
-);
-
-INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "Filename", "IsDeleted", "ItemId", "UpdatedAt")
-SELECT "Id", "Blob", "CreatedAt", "Filename", "IsDeleted", "ItemId", "UpdatedAt"
-FROM "Attachments";
-
-CREATE TABLE "ef_temp_Passkeys" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_Passkeys" PRIMARY KEY,
- "AdditionalData" BLOB NULL,
- "CreatedAt" TEXT NOT NULL,
- "DisplayName" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- "ItemId" TEXT NOT NULL,
- "PrfKey" BLOB NULL,
- "PrivateKey" TEXT NOT NULL,
- "PublicKey" TEXT NOT NULL,
- "RpId" TEXT COLLATE NOCASE NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- "UserHandle" BLOB NOT NULL,
- CONSTRAINT "FK_Passkeys_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE
-);
-
-INSERT INTO "ef_temp_Passkeys" ("Id", "AdditionalData", "CreatedAt", "DisplayName", "IsDeleted", "ItemId", "PrfKey", "PrivateKey", "PublicKey", "RpId", "UpdatedAt", "UserHandle")
-SELECT "Id", "AdditionalData", "CreatedAt", "DisplayName", "IsDeleted", "ItemId", "PrfKey", "PrivateKey", "PublicKey", "RpId", "UpdatedAt", "UserHandle"
-FROM "Passkeys";
-
-CREATE TABLE "ef_temp_TotpCodes" (
- "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,
- "CreatedAt" TEXT NOT NULL,
- "IsDeleted" INTEGER NOT NULL,
- "ItemId" TEXT NOT NULL,
- "Name" TEXT NOT NULL,
- "SecretKey" TEXT NOT NULL,
- "UpdatedAt" TEXT NOT NULL,
- CONSTRAINT "FK_TotpCodes_Items_ItemId" FOREIGN KEY ("ItemId") REFERENCES "Items" ("Id") ON DELETE CASCADE
-);
-
-INSERT INTO "ef_temp_TotpCodes" ("Id", "CreatedAt", "IsDeleted", "ItemId", "Name", "SecretKey", "UpdatedAt")
-SELECT "Id", "CreatedAt", "IsDeleted", "ItemId", "Name", "SecretKey", "UpdatedAt"
-FROM "TotpCodes";
-
-COMMIT;
-
-PRAGMA foreign_keys = 0;
-
-BEGIN TRANSACTION;
-DROP TABLE "Attachments";
-
-ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";
-
-DROP TABLE "Passkeys";
-
-ALTER TABLE "ef_temp_Passkeys" RENAME TO "Passkeys";
-
-DROP TABLE "TotpCodes";
-
-ALTER TABLE "ef_temp_TotpCodes" RENAME TO "TotpCodes";
-
-COMMIT;
-
-PRAGMA foreign_keys = 1;
-
-BEGIN TRANSACTION;
-CREATE INDEX "IX_Attachments_ItemId" ON "Attachments" ("ItemId");
-
-CREATE INDEX "IX_Passkeys_ItemId" ON "Passkeys" ("ItemId");
-
-CREATE INDEX "IX_Passkeys_RpId" ON "Passkeys" ("RpId");
-
-CREATE INDEX "IX_TotpCodes_ItemId" ON "TotpCodes" ("ItemId");
-
-COMMIT;
-
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '9.0.4');
- """.trimIndent(),
- 12 to """
-BEGIN TRANSACTION;
-INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20260130221620_2.0.0-MajorVersionBump', '9.0.4');
-
-COMMIT;
- """.trimIndent(),
- )
-
- /**
- * Get migration SQL for upgrading from a specific revision.
- */
- fun getMigrationSql(fromRevision: Int): String? {
- return migrations[fromRevision]
- }
-}
diff --git a/core/rust/src/vault_items/items.rs b/core/rust/src/vault_items/items.rs
new file mode 100644
index 000000000..2e7f8cba0
--- /dev/null
+++ b/core/rust/src/vault_items/items.rs
@@ -0,0 +1,193 @@
+//! Item reads with their fields and folder paths, TOTP codes, and single field-value appends.
+
+use std::collections::HashMap;
+
+use rusqlite::{params, Connection};
+
+use super::{blob, new_id, sql_error, timestamp_ms, VaultItem, VaultItemField, VaultTotpCode};
+use crate::common::error::VaultResult;
+use crate::common::timestamp::now_vault_datetime;
+use crate::vault_model::{id_key, system_field};
+
+/// Folder nesting cap (root is depth 0), the same as core/client `FolderUtils.MAX_FOLDER_DEPTH`.
+const MAX_FOLDER_DEPTH: usize = 4;
+
+/// Every active item: not deleted, not in the trash and not archived. This is what autofill reads.
+const GET_ALL_ACTIVE: &str = "
+ SELECT
+ i.Id, i.ManifestId, i.Name, i.ItemType, i.FolderId,
+ l.FileData AS Logo, l.Kind AS LogoKind, l.Source AS LogoSource,
+ EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.ManifestId = i.ManifestId AND pk.IsDeleted = 0) AS HasPasskey,
+ EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.ManifestId = i.ManifestId AND att.IsDeleted = 0) AS HasAttachment,
+ EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.ManifestId = i.ManifestId AND tc.IsDeleted = 0) AS HasTotp,
+ i.CreatedAt, i.UpdatedAt
+ FROM Items i
+ LEFT JOIN Logos l ON l.Id = i.LogoId AND l.ManifestId = i.ManifestId
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
+ ORDER BY i.CreatedAt DESC";
+
+/// The live field values of every active item, in display order.
+const GET_ACTIVE_FIELD_VALUES: &str = "
+ SELECT
+ fv.ItemId, fv.ManifestId, fv.FieldKey, fv.FieldDefinitionId, fv.Value, fv.Weight,
+ fd.Label AS CustomLabel, fd.FieldType AS CustomFieldType, fd.IsHidden AS CustomIsHidden, fd.EnableHistory AS CustomEnableHistory
+ FROM FieldValues fv
+ INNER JOIN Items i ON i.Id = fv.ItemId AND i.ManifestId = fv.ManifestId
+ LEFT JOIN FieldDefinitions fd ON fd.ManifestId = fv.ManifestId AND fd.Id = fv.FieldDefinitionId
+ WHERE fv.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
+ ORDER BY fv.Weight, fv.ValueIndex";
+
+/// Every live folder.
+const GET_ALL_FOLDERS: &str = "SELECT Id, ManifestId, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0";
+
+/// An item's live TOTP codes.
+const GET_TOTP_CODES: &str = "
+ SELECT Id, ItemId, Name, SecretKey, Algorithm, Digits, Period
+ FROM TotpCodes
+ WHERE ItemId = ?1 AND ManifestId = ?2 AND IsDeleted = 0";
+
+/// Insert one field value after the field's existing values.
+pub(super) const INSERT_FIELD_VALUE: &str = "
+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
+ VALUES (?1, ?2, NULL, ?3, ?4, ?5,
+ (SELECT COALESCE(MAX(ValueIndex), -1) + 1 FROM FieldValues WHERE ItemId = ?2 AND ManifestId = ?7 AND FieldKey = ?3 AND IsDeleted = 0),
+ ?6, ?6, 0, ?7)";
+
+/// Every active item with its fields and folder path, newest first.
+pub fn get_all_active_items(conn: &Connection) -> VaultResult<Vec<VaultItem>> {
+ let mut fields = active_fields(conn)?;
+ let folder_paths = folder_paths(conn)?;
+
+ let mut statement = conn.prepare_cached(GET_ALL_ACTIVE).map_err(sql_error)?;
+ let rows = statement
+ .query_map([], |row| {
+ let id: String = row.get("Id")?;
+ let manifest_id: String = row.get("ManifestId")?;
+ let folder_id: Option<String> = row.get("FolderId")?;
+ let folder_path = folder_id.as_deref().and_then(|folder| folder_paths.get(&(id_key(&manifest_id), id_key(folder)))).cloned().unwrap_or_default();
+ Ok(VaultItem {
+ fields: fields.remove(&(id_key(&manifest_id), id_key(&id))).unwrap_or_default(),
+ name: row.get("Name")?,
+ item_type: row.get("ItemType")?,
+ logo: blob(row, "Logo")?,
+ logo_kind: row.get("LogoKind")?,
+ logo_source: row.get("LogoSource")?,
+ folder_id,
+ folder_path,
+ has_passkey: row.get("HasPasskey")?,
+ has_attachment: row.get("HasAttachment")?,
+ has_totp: row.get("HasTotp")?,
+ created_at_ms: timestamp_ms(row.get("CreatedAt")?),
+ updated_at_ms: timestamp_ms(row.get("UpdatedAt")?),
+ id,
+ manifest_id,
+ })
+ })
+ .map_err(sql_error)?;
+ rows.collect::<Result<_, _>>().map_err(sql_error)
+}
+
+/// The live TOTP codes of one item.
+pub fn get_totp_codes_for_item(conn: &Connection, item_id: &str, manifest_id: &str) -> VaultResult<Vec<VaultTotpCode>> {
+ let mut statement = conn.prepare_cached(GET_TOTP_CODES).map_err(sql_error)?;
+ let rows = statement
+ .query_map(params![item_id, manifest_id], |row| {
+ Ok(VaultTotpCode {
+ id: row.get("Id")?,
+ item_id: row.get("ItemId")?,
+ name: row.get::<_, Option<String>>("Name")?.unwrap_or_default(),
+ secret_key: row.get("SecretKey")?,
+ algorithm: row.get::<_, Option<String>>("Algorithm")?.unwrap_or_else(|| "SHA1".to_string()),
+ digits: row.get::<_, Option<u32>>("Digits")?.unwrap_or(6),
+ period: row.get::<_, Option<u32>>("Period")?.unwrap_or(30),
+ })
+ })
+ .map_err(sql_error)?;
+ rows.collect::<Result<_, _>>().map_err(sql_error)
+}
+
+/// Append one value to a system field of an item, after the values it already has, and return the rows inserted.
+pub fn append_field_value(conn: &Connection, item_id: &str, manifest_id: &str, field_key: &str, value: &str) -> VaultResult<u64> {
+ insert_field_value(conn, item_id, manifest_id, field_key, value, &now_vault_datetime())
+}
+
+/// Insert one system field value, weighted with the field's default display order like every other writer.
+pub(super) fn insert_field_value(conn: &Connection, item_id: &str, manifest_id: &str, field_key: &str, value: &str, now: &str) -> VaultResult<u64> {
+ let weight = system_field(field_key).map(|field| field.default_display_order).unwrap_or(0);
+ let changed = conn.execute(INSERT_FIELD_VALUE, params![new_id(), item_id, field_key, value, weight, now, manifest_id]).map_err(sql_error)?;
+ Ok(changed as u64)
+}
+
+/// The fields of every active item, keyed by (manifest, item). Rows of a system field this build does not know are skipped.
+fn active_fields(conn: &Connection) -> VaultResult<HashMap<(String, String), Vec<VaultItemField>>> {
+ let mut statement = conn.prepare_cached(GET_ACTIVE_FIELD_VALUES).map_err(sql_error)?;
+ let mut rows = statement.query([]).map_err(sql_error)?;
+ let mut fields: HashMap<(String, String), Vec<VaultItemField>> = HashMap::new();
+ while let Some(row) = rows.next().map_err(sql_error)? {
+ let field_key: Option<String> = row.get("FieldKey").map_err(sql_error)?;
+ let value: String = row.get::<_, Option<String>>("Value").map_err(sql_error)?.unwrap_or_default();
+ let field = match field_key.filter(|key| !key.is_empty()) {
+ Some(key) => {
+ let Some(system) = system_field(&key) else { continue };
+ VaultItemField {
+ label: key.clone(),
+ field_key: key,
+ field_type: system.field_type.to_string(),
+ value,
+ is_hidden: system.is_hidden,
+ display_order: system.default_display_order,
+ is_custom_field: false,
+ enable_history: system.enable_history,
+ }
+ }
+ None => VaultItemField {
+ field_key: row.get::<_, Option<String>>("FieldDefinitionId").map_err(sql_error)?.unwrap_or_default(),
+ label: row.get::<_, Option<String>>("CustomLabel").map_err(sql_error)?.unwrap_or_default(),
+ field_type: row.get::<_, Option<String>>("CustomFieldType").map_err(sql_error)?.unwrap_or_else(|| "Text".to_string()),
+ value,
+ is_hidden: row.get::<_, Option<i64>>("CustomIsHidden").map_err(sql_error)? == Some(1),
+ display_order: row.get::<_, Option<i64>>("Weight").map_err(sql_error)?.unwrap_or(0),
+ is_custom_field: true,
+ enable_history: row.get::<_, Option<i64>>("CustomEnableHistory").map_err(sql_error)? == Some(1),
+ },
+ };
+ let item_id: String = row.get("ItemId").map_err(sql_error)?;
+ let manifest_id: String = row.get("ManifestId").map_err(sql_error)?;
+ fields.entry((id_key(&manifest_id), id_key(&item_id))).or_default().push(field);
+ }
+ Ok(fields)
+}
+
+/// The path of folder names of every folder, keyed by (manifest, folder). A parent link only resolves inside its own manifest.
+fn folder_paths(conn: &Connection) -> VaultResult<HashMap<(String, String), Vec<String>>> {
+ struct Folder {
+ name: String,
+ parent: Option<String>,
+ }
+
+ let mut statement = conn.prepare_cached(GET_ALL_FOLDERS).map_err(sql_error)?;
+ let mut rows = statement.query([]).map_err(sql_error)?;
+ let mut folders: HashMap<(String, String), Folder> = HashMap::new();
+ while let Some(row) = rows.next().map_err(sql_error)? {
+ let id: String = row.get("Id").map_err(sql_error)?;
+ let manifest_id: String = row.get("ManifestId").map_err(sql_error)?;
+ let name: Option<String> = row.get("Name").map_err(sql_error)?;
+ let parent: Option<String> = row.get("ParentFolderId").map_err(sql_error)?;
+ folders.insert((id_key(&manifest_id), id_key(&id)), Folder { name: name.unwrap_or_default(), parent: parent.map(|p| id_key(&p)) });
+ }
+
+ let mut paths = HashMap::new();
+ for (manifest_id, id) in folders.keys() {
+ let mut path = Vec::new();
+ let mut current = Some(id.clone());
+ while let Some(folder) = current.and_then(|folder_id| folders.get(&(manifest_id.clone(), folder_id))) {
+ if path.len() > MAX_FOLDER_DEPTH {
+ break;
+ }
+ path.insert(0, folder.name.clone());
+ current = folder.parent.clone();
+ }
+ paths.insert((manifest_id.clone(), id.clone()), path);
+ }
+ Ok(paths)
+}
diff --git a/core/rust/src/vault_items/logos.rs b/core/rust/src/vault_items/logos.rs
new file mode 100644
index 000000000..50fe11b79
--- /dev/null
+++ b/core/rust/src/vault_items/logos.rs
@@ -0,0 +1,74 @@
+//! Which logo an item gets when it is written.
+
+use rusqlite::{params, Connection, OptionalExtension};
+
+use super::sql_error;
+use crate::common::error::VaultResult;
+use crate::favicon::favicon_source_key;
+use crate::vault_codec::logo_id_for;
+
+const FAVICON: &str = "favicon";
+const FAVICON_MIME_TYPE: &str = "image/x-icon";
+
+const GET_BY_ID: &str = "SELECT Kind, Source FROM Logos WHERE Id = ?1 AND ManifestId = ?2 AND IsDeleted = 0";
+const GET_FAVICON_ID: &str = "SELECT Id FROM Logos WHERE ManifestId = ?1 AND Kind = 'favicon' AND Source = ?2 AND IsDeleted = 0 LIMIT 1";
+const GET_BEST_FAVICON: &str = "
+ SELECT FileData, MimeType FROM Logos
+ WHERE Kind = 'favicon' AND Source = ?1 AND IsDeleted = 0
+ ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC
+ LIMIT 1";
+const UPSERT_FAVICON: &str = "
+ INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?1, 'favicon', ?2, ?3, ?4, ?5, ?6, ?6, 0)
+ ON CONFLICT(ManifestId, Id) DO UPDATE SET
+ FileData = excluded.FileData,
+ MimeType = excluded.MimeType,
+ UpdatedAt = excluded.UpdatedAt,
+ IsDeleted = 0";
+const GET_ITEM_LOGO_ID: &str = "SELECT LogoId FROM Items WHERE Id = ?1 AND ManifestId = ?2";
+const SET_ITEM_LOGO_ID: &str = "UPDATE Items SET LogoId = ?1, UpdatedAt = ?2 WHERE Id = ?3 AND ManifestId = ?4";
+
+/// The logo id an item in `scope` should carry for `url`, or None to keep what it has (or have none on create).
+pub(super) fn resolve_logo_id(conn: &Connection, scope: &str, existing_logo_id: Option<&str>, url: &str, logo: Option<&[u8]>, now: &str) -> VaultResult<Option<String>> {
+ let source = favicon_source_key(url);
+ if let Some(id) = existing_logo_id {
+ let existing: Option<(String, String)> = conn.query_row(GET_BY_ID, params![id, scope], |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(sql_error)?;
+ // A logo the user chose, or this domain's favicon, stays.
+ if existing.is_some_and(|(kind, existing_source)| kind != FAVICON || existing_source == source) {
+ return Ok(Some(id.to_string()));
+ }
+ }
+ if source.is_empty() {
+ return Ok(None);
+ }
+ if let Some(bytes) = logo.filter(|bytes| !bytes.is_empty()) {
+ return upsert_favicon(conn, scope, &source, Some(bytes), Some(FAVICON_MIME_TYPE), now).map(Some);
+ }
+ favicon_in_scope(conn, scope, &source, now)
+}
+
+/// Point an existing item at the logo [`resolve_logo_id`] picks, when that differs from the one it has.
+pub(super) fn refresh_item_logo(conn: &Connection, item_id: &str, manifest_id: &str, url: &str, logo: Option<&[u8]>, now: &str) -> VaultResult<()> {
+ let current: Option<String> = conn.query_row(GET_ITEM_LOGO_ID, params![item_id, manifest_id], |row| row.get(0)).optional().map_err(sql_error)?.flatten();
+ let Some(logo_id) = resolve_logo_id(conn, manifest_id, current.as_deref(), url, logo, now)? else { return Ok(()) };
+ if current.as_deref() != Some(logo_id.as_str()) {
+ conn.execute(SET_ITEM_LOGO_ID, params![logo_id, now, item_id, manifest_id]).map_err(sql_error)?;
+ }
+ Ok(())
+}
+
+/// The id of the domain's favicon inside `manifest_id`, copied in from another manifest when it is not there yet; None when the vault has none.
+fn favicon_in_scope(conn: &Connection, manifest_id: &str, source: &str, now: &str) -> VaultResult<Option<String>> {
+ if let Some(id) = conn.query_row(GET_FAVICON_ID, params![manifest_id, source], |row| row.get(0)).optional().map_err(sql_error)? {
+ return Ok(Some(id));
+ }
+ let origin: Option<(Option<Vec<u8>>, Option<String>)> = conn.query_row(GET_BEST_FAVICON, params![source], |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(sql_error)?;
+ origin.map(|(data, mime_type)| upsert_favicon(conn, manifest_id, source, data.as_deref(), mime_type.as_deref(), now)).transpose()
+}
+
+/// Insert or refresh the domain's favicon in one manifest, under the id derived for that key.
+fn upsert_favicon(conn: &Connection, manifest_id: &str, source: &str, data: Option<&[u8]>, mime_type: Option<&str>, now: &str) -> VaultResult<String> {
+ let id = logo_id_for(manifest_id, FAVICON, source);
+ conn.execute(UPSERT_FAVICON, params![id, source, manifest_id, data, mime_type, now]).map_err(sql_error)?;
+ Ok(id)
+}
diff --git a/core/rust/src/vault_items/mod.rs b/core/rust/src/vault_items/mod.rs
new file mode 100644
index 000000000..f0d03eb74
--- /dev/null
+++ b/core/rust/src/vault_items/mod.rs
@@ -0,0 +1,162 @@
+//! Item, passkey, TOTP and usage-statistics reads and writes on an open vault database.
+
+mod items;
+mod logos;
+mod passkeys;
+mod stats;
+
+#[cfg(test)]
+mod tests;
+
+pub use items::{append_field_value, get_all_active_items, get_totp_codes_for_item};
+pub use passkeys::{
+ add_passkey_to_item, create_item_with_passkey, get_all_passkeys_with_items, get_items_without_passkey_for_rp_id, get_passkey_by_id,
+ get_passkey_in_manifest, get_passkeys_for_item, get_passkeys_for_rp_id, replace_passkey,
+};
+pub use stats::{record_item_use, ItemUsageAction};
+
+use rusqlite::types::ValueRef;
+use rusqlite::Row;
+use serde::Serialize;
+
+use crate::common::error::VaultError;
+use crate::common::timestamp::parse_vault_datetime;
+
+/// An active item with its fields, as the autofill layers read it.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct VaultItem {
+ pub id: String,
+ pub manifest_id: String,
+ pub name: Option<String>,
+ pub item_type: String,
+ /// The logo bytes; None for a built-in logo, which the host draws from its catalog by `logo_source`.
+ pub logo: Option<Vec<u8>>,
+ pub logo_kind: Option<String>,
+ pub logo_source: Option<String>,
+ pub folder_id: Option<String>,
+ /// Folder names from the root down to the item's folder; empty outside any folder.
+ pub folder_path: Vec<String>,
+ pub fields: Vec<VaultItemField>,
+ pub has_passkey: bool,
+ pub has_attachment: bool,
+ pub has_totp: bool,
+ pub created_at_ms: i64,
+ pub updated_at_ms: i64,
+}
+
+/// One value of an item field. A multi-value field yields one entry per value, in value order.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct VaultItemField {
+ /// The system field key, or the FieldDefinitionId of a custom field.
+ pub field_key: String,
+ /// The custom field's label; for a system field the key itself, which the UI translates.
+ pub label: String,
+ pub field_type: String,
+ pub value: String,
+ pub is_hidden: bool,
+ pub display_order: i64,
+ pub is_custom_field: bool,
+ pub enable_history: bool,
+}
+
+/// A stored passkey. The keys are JWK text.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct VaultPasskey {
+ pub id: String,
+ pub item_id: String,
+ pub manifest_id: String,
+ pub rp_id: String,
+ pub user_handle: Option<Vec<u8>>,
+ pub public_key: String,
+ pub private_key: String,
+ pub prf_key: Option<Vec<u8>>,
+ pub display_name: String,
+ pub additional_data: Option<Vec<u8>>,
+ pub created_at_ms: i64,
+ pub updated_at_ms: i64,
+}
+
+/// A passkey with the name and account of the item it belongs to.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct VaultPasskeyWithItem {
+ pub passkey: VaultPasskey,
+ pub service_name: Option<String>,
+ pub username: Option<String>,
+ pub email: Option<String>,
+}
+
+/// A passkey to write. The manifest and item come from the call it is passed to.
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+pub struct NewPasskey {
+ pub id: String,
+ pub rp_id: String,
+ pub user_handle: Option<Vec<u8>>,
+ pub public_key: String,
+ pub private_key: String,
+ pub prf_key: Option<Vec<u8>>,
+ pub display_name: String,
+}
+
+/// A Login item without a passkey that a new passkey could be added to.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct PasskeyMergeCandidate {
+ pub item_id: String,
+ pub manifest_id: String,
+ pub service_name: Option<String>,
+ pub urls: Vec<String>,
+ pub username: Option<String>,
+ pub email: Option<String>,
+ pub has_password: bool,
+ pub created_at_ms: i64,
+ pub updated_at_ms: i64,
+}
+
+/// A TOTP code of an item.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
+#[serde(rename_all = "camelCase")]
+pub struct VaultTotpCode {
+ pub id: String,
+ pub item_id: String,
+ pub name: String,
+ pub secret_key: String,
+ pub algorithm: String,
+ pub digits: u32,
+ pub period: u32,
+}
+
+/// A stored timestamp as Unix milliseconds, 0 when it cannot be read.
+fn timestamp_ms(text: Option<String>) -> i64 {
+ text.as_deref().and_then(parse_vault_datetime).map(|at| at.timestamp_millis()).unwrap_or(0)
+}
+
+/// A BLOB column's bytes, None for NULL or any other type.
+fn blob(row: &Row<'_>, column: &str) -> rusqlite::Result<Option<Vec<u8>>> {
+ Ok(match row.get_ref(column)? {
+ ValueRef::Blob(bytes) => Some(bytes.to_vec()),
+ _ => None,
+ })
+}
+
+/// A new lowercase v4 id.
+fn new_id() -> String {
+ let mut bytes = [0u8; 16];
+ crate::common::rng::fill_random(&mut bytes);
+ crate::common::encoding::uuid_from_bytes(bytes, 4)
+}
+
+/// The vault error for a failed statement.
+fn sql_error(error: rusqlite::Error) -> VaultError {
+ crate::sqlite_host::sql_error(error)
+}
diff --git a/core/rust/src/vault_items/passkeys.rs b/core/rust/src/vault_items/passkeys.rs
new file mode 100644
index 000000000..0359fc55f
--- /dev/null
+++ b/core/rust/src/vault_items/passkeys.rs
@@ -0,0 +1,234 @@
+//! Passkey reads and the passkey writes of the native authenticators.
+
+use std::collections::HashMap;
+
+use rusqlite::{params, Connection, OptionalExtension, Row};
+
+use super::items::insert_field_value;
+use super::logos::{refresh_item_logo, resolve_logo_id};
+use super::{blob, sql_error, timestamp_ms, NewPasskey, PasskeyMergeCandidate, VaultPasskey, VaultPasskeyWithItem};
+use crate::common::error::{VaultError, VaultResult};
+use crate::common::timestamp::now_vault_datetime;
+use crate::credential_matcher::{filter_credentials, AutofillMatchingMode, Credential, CredentialMatcherInput};
+use crate::vault_model::id_key;
+
+/// The passkey columns plus the name and account of the item, which must be live (not deleted, not in the trash).
+const SELECT_WITH_ITEM: &str = "
+ SELECT
+ p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey, p.DisplayName, p.AdditionalData,
+ p.CreatedAt, p.UpdatedAt,
+ i.Name AS ServiceName,
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0 ORDER BY fv.ValueIndex LIMIT 1) AS Username,
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.email' AND fv.IsDeleted = 0 ORDER BY fv.ValueIndex LIMIT 1) AS Email
+ FROM Passkeys p
+ INNER JOIN Items i ON i.Id = p.ItemId AND i.ManifestId = p.ManifestId AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ WHERE p.IsDeleted = 0";
+
+/// Live Login items that have no live passkey yet, newest change first.
+const GET_ITEMS_WITHOUT_PASSKEY: &str = "
+ SELECT
+ i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0 ORDER BY fv.ValueIndex LIMIT 1) AS Username,
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.email' AND fv.IsDeleted = 0 ORDER BY fv.ValueIndex LIMIT 1) AS Email,
+ EXISTS (SELECT 1 FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.password' AND fv.IsDeleted = 0 AND fv.Value <> '') AS HasPassword
+ FROM Items i
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL AND i.ItemType = 'Login'
+ AND NOT EXISTS (SELECT 1 FROM Passkeys p WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0)
+ ORDER BY i.UpdatedAt DESC";
+
+/// The live URLs of every item, in value order.
+const GET_ALL_URLS: &str = "SELECT ItemId, ManifestId, Value FROM FieldValues WHERE FieldKey = 'login.url' AND IsDeleted = 0 ORDER BY ValueIndex";
+
+const INSERT_ITEM: &str = "
+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
+ VALUES (?1, ?2, 'Login', ?3, NULL, ?4, ?4, 0, ?5)";
+
+const INSERT_PASSKEY: &str = "
+ INSERT INTO Passkeys (Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, NULL, ?10, ?10, 0)";
+
+const SOFT_DELETE_PASSKEY: &str = "UPDATE Passkeys SET IsDeleted = 1, UpdatedAt = ?1 WHERE Id = ?2 AND ManifestId = ?3";
+
+/// The passkey with this credential id in any manifest, newest first when several manifests hold it.
+pub fn get_passkey_by_id(conn: &Connection, passkey_id: &str) -> VaultResult<Option<VaultPasskeyWithItem>> {
+ let sql = format!("{SELECT_WITH_ITEM} AND p.Id = ?1 ORDER BY p.CreatedAt DESC, p.ManifestId LIMIT 1");
+ conn.query_row(&sql, params![id_key(passkey_id)], passkey_with_item).optional().map_err(sql_error)
+}
+
+/// The passkey with this id inside one manifest.
+pub fn get_passkey_in_manifest(conn: &Connection, passkey_id: &str, manifest_id: &str) -> VaultResult<Option<VaultPasskeyWithItem>> {
+ let sql = format!("{SELECT_WITH_ITEM} AND p.Id = ?1 AND p.ManifestId = ?2");
+ conn.query_row(&sql, params![id_key(passkey_id), manifest_id], passkey_with_item).optional().map_err(sql_error)
+}
+
+/// The passkeys of one item, newest first.
+pub fn get_passkeys_for_item(conn: &Connection, item_id: &str, manifest_id: &str) -> VaultResult<Vec<VaultPasskey>> {
+ let sql = format!("{SELECT_WITH_ITEM} AND p.ItemId = ?1 AND p.ManifestId = ?2 ORDER BY p.CreatedAt DESC");
+ let rows = query_with_item(conn, &sql, params![id_key(item_id), manifest_id])?;
+ Ok(rows.into_iter().map(|row| row.passkey).collect())
+}
+
+/// The passkeys for a relying party, newest first, narrowed to an account when `user_name` or `user_handle` is given.
+pub fn get_passkeys_for_rp_id(conn: &Connection, rp_id: &str, user_name: Option<&str>, user_handle: Option<&[u8]>) -> VaultResult<Vec<VaultPasskeyWithItem>> {
+ let sql = format!("{SELECT_WITH_ITEM} AND p.RpId = ?1 ORDER BY p.CreatedAt DESC, p.ManifestId");
+ let rows = query_with_item(conn, &sql, params![rp_id])?;
+ Ok(rows
+ .into_iter()
+ .filter(|row| user_name.is_none_or(|name| row.username.as_deref() == Some(name)))
+ .filter(|row| user_handle.is_none_or(|handle| row.passkey.user_handle.as_deref() == Some(handle)))
+ .collect())
+}
+
+/// Every passkey whose item is live, newest first.
+pub fn get_all_passkeys_with_items(conn: &Connection) -> VaultResult<Vec<VaultPasskeyWithItem>> {
+ let sql = format!("{SELECT_WITH_ITEM} ORDER BY p.CreatedAt DESC, p.ManifestId");
+ query_with_item(conn, &sql, [])
+}
+
+/// The Login items without a passkey that match a relying party, best match first, which a new passkey could be added to.
+pub fn get_items_without_passkey_for_rp_id(conn: &Connection, rp_id: &str, rp_name: Option<&str>, user_name: Option<&str>) -> VaultResult<Vec<PasskeyMergeCandidate>> {
+ if rp_id.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let mut urls = urls_by_item(conn)?;
+ let mut statement = conn.prepare_cached(GET_ITEMS_WITHOUT_PASSKEY).map_err(sql_error)?;
+ let candidates: Vec<PasskeyMergeCandidate> = statement
+ .query_map([], |row| {
+ let item_id: String = row.get("Id")?;
+ let manifest_id: String = row.get("ManifestId")?;
+ Ok(PasskeyMergeCandidate {
+ urls: urls.remove(&(id_key(&manifest_id), id_key(&item_id))).unwrap_or_default(),
+ service_name: row.get("Name")?,
+ username: row.get("Username")?,
+ email: row.get("Email")?,
+ has_password: row.get("HasPassword")?,
+ created_at_ms: timestamp_ms(row.get("CreatedAt")?),
+ updated_at_ms: timestamp_ms(row.get("UpdatedAt")?),
+ item_id,
+ manifest_id,
+ })
+ })
+ .map_err(sql_error)?
+ .collect::<Result<_, _>>()
+ .map_err(sql_error)?;
+
+ // The matcher sees each candidate under its position, so an item id held by two manifests stays two candidates.
+ let credentials = candidates
+ .iter()
+ .enumerate()
+ .map(|(index, candidate)| Credential { id: index.to_string(), item_name: candidate.service_name.clone(), item_urls: candidate.urls.clone(), username: candidate.username.clone() })
+ .collect();
+ let output = filter_credentials(CredentialMatcherInput {
+ credentials,
+ current_url: format!("https://{rp_id}"),
+ page_title: rp_name.unwrap_or_default().to_string(),
+ matching_mode: AutofillMatchingMode::UrlSubdomain,
+ ignore_port: false,
+ max_results: None,
+ });
+
+ Ok(output
+ .matched_ids
+ .iter()
+ .filter_map(|id| id.parse::<usize>().ok().and_then(|index| candidates.get(index)))
+ .filter(|candidate| user_name.is_none_or(|name| candidate.username.as_deref() == Some(name)))
+ .cloned()
+ .collect())
+}
+
+/// Create a Login item in `manifest_id` that holds a new passkey, with its URL, username and favicon.
+#[allow(clippy::too_many_arguments)]
+pub fn create_item_with_passkey(
+ conn: &Connection,
+ manifest_id: &str,
+ item_id: &str,
+ item_name: &str,
+ url: &str,
+ user_name: Option<&str>,
+ passkey: &NewPasskey,
+ logo: Option<&[u8]>,
+) -> VaultResult<()> {
+ let now = now_vault_datetime();
+ let item_id = id_key(item_id);
+ let logo_id = resolve_logo_id(conn, manifest_id, None, url, logo, &now)?;
+ conn.execute(INSERT_ITEM, params![item_id, item_name, logo_id, now, manifest_id]).map_err(sql_error)?;
+ if !url.is_empty() {
+ insert_field_value(conn, &item_id, manifest_id, "login.url", url, &now)?;
+ }
+ if let Some(user_name) = user_name.filter(|name| !name.is_empty()) {
+ insert_field_value(conn, &item_id, manifest_id, "login.username", user_name, &now)?;
+ }
+ insert_passkey(conn, &item_id, manifest_id, passkey, &now)
+}
+
+/// Add a new passkey to an existing item, refreshing the item's favicon for `url`.
+pub fn add_passkey_to_item(conn: &Connection, item_id: &str, manifest_id: &str, passkey: &NewPasskey, url: &str, logo: Option<&[u8]>) -> VaultResult<()> {
+ let now = now_vault_datetime();
+ let item_id = id_key(item_id);
+ refresh_item_logo(conn, &item_id, manifest_id, url, logo, &now)?;
+ insert_passkey(conn, &item_id, manifest_id, passkey, &now)
+}
+
+/// Replace a passkey with a new one on the same item, refreshing the item's favicon for `url`. Returns the item id.
+pub fn replace_passkey(conn: &Connection, old_passkey_id: &str, manifest_id: &str, passkey: &NewPasskey, url: &str, logo: Option<&[u8]>) -> VaultResult<String> {
+ let old = get_passkey_in_manifest(conn, old_passkey_id, manifest_id)?.ok_or_else(|| VaultError::General(format!("Passkey not found: {old_passkey_id}")))?;
+ let now = now_vault_datetime();
+ let item_id = old.passkey.item_id;
+ refresh_item_logo(conn, &item_id, manifest_id, url, logo, &now)?;
+ conn.execute(SOFT_DELETE_PASSKEY, params![now, old.passkey.id, manifest_id]).map_err(sql_error)?;
+ insert_passkey(conn, &item_id, manifest_id, passkey, &now)?;
+ Ok(item_id)
+}
+
+fn insert_passkey(conn: &Connection, item_id: &str, manifest_id: &str, passkey: &NewPasskey, now: &str) -> VaultResult<()> {
+ conn.execute(
+ INSERT_PASSKEY,
+ params![id_key(&passkey.id), item_id, manifest_id, passkey.rp_id, passkey.user_handle, passkey.public_key, passkey.private_key, passkey.prf_key, passkey.display_name, now],
+ )
+ .map_err(sql_error)?;
+ Ok(())
+}
+
+fn query_with_item<P: rusqlite::Params>(conn: &Connection, sql: &str, params: P) -> VaultResult<Vec<VaultPasskeyWithItem>> {
+ let mut statement = conn.prepare_cached(sql).map_err(sql_error)?;
+ let rows = statement.query_map(params, passkey_with_item).map_err(sql_error)?;
+ rows.collect::<Result<_, _>>().map_err(sql_error)
+}
+
+fn passkey_with_item(row: &Row<'_>) -> rusqlite::Result<VaultPasskeyWithItem> {
+ Ok(VaultPasskeyWithItem {
+ passkey: VaultPasskey {
+ id: row.get("Id")?,
+ item_id: row.get("ItemId")?,
+ manifest_id: row.get("ManifestId")?,
+ rp_id: row.get("RpId")?,
+ user_handle: blob(row, "UserHandle")?,
+ public_key: row.get("PublicKey")?,
+ private_key: row.get("PrivateKey")?,
+ prf_key: blob(row, "PrfKey")?,
+ display_name: row.get::<_, Option<String>>("DisplayName")?.unwrap_or_default(),
+ additional_data: blob(row, "AdditionalData")?,
+ created_at_ms: timestamp_ms(row.get("CreatedAt")?),
+ updated_at_ms: timestamp_ms(row.get("UpdatedAt")?),
+ },
+ service_name: row.get("ServiceName")?,
+ username: row.get("Username")?,
+ email: row.get("Email")?,
+ })
+}
+
+/// The live URLs of every item, keyed by (manifest, item).
+fn urls_by_item(conn: &Connection) -> VaultResult<HashMap<(String, String), Vec<String>>> {
+ let mut statement = conn.prepare_cached(GET_ALL_URLS).map_err(sql_error)?;
+ let mut rows = statement.query([]).map_err(sql_error)?;
+ let mut urls: HashMap<(String, String), Vec<String>> = HashMap::new();
+ while let Some(row) = rows.next().map_err(sql_error)? {
+ let item_id: String = row.get(0).map_err(sql_error)?;
+ let manifest_id: String = row.get(1).map_err(sql_error)?;
+ if let Some(value) = row.get::<_, Option<String>>(2).map_err(sql_error)?.filter(|value| !value.is_empty()) {
+ urls.entry((id_key(&manifest_id), id_key(&item_id))).or_default().push(value);
+ }
+ }
+ Ok(urls)
+}
diff --git a/core/rust/src/vault_items/stats.rs b/core/rust/src/vault_items/stats.rs
new file mode 100644
index 000000000..eac69bc60
--- /dev/null
+++ b/core/rust/src/vault_items/stats.rs
@@ -0,0 +1,52 @@
+//! Per-item usage statistics.
+
+use rusqlite::{params, Connection, OptionalExtension};
+
+use super::sql_error;
+use crate::common::error::VaultResult;
+use crate::common::timestamp::now_vault_datetime;
+
+/// What the user did with an item. Each action bumps its own timestamp and counter next to the aggregate pair.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
+pub enum ItemUsageAction {
+ /// A credential filled into a form.
+ Autofill,
+ /// A value copied to the clipboard.
+ Copy,
+ /// A passkey assertion.
+ Passkey,
+}
+
+impl ItemUsageAction {
+ /// The UPDATE for this action. The column names are a closed set, never caller input.
+ fn update_sql(self) -> &'static str {
+ match self {
+ Self::Autofill => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastAutofilledAt = ?1, AutofillCount = AutofillCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",
+ Self::Copy => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastCopiedAt = ?1, CopyCount = CopyCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",
+ Self::Passkey => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastPasskeyAuthAt = ?1, PasskeyAuthCount = PasskeyAuthCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",
+ }
+ }
+}
+
+const ITEM_EXISTS: &str = "SELECT 1 FROM Items WHERE Id = ?1 AND ManifestId = ?2";
+
+const INSERT_ROW: &str = "
+ INSERT OR IGNORE INTO ItemStats (
+ ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,
+ LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted
+ )
+ VALUES (?1, ?2, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?3, ?3, 0)";
+
+/// Record one use of an item. Returns false, writing nothing, when the item does not exist. Clearing
+/// `IsDeleted` revives a row the pruner tombstoned.
+pub fn record_item_use(conn: &Connection, item_id: &str, manifest_id: &str, action: ItemUsageAction) -> VaultResult<bool> {
+ let item_id = crate::vault_model::id_key(item_id);
+ if conn.query_row(ITEM_EXISTS, params![item_id, manifest_id], |_| Ok(())).optional().map_err(sql_error)?.is_none() {
+ return Ok(false);
+ }
+ let now = now_vault_datetime();
+ conn.execute(INSERT_ROW, params![manifest_id, item_id, now]).map_err(sql_error)?;
+ conn.execute(action.update_sql(), params![now, manifest_id, item_id]).map_err(sql_error)?;
+ Ok(true)
+}
diff --git a/core/rust/src/vault_items/tests.rs b/core/rust/src/vault_items/tests.rs
new file mode 100644
index 000000000..4541abc10
--- /dev/null
+++ b/core/rust/src/vault_items/tests.rs
@@ -0,0 +1,212 @@
+use rusqlite::{params, Connection};
+
+use super::*;
+use crate::sqlite_host::MemoryDatabase;
+use crate::vault_codec::logo_id_for;
+
+const PERSONAL: &str = "11111111-1111-4111-8111-111111111111";
+const SHARED: &str = "22222222-2222-4222-8222-222222222222";
+const ITEM: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+const T0: &str = "2026-01-01 10:00:00.000";
+const T1: &str = "2026-01-02 10:00:00.000";
+
+fn with_vault<R>(f: impl FnOnce(&Connection) -> R) -> R {
+ let db = MemoryDatabase::with_latest_schema().unwrap();
+ db.with_connection(|conn| Ok(f(conn))).unwrap()
+}
+
+fn insert_item(conn: &Connection, manifest_id: &str, id: &str, name: &str, created_at: &str) {
+ conn.execute(
+ "INSERT INTO Items (Id, ManifestId, Name, ItemType, CreatedAt, UpdatedAt, IsDeleted) VALUES (?1, ?2, ?3, 'Login', ?4, ?4, 0)",
+ params![id, manifest_id, name, created_at],
+ )
+ .unwrap();
+}
+
+fn insert_value(conn: &Connection, manifest_id: &str, item_id: &str, field_key: &str, value: &str, value_index: i64) {
+ conn.execute(
+ "INSERT INTO FieldValues (Id, ManifestId, ItemId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, 0)",
+ params![new_id(), manifest_id, item_id, field_key, value, crate::vault_model::system_field(field_key).map_or(0, |f| f.default_display_order), value_index, T0],
+ )
+ .unwrap();
+}
+
+fn new_passkey(id: &str, rp_id: &str, user_handle: &[u8]) -> NewPasskey {
+ NewPasskey {
+ id: id.to_string(),
+ rp_id: rp_id.to_string(),
+ user_handle: Some(user_handle.to_vec()),
+ public_key: "{\"kty\":\"EC\"}".to_string(),
+ private_key: "{\"kty\":\"EC\",\"d\":\"x\"}".to_string(),
+ prf_key: None,
+ display_name: "me".to_string(),
+ }
+}
+
+#[test]
+fn active_items_carry_registry_metadata_and_skip_unknown_system_fields() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ insert_value(conn, PERSONAL, ITEM, "login.password", "secret", 0);
+ insert_value(conn, PERSONAL, ITEM, "login.url", "https://a.example.com", 0);
+ insert_value(conn, PERSONAL, ITEM, "login.url", "https://b.example.com", 1);
+ insert_value(conn, PERSONAL, ITEM, "future.field", "x", 0);
+
+ let items = get_all_active_items(conn).unwrap();
+ assert_eq!(items.len(), 1);
+ let keys: Vec<(&str, &str)> = items[0].fields.iter().map(|f| (f.field_key.as_str(), f.value.as_str())).collect();
+ assert_eq!(keys, vec![("login.url", "https://a.example.com"), ("login.url", "https://b.example.com"), ("login.password", "secret")]);
+
+ let password = &items[0].fields[2];
+ assert_eq!((password.field_type.as_str(), password.is_hidden, password.enable_history, password.display_order), ("Password", true, true, 20));
+ assert_eq!(items[0].created_at_ms, 1_767_261_600_000);
+ });
+}
+
+#[test]
+fn active_items_keep_two_manifests_apart_and_leave_out_trash_and_archive() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Personal", T0);
+ insert_item(conn, SHARED, ITEM, "Shared", T1);
+ insert_value(conn, SHARED, ITEM, "login.username", "shared-user", 0);
+ insert_item(conn, PERSONAL, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", "Trashed", T0);
+ conn.execute("UPDATE Items SET DeletedAt = ?1 WHERE Name = 'Trashed'", [T1]).unwrap();
+ insert_item(conn, PERSONAL, "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "Archived", T0);
+ conn.execute("UPDATE Items SET ArchivedAt = ?1 WHERE Name = 'Archived'", [T1]).unwrap();
+
+ let items = get_all_active_items(conn).unwrap();
+ let names: Vec<_> = items.iter().map(|i| (i.name.clone().unwrap(), i.fields.len())).collect();
+ assert_eq!(names, vec![("Shared".to_string(), 1), ("Personal".to_string(), 0)]);
+ });
+}
+
+#[test]
+fn folder_paths_resolve_within_the_item_manifest() {
+ with_vault(|conn| {
+ let parent = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
+ let child = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
+ for (manifest_id, id, name, parent_id) in [(PERSONAL, parent, "Work", None), (PERSONAL, child, "Mail", Some(parent)), (SHARED, parent, "Other", None)] {
+ conn.execute(
+ "INSERT INTO Folders (Id, ManifestId, Name, ParentFolderId, Weight, CreatedAt, UpdatedAt, IsDeleted) VALUES (?1, ?2, ?3, ?4, 0, ?5, ?5, 0)",
+ params![id, manifest_id, name, parent_id, T0],
+ )
+ .unwrap();
+ }
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ conn.execute("UPDATE Items SET FolderId = ?1", [child]).unwrap();
+
+ assert_eq!(get_all_active_items(conn).unwrap()[0].folder_path, vec!["Work", "Mail"]);
+ });
+}
+
+#[test]
+fn passkey_item_is_created_with_url_username_and_favicon() {
+ with_vault(|conn| {
+ let passkey = new_passkey("ABCDEF00-0000-4000-8000-000000000001", "example.com", b"user-1");
+ create_item_with_passkey(conn, PERSONAL, ITEM, "Example", "https://example.com", Some("alice"), &passkey, Some(b"icon")).unwrap();
+
+ let item = &get_all_active_items(conn).unwrap()[0];
+ assert!(item.has_passkey);
+ assert_eq!(item.logo.as_deref(), Some(&b"icon"[..]));
+ let weights: Vec<i64> = conn.prepare("SELECT Weight FROM FieldValues ORDER BY Weight").unwrap().query_map([], |r| r.get(0)).unwrap().map(Result::unwrap).collect();
+ assert_eq!(weights, vec![5, 15]);
+
+ let found = get_passkeys_for_rp_id(conn, "example.com", Some("alice"), Some(b"user-1")).unwrap();
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].passkey.id, "abcdef00-0000-4000-8000-000000000001");
+ assert_eq!(found[0].service_name.as_deref(), Some("Example"));
+ assert!(get_passkeys_for_rp_id(conn, "example.com", None, Some(b"user-2")).unwrap().is_empty());
+ assert!(get_passkey_by_id(conn, "ABCDEF00-0000-4000-8000-000000000001").unwrap().is_some());
+ });
+}
+
+#[test]
+fn replacing_a_passkey_keeps_the_item_and_drops_the_old_key() {
+ with_vault(|conn| {
+ create_item_with_passkey(conn, PERSONAL, ITEM, "Example", "https://example.com", None, &new_passkey("00000000-0000-4000-8000-000000000001", "example.com", b"u"), None).unwrap();
+ let item_id = replace_passkey(conn, "00000000-0000-4000-8000-000000000001", PERSONAL, &new_passkey("00000000-0000-4000-8000-000000000002", "example.com", b"u"), "https://example.com", None).unwrap();
+
+ assert_eq!(item_id, ITEM);
+ let ids: Vec<String> = get_passkeys_for_item(conn, ITEM, PERSONAL).unwrap().into_iter().map(|p| p.id).collect();
+ assert_eq!(ids, vec!["00000000-0000-4000-8000-000000000002"]);
+ assert!(replace_passkey(conn, "00000000-0000-4000-8000-000000000009", PERSONAL, &new_passkey("00000000-0000-4000-8000-000000000003", "example.com", b"u"), "", None).is_err());
+ });
+}
+
+#[test]
+fn a_favicon_from_another_manifest_is_copied_into_the_item_manifest() {
+ with_vault(|conn| {
+ create_item_with_passkey(conn, SHARED, ITEM, "Shared", "https://example.com", None, &new_passkey("00000000-0000-4000-8000-000000000001", "example.com", b"u"), Some(b"icon")).unwrap();
+ create_item_with_passkey(conn, PERSONAL, ITEM, "Personal", "https://example.com", None, &new_passkey("00000000-0000-4000-8000-000000000002", "example.com", b"u"), None).unwrap();
+
+ let logo_id: String = conn.query_row("SELECT LogoId FROM Items WHERE ManifestId = ?1", [PERSONAL], |r| r.get(0)).unwrap();
+ assert_eq!(logo_id, logo_id_for(PERSONAL, "favicon", "example.com"));
+ let personal = get_all_active_items(conn).unwrap().into_iter().find(|i| i.manifest_id == PERSONAL).unwrap();
+ assert_eq!(personal.logo.as_deref(), Some(&b"icon"[..]));
+ });
+}
+
+#[test]
+fn adding_a_passkey_keeps_a_chosen_logo_and_the_domain_favicon() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ let builtin = logo_id_for(PERSONAL, "builtin", "github");
+ conn.execute("INSERT INTO Logos (Id, Kind, Source, ManifestId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?1, 'builtin', 'github', ?2, ?3, ?3, 0)", params![builtin, PERSONAL, T0]).unwrap();
+ conn.execute("UPDATE Items SET LogoId = ?1", [&builtin]).unwrap();
+ add_passkey_to_item(conn, ITEM, PERSONAL, &new_passkey("00000000-0000-4000-8000-000000000001", "example.com", b"u"), "https://example.com", Some(b"icon")).unwrap();
+ let logo_id: String = conn.query_row("SELECT LogoId FROM Items", [], |r| r.get(0)).unwrap();
+ assert_eq!(logo_id, builtin);
+
+ conn.execute("UPDATE Items SET LogoId = NULL", []).unwrap();
+ add_passkey_to_item(conn, ITEM, PERSONAL, &new_passkey("00000000-0000-4000-8000-000000000002", "example.com", b"u"), "https://example.com", Some(b"icon")).unwrap();
+ add_passkey_to_item(conn, ITEM, PERSONAL, &new_passkey("00000000-0000-4000-8000-000000000003", "example.com", b"u"), "https://example.com", Some(b"newer")).unwrap();
+ assert_eq!(get_all_active_items(conn).unwrap()[0].logo.as_deref(), Some(&b"icon"[..]));
+ });
+}
+
+#[test]
+fn merge_candidates_are_matched_by_rp_id_and_stay_apart_per_manifest() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ insert_value(conn, PERSONAL, ITEM, "login.url", "https://example.com/login", 0);
+ insert_item(conn, SHARED, ITEM, "Example shared", T1);
+ insert_value(conn, SHARED, ITEM, "login.url", "https://example.com", 0);
+ insert_value(conn, SHARED, ITEM, "login.username", "bob", 0);
+ insert_item(conn, PERSONAL, "ffffffff-ffff-4fff-8fff-ffffffffffff", "Other", T0);
+ insert_value(conn, PERSONAL, "ffffffff-ffff-4fff-8fff-ffffffffffff", "login.url", "https://other.org", 0);
+
+ let candidates = get_items_without_passkey_for_rp_id(conn, "example.com", None, None).unwrap();
+ let mut manifests: Vec<&str> = candidates.iter().map(|c| c.manifest_id.as_str()).collect();
+ manifests.sort();
+ assert_eq!(manifests, vec![PERSONAL, SHARED]);
+
+ let bob = get_items_without_passkey_for_rp_id(conn, "example.com", None, Some("bob")).unwrap();
+ assert_eq!(bob.len(), 1);
+ assert_eq!(bob[0].manifest_id, SHARED);
+ });
+}
+
+#[test]
+fn recording_a_use_counts_per_action_and_ignores_missing_items() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ assert!(record_item_use(conn, ITEM, PERSONAL, ItemUsageAction::Autofill).unwrap());
+ assert!(record_item_use(conn, ITEM, PERSONAL, ItemUsageAction::Passkey).unwrap());
+ assert!(!record_item_use(conn, ITEM, SHARED, ItemUsageAction::Copy).unwrap());
+
+ let counts: (i64, i64, i64) = conn.query_row("SELECT UseCount, AutofillCount, PasskeyAuthCount FROM ItemStats", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).unwrap();
+ assert_eq!(counts, (2, 1, 1));
+ });
+}
+
+#[test]
+fn appended_values_go_after_the_existing_ones() {
+ with_vault(|conn| {
+ insert_item(conn, PERSONAL, ITEM, "Example", T0);
+ insert_value(conn, PERSONAL, ITEM, "login.url", "https://a.example.com", 0);
+ append_field_value(conn, ITEM, PERSONAL, "login.url", "https://b.example.com").unwrap();
+
+ let urls: Vec<String> = get_all_active_items(conn).unwrap()[0].fields.iter().map(|f| f.value.clone()).collect();
+ assert_eq!(urls, vec!["https://a.example.com", "https://b.example.com"]);
+ });
+}
diff --git a/core/rust/src/vault_model/generated.rs b/core/rust/src/vault_model/generated.rs
index 060fd9eae..85c759e9c 100644
--- a/core/rust/src/vault_model/generated.rs
+++ b/core/rust/src/vault_model/generated.rs
@@ -4,7 +4,7 @@
//! core/models/src/vault/VaultTableRegistry.ts by core/models/scripts/generate-vault-table-registry.cjs.
//! Edit the TypeScript source and run 'core/models/build.sh' to regenerate.
-use super::{BlobColumn, TableConfig};
+use super::{BlobColumn, SystemField, TableConfig};
/// All tables that need LWW merge, in registry order. Order matters: a merge inserts rows
/// in this order, so child tables must be listed after the table they reference (Items first).
@@ -84,6 +84,25 @@ pub static PERSONAL_TABLES: &[&str] = &[];
/// adding two different things) and is not derived.
pub static MULTI_VALUE_FIELD_KEYS: &[&str] = &["login.url"];
+/// The system fields and their metadata, from SystemFieldRegistry, in registry order.
+pub static SYSTEM_FIELDS: &[SystemField] = &[
+ SystemField { key: "login.email", field_type: "Email", is_hidden: false, is_multi_value: false, enable_history: true, default_display_order: 10 },
+ SystemField { key: "login.username", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: true, default_display_order: 15 },
+ SystemField { key: "login.password", field_type: "Password", is_hidden: true, is_multi_value: false, enable_history: true, default_display_order: 20 },
+ SystemField { key: "login.url", field_type: "URL", is_hidden: false, is_multi_value: true, enable_history: false, default_display_order: 5 },
+ SystemField { key: "alias.first_name", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 20 },
+ SystemField { key: "alias.last_name", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 30 },
+ SystemField { key: "alias.gender", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 50 },
+ SystemField { key: "alias.birthdate", field_type: "Date", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 60 },
+ SystemField { key: "card.cardholder_name", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 10 },
+ SystemField { key: "card.number", field_type: "Hidden", is_hidden: true, is_multi_value: false, enable_history: false, default_display_order: 20 },
+ SystemField { key: "card.expiry_month", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 30 },
+ SystemField { key: "card.expiry_year", field_type: "Text", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 40 },
+ SystemField { key: "card.cvv", field_type: "Hidden", is_hidden: true, is_multi_value: false, enable_history: false, default_display_order: 50 },
+ SystemField { key: "card.pin", field_type: "Hidden", is_hidden: true, is_multi_value: false, enable_history: false, default_display_order: 60 },
+ SystemField { key: "notes.content", field_type: "TextArea", is_hidden: false, is_multi_value: false, enable_history: false, default_display_order: 100 },
+];
+
/// System field keys whose field holds one value. A key in neither list is a field this build does
/// not know (a newer writer's), whose rows the codec leaves as it found them.
pub static SINGLE_VALUE_FIELD_KEYS: &[&str] = &["login.email", "login.username", "login.password", "alias.first_name", "alias.last_name", "alias.gender", "alias.birthdate", "card.cardholder_name", "card.number", "card.expiry_month", "card.expiry_year", "card.cvv", "card.pin", "notes.content"];
diff --git a/core/rust/src/vault_model/mod.rs b/core/rust/src/vault_model/mod.rs
index 892b48d46..1671b333d 100644
--- a/core/rust/src/vault_model/mod.rs
+++ b/core/rust/src/vault_model/mod.rs
@@ -18,6 +18,22 @@ pub fn ids_equal(a: &str, b: &str) -> bool {
a.trim().eq_ignore_ascii_case(b.trim())
}
+/// A system field and the metadata every client reads it with.
+#[derive(Debug, Clone)]
+pub struct SystemField {
+ pub key: &'static str,
+ pub field_type: &'static str,
+ pub is_hidden: bool,
+ pub is_multi_value: bool,
+ pub enable_history: bool,
+ pub default_display_order: i64,
+}
+
+/// The system field with this key (case-insensitive), or None for a key this build does not know.
+pub fn system_field(key: &str) -> Option<&'static SystemField> {
+ SYSTEM_FIELDS.iter().find(|field| field.key.eq_ignore_ascii_case(key))
+}
+
/// A column whose bytes are extracted into a content-addressed blob.
#[derive(Debug, Clone)]
pub struct BlobColumn {
diff --git a/core/rust/src/vault_sync/tests/test_host.rs b/core/rust/src/vault_sync/tests/test_host.rs
index 16a64d554..6228ecd1d 100644
--- a/core/rust/src/vault_sync/tests/test_host.rs
+++ b/core/rust/src/vault_sync/tests/test_host.rs
@@ -45,13 +45,9 @@ pub struct TestHost {
pub logs: Vec<String>,
}
-/// The current client schema, read from the TypeScript source of truth.
+/// The current client schema.
pub fn complete_schema_sql() -> String {
- let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../vault/src/sql/SqlConstants.ts");
- let source = std::fs::read_to_string(path).expect("core/vault/src/sql/SqlConstants.ts");
- let start = source.find("COMPLETE_SCHEMA_SQL = `").expect("COMPLETE_SCHEMA_SQL") + "COMPLETE_SCHEMA_SQL = `".len();
- let end = source[start..].find("`;").expect("end of template literal") + start;
- source[start..end].replace('\u{feff}', "")
+ sqlite_host::VAULT_SCHEMA_SQL.to_string()
}
/// Open a database from its file bytes, in memory.
diff --git a/core/vault/build.sh b/core/vault/build.sh
index 7abe4e07b..9b280885b 100755
--- a/core/vault/build.sh
+++ b/core/vault/build.sh
@@ -10,7 +10,7 @@ echo "📦 Building $package_name..."
npm install && npm run lint && npm run test && npm run build
echo ""
-echo "🔄 Generating platform-specific vault SQL (Swift, Kotlin)..."
+echo "🔄 Generating the vault schema for the Rust core..."
node scripts/generate-vault-sql.cjs
echo "✅ Vault build completed."
diff --git a/core/vault/scripts/generate-vault-sql.cjs b/core/vault/scripts/generate-vault-sql.cjs
index dd01b0e82..1510dfba6 100644
--- a/core/vault/scripts/generate-vault-sql.cjs
+++ b/core/vault/scripts/generate-vault-sql.cjs
@@ -1,462 +1,40 @@
#!/usr/bin/env node
/**
- * Generates VaultVersions and VaultSql for Swift and Kotlin from TypeScript source.
- * This allows native iOS and Android code to create vaults with the correct SQL schema.
+ * Writes the complete vault schema from the TypeScript source to a .sql file that the Rust core embeds,
+ * so the native apps open a vault on the latest schema through SqliteMemoryDatabase.withLatestSchema().
*/
const fs = require('fs');
const path = require('path');
-// Paths
const REPO_ROOT = path.join(__dirname, '../../..');
-const TS_VERSIONS_SOURCE = path.join(REPO_ROOT, 'core/vault/src/sql/VaultVersions.ts');
const TS_SQL_SOURCE = path.join(REPO_ROOT, 'core/vault/src/sql/SqlConstants.ts');
-
-// Output paths
-// Note: VaultModels is a framework that can be imported by other targets (including AliasVaultUITests)
-const SWIFT_OUTPUT_DIR = path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels');
-const KOTLIN_OUTPUT_DIR = path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models');
-
-/**
- * Parse VaultVersions from TypeScript source
- */
-function parseVaultVersions(tsContent) {
- const versions = [];
-
- // Find the VAULT_VERSIONS array
- const match = tsContent.match(/export const VAULT_VERSIONS[^=]*=\s*\[([\s\S]*?)\];/);
- if (!match) {
- throw new Error('Could not find VAULT_VERSIONS in source');
- }
-
- const body = match[1];
-
- // Match each version object
- const versionRegex = /\{\s*revision:\s*(\d+),\s*version:\s*'([^']+)',\s*description:\s*'([^']+)',\s*releaseVersion:\s*'([^']+)',\s*compatibleUpToVersion:\s*'([^']+)',?\s*\}/g;
- let versionMatch;
-
- while ((versionMatch = versionRegex.exec(body)) !== null) {
- versions.push({
- revision: parseInt(versionMatch[1], 10),
- version: versionMatch[2],
- description: versionMatch[3],
- releaseVersion: versionMatch[4],
- compatibleUpToVersion: versionMatch[5]
- });
- }
-
- return versions;
-}
+const SQL_OUTPUT = path.join(REPO_ROOT, 'core/rust/src/sqlite_host/vault_schema.sql');
/**
* Parse COMPLETE_SCHEMA_SQL from TypeScript source
*/
function parseCompleteSchemaSql(tsContent) {
- // Find the COMPLETE_SCHEMA_SQL constant
const match = tsContent.match(/export const COMPLETE_SCHEMA_SQL\s*=\s*`([\s\S]*?)`;/);
if (!match) {
throw new Error('Could not find COMPLETE_SCHEMA_SQL in source');
}
- return match[1].trim();
-}
-
-/**
- * Parse MIGRATION_SCRIPTS from TypeScript source
- */
-function parseMigrationScripts(tsContent) {
- const migrations = {};
-
- // Find the MIGRATION_SCRIPTS object
- const match = tsContent.match(/export const MIGRATION_SCRIPTS:\s*Record<number,\s*string>\s*=\s*\{([\s\S]*?)\n\};/);
- if (!match) {
- // MIGRATION_SCRIPTS might be optional or have different format
- console.log('Note: MIGRATION_SCRIPTS not found or has different format');
- return migrations;
- }
-
- const body = match[1];
-
- // Match each migration: number: `sql`
- const migrationRegex = /(\d+):\s*`([\s\S]*?)`/g;
- let migrationMatch;
-
- while ((migrationMatch = migrationRegex.exec(body)) !== null) {
- migrations[parseInt(migrationMatch[1], 10)] = migrationMatch[2].trim();
- }
-
- return migrations;
-}
-
-/**
- * Escape string for Swift multiline string literal
- */
-function escapeSwiftString(str) {
- // Swift multiline strings handle most escaping, but we need to escape backslashes and quotes
- return str
- .replace(/\\/g, '\\\\')
- .replace(/"/g, '\\"');
-}
-
-/**
- * Escape string for Kotlin multiline string literal (trimIndent)
- */
-function escapeKotlinString(str) {
- // Kotlin raw strings don't need much escaping, but $ needs escaping
- return str.replace(/\$/g, '\\$');
-}
-
-/**
- * Generate Swift VaultVersions struct
- */
-function generateSwiftVaultVersions(versions) {
- const latestVersion = versions[versions.length - 1];
-
- const versionsArray = versions.map(v => {
- return ` VaultVersion(
- revision: ${v.revision},
- version: "${v.version}",
- description: "${v.description}",
- releaseVersion: "${v.releaseVersion}",
- compatibleUpToVersion: "${v.compatibleUpToVersion}"
- )`;
- }).join(',\n');
-
- return `// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/VaultVersions.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-// swiftlint:disable all
-
-import Foundation
-
-/// Vault database version information.
-public struct VaultVersion {
- /// The migration revision number.
- public let revision: Int
-
- /// The internal migration version number that equals the AliasClientDb database version (e.g., "1.5.0").
- public let version: String
-
- /// Description of changes in this version.
- public let description: String
-
- /// The AliasVault release that this vault version was introduced in (e.g., "0.14.0").
- public let releaseVersion: String
-
- /// The last AliasVault release version that the vault was compatible with before requiring this migration.
- public let compatibleUpToVersion: String
-}
-
-/// Registry of all vault versions.
-public struct VaultVersions {
- /// All vault migrations/versions in chronological order.
- public static let all: [VaultVersion] = [
-${versionsArray}
- ]
-
- /// Get the latest vault version.
- public static var latest: VaultVersion {
- return all.last!
- }
-
- /// Get the latest vault version string (e.g., "1.7.0").
- public static var latestVersion: String {
- return latest.version
- }
-
- /// Get the latest vault revision number.
- public static var latestRevision: Int {
- return latest.revision
- }
-
- /// Find a vault version by revision number.
- public static func findByRevision(_ revision: Int) -> VaultVersion? {
- return all.first { $0.revision == revision }
- }
-
- /// Find a vault version by version string.
- public static func findByVersion(_ version: String) -> VaultVersion? {
- return all.first { $0.version == version }
- }
-}
-
-// swiftlint:enable all
-`;
-}
-
-/**
- * Generate Kotlin VaultVersions object
- */
-function generateKotlinVaultVersions(versions) {
- const versionsArray = versions.map(v => {
- return ` VaultVersion(
- revision = ${v.revision},
- version = "${v.version}",
- description = "${v.description}",
- releaseVersion = "${v.releaseVersion}",
- compatibleUpToVersion = "${v.compatibleUpToVersion}",
- )`;
- }).join(',\n');
-
- return `// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/VaultVersions.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-@file:Suppress("all")
-
-package net.aliasvault.app.vaultstore.models
-
-/**
- * Vault database version information.
- */
-data class VaultVersion(
- /** The migration revision number. */
- val revision: Int,
- /** The internal migration version number that equals the AliasClientDb database version (e.g., "1.5.0"). */
- val version: String,
- /** Description of changes in this version. */
- val description: String,
- /** The AliasVault release that this vault version was introduced in (e.g., "0.14.0"). */
- val releaseVersion: String,
- /** The last AliasVault release version that the vault was compatible with before requiring this migration. */
- val compatibleUpToVersion: String,
-)
-
-/**
- * Registry of all vault versions.
- */
-object VaultVersions {
- /**
- * All vault migrations/versions in chronological order.
- */
- val all: List<VaultVersion> = listOf(
-${versionsArray},
- )
-
- /**
- * Get the latest vault version.
- */
- val latest: VaultVersion
- get() = all.last()
-
- /**
- * Get the latest vault version string (e.g., "1.7.0").
- */
- val latestVersion: String
- get() = latest.version
-
- /**
- * Get the latest vault revision number.
- */
- val latestRevision: Int
- get() = latest.revision
-
- /**
- * Find a vault version by revision number.
- */
- fun findByRevision(revision: Int): VaultVersion? {
- return all.find { it.revision == revision }
- }
-
- /**
- * Find a vault version by version string.
- */
- fun findByVersion(version: String): VaultVersion? {
- return all.find { it.version == version }
- }
-}
-`;
-}
-
-/**
- * Indent each line of a multi-line string for Swift multi-line string literals
- */
-function indentSwiftMultilineString(str, spaces = 8) {
- const indent = ' '.repeat(spaces);
- return str.split('\n').map(line => indent + line).join('\n');
-}
-
-/**
- * Generate Swift VaultSql struct
- */
-function generateSwiftVaultSql(completeSchemaSql, migrations) {
- const escapedSql = escapeSwiftString(completeSchemaSql);
- const indentedSql = indentSwiftMultilineString(escapedSql);
-
- // Generate migration entries
- const migrationEntries = Object.entries(migrations).map(([key, sql]) => {
- const escapedMigrationSql = escapeSwiftString(sql);
- const indentedMigrationSql = indentSwiftMultilineString(escapedMigrationSql, 12);
- return ` ${key}: """
-${indentedMigrationSql}
- """`;
- }).join(',\n');
-
- const migrationsDict = Object.keys(migrations).length > 0
- ? `
- /// Migration SQL scripts indexed by migration number.
- /// Key is the source migration number (migration FROM this version).
- public static let migrations: [Int: String] = [
-${migrationEntries}
- ]`
- : `
- /// Migration SQL scripts indexed by migration number.
- public static let migrations: [Int: String] = [:]`;
-
- return `// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/SqlConstants.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-// swiftlint:disable all
-
-import Foundation
-
-/// SQL statements for vault creation and migration.
-public struct VaultSql {
- /// Complete database schema SQL for creating a new vault with the latest schema.
- public static let completeSchema = """
-${indentedSql}
- """
-${migrationsDict}
-
- /// Get migration SQL for upgrading from a specific revision.
- public static func getMigrationSql(fromRevision: Int) -> String? {
- return migrations[fromRevision]
- }
-}
-
-// swiftlint:enable all
-`;
-}
-
-/**
- * Generate Kotlin VaultSql object
- */
-function generateKotlinVaultSql(completeSchemaSql, migrations) {
- const escapedSql = escapeKotlinString(completeSchemaSql);
-
- // Generate migration entries
- const migrationEntries = Object.entries(migrations).map(([key, sql]) => {
- const escapedMigrationSql = escapeKotlinString(sql);
- return ` ${key} to """
-${escapedMigrationSql}
- """.trimIndent()`;
- }).join(',\n');
-
- const migrationsMap = Object.keys(migrations).length > 0
- ? `
- /**
- * Migration SQL scripts indexed by migration number.
- * Key is the source migration number (migration FROM this version).
- */
- val migrations: Map<Int, String> = mapOf(
-${migrationEntries},
- )`
- : `
- /**
- * Migration SQL scripts indexed by migration number.
- */
- val migrations: Map<Int, String> = emptyMap()`;
-
- return `// <auto-generated />
-// This file is auto-generated from core/vault/src/sql/SqlConstants.ts
-// Do not edit this file directly. Run './build.sh' in core/vault to regenerate.
-@file:Suppress("all")
-
-package net.aliasvault.app.vaultstore.models
-
-/**
- * SQL statements for vault creation and migration.
- */
-object VaultSql {
- /**
- * Complete database schema SQL for creating a new vault with the latest schema.
- */
- val completeSchema = """
-${escapedSql}
- """.trimIndent()
-${migrationsMap}
-
- /**
- * Get migration SQL for upgrading from a specific revision.
- */
- fun getMigrationSql(fromRevision: Int): String? {
- return migrations[fromRevision]
- }
-}
-`;
-}
-
-/**
- * Ensure directory exists
- */
-function ensureDir(filePath) {
- const dir = path.dirname(filePath);
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true });
- }
+ return match[1].replace(//g, '').trim();
}
/**
* Main execution
*/
function main() {
- console.log('Generating vault SQL for Swift and Kotlin...\n');
-
- // Read TypeScript VaultVersions source
- if (!fs.existsSync(TS_VERSIONS_SOURCE)) {
- throw new Error(`Source file not found: ${TS_VERSIONS_SOURCE}`);
- }
-
- const tsVersionsContent = fs.readFileSync(TS_VERSIONS_SOURCE, 'utf8');
- const versions = parseVaultVersions(tsVersionsContent);
-
- if (versions.length === 0) {
- throw new Error('No vault versions found in source file');
- }
-
- console.log(`Parsed ${versions.length} vault versions`);
- console.log(`Latest version: ${versions[versions.length - 1].version} (revision ${versions[versions.length - 1].revision})`);
-
- // Read TypeScript SqlConstants source
if (!fs.existsSync(TS_SQL_SOURCE)) {
throw new Error(`Source file not found: ${TS_SQL_SOURCE}`);
}
- const tsSqlContent = fs.readFileSync(TS_SQL_SOURCE, 'utf8');
- const completeSchemaSql = parseCompleteSchemaSql(tsSqlContent);
- const migrations = parseMigrationScripts(tsSqlContent);
-
- console.log(`Parsed complete schema SQL (${completeSchemaSql.length} chars)`);
- console.log(`Parsed ${Object.keys(migrations).length} migration scripts`);
-
- // Generate Swift VaultVersions
- const swiftVersionsPath = path.join(SWIFT_OUTPUT_DIR, 'VaultVersions.swift');
- ensureDir(swiftVersionsPath);
- const swiftVersionsContent = generateSwiftVaultVersions(versions);
- fs.writeFileSync(swiftVersionsPath, swiftVersionsContent, 'utf8');
- console.log(`Generated: ${swiftVersionsPath}`);
-
- // Generate Swift VaultSql
- const swiftSqlPath = path.join(SWIFT_OUTPUT_DIR, 'VaultSql.swift');
- ensureDir(swiftSqlPath);
- const swiftSqlContent = generateSwiftVaultSql(completeSchemaSql, migrations);
- fs.writeFileSync(swiftSqlPath, swiftSqlContent, 'utf8');
- console.log(`Generated: ${swiftSqlPath}`);
-
- // Generate Kotlin VaultVersions
- const kotlinVersionsPath = path.join(KOTLIN_OUTPUT_DIR, 'VaultVersions.kt');
- ensureDir(kotlinVersionsPath);
- const kotlinVersionsContent = generateKotlinVaultVersions(versions);
- fs.writeFileSync(kotlinVersionsPath, kotlinVersionsContent, 'utf8');
- console.log(`Generated: ${kotlinVersionsPath}`);
-
- // Generate Kotlin VaultSql
- const kotlinSqlPath = path.join(KOTLIN_OUTPUT_DIR, 'VaultSql.kt');
- ensureDir(kotlinSqlPath);
- const kotlinSqlContent = generateKotlinVaultSql(completeSchemaSql, migrations);
- fs.writeFileSync(kotlinSqlPath, kotlinSqlContent, 'utf8');
- console.log(`Generated: ${kotlinSqlPath}`);
-
- console.log('\nVault SQL generation complete!');
+ const completeSchemaSql = parseCompleteSchemaSql(fs.readFileSync(TS_SQL_SOURCE, 'utf8'));
+ const header = '-- <auto-generated />\n-- Generated from core/vault/src/sql/SqlConstants.ts by core/vault/scripts/generate-vault-sql.cjs. Do not edit manually.\n';
+ fs.writeFileSync(SQL_OUTPUT, `${header}${completeSchemaSql}\n`, 'utf8');
+ console.log(`Generated: ${SQL_OUTPUT} (${completeSchemaSql.length} chars)`);
}
main();