Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add multi-source service importer logic ported from .NET (#2413)
Leendert de Borst049b3d663566
diff --git a/core/client/src/transfer/import/importers/bitwarden/BitwardenCsvImporter.ts b/core/client/src/transfer/import/importers/bitwarden/BitwardenCsvImporter.tsnew file mode 100644index 000000000..63e83d7ac--- /dev/null+++ b/core/client/src/transfer/import/importers/bitwarden/BitwardenCsvImporter.ts@@ -0,0 +1,45 @@+import { ItemTypes } from '@aliasvault/models/vault';++import { nullIfBlank } from '../../../shared/StringUtils';+import { readImportCsv } from '../../readers/CsvImport';+import { optionalText, text } from '../../readers/CsvRecordMapper';+import { mapItemType, parseUrls } from '../shared/CredentialHelpers';++import type { ImportedCredential } from '../../models/ImportedCredential';++const COLUMNS = {+ folder: text,+ type: text,+ name: text,+ notes: optionalText,+ login_uri: optionalText,+ login_username: optionalText,+ login_password: optionalText,+ login_totp: optionalText,+};++const ITEM_TYPES = {+ login: ItemTypes.Login,+ note: ItemTypes.Note,+ securenote: ItemTypes.Note,+ card: ItemTypes.CreditCard,+ identity: ItemTypes.Alias,+};++/**+ * Import a Bitwarden CSV export.+ * @param fileContent - The CSV file content+ * @returns The imported credentials+ */+export function importBitwardenCsv(fileContent: string): ImportedCredential[] {+ return readImportCsv(fileContent, COLUMNS).map(record => ({+ ServiceName: record.name,+ ServiceUrls: parseUrls(record.login_uri),+ Username: record.login_username,+ Password: record.login_password,+ TwoFactorSecret: record.login_totp,+ Notes: record.notes,+ FolderPath: nullIfBlank(record.folder),+ ItemType: mapItemType(record.type, ITEM_TYPES),+ }));+}diff --git a/core/client/src/transfer/import/importers/bitwarden/BitwardenJson.ts b/core/client/src/transfer/import/importers/bitwarden/BitwardenJson.tsnew file mode 100644index 000000000..be359f6fd--- /dev/null+++ b/core/client/src/transfer/import/importers/bitwarden/BitwardenJson.ts@@ -0,0 +1,280 @@+import { parseDateTime } from '../../../shared/DateTimeUtils';+import { getProperty, readBoolean, readNumber, readObject, readObjectArray, readString, readStringArray, requireObject, type JsonObject } from '../../readers/JsonReader';++/*+ * The Bitwarden JSON export (data.json inside a .zip export).+ */++/** Bitwarden item types. */+export const BitwardenItemTypes = { Login: 1, SecureNote: 2, Card: 3, Identity: 4 } as const;++/** Bitwarden custom field types. */+export const BitwardenFieldTypes = { Text: 0, Hidden: 1, Boolean: 2, Linked: 3 } as const;++/**+ * The export root.+ */+export type BitwardenJsonExport = {+ Encrypted: boolean;+ Folders: BitwardenFolder[];+ /** The items as raw JSON. */+ Items: unknown[];+ /** Collections (organization exports). */+ Collections: BitwardenCollection[] | null;+};++/**+ * A folder.+ */+export type BitwardenFolder = {+ Id: string | null;+ Name: string | null;+};++/**+ * A collection.+ */+export type BitwardenCollection = {+ Id: string | null;+ Name: string | null;+};++/**+ * An item.+ */+export type BitwardenItem = {+ Id: string | null;+ OrganizationId: string | null;+ FolderId: string | null;+ /** One of {@link BitwardenItemTypes}. */+ Type: number;+ Reprompt: number;+ Name: string | null;+ Notes: string | null;+ Favorite: boolean;+ RevisionDate: Date | null;+ PasswordHistory: BitwardenPasswordHistory[] | null;+ Fields: BitwardenField[] | null;+ Login: BitwardenLogin | null;+ SecureNote: BitwardenSecureNote | null;+ Card: BitwardenCard | null;+ Identity: BitwardenIdentity | null;+ CollectionIds: (string | null)[] | null;+};++/**+ * A password history entry.+ */+export type BitwardenPasswordHistory = {+ LastUsedDate: Date | null;+ Password: string | null;+};++/**+ * A custom field.+ */+export type BitwardenField = {+ Name: string | null;+ Value: string | null;+ LinkedId: number | null;+ /** One of {@link BitwardenFieldTypes}. */+ Type: number;+};++/**+ * Login data.+ */+export type BitwardenLogin = {+ Uris: BitwardenUri[] | null;+ Username: string | null;+ Password: string | null;+ Totp: string | null;+};++/**+ * A login URI.+ */+export type BitwardenUri = {+ Match: number | null;+ Uri: string | null;+};++/**+ * Secure note data.+ */+export type BitwardenSecureNote = {+ Type: number;+};++/**+ * Card data.+ */+export type BitwardenCard = {+ CardholderName: string | null;+ Brand: string | null;+ Number: string | null;+ ExpMonth: string | null;+ ExpYear: string | null;+ Code: string | null;+};++/**+ * Identity data.+ */+export type BitwardenIdentity = {+ Title: string | null;+ FirstName: string | null;+ MiddleName: string | null;+ LastName: string | null;+ Address1: string | null;+ Address2: string | null;+ Address3: string | null;+ City: string | null;+ State: string | null;+ PostalCode: string | null;+ Country: string | null;+ Company: string | null;+ Email: string | null;+ Phone: string | null;+ Ssn: string | null;+ Username: string | null;+ PassportNumber: string | null;+ LicenseNumber: string | null;+};++/**+ * Read the export root.+ * @param root - The parsed data.json+ * @returns The export+ */+export function parseBitwardenJsonExport(root: unknown): BitwardenJsonExport {+ const obj = requireObject(root, 'data.json');+ return {+ Encrypted: readBoolean(obj, 'encrypted') ?? false,+ Folders: readObjectArray(obj, 'folders', parseBitwardenFolder) ?? [],+ Items: readItemsRaw(obj),+ Collections: readObjectArray(obj, 'collections', (element): BitwardenCollection => ({ Id: readString(element, 'id'), Name: readString(element, 'name') })),+ };+}++/**+ * Read the raw item elements, left unparsed so each item can fail on its own.+ * @param obj - The export root+ * @returns The items, empty when absent+ */+function readItemsRaw(obj: JsonObject): unknown[] {+ const value = getProperty(obj, 'items');+ return Array.isArray(value) ? value : [];+}++/**+ * Read a folder.+ * @param element - The folder JSON+ * @returns The folder+ */+function parseBitwardenFolder(element: JsonObject): BitwardenFolder {+ return { Id: readString(element, 'id'), Name: readString(element, 'name') };+}++/**+ * Read one item.+ * @param element - The item JSON+ * @returns The item+ */+export function parseBitwardenItem(element: unknown): BitwardenItem {+ const obj = requireObject(element, 'Item');+ return {+ Id: readString(obj, 'id'),+ OrganizationId: readString(obj, 'organizationId'),+ FolderId: readString(obj, 'folderId'),+ Type: readNumber(obj, 'type') ?? 0,+ Reprompt: readNumber(obj, 'reprompt') ?? 0,+ Name: readString(obj, 'name'),+ Notes: readString(obj, 'notes'),+ Favorite: readBoolean(obj, 'favorite') ?? false,+ RevisionDate: parseDateTime(readString(obj, 'revisionDate')),+ PasswordHistory: readObjectArray(obj, 'passwordHistory', (entry): BitwardenPasswordHistory => ({ LastUsedDate: parseDateTime(readString(entry, 'lastUsedDate')), Password: readString(entry, 'password') })),+ Fields: readObjectArray(obj, 'fields', (field): BitwardenField => ({ Name: readString(field, 'name'), Value: readString(field, 'value'), LinkedId: readNumber(field, 'linkedId'), Type: readNumber(field, 'type') ?? 0 })),+ Login: parseBitwardenLogin(readObject(obj, 'login')),+ SecureNote: parseBitwardenSecureNote(readObject(obj, 'secureNote')),+ Card: parseBitwardenCard(readObject(obj, 'card')),+ Identity: parseBitwardenIdentity(readObject(obj, 'identity')),+ CollectionIds: readStringArray(obj, 'collectionIds'),+ };+}++/**+ * Read login data.+ * @param obj - The login JSON, or null+ * @returns The login, or null+ */+function parseBitwardenLogin(obj: JsonObject | null): BitwardenLogin | null {+ if (!obj) {+ return null;+ }+ return {+ Uris: readObjectArray(obj, 'uris', (uri): BitwardenUri => ({ Match: readNumber(uri, 'match'), Uri: readString(uri, 'uri') })),+ Username: readString(obj, 'username'),+ Password: readString(obj, 'password'),+ Totp: readString(obj, 'totp'),+ };+}++/**+ * Read secure note data.+ * @param obj - The secure note JSON, or null+ * @returns The secure note, or null+ */+function parseBitwardenSecureNote(obj: JsonObject | null): BitwardenSecureNote | null {+ return obj ? { Type: readNumber(obj, 'type') ?? 0 } : null;+}++/**+ * Read card data.+ * @param obj - The card JSON, or null+ * @returns The card, or null+ */+function parseBitwardenCard(obj: JsonObject | null): BitwardenCard | null {+ if (!obj) {+ return null;+ }+ return {+ CardholderName: readString(obj, 'cardholderName'),+ Brand: readString(obj, 'brand'),+ Number: readString(obj, 'number'),+ ExpMonth: readString(obj, 'expMonth'),+ ExpYear: readString(obj, 'expYear'),+ Code: readString(obj, 'code'),+ };+}++/**+ * Read identity data.+ * @param obj - The identity JSON, or null+ * @returns The identity, or null+ */+function parseBitwardenIdentity(obj: JsonObject | null): BitwardenIdentity | null {+ if (!obj) {+ return null;+ }+ return {+ Title: readString(obj, 'title'),+ FirstName: readString(obj, 'firstName'),+ MiddleName: readString(obj, 'middleName'),+ LastName: readString(obj, 'lastName'),+ Address1: readString(obj, 'address1'),+ Address2: readString(obj, 'address2'),+ Address3: readString(obj, 'address3'),+ City: readString(obj, 'city'),+ State: readString(obj, 'state'),+ PostalCode: readString(obj, 'postalCode'),+ Country: readString(obj, 'country'),+ Company: readString(obj, 'company'),+ Email: readString(obj, 'email'),+ Phone: readString(obj, 'phone'),+ Ssn: readString(obj, 'ssn'),+ Username: readString(obj, 'username'),+ PassportNumber: readString(obj, 'passportNumber'),+ LicenseNumber: readString(obj, 'licenseNumber'),+ };+}diff --git a/core/client/src/transfer/import/importers/bitwarden/BitwardenZipImporter.ts b/core/client/src/transfer/import/importers/bitwarden/BitwardenZipImporter.tsnew file mode 100644index 000000000..3676b39e5--- /dev/null+++ b/core/client/src/transfer/import/importers/bitwarden/BitwardenZipImporter.ts@@ -0,0 +1,103 @@+import { FieldTypes, ItemTypes, type ItemType } from '@aliasvault/models/vault';++import { isBlank, nonBlank } from '../../../shared/StringUtils';+import { ImportException, ImportStage } from '../../models/ImportException';+import { readStringAtPath } from '../../readers/JsonReader';+import { convertArchiveItems, openArchive, readArchiveJson } from '../shared/ArchiveImport';+import { addCustomField, appendNotes } from '../shared/CredentialHelpers';++import { BitwardenFieldTypes, BitwardenItemTypes, parseBitwardenItem, parseBitwardenJsonExport, type BitwardenIdentity, type BitwardenItem } from './BitwardenJson';++import type { ImportedCredential } from '../../models/ImportedCredential';+import type { ImportFileResult } from '../../models/ImportFileResult';++/** Bitwarden item types by number. */+const ITEM_TYPES: Readonly<Record<number, ItemType>> = {+ [BitwardenItemTypes.Login]: ItemTypes.Login,+ [BitwardenItemTypes.SecureNote]: ItemTypes.Note,+ [BitwardenItemTypes.Card]: ItemTypes.CreditCard,+ [BitwardenItemTypes.Identity]: ItemTypes.Alias,+};++/**+ * Import a Bitwarden .zip export: data.json plus the attachments stored as attachments/<item id>/<file name>.+ * @param archiveBytes - The archive bytes+ * @returns The credentials and the items that could not be read+ * @throws {ImportException} When the archive cannot be opened, data.json cannot be read or the export is encrypted.+ */+export function importBitwardenZip(archiveBytes: Uint8Array): ImportFileResult {+ const archive = openArchive(archiveBytes);+ const exportData = parseBitwardenJsonExport(readArchiveJson(archive, 'data.json'));+ if (exportData.Encrypted) {+ throw new ImportException(ImportStage.Parse, 'Encrypted Bitwarden exports are not supported. Please export as unencrypted.');+ }++ const folderNames = new Map(exportData.Folders.filter(folder => !isBlank(folder.Id) && !isBlank(folder.Name)).map(folder => [folder.Id!, folder.Name!]));+ const attachments = archive.filesUnder('attachments/');++ return convertArchiveItems(exportData.Items, element => {+ const item = parseBitwardenItem(element);+ const credential = convertItem(item, item.FolderId ? folderNames.get(item.FolderId) ?? null : null);++ if (!isBlank(item.Id)) {+ const prefix = `attachments/${item.Id}/`.toLowerCase();+ const itemAttachments = [...attachments].filter(([path]) => path.toLowerCase().startsWith(prefix));+ if (itemAttachments.length > 0) {+ credential.Attachments = itemAttachments.map(([path, data]) => ({ Filename: path.substring(prefix.length), Blob: data }));+ }+ }+ return credential;+ }, element => readStringAtPath(element, 'name'));+}++/**+ * Convert a Bitwarden item to a credential.+ * @param item - The item+ * @param folderPath - The name of the item's folder, or null+ * @returns The credential+ */+function convertItem(item: BitwardenItem, folderPath: string | null): ImportedCredential {+ const credential: ImportedCredential = {+ ServiceName: item.Name,+ Notes: item.Notes,+ UpdatedAt: item.RevisionDate,+ FolderPath: folderPath,+ ItemType: ITEM_TYPES[item.Type] ?? ItemTypes.Login,+ };++ if (credential.ItemType === ItemTypes.Login && item.Login) {+ credential.Username = item.Login.Username;+ credential.Password = item.Login.Password;+ credential.TwoFactorSecret = item.Login.Totp;+ if (item.Login.Uris && item.Login.Uris.length > 0) {+ credential.ServiceUrls = nonBlank(item.Login.Uris.map(uri => uri.Uri));+ }+ } else if (credential.ItemType === ItemTypes.CreditCard && item.Card) {+ credential.Creditcard = { CardholderName: item.Card.CardholderName, Number: item.Card.Number, ExpiryMonth: item.Card.ExpMonth, ExpiryYear: item.Card.ExpYear, Cvv: item.Card.Code };+ } else if (credential.ItemType === ItemTypes.Alias && item.Identity) {+ applyIdentity(credential, item.Identity);+ }++ // Linked fields point at another field of the item and have no value of their own.+ for (const field of item.Fields ?? []) {+ if (field.Type !== BitwardenFieldTypes.Linked) {+ addCustomField(credential, field.Name, field.Value, field.Type === BitwardenFieldTypes.Hidden ? FieldTypes.Hidden : FieldTypes.Text);+ }+ }++ return credential;+}++/**+ * Take the name and email of an identity; the details without a field of their own go into the notes.+ * @param credential - The credential to fill+ * @param identity - The identity+ */+function applyIdentity(credential: ImportedCredential, identity: BitwardenIdentity): void {+ credential.Alias = { FirstName: identity.FirstName, LastName: identity.LastName };+ credential.Email = identity.Email;++ const address = nonBlank([identity.Address1, identity.Address2, identity.Address3, identity.City, identity.State, identity.PostalCode, identity.Country]).join(', ');+ const details: [string, string | null][] = [['Title', identity.Title], ['Company', identity.Company], ['Phone', identity.Phone], ['Address', address]];+ appendNotes(credential, details.filter(([, value]) => !isBlank(value)).map(([label, value]) => `${label}: ${value}`));+}diff --git a/core/client/src/transfer/import/importers/onepassword/OnePassword1pux.ts b/core/client/src/transfer/import/importers/onepassword/OnePassword1pux.tsnew file mode 100644index 000000000..0cb6096d1--- /dev/null+++ b/core/client/src/transfer/import/importers/onepassword/OnePassword1pux.ts@@ -0,0 +1,382 @@+import { getProperty, readBoolean, readNumber, readObject, readObjectArray, readString, readStringArray, requireObject, type JsonObject } from '../../readers/JsonReader';++/*+ * The 1Password .1pux export format: export.attributes (version) and export.data (accounts, vaults, items).+ * Items are kept as raw JSON and deserialized one by one so a single malformed item does not abort the import.+ */++/** 1Password item categories by category id. */+export const OnePasswordCategories = { Login: '001', CreditCard: '002', SecureNote: '003', Identity: '004', Password: '005', Document: '006' } as const;++/** The vault type of the personal vault. */+export const OnePasswordPersonalVaultType = 'P';++/**+ * export.data.+ */+export type OnePassword1puxData = {+ Accounts: OnePasswordAccount[];+};++/**+ * export.attributes.+ */+export type OnePassword1puxAttributes = {+ Version: number;+ Description: string | null;+ CreatedAt: number;+};++/**+ * An account.+ */+export type OnePasswordAccount = {+ Attrs: OnePasswordAccountAttrs | null;+ Vaults: OnePasswordVault[];+};++/**+ * Account attributes.+ */+export type OnePasswordAccountAttrs = {+ AccountName: string | null;+ Name: string | null;+ Avatar: string | null;+ Email: string | null;+ Uuid: string | null;+ Domain: string | null;+};++/**+ * A vault.+ */+export type OnePasswordVault = {+ Attrs: OnePasswordVaultAttrs | null;+ /** The items as raw JSON. */+ Items: unknown[];+};++/**+ * Vault attributes.+ */+export type OnePasswordVaultAttrs = {+ Uuid: string | null;+ Desc: string | null;+ Avatar: string | null;+ Name: string | null;+ /** {@link OnePasswordPersonalVaultType} for the personal vault. */+ Type: string | null;+};++/**+ * An item.+ */+export type OnePasswordItem = {+ Uuid: string | null;+ FavIndex: number | null;+ CreatedAt: number | null;+ UpdatedAt: number | null;+ State: string | null;+ /** One of {@link OnePasswordCategories}. */+ CategoryUuid: string | null;+ Overview: OnePasswordOverview | null;+ Details: OnePasswordDetails | null;+};++/**+ * Item overview.+ */+export type OnePasswordOverview = {+ Subtitle: string | null;+ Urls: OnePasswordUrl[] | null;+ Title: string | null;+ Url: string | null;+ Ps: number | null;+ Tags: (string | null)[] | null;+};++/**+ * A URL.+ */+export type OnePasswordUrl = {+ Label: string | null;+ Url: string | null;+};++/**+ * Item details.+ */+export type OnePasswordDetails = {+ LoginFields: OnePasswordLoginField[] | null;+ NotesPlain: string | null;+ Sections: OnePasswordSection[] | null;+ PasswordHistory: OnePasswordPasswordHistory[] | null;+ DocumentAttributes: OnePasswordDocumentAttributes | null;+};++/**+ * A login field.+ */+export type OnePasswordLoginField = {+ Value: string | null;+ Id: string | null;+ Name: string | null;+ FieldType: string | null;+ /** "username" or "password". */+ Designation: string | null;+};++/**+ * A section.+ */+export type OnePasswordSection = {+ Title: string | null;+ Name: string | null;+ Fields: OnePasswordField[] | null;+};++/**+ * A section field.+ */+export type OnePasswordField = {+ Title: string | null;+ Id: string | null;+ Value: OnePasswordFieldValue | null;+ Guarded: boolean;+ Multiline: boolean;+ DontGenerate: boolean;+};++/**+ * A field value; exactly one of the members is set.+ */+export type OnePasswordFieldValue = {+ String: string | null;+ Concealed: string | null;+ Date: number | null;+ /** YYYYMM. */+ MonthYear: number | null;+ Totp: string | null;+ Url: string | null;+ CreditCardNumber: string | null;+ Menu: string | null;+ File: OnePasswordFileValue | null;+ Email: OnePasswordEmailValue | null;+ Phone: string | null;+ Address: OnePasswordAddressValue | null;+};++/**+ * A password history entry.+ */+export type OnePasswordPasswordHistory = {+ Value: string | null;+ Time: number | null;+};++/**+ * Document attributes of a Document item.+ */+export type OnePasswordDocumentAttributes = {+ FileName: string | null;+ DocumentId: string | null;+ DecryptedSize: number | null;+};++/**+ * A file field value.+ */+export type OnePasswordFileValue = {+ FileName: string | null;+ DocumentId: string | null;+ DecryptedSize: number | null;+};++/**+ * An email field value.+ */+export type OnePasswordEmailValue = {+ EmailAddress: string | null;+};++/**+ * An address field value.+ */+export type OnePasswordAddressValue = {+ Street: string | null;+ City: string | null;+ Country: string | null;+ Zip: string | null;+ State: string | null;+};++/**+ * Read export.attributes.+ * @param root - The parsed export.attributes+ * @returns The attributes+ */+export function parseOnePassword1puxAttributes(root: unknown): OnePassword1puxAttributes {+ const obj = requireObject(root, 'export.attributes');+ return { Version: readNumber(obj, 'version') ?? 0, Description: readString(obj, 'description'), CreatedAt: readNumber(obj, 'createdAt') ?? 0 };+}++/**+ * Read export.data.+ * @param root - The parsed export.data+ * @returns The data+ */+export function parseOnePassword1puxData(root: unknown): OnePassword1puxData {+ const obj = requireObject(root, 'export.data');+ return { Accounts: readObjectArray(obj, 'accounts', parseOnePasswordAccount) ?? [] };+}++/**+ * Read an account.+ * @param obj - The account JSON+ * @returns The account+ */+function parseOnePasswordAccount(obj: JsonObject): OnePasswordAccount {+ const attrs = readObject(obj, 'attrs');+ return {+ Attrs: attrs ? { AccountName: readString(attrs, 'accountName'), Name: readString(attrs, 'name'), Avatar: readString(attrs, 'avatar'), Email: readString(attrs, 'email'), Uuid: readString(attrs, 'uuid'), Domain: readString(attrs, 'domain') } : null,+ Vaults: readObjectArray(obj, 'vaults', parseOnePasswordVault) ?? [],+ };+}++/**+ * Read a vault.+ * @param obj - The vault JSON+ * @returns The vault+ */+function parseOnePasswordVault(obj: JsonObject): OnePasswordVault {+ const attrs = readObject(obj, 'attrs');+ const items = getProperty(obj, 'items');+ return {+ Attrs: attrs ? { Uuid: readString(attrs, 'uuid'), Desc: readString(attrs, 'desc'), Avatar: readString(attrs, 'avatar'), Name: readString(attrs, 'name'), Type: readString(attrs, 'type') } : null,+ Items: Array.isArray(items) ? items : [],+ };+}++/**+ * Read one item.+ * @param element - The item JSON+ * @returns The item+ */+export function parseOnePasswordItem(element: unknown): OnePasswordItem {+ const obj = requireObject(element, 'Item');+ return {+ Uuid: readString(obj, 'uuid'),+ FavIndex: readNumber(obj, 'favIndex'),+ CreatedAt: readNumber(obj, 'createdAt'),+ UpdatedAt: readNumber(obj, 'updatedAt'),+ State: readString(obj, 'state'),+ CategoryUuid: readString(obj, 'categoryUuid'),+ Overview: parseOnePasswordOverview(readObject(obj, 'overview')),+ Details: parseOnePasswordDetails(readObject(obj, 'details')),+ };+}++/**+ * Read the overview.+ * @param obj - The overview JSON, or null+ * @returns The overview, or null+ */+function parseOnePasswordOverview(obj: JsonObject | null): OnePasswordOverview | null {+ if (!obj) {+ return null;+ }+ return {+ Subtitle: readString(obj, 'subtitle'),+ Urls: readObjectArray(obj, 'urls', (url): OnePasswordUrl => ({ Label: readString(url, 'label'), Url: readString(url, 'url') })),+ Title: readString(obj, 'title'),+ Url: readString(obj, 'url'),+ Ps: readNumber(obj, 'ps'),+ Tags: readStringArray(obj, 'tags'),+ };+}++/**+ * Read the details.+ * @param obj - The details JSON, or null+ * @returns The details, or null+ */+function parseOnePasswordDetails(obj: JsonObject | null): OnePasswordDetails | null {+ if (!obj) {+ return null;+ }+ return {+ LoginFields: readObjectArray(obj, 'loginFields', (field): OnePasswordLoginField => ({ Value: readString(field, 'value'), Id: readString(field, 'id'), Name: readString(field, 'name'), FieldType: readString(field, 'fieldType'), Designation: readString(field, 'designation') })),+ NotesPlain: readString(obj, 'notesPlain'),+ Sections: readObjectArray(obj, 'sections', parseOnePasswordSection),+ PasswordHistory: readObjectArray(obj, 'passwordHistory', (entry): OnePasswordPasswordHistory => ({ Value: readString(entry, 'value'), Time: readNumber(entry, 'time') })),+ DocumentAttributes: parseOnePasswordFileValue(readObject(obj, 'documentAttributes')),+ };+}++/**+ * Read a section.+ * @param obj - The section JSON+ * @returns The section+ */+function parseOnePasswordSection(obj: JsonObject): OnePasswordSection {+ return {+ Title: readString(obj, 'title'),+ Name: readString(obj, 'name'),+ Fields: readObjectArray(obj, 'fields', parseOnePasswordField),+ };+}++/**+ * Read a section field.+ * @param obj - The field JSON+ * @returns The field+ */+function parseOnePasswordField(obj: JsonObject): OnePasswordField {+ return {+ Title: readString(obj, 'title'),+ Id: readString(obj, 'id'),+ Value: parseOnePasswordFieldValue(readObject(obj, 'value')),+ Guarded: readBoolean(obj, 'guarded') ?? false,+ Multiline: readBoolean(obj, 'multiline') ?? false,+ DontGenerate: readBoolean(obj, 'dontGenerate') ?? false,+ };+}++/**+ * Read a field value.+ * @param obj - The value JSON, or null+ * @returns The value, or null+ */+function parseOnePasswordFieldValue(obj: JsonObject | null): OnePasswordFieldValue | null {+ if (!obj) {+ return null;+ }+ const email = readObject(obj, 'email');+ const address = readObject(obj, 'address');+ return {+ String: readString(obj, 'string'),+ Concealed: readString(obj, 'concealed'),+ Date: readNumber(obj, 'date'),+ MonthYear: readNumber(obj, 'monthYear'),+ Totp: readString(obj, 'totp'),+ Url: readString(obj, 'url'),+ CreditCardNumber: readString(obj, 'creditCardNumber'),+ Menu: readString(obj, 'menu'),+ File: parseOnePasswordFileValue(readObject(obj, 'file')),+ Email: email ? { EmailAddress: readString(email, 'email_address') } : null,+ Phone: readString(obj, 'phone'),+ Address: address ? { Street: readString(address, 'street'), City: readString(address, 'city'), Country: readString(address, 'country'), Zip: readString(address, 'zip'), State: readString(address, 'state') } : null,+ };+}++/**+ * Read a file value (also the shape of documentAttributes).+ * @param obj - The file JSON, or null+ * @returns The file value, or null+ */+function parseOnePasswordFileValue(obj: JsonObject | null): OnePasswordFileValue | null {+ if (!obj) {+ return null;+ }+ return { FileName: readString(obj, 'fileName'), DocumentId: readString(obj, 'documentId'), DecryptedSize: readNumber(obj, 'decryptedSize') };+}diff --git a/core/client/src/transfer/import/importers/onepassword/OnePassword1puxImporter.ts b/core/client/src/transfer/import/importers/onepassword/OnePassword1puxImporter.tsnew file mode 100644index 000000000..26cc628f4--- /dev/null+++ b/core/client/src/transfer/import/importers/onepassword/OnePassword1puxImporter.ts@@ -0,0 +1,283 @@+import { FieldTypes, ItemTypes, type FieldType, type ItemType } from '@aliasvault/models/vault';++import { formatDateOnly, fromUnixTimeSeconds } from '../../../shared/DateTimeUtils';+import { isBlank, nonBlank, nullIfBlank } from '../../../shared/StringUtils';+import { ImportException, ImportStage } from '../../models/ImportException';+import { readStringAtPath } from '../../readers/JsonReader';+import { convertArchiveItems, openArchive, readArchiveJson } from '../shared/ArchiveImport';+import { addAttachment, addCustomField } from '../shared/CredentialHelpers';++import { OnePasswordCategories, OnePasswordPersonalVaultType, parseOnePassword1puxAttributes, parseOnePassword1puxData, parseOnePasswordItem, type OnePasswordField, type OnePasswordFieldValue, type OnePasswordItem, type OnePasswordVault } from './OnePassword1pux';++import type { ImportedAlias } from '../../models/ImportedAlias';+import type { ImportedCredential } from '../../models/ImportedCredential';+import type { ImportedCreditcard } from '../../models/ImportedCreditcard';+import type { ImportFileResult } from '../../models/ImportFileResult';++/** The only .1pux format version this importer reads. */+const SUPPORTED_VERSION = 3;++/** 1Password categories by id; anything else imports as a Login. */+const ITEM_TYPES: Readonly<Record<string, ItemType>> = {+ [OnePasswordCategories.Login]: ItemTypes.Login,+ [OnePasswordCategories.CreditCard]: ItemTypes.CreditCard,+ [OnePasswordCategories.SecureNote]: ItemTypes.Note,+ [OnePasswordCategories.Identity]: ItemTypes.Alias,+ [OnePasswordCategories.Password]: ItemTypes.Login,+ [OnePasswordCategories.Document]: ItemTypes.Note,+};++/** The built-in vaults; the first one holding items goes to the root folder instead of becoming a folder. */+const DEFAULT_VAULT_NAMES = new Set(['private', 'personal', 'employee']);++/** Identity fields by lower case field title. */+const IDENTITY_FIELDS: Readonly<Record<string, 'FirstName' | 'LastName' | 'Gender'>> = {+ 'first name': 'FirstName',+ firstname: 'FirstName',+ 'last name': 'LastName',+ lastname: 'LastName',+ gender: 'Gender',+ sex: 'Gender',+};+const BIRTH_DATE_TITLES = new Set(['birth date', 'birthdate', 'date of birth']);++/** Credit card fields by lower case field title. */+const CARD_FIELDS: Readonly<Record<string, 'CardholderName' | 'Number' | 'Cvv' | 'Pin'>> = {+ 'cardholder name': 'CardholderName',+ cardholder: 'CardholderName',+ 'name on card': 'CardholderName',+ number: 'Number',+ 'card number': 'Number',+ cardnumber: 'Number',+ cvv: 'Cvv',+ 'verification number': 'Cvv',+ 'security code': 'Cvv',+ cvc: 'Cvv',+ pin: 'Pin',+ 'pin code': 'Pin',+};+const EXPIRY_TITLES = new Set(['expiry date', 'expiration date', 'expires']);++/** The text members of a field value in the order they are tried, with the field type each maps to. */+const TEXT_VALUE_MEMBERS: readonly ['String' | 'Concealed' | 'Url' | 'CreditCardNumber' | 'Menu' | 'Phone', FieldType][] = [+ ['String', FieldTypes.Text],+ ['Concealed', FieldTypes.Hidden],+ ['Url', FieldTypes.URL],+ ['CreditCardNumber', FieldTypes.Text],+ ['Menu', FieldTypes.Text],+ ['Phone', FieldTypes.Phone],+];++/**+ * Import a 1Password .1pux export. Every vault except the default one becomes a folder; attachments are stored as+ * files/<document id>__<file name>.+ * @param archiveBytes - The archive bytes+ * @returns The credentials and the items that could not be read+ * @throws {ImportException} When the archive cannot be opened, export.data cannot be read or the format version is unsupported.+ */+export function importOnePassword1pux(archiveBytes: Uint8Array): ImportFileResult {+ const archive = openArchive(archiveBytes);+ if (archive.has('export.attributes')) {+ const attributes = parseOnePassword1puxAttributes(readArchiveJson(archive, 'export.attributes'));+ if (attributes.Version !== SUPPORTED_VERSION) {+ throw new ImportException(ImportStage.Parse, `Unsupported 1Password export version: ${attributes.Version}. Expected version ${SUPPORTED_VERSION}.`);+ }+ }++ const vaults = parseOnePassword1puxData(readArchiveJson(archive, 'export.data')).Accounts.flatMap(account => account.Vaults);+ const rootVaultName = vaults.find(isRootVault)?.Attrs?.Name?.toLowerCase();+ const entries = vaults.flatMap(vault => {+ const vaultName = vault.Attrs?.Name ?? null;+ return vault.Items.map(element => ({ element, folderPath: vaultName?.toLowerCase() === rootVaultName ? null : vaultName }));+ });+ const files = archive.filesUnder('files/');++ return convertArchiveItems(entries, ({ element, folderPath }) => convertItem(parseOnePasswordItem(element), folderPath, files), ({ element }) => readStringAtPath(element, 'overview', 'title'));+}++/**+ * Whether a vault is a built-in one holding items, whose items go to the root folder.+ * @param vault - The vault+ * @returns True for the root vault candidate+ */+function isRootVault(vault: OnePasswordVault): boolean {+ const name = vault.Attrs?.Name;+ return vault.Items.length > 0 && !isBlank(name) && (DEFAULT_VAULT_NAMES.has(name.toLowerCase()) || vault.Attrs?.Type === OnePasswordPersonalVaultType);+}++/**+ * Convert a 1Password item to a credential.+ * @param item - The item+ * @param folderPath - The vault name, or null for the root folder+ * @param files - The archive's files under files/+ * @returns The credential+ */+function convertItem(item: OnePasswordItem, folderPath: string | null, files: Map<string, Uint8Array>): ImportedCredential {+ const credential: ImportedCredential = {+ ServiceName: item.Overview?.Title ?? null,+ Notes: item.Details?.NotesPlain ?? null,+ FolderPath: folderPath,+ CreatedAt: fromUnixTimeSeconds(item.CreatedAt),+ UpdatedAt: fromUnixTimeSeconds(item.UpdatedAt),+ ItemType: item.CategoryUuid && Object.hasOwn(ITEM_TYPES, item.CategoryUuid) ? ITEM_TYPES[item.CategoryUuid] : ItemTypes.Login,+ };++ if (item.Overview?.Urls && item.Overview.Urls.length > 0) {+ credential.ServiceUrls = nonBlank(item.Overview.Urls.map(url => url.Url));+ }+ if (item.Overview?.Tags && item.Overview.Tags.length > 0) {+ credential.Tags = nonBlank(item.Overview.Tags);+ }++ for (const field of item.Details?.LoginFields ?? []) {+ if (field.Designation === 'username' && !isBlank(field.Value)) {+ credential.Username = field.Value;+ } else if (field.Designation === 'password' && !isBlank(field.Value)) {+ credential.Password = field.Value;+ }+ }++ for (const field of (item.Details?.Sections ?? []).flatMap(section => section.Fields ?? [])) {+ applySectionField(credential, field, files);+ }++ const document = item.Details?.DocumentAttributes;+ if (document && !isBlank(document.DocumentId) && !isBlank(document.FileName)) {+ const data = files.get(`files/${document.DocumentId}__${document.FileName}`);+ if (data) {+ addAttachment(credential, document.FileName, data);+ }+ }++ if (!isBlank(item.Uuid)) {+ const prefix = `files/${item.Uuid}__`.toLowerCase();+ for (const [path, data] of files) {+ if (path.toLowerCase().startsWith(prefix)) {+ addAttachment(credential, path.substring(prefix.length), data);+ }+ }+ }++ return credential;+}++/**+ * Apply one section field: a file becomes an attachment, a TOTP field the 2FA secret, and every other field a+ * custom field, after identity and card fields have also filled their own slots.+ * @param credential - The credential to fill+ * @param field - The field+ * @param files - The archive's files under files/+ */+function applySectionField(credential: ImportedCredential, field: OnePasswordField, files: Map<string, Uint8Array>): void {+ const value = field.Value;+ if (!value) {+ return;+ }++ if (value.File && !isBlank(value.File.DocumentId) && !isBlank(value.File.FileName)) {+ const data = files.get(`files/${value.File.DocumentId}__${value.File.FileName}`);+ if (data) {+ addAttachment(credential, value.File.FileName, data);+ }+ return;+ }++ if (isBlank(field.Title)) {+ return;+ }++ if (!isBlank(value.Totp)) {+ credential.TwoFactorSecret = value.Totp;+ return;+ }++ const title = field.Title.toLowerCase();+ const resolved = resolveFieldValue(value);++ if (credential.ItemType === ItemTypes.Alias) {+ credential.Alias ??= {};+ applyIdentityField(credential.Alias, title, value, resolved.value);+ }+ if (credential.ItemType === ItemTypes.CreditCard) {+ credential.Creditcard ??= {};+ applyCardField(credential.Creditcard, title, value, nullIfBlank(resolved.value));+ }++ addCustomField(credential, field.Title, resolved.value, resolved.fieldType);+}++/**+ * Fill an identity slot from a section field.+ * @param alias - The alias to fill+ * @param title - The lower case field title+ * @param value - The field value+ * @param text - The field value as text+ */+function applyIdentityField(alias: ImportedAlias, title: string, value: OnePasswordFieldValue, text: string | null): void {+ if (isBlank(text)) {+ return;+ }+ if (Object.hasOwn(IDENTITY_FIELDS, title)) {+ alias[IDENTITY_FIELDS[title]] = text;+ } else if (BIRTH_DATE_TITLES.has(title)) {+ alias.BirthDate = fromUnixTimeSeconds(value.Date);+ }+}++/**+ * Fill a credit card slot from a section field. Card numbers prefer the creditCardNumber member and expiry dates+ * come from the monthYear member (YYYYMM).+ * @param card - The card to fill+ * @param title - The lower case field title+ * @param value - The field value+ * @param text - The field value as non-blank text, or null+ */+function applyCardField(card: ImportedCreditcard, title: string, value: OnePasswordFieldValue, text: string | null): void {+ if (Object.hasOwn(CARD_FIELDS, title)) {+ const slot = CARD_FIELDS[title];+ const slotValue = slot === 'Number' ? nullIfBlank(value.CreditCardNumber) ?? text : text;+ if (slotValue) {+ card[slot] = slotValue;+ }+ } else if (EXPIRY_TITLES.has(title)) {+ const monthYear = /^(\d{4})(\d{2})$/.exec(String(value.MonthYear ?? ''));+ if (monthYear) {+ card.ExpiryYear = monthYear[1];+ card.ExpiryMonth = monthYear[2];+ }+ }+}++/**+ * Resolve a field value to text and the field type it maps to.+ * @param value - The field value+ * @returns The text, null when the field is empty, and its field type+ */+function resolveFieldValue(value: OnePasswordFieldValue): { value: string | null; fieldType: FieldType } {+ for (const [member, fieldType] of TEXT_VALUE_MEMBERS) {+ const text = value[member];+ if (!isBlank(text)) {+ return { value: text, fieldType };+ }+ }++ if (value.Email?.EmailAddress !== null && value.Email?.EmailAddress !== undefined) {+ return { value: value.Email.EmailAddress, fieldType: FieldTypes.Email };+ }+ if (value.Address) {+ const address = nonBlank([value.Address.Street, value.Address.City, value.Address.State, value.Address.Zip, value.Address.Country]).join(', ');+ return { value: nullIfBlank(address), fieldType: FieldTypes.Text };+ }+ if (value.Date !== null) {+ // A "yyyy-MM-dd" string, which the Date field renders as-is.+ const date = fromUnixTimeSeconds(value.Date);+ return { value: date ? formatDateOnly(date) : null, fieldType: FieldTypes.Date };+ }+ if (value.MonthYear !== null) {+ // A month without a day is kept as "yyyy-MM" text rather than a Date field.+ const monthYear = /^(\d{4})(\d{2})$/.exec(String(value.MonthYear));+ return { value: monthYear ? `${monthYear[1]}-${monthYear[2]}` : null, fieldType: FieldTypes.Text };+ }++ return { value: null, fieldType: FieldTypes.Text };+}diff --git a/core/client/src/transfer/import/importers/onepassword/OnePasswordCsvImporter.ts b/core/client/src/transfer/import/importers/onepassword/OnePasswordCsvImporter.tsnew file mode 100644index 000000000..702b1883b--- /dev/null+++ b/core/client/src/transfer/import/importers/onepassword/OnePasswordCsvImporter.ts@@ -0,0 +1,33 @@+import { nullIfBlank } from '../../../shared/StringUtils';+import { readImportCsv } from '../../readers/CsvImport';+import { optionalText, text } from '../../readers/CsvRecordMapper';+import { parseUrls } from '../shared/CredentialHelpers';++import type { ImportedCredential } from '../../models/ImportedCredential';++const COLUMNS = {+ Title: text,+ Url: text,+ Username: text,+ Password: text,+ OTPAuth: optionalText,+ Tags: optionalText,+ Notes: optionalText,+};++/**+ * Import a 1Password CSV export. The tags become the folder.+ * @param fileContent - The CSV file content+ * @returns The imported credentials+ */+export function importOnePasswordCsv(fileContent: string): ImportedCredential[] {+ return readImportCsv(fileContent, COLUMNS).map(record => ({+ ServiceName: record.Title,+ ServiceUrls: parseUrls(record.Url),+ Username: record.Username,+ Password: record.Password,+ TwoFactorSecret: record.OTPAuth,+ Notes: record.Notes,+ FolderPath: nullIfBlank(record.Tags),+ }));+}diff --git a/core/client/src/transfer/import/importers/protonpass/ProtonPassCsvImporter.ts b/core/client/src/transfer/import/importers/protonpass/ProtonPassCsvImporter.tsnew file mode 100644index 000000000..3378c5b37--- /dev/null+++ b/core/client/src/transfer/import/importers/protonpass/ProtonPassCsvImporter.ts@@ -0,0 +1,49 @@+import { ItemTypes } from '@aliasvault/models/vault';++import { nullIfBlank } from '../../../shared/StringUtils';+import { readImportCsv } from '../../readers/CsvImport';+import { optionalText, text } from '../../readers/CsvRecordMapper';+import { mapItemType, parseUrls } from '../shared/CredentialHelpers';++import type { ImportedCredential } from '../../models/ImportedCredential';++const COLUMNS = {+ type: text,+ name: text,+ url: text,+ email: text,+ username: text,+ password: text,+ note: optionalText,+ totp: optionalText,+ vault: text,+};++/** Proton Pass export types and their AliasVault equivalents. */+const ITEM_TYPES = {+ login: ItemTypes.Login,+ note: ItemTypes.Note,+ // A Proton Pass alias is an email alias, not an identity, so it imports as a standard Login type.+ alias: ItemTypes.Login,+ creditcard: ItemTypes.CreditCard,+};++/**+ * Import a Proton Pass CSV export.+ * @param fileContent - The CSV file content+ * @returns The imported credentials+ */+export function importProtonPassCsv(fileContent: string): ImportedCredential[] {+ return readImportCsv(fileContent, COLUMNS).map(record => ({+ ServiceName: record.name,+ ServiceUrls: parseUrls(record.url),+ Email: record.email,+ Username: record.username,+ Password: record.password,+ Notes: record.note,+ TwoFactorSecret: record.totp,+ // The vault becomes the folder.+ FolderPath: nullIfBlank(record.vault),+ ItemType: mapItemType(record.type, ITEM_TYPES),+ }));+}diff --git a/core/client/src/transfer/import/importers/protonpass/ProtonPassJson.ts b/core/client/src/transfer/import/importers/protonpass/ProtonPassJson.tsnew file mode 100644index 000000000..10f0c7ee3--- /dev/null+++ b/core/client/src/transfer/import/importers/protonpass/ProtonPassJson.ts@@ -0,0 +1,262 @@+import { getProperty, isJsonObject, readBoolean, readNumber, readObject, readObjectArray, readString, readStringArray, requireObject, type JsonObject } from '../../readers/JsonReader';++/*+ * The Proton Pass JSON export (data.json inside a .zip export).+ */++/** Proton Pass item states; older exports leave the state out, which means active. */+export const ProtonPassItemStates = { Active: 1, Trashed: 2 } as const;++/**+ * The export root.+ */+export type ProtonPassJsonExport = {+ UserId: string | null;+ Version: string | null;+ Encrypted: boolean;+ /** The vaults, keyed by vault id. */+ Vaults: Map<string, ProtonPassVault>;+};++/**+ * A vault.+ */+export type ProtonPassVault = {+ Name: string | null;+ Description: string | null;+ Display: ProtonPassDisplay | null;+ /** The items as raw JSON. */+ Items: unknown[];+};++/**+ * Vault display settings.+ */+export type ProtonPassDisplay = {+ Color: number;+ Icon: number;+};++/**+ * An item envelope.+ */+export type ProtonPassItem = {+ ItemId: string | null;+ ShareId: string | null;+ Data: ProtonPassItemData | null;+ /** One of {@link ProtonPassItemStates}. */+ State: number | null;+ /** The generated email of an alias item. */+ AliasEmail: string | null;+ ContentFormatVersion: number | null;+ CreateTime: number | null;+ ModifyTime: number | null;+ Pinned: boolean;+ ShareCount: number;+ Files: ProtonPassFile[] | null;+};++/**+ * Item data.+ */+export type ProtonPassItemData = {+ Metadata: ProtonPassMetadata | null;+ ExtraFields: ProtonPassExtraField[] | null;+ /** login, note, alias, creditCard or identity. */+ Type: string | null;+ Content: ProtonPassContent | null;+};++/**+ * Item metadata.+ */+export type ProtonPassMetadata = {+ Name: string | null;+ Note: string | null;+ ItemUuid: string | null;+};++/**+ * Type-specific content, one flat shape for every item type.+ */+export type ProtonPassContent = {+ ItemUsername: string | null;+ ItemEmail: string | null;+ Password: string | null;+ Urls: (string | null)[] | null;+ TotpUri: string | null;+ Passkeys: ProtonPassPasskey[] | null;+ CardholderName: string | null;+ Number: string | null;+ VerificationNumber: string | null;+ Pin: string | null;+ ExpirationDate: string | null;+ CardType: number | null;+ FirstName: string | null;+ LastName: string | null;+ FullName: string | null;+ Email: string | null;+};++/**+ * A passkey.+ */+export type ProtonPassPasskey = {+ CredentialId: string | null;+ RpId: string | null;+ RpName: string | null;+ UserName: string | null;+};++/**+ * A custom field.+ */+export type ProtonPassExtraField = {+ FieldName: string | null;+ /** text, hidden, totp or date. */+ Type: string | null;+ Data: ProtonPassExtraFieldData | null;+};++/**+ * Custom field data.+ */+export type ProtonPassExtraFieldData = {+ Content: string | null;+};++/**+ * A file attached to an item.+ */+export type ProtonPassFile = {+ FileId: string | null;+ Name: string | null;+ MimeType: string | null;+ Size: number | null;+};++/**+ * Read the export root.+ * @param root - The parsed data.json+ * @returns The export+ */+export function parseProtonPassJsonExport(root: unknown): ProtonPassJsonExport {+ const obj = requireObject(root, 'data.json');+ const vaults = new Map<string, ProtonPassVault>();+ const vaultsObj = readObject(obj, 'vaults');+ if (vaultsObj) {+ for (const [vaultId, vault] of Object.entries(vaultsObj)) {+ vaults.set(vaultId, parseProtonPassVault(requireObject(vault, `Vault '${vaultId}'`)));+ }+ }+ return {+ UserId: readString(obj, 'userId'),+ Version: readString(obj, 'version'),+ Encrypted: readBoolean(obj, 'encrypted') ?? false,+ Vaults: vaults,+ };+}++/**+ * Read a vault.+ * @param obj - The vault JSON+ * @returns The vault+ */+function parseProtonPassVault(obj: JsonObject): ProtonPassVault {+ const display = readObject(obj, 'display');+ const items = getProperty(obj, 'items');+ return {+ Name: readString(obj, 'name'),+ Description: readString(obj, 'description'),+ Display: display ? { Color: readNumber(display, 'color') ?? 0, Icon: readNumber(display, 'icon') ?? 0 } : null,+ Items: Array.isArray(items) ? items : [],+ };+}++/**+ * Read one item envelope.+ * @param element - The item JSON+ * @returns The item+ */+export function parseProtonPassItem(element: unknown): ProtonPassItem {+ const obj = requireObject(element, 'Item');+ return {+ ItemId: readString(obj, 'itemId'),+ ShareId: readString(obj, 'shareId'),+ Data: parseProtonPassItemData(readObject(obj, 'data')),+ State: readNumber(obj, 'state'),+ AliasEmail: readString(obj, 'aliasEmail'),+ ContentFormatVersion: readNumber(obj, 'contentFormatVersion'),+ CreateTime: readNumber(obj, 'createTime'),+ ModifyTime: readNumber(obj, 'modifyTime'),+ Pinned: readBoolean(obj, 'pinned') ?? false,+ ShareCount: readNumber(obj, 'shareCount') ?? 0,+ Files: readObjectArray(obj, 'files', (file): ProtonPassFile => ({ FileId: readString(file, 'fileID'), Name: readString(file, 'name'), MimeType: readString(file, 'mimeType'), Size: readNumber(file, 'size') })),+ };+}++/**+ * Read item data.+ * @param obj - The data JSON, or null+ * @returns The data, or null+ */+function parseProtonPassItemData(obj: JsonObject | null): ProtonPassItemData | null {+ if (!obj) {+ return null;+ }+ const metadata = readObject(obj, 'metadata');+ return {+ Metadata: metadata ? { Name: readString(metadata, 'name'), Note: readString(metadata, 'note'), ItemUuid: readString(metadata, 'itemUuid') } : null,+ ExtraFields: readObjectArray(obj, 'extraFields', parseProtonPassExtraField),+ Type: readString(obj, 'type'),+ Content: parseProtonPassContent(readObject(obj, 'content')),+ };+}++/**+ * Read a custom field.+ * @param obj - The field JSON+ * @returns The field+ */+function parseProtonPassExtraField(obj: JsonObject): ProtonPassExtraField {+ const data = readObject(obj, 'data');+ return {+ FieldName: readString(obj, 'fieldName'),+ Type: readString(obj, 'type'),+ Data: data ? { Content: readString(data, 'content') } : null,+ };+}++/**+ * Read type-specific content.+ * @param obj - The content JSON, or null+ * @returns The content, or null+ */+function parseProtonPassContent(obj: JsonObject | null): ProtonPassContent | null {+ if (!obj) {+ return null;+ }++ const passkeys = getProperty(obj, 'passkeys');++ return {+ ItemUsername: readString(obj, 'itemUsername'),+ ItemEmail: readString(obj, 'itemEmail'),+ Password: readString(obj, 'password'),+ Urls: readStringArray(obj, 'urls'),+ TotpUri: readString(obj, 'totpUri'),+ Passkeys: Array.isArray(passkeys)+ ? passkeys.filter(isJsonObject).map((passkey): ProtonPassPasskey => ({ CredentialId: readString(passkey, 'credentialId'), RpId: readString(passkey, 'rpId'), RpName: readString(passkey, 'rpName'), UserName: readString(passkey, 'userName') }))+ : null,+ CardholderName: readString(obj, 'cardholderName'),+ Number: readString(obj, 'number'),+ VerificationNumber: readString(obj, 'verificationNumber'),+ Pin: readString(obj, 'pin'),+ ExpirationDate: readString(obj, 'expirationDate'),+ CardType: readNumber(obj, 'cardType'),+ FirstName: readString(obj, 'firstName'),+ LastName: readString(obj, 'lastName'),+ FullName: readString(obj, 'fullName'),+ Email: readString(obj, 'email'),+ };+}diff --git a/core/client/src/transfer/import/importers/protonpass/ProtonPassZipImporter.ts b/core/client/src/transfer/import/importers/protonpass/ProtonPassZipImporter.tsnew file mode 100644index 000000000..f401392cf--- /dev/null+++ b/core/client/src/transfer/import/importers/protonpass/ProtonPassZipImporter.ts@@ -0,0 +1,194 @@+import { FieldTypes, ItemTypes } from '@aliasvault/models/vault';++import { fromUnixTimeSeconds } from '../../../shared/DateTimeUtils';+import { isBlank, nonBlank, nullIfBlank } from '../../../shared/StringUtils';+import { ImportException, ImportStage } from '../../models/ImportException';+import { readStringAtPath } from '../../readers/JsonReader';+import { convertArchiveItems, openArchive, readArchiveJson } from '../shared/ArchiveImport';+import { addAttachment, addCustomField, mapItemType } from '../shared/CredentialHelpers';++import { ProtonPassItemStates, parseProtonPassItem, parseProtonPassJsonExport, type ProtonPassContent, type ProtonPassItem } from './ProtonPassJson';++import type { ImportedCredential } from '../../models/ImportedCredential';+import type { ImportedCreditcard } from '../../models/ImportedCreditcard';+import type { ImportFileResult } from '../../models/ImportFileResult';++const DATA_JSON_PATH = 'Proton Pass/data.json';+const ENCRYPTED_DATA_PATH = 'Proton Pass/data.pgp';+const FILES_PATH = 'Proton Pass/files/';++/** The default vault; its items go to the root folder instead of a "Personal" folder. */+const DEFAULT_VAULT_NAME = 'personal';++/** A Proton Pass alias is an email alias, not an identity, so it imports as a Login. */+const ITEM_TYPES = {+ login: ItemTypes.Login,+ note: ItemTypes.Note,+ alias: ItemTypes.Login,+ creditcard: ItemTypes.CreditCard,+ identity: ItemTypes.Alias,+};++/**+ * Import a Proton Pass .zip export. Every vault except the default one becomes a folder.+ * @param archiveBytes - The archive bytes+ * @returns The credentials and the items that could not be read+ * @throws {ImportException} When the archive cannot be opened, data.json cannot be read or the export is encrypted.+ */+export function importProtonPassZip(archiveBytes: Uint8Array): ImportFileResult {+ const archive = openArchive(archiveBytes);+ if (archive.has(ENCRYPTED_DATA_PATH)) {+ throw new ImportException(ImportStage.Parse, 'Encrypted Proton Pass exports (data.pgp) are not supported.');+ }++ const exportData = parseProtonPassJsonExport(readArchiveJson(archive, DATA_JSON_PATH));+ if (exportData.Encrypted) {+ throw new ImportException(ImportStage.Parse, 'Encrypted Proton Pass exports are not supported. Please export without a password.');+ }++ const vaults = [...exportData.Vaults.values()];+ const rootVault = vaults.find(vault => vault.Name?.toLowerCase() === DEFAULT_VAULT_NAME);+ const entries = vaults.flatMap(vault => vault.Items.map(element => ({ element, folderPath: vault === rootVault ? null : vault.Name })));+ const files = archive.filesUnder(FILES_PATH);++ return convertArchiveItems(entries, ({ element, folderPath }) => {+ const item = parseProtonPassItem(element);+ if (item.State === ProtonPassItemStates.Trashed || !item.Data) {+ return null;+ }+ const credential = convertItem(item, folderPath);+ addFiles(credential, item, files);+ return credential;+ }, ({ element }) => readStringAtPath(element, 'data', 'metadata', 'name'));+}++/**+ * Convert a Proton Pass item to a credential.+ * @param item - The item, with its data+ * @param folderPath - The vault name, or null for the root folder+ * @returns The credential+ */+function convertItem(item: ProtonPassItem, folderPath: string | null): ImportedCredential {+ const data = item.Data!;+ const content = data.Content;+ const credential: ImportedCredential = {+ ServiceName: data.Metadata?.Name ?? null,+ Notes: data.Metadata?.Note ?? null,+ FolderPath: folderPath,+ CreatedAt: fromUnixTimeSeconds(item.CreateTime),+ UpdatedAt: fromUnixTimeSeconds(item.ModifyTime),+ ItemType: mapItemType(data.Type, ITEM_TYPES) ?? ItemTypes.Login,+ };++ switch (data.Type?.toLowerCase()) {+ case 'login':+ if (content) {+ credential.Username = nullIfBlank(content.ItemUsername);+ credential.Email = nullIfBlank(content.ItemEmail);+ credential.Password = nullIfBlank(content.Password);+ credential.TwoFactorSecret = nullIfBlank(content.TotpUri);+ if (content.Urls && content.Urls.length > 0) {+ credential.ServiceUrls = nonBlank(content.Urls);+ }+ }+ break;+ case 'alias':+ // The generated address lives on the item envelope, not in the content.+ credential.Email = item.AliasEmail;+ credential.Username = item.AliasEmail;+ break;+ case 'creditcard':+ if (content) {+ credential.Creditcard = {+ CardholderName: nullIfBlank(content.CardholderName),+ Number: nullIfBlank(content.Number),+ Cvv: nullIfBlank(content.VerificationNumber),+ Pin: nullIfBlank(content.Pin),+ ...parseExpirationDate(content.ExpirationDate),+ };+ }+ break;+ case 'identity':+ if (content) {+ applyIdentity(credential, content);+ }+ break;+ }++ for (const field of data.ExtraFields ?? []) {+ const value = field.Data?.Content;+ if (isBlank(field.FieldName) || isBlank(value)) {+ continue;+ }++ // A TOTP field, or any field holding an otpauth:// URI, fills the 2FA slot when the login has none.+ const type = field.Type?.toLowerCase();+ if ((type === 'totp' || value.toLowerCase().startsWith('otpauth://')) && isBlank(credential.TwoFactorSecret)) {+ credential.TwoFactorSecret = value;+ continue;+ }++ addCustomField(credential, field.FieldName, value, type === 'hidden' ? FieldTypes.Hidden : FieldTypes.Text);+ }++ return credential;+}++/**+ * Split a Proton Pass expiration, written as "YYYY-MM" (or "MMYY" by older versions), into month and year.+ * @param expirationDate - The expiration text+ * @returns The month and year, empty when the format is not recognised+ */+function parseExpirationDate(expirationDate: string | null): Pick<ImportedCreditcard, 'ExpiryMonth' | 'ExpiryYear'> {+ const value = expirationDate?.trim() ?? '';+ const yearMonth = /^(\d{4})-(\d{1,2})$/.exec(value);+ if (yearMonth) {+ return { ExpiryYear: yearMonth[1], ExpiryMonth: yearMonth[2].padStart(2, '0') };+ }+ const monthYear = /^(\d{2})(\d{2})$/.exec(value);+ return monthYear ? { ExpiryMonth: monthYear[1], ExpiryYear: `20${monthYear[2]}` } : {};+}++/**+ * Take the name and email of an identity; without first and last name, the full name splits on its first space.+ * @param credential - The credential to fill+ * @param content - The identity content+ */+function applyIdentity(credential: ImportedCredential, content: ProtonPassContent): void {+ let firstName = content.FirstName;+ let lastName = content.LastName;+ if (isBlank(firstName) && isBlank(lastName) && !isBlank(content.FullName)) {+ const [first, ...rest] = content.FullName.split(' ').filter(part => part.length > 0);+ firstName = first ?? null;+ lastName = rest.length > 0 ? rest.join(' ') : null;+ }++ credential.Alias = { FirstName: nullIfBlank(firstName), LastName: nullIfBlank(lastName) };+ if (!isBlank(content.Email)) {+ credential.Email = content.Email;+ }+}++/**+ * Attach the files an item references. The layout under "Proton Pass/files/" is not documented, so+ * files/<id>, files/<id>/<name> and files/<id>.<ext> all match.+ * @param credential - The credential to fill+ * @param item - The item+ * @param files - The archive's files under the files folder+ */+function addFiles(credential: ImportedCredential, item: ProtonPassItem, files: Map<string, Uint8Array>): void {+ for (const file of item.Files ?? []) {+ if (isBlank(file.FileId)) {+ continue;+ }++ const id = file.FileId.toLowerCase();+ const match = [...files].find(([path]) => {+ const relative = path.substring(FILES_PATH.length).toLowerCase();+ return relative === id || relative.startsWith(`${id}/`) || relative.startsWith(`${id}.`);+ });+ if (match) {+ addAttachment(credential, isBlank(file.Name) ? file.FileId : file.Name, match[1]);+ }+ }+}