Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: add keeper sync fns file
adilson59525501fb13
diff --git a/backend/src/services/app-connection/keeper/keeper-connection-fns.ts b/backend/src/services/app-connection/keeper/keeper-connection-fns.tsindex a472b1956c..f29b064812 100644--- a/backend/src/services/app-connection/keeper/keeper-connection-fns.ts+++ b/backend/src/services/app-connection/keeper/keeper-connection-fns.ts@@ -2,29 +2,61 @@ import { HttpStatusCode, isAxiosError } from "axios";import { BadRequestError } from "@app/lib/errors";import { removeTrailingSlash } from "@app/lib/fn/string";+import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator/safe-request";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { KeeperConnectionMethod } from "./keeper-connection-enums";-import { TKeeperConnectionConfig, TKeeperExecuteCommandResponse } from "./keeper-connection-types";+import {+ TKeeperCommandResponse,+ TKeeperConnection,+ TKeeperConnectionConfig,+ TKeeperCredentials,+ TKeeperListSharedFoldersRow,+ TKeeperSharedFolder+} from "./keeper-connection-types";-export const getKeeperConnectionListItem = () => {- return {- name: "Keeper" as const,- app: AppConnection.Keeper as const,- methods: Object.values(KeeperConnectionMethod) as [KeeperConnectionMethod.ApiKey]- };+export const KEEPER_UID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;++export const isAddressableKeeperUid = (uid: string) => KEEPER_UID_PATTERN.test(uid) && !uid.startsWith("-");++export const quoteKeeperArg = (value: string) => `'${value.replace(/'/g, `'"'"'`)}'`;++export class KeeperCommandError extends Error {+ statusCode?: number;++ constructor({ message, statusCode }: { message: string; statusCode?: number }) {+ super(message);+ this.name = "KeeperCommandError";+ this.statusCode = statusCode;+ }+}++const redactSensitiveValues = (text: string, sensitiveValues: string[]) =>+ sensitiveValues.filter(Boolean).reduce((redacted, value) => redacted.split(value).join("[REDACTED]"), text);++const getKeeperErrorReason = (body: unknown) => {+ if (!body || typeof body !== "object") return undefined;++ const { error, message } = body as TKeeperCommandResponse;+ if (typeof error === "string" && error.trim()) return error.trim();+ if (typeof message === "string" && message.trim()) return message.trim();++ return undefined;};-export const validateKeeperConnectionCredentials = async (config: TKeeperConnectionConfig) => {- const { apiKey, instanceUrl } = config.credentials;- const baseUrl = removeTrailingSlash(instanceUrl);+export const executeKeeperCommand = async <T = unknown>(+ { apiKey, instanceUrl }: TKeeperCredentials,+ command: string,+ { sensitiveValues = [] }: { sensitiveValues?: string[] } = {}+) => {+ const [commandName] = command.split(" ");- let response: TKeeperExecuteCommandResponse | undefined;+ let response: TKeeperCommandResponse<T>;try {- const { data } = await safeRequest.post<TKeeperExecuteCommandResponse>(- `${baseUrl}/api/v1/executecommand`,- { command: "whoami" },+ const { data } = await safeRequest.post<TKeeperCommandResponse<T>>(+ `${removeTrailingSlash(instanceUrl)}/api/v1/executecommand`,+ { command },{headers: {"api-key": apiKey,@@ -40,31 +72,76 @@ export const validateKeeperConnectionCredentials = async (config: TKeeperConnect}if (isAxiosError(error) && error.response) {+ logger.error({ error }, "Keeper Commander error");const { status } = error.response;+ const reason = getKeeperErrorReason(error.response.data as unknown);- if (status === HttpStatusCode.Unauthorized || status === HttpStatusCode.Forbidden) {- throw new BadRequestError({- message: "Unable to validate connection: the Keeper API key was rejected. Verify the key and try again."- });- }-- throw new BadRequestError({- message: `Unable to validate connection: Keeper Commander returned ${status} status. Verify the instance URL and API key and try again.`+ throw new KeeperCommandError({+ statusCode: status,+ message: reason+ ? `Keeper Commander failed to run '${commandName}' (${status} status): ${redactSensitiveValues(reason, sensitiveValues)}`+ : `Keeper Commander returned ${status} status when running '${commandName}'.`});}- throw new BadRequestError({- message:- "Unable to validate connection: could not reach Keeper Commander. Verify the instance URL points to a running Commander Service Mode instance."+ const networkErrorCode = isAxiosError(error) && error.code ? ` (${error.code})` : "";++ throw new KeeperCommandError({+ message: `Could not reach Keeper Commander${networkErrorCode}. Verify the instance URL points to a running Commander Service Mode instance.`});}if (response?.status !== "success") {- throw new BadRequestError({- message:- "Unable to validate connection: Keeper Commander did not accept the request. Verify the API key is allowed to run the 'whoami' command."+ const reason = getKeeperErrorReason(response);++ throw new KeeperCommandError({+ message: reason+ ? `Keeper Commander failed to run '${commandName}': ${redactSensitiveValues(reason, sensitiveValues)}`+ : `Keeper Commander did not accept the '${commandName}' command. Verify the API key is allowed to run it.`});}+ return response.data;+};++export const getKeeperConnectionListItem = () => {+ return {+ name: "Keeper" as const,+ app: AppConnection.Keeper as const,+ methods: Object.values(KeeperConnectionMethod) as [KeeperConnectionMethod.ApiKey]+ };+};++export const validateKeeperConnectionCredentials = async (config: TKeeperConnectionConfig) => {+ try {+ await executeKeeperCommand(config.credentials, "whoami");+ } catch (error: unknown) {+ if (!(error instanceof KeeperCommandError)) {+ throw error;+ }++ if (error.statusCode === HttpStatusCode.Unauthorized || error.statusCode === HttpStatusCode.Forbidden) {+ throw new BadRequestError({+ message: "Unable to validate connection: the Keeper API key was rejected. Verify the key and try again."+ });+ }++ throw new BadRequestError({ message: `Unable to validate connection: ${error.message}` });+ }+return config.credentials;};++export const listKeeperSharedFolders = async (appConnection: TKeeperConnection): Promise<TKeeperSharedFolder[]> => {+ const rows = await executeKeeperCommand<TKeeperListSharedFoldersRow[]>(+ appConnection.credentials,+ "list-sf --format=json"+ );++ if (!Array.isArray(rows)) return [];++ return rows+ .filter((row) => typeof row?.shared_folder_uid === "string" && KEEPER_UID_PATTERN.test(row.shared_folder_uid))+ .map((row) => ({ uid: row.shared_folder_uid, name: row.name || row.shared_folder_uid }))+ .sort((a, b) => a.name.localeCompare(b.name));+};diff --git a/backend/src/services/app-connection/keeper/keeper-connection-types.ts b/backend/src/services/app-connection/keeper/keeper-connection-types.tsindex f45396b1ed..2a283ba34e 100644--- a/backend/src/services/app-connection/keeper/keeper-connection-types.ts+++ b/backend/src/services/app-connection/keeper/keeper-connection-types.ts@@ -21,6 +21,26 @@ export type TKeeperConnectionConfig = DiscriminativePick<TKeeperConnectionInput,orgId: string;};-export type TKeeperExecuteCommandResponse = {+export type TKeeperCredentials = {+ apiKey: string;+ instanceUrl: string;+};++export type TKeeperCommandResponse<T = unknown> = {status?: string;+ command?: string;+ data?: T;+ error?: string;+ message?: string;+};++export type TKeeperListSharedFoldersRow = {+ shared_folder_uid: string;+ name: string;+ folder_type?: string;+};++export type TKeeperSharedFolder = {+ uid: string;+ name: string;};diff --git a/backend/src/services/secret-sync/keeper/index.ts b/backend/src/services/secret-sync/keeper/index.tsnew file mode 100644index 0000000000..8e15a58231--- /dev/null+++ b/backend/src/services/secret-sync/keeper/index.ts@@ -0,0 +1,4 @@+export * from "./keeper-sync-constants";+export * from "./keeper-sync-fns";+export * from "./keeper-sync-schemas";+export * from "./keeper-sync-types";diff --git a/backend/src/services/secret-sync/keeper/keeper-sync-fns.test.ts b/backend/src/services/secret-sync/keeper/keeper-sync-fns.test.tsnew file mode 100644index 0000000000..f2b5b057a8--- /dev/null+++ b/backend/src/services/secret-sync/keeper/keeper-sync-fns.test.ts@@ -0,0 +1,277 @@+import { AxiosError, AxiosHeaders } from "axios";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { KeeperCommandError } from "@app/services/app-connection/keeper";++import { SecretSyncError } from "../secret-sync-errors";+import { TSecretSyncPayload } from "../secret-sync-payload";+import { KeeperSyncFns } from "./keeper-sync-fns";+import { TKeeperSyncWithCredentials } from "./keeper-sync-types";++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({}) }));+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const { post } = vi.hoisted(() => ({ post: vi.fn() }));+vi.mock("@app/lib/validator/safe-request", () => ({ safeRequest: { post } }));++type TFakeRecord = { uid: string; title: string; type?: string; password?: string };++const FOLDER_UID = "FolderUid_123-abc";++const syncWith = (syncOptions: { disableSecretDeletion?: boolean; keySchema?: string } = {}, folderUid = FOLDER_UID) =>+ ({+ destination: "keeper",+ destinationConfig: { folderUid, folderName: "Shared" },+ environment: { slug: "dev" },+ syncOptions: { disableSecretDeletion: false, ...syncOptions },+ connection: { method: "api-key", credentials: { apiKey: "api-key", instanceUrl: "https://keeper.example.com/" } }+ }) as unknown as TKeeperSyncWithCredentials;++const payloadOf = (secrets: Record<string, string>) =>+ ({+ flatten: () => Object.fromEntries(Object.entries(secrets).map(([key, value]) => [key, { value }]))+ }) as unknown as TSecretSyncPayload;++const success = (data: unknown) => ({ data: { status: "success", command: "test", data } });++const base64 = (value: string) => Buffer.from(value, "utf8").toString("base64");++const fakeKeeper = (+ records: TFakeRecord[],+ lsShape: "rows" | "grouped" = "rows",+ respondToWrite?: (command: string) => unknown+) => {+ post.mockImplementation(async (_url: string, { command }: { command: string }) => {+ if (command.startsWith("ls ")) {+ if (lsShape === "grouped") {+ return success({+ folders: [{ uid: "SubFolder", name: "Nested" }],+ records: records.map((record) => ({ uid: record.uid, title: record.title, type: record.type ?? "login" }))+ });+ }++ return success([+ { type: "folder", uid: "SubFolder", name: "Nested", details: "Flags: S" },+ ...records.map((record) => ({+ type: "record",+ uid: record.uid,+ name: record.title,+ details: `Type: ${record.type ?? "login"}, Description: `+ }))+ ]);+ }++ if (command.startsWith("get ")) {+ const record = records.find((r) => command === `get --format=json ${r.uid}`);+ return success({+ record_uid: record?.uid,+ title: record?.title,+ type: record?.type ?? "login",+ fields: [+ { type: "login", value: [] },+ { type: "password", value: record?.password === undefined ? [] : [record.password] }+ ]+ });+ }++ return respondToWrite?.(command) ?? success(null);+ });+};++const sentCommands = () => post.mock.calls.map(([, body]) => (body as { command: string }).command);++const writeCommands = () => sentCommands().filter((command) => !/^(ls|get) /.test(command));++describe("KeeperSyncFns", () => {+ beforeEach(() => {+ post.mockReset();+ });++ it("sends every command to the Service Mode endpoint with the API key", async () => {+ fakeKeeper([]);++ await KeeperSyncFns.getSecrets(syncWith());++ const [url, body, options] = post.mock.calls[0] as [+ string,+ { command: string },+ { headers: Record<string, string> }+ ];+ expect(url).toBe("https://keeper.example.com/api/v1/executecommand");+ expect(body).toEqual({ command: `ls --format=json ${FOLDER_UID}` });+ expect(options.headers["api-key"]).toBe("api-key");+ });++ it("creates missing records, updates changed ones and skips unchanged ones", async () => {+ fakeKeeper([+ { uid: "uid-same", title: "SAME", password: "unchanged" },+ { uid: "uid-changed", title: "CHANGED", password: "old" }+ ]);++ await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ SAME: "unchanged", CHANGED: "new", NEW: "fresh" }));++ expect(writeCommands()).toEqual([+ `record-update -f --record=uid-changed 'password=$BASE64:${base64("new")}'`,+ `record-add -f --folder=${FOLDER_UID} --record-type=login --title='NEW' 'password=$BASE64:${base64("fresh")}'`+ ]);+ });++ it("quotes titles so quotes, spaces and leading dashes survive shell tokenizing", async () => {+ fakeKeeper([]);++ await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ '-it\'s a "key"': "value with 'quotes'\nand lines" }));++ expect(writeCommands()).toEqual([+ `record-add -f --folder=${FOLDER_UID} --record-type=login --title='-it'"'"'s a "key"' 'password=$BASE64:${base64(+ "value with 'quotes'\nand lines"+ )}'`+ ]);+ });++ it("rejects keys Commander would expand as variables before writing anything", async () => {+ fakeKeeper([]);++ const error = await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ OK: "a", [`\${HOME}`]: "b" })).catch(+ (err: unknown) => err+ );++ expect(error).toBeInstanceOf(SecretSyncError);+ expect((error as SecretSyncError).shouldRetry).toBe(false);+ expect((error as SecretSyncError).secretKey).toBe(`\${HOME}`);+ expect(post).not.toHaveBeenCalled();+ });++ it("deletes stale records that match the key schema", async () => {+ fakeKeeper([+ { uid: "uid-keep", title: "INF_KEEP", password: "a" },+ { uid: "uid-stale", title: "INF_STALE", password: "b" },+ { uid: "uid-foreign", title: "FOREIGN", password: "c" }+ ]);++ await KeeperSyncFns.syncSecrets(syncWith({ keySchema: "INF_{{secretKey}}" }), payloadOf({ INF_KEEP: "a" }));++ expect(writeCommands()).toEqual(["rm -f --purge uid-stale"]);+ });++ it("keeps stale records when secret deletion is disabled", async () => {+ fakeKeeper([{ uid: "uid-stale", title: "STALE", password: "b" }]);++ await KeeperSyncFns.syncSecrets(syncWith({ disableSecretDeletion: true }), payloadOf({}));++ expect(writeCommands()).toEqual([]);+ });++ it("deletes duplicate records that share a synced title", async () => {+ fakeKeeper([+ { uid: "uid-first", title: "DUP", password: "value" },+ { uid: "uid-second", title: "DUP", password: "other" }+ ]);++ await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ DUP: "value" }));++ expect(writeCommands()).toEqual(["rm -f --purge uid-second"]);+ });++ it("never touches records that are not login records", async () => {+ fakeKeeper([{ uid: "uid-db", title: "DB", type: "databaseCredentials", password: "secret" }]);++ await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({}));++ expect(writeCommands()).toEqual([]);+ });++ it("skips record UIDs that are not valid Keeper UIDs", async () => {+ fakeKeeper([{ uid: "bad uid'; rm", title: "BAD", password: "x" }]);++ await expect(KeeperSyncFns.getSecrets(syncWith())).resolves.toEqual({});+ expect(sentCommands()).toEqual([`ls --format=json ${FOLDER_UID}`]);+ });++ it("skips records whose UID starts with a dash, since Service Mode blocks the -- separator", async () => {+ fakeKeeper([+ { uid: "-dashUid", title: "DASH", password: "x" },+ { uid: "uid-a", title: "A", password: "a" }+ ]);++ await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ A: "a" }));++ expect(sentCommands()).toEqual([`ls --format=json ${FOLDER_UID}`, "get --format=json uid-a"]);+ });++ it("refuses a shared folder whose UID starts with a dash before sending anything", async () => {+ fakeKeeper([]);++ const error = await KeeperSyncFns.syncSecrets(syncWith({}, "-folderUid"), payloadOf({ A: "a" })).catch(+ (err: unknown) => err+ );++ expect(error).toBeInstanceOf(SecretSyncError);+ expect((error as SecretSyncError).shouldRetry).toBe(false);+ expect(post).not.toHaveBeenCalled();+ });++ it.each(["rows", "grouped"] as const)("imports login records from the %s ls shape", async (lsShape) => {+ fakeKeeper(+ [+ { uid: "uid-a", title: "A", password: "a-value" },+ { uid: "uid-empty", title: "EMPTY" },+ { uid: "uid-note", title: "NOTE", type: "encryptedNotes" }+ ],+ lsShape+ );++ await expect(KeeperSyncFns.getSecrets(syncWith())).resolves.toEqual({+ A: { value: "a-value" },+ EMPTY: { value: "" }+ });+ });++ it("removes only the records named in the payload", async () => {+ fakeKeeper([+ { uid: "uid-a", title: "A", password: "a" },+ { uid: "uid-b", title: "B", password: "b" }+ ]);++ await KeeperSyncFns.removeSecrets(syncWith(), payloadOf({ A: "a" }));++ expect(writeCommands()).toEqual(["rm -f --purge uid-a"]);+ });++ it("redacts the secret value from Keeper's error text", async () => {+ fakeKeeper([], "rows", (command) =>+ command.startsWith("record-add")+ ? { data: { status: "error", command: "record-add", error: `Invalid value s3cr3t (${base64("s3cr3t")})` } }+ : undefined+ );++ const error = (await KeeperSyncFns.syncSecrets(syncWith(), payloadOf({ KEY: "s3cr3t" })).catch(+ (err: unknown) => err+ )) as SecretSyncError;++ expect(error).toBeInstanceOf(SecretSyncError);+ expect(error.secretKey).toBe("KEY");+ expect(error.error).toBeInstanceOf(KeeperCommandError);+ const { message } = error.error as KeeperCommandError;+ expect(message).toContain("record-add");+ expect(message).not.toContain("s3cr3t");+ expect(message).not.toContain(base64("s3cr3t"));+ });++ it("wraps HTTP failures without exposing the Axios error", async () => {+ post.mockRejectedValue(+ new AxiosError("forbidden", "ERR_BAD_REQUEST", undefined, undefined, {+ status: 403,+ statusText: "Forbidden",+ headers: {},+ config: { headers: new AxiosHeaders() },+ data: { status: "error", error: "Command 'ls' is not allowed for this API key" }+ })+ );++ const error = await KeeperSyncFns.getSecrets(syncWith()).catch((err: unknown) => err);++ expect(error).toBeInstanceOf(KeeperCommandError);+ expect((error as KeeperCommandError).statusCode).toBe(403);+ expect((error as KeeperCommandError).message).toContain("is not allowed for this API key");+ });+});diff --git a/backend/src/services/secret-sync/keeper/keeper-sync-fns.ts b/backend/src/services/secret-sync/keeper/keeper-sync-fns.tsnew file mode 100644index 0000000000..ee36c426d9--- /dev/null+++ b/backend/src/services/secret-sync/keeper/keeper-sync-fns.ts@@ -0,0 +1,202 @@+/* eslint-disable no-await-in-loop */+import { logger } from "@app/lib/logger";+import {+ executeKeeperCommand,+ isAddressableKeeperUid,+ KEEPER_UID_PATTERN,+ quoteKeeperArg,+ TKeeperCredentials+} from "@app/services/app-connection/keeper";+import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";+import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";+import { TSecretSyncPayload } from "@app/services/secret-sync/secret-sync-payload";+import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";++import {+ TKeeperListResponse,+ TKeeperLoginRecord,+ TKeeperRecord,+ TKeeperSyncWithCredentials+} from "./keeper-sync-types";++const KEEPER_LOGIN_RECORD_TYPE = "login";+const KEEPER_VARIABLE_EXPANSION_TOKEN = "${";++const getListedRecordUids = (listing: TKeeperListResponse | undefined) => {+ const entries = Array.isArray(listing)+ ? listing.filter((entry) => entry?.type === "record")+ : (listing?.records ?? []);++ return entries+ .map((entry) => entry?.uid ?? entry?.record_uid)+ .filter((uid): uid is string => typeof uid === "string" && KEEPER_UID_PATTERN.test(uid));+};++const getPasswordValue = (record: TKeeperRecord) => {+ const [value] = record.fields?.find((field) => field?.type === "password")?.value ?? [];+ return typeof value === "string" ? value : "";+};++const listKeeperLoginRecords = async (credentials: TKeeperCredentials, folderUid: string) => {+ if (!isAddressableKeeperUid(folderUid)) {+ throw new SecretSyncError({+ shouldRetry: false,+ message: `Keeper shared folder UID '${folderUid}' cannot be addressed through Keeper Commander Service Mode. Choose a different shared folder.`+ });+ }++ const listing = await executeKeeperCommand<TKeeperListResponse>(credentials, `ls --format=json ${folderUid}`);++ const listedUids = getListedRecordUids(listing);+ const unaddressableUids = listedUids.filter((uid) => !isAddressableKeeperUid(uid));+ if (unaddressableUids.length) {+ logger.warn(+ `Skipping Keeper records whose UID starts with '-', which Service Mode cannot address [folderUid=${folderUid}] [recordUids=${unaddressableUids.join(",")}]`+ );+ }++ const records = new Map<string, TKeeperLoginRecord>();+ const duplicates: TKeeperLoginRecord[] = [];++ for (const uid of listedUids.filter(isAddressableKeeperUid)) {+ const record = await executeKeeperCommand<TKeeperRecord>(credentials, `get --format=json ${uid}`);++ if (record?.type !== KEEPER_LOGIN_RECORD_TYPE || typeof record.title !== "string") {+ // eslint-disable-next-line no-continue+ continue;+ }++ const loginRecord = { uid, title: record.title, value: getPasswordValue(record) };++ if (records.has(loginRecord.title)) {+ duplicates.push(loginRecord);+ } else {+ records.set(loginRecord.title, loginRecord);+ }+ }++ return { records, duplicates };+};++const getPasswordFieldArg = (value: string) => {+ const encodedValue = Buffer.from(value, "utf8").toString("base64");++ return {+ arg: quoteKeeperArg(`password=$BASE64:${encodedValue}`),+ sensitiveValues: [value, encodedValue]+ };+};++const createKeeperLoginRecord = (credentials: TKeeperCredentials, folderUid: string, title: string, value: string) => {+ const { arg, sensitiveValues } = getPasswordFieldArg(value);++ return executeKeeperCommand(+ credentials,+ `record-add -f --folder=${folderUid} --record-type=${KEEPER_LOGIN_RECORD_TYPE} --title=${quoteKeeperArg(title)} ${arg}`,+ { sensitiveValues }+ );+};++const updateKeeperLoginRecordValue = (credentials: TKeeperCredentials, recordUid: string, value: string) => {+ const { arg, sensitiveValues } = getPasswordFieldArg(value);++ return executeKeeperCommand(credentials, `record-update -f --record=${recordUid} ${arg}`, {+ sensitiveValues+ });+};++const deleteKeeperRecord = (credentials: TKeeperCredentials, recordUid: string) =>+ executeKeeperCommand(credentials, `rm -f --purge ${recordUid}`);++export const KeeperSyncFns = {+ async syncSecrets(secretSync: TKeeperSyncWithCredentials, payload: TSecretSyncPayload) {+ const secretMap = payload.flatten();+ const {+ connection,+ environment,+ destinationConfig: { folderUid },+ syncOptions: { disableSecretDeletion, keySchema }+ } = secretSync;++ const unsupportedKeys = Object.keys(secretMap).filter((key) => key.includes(KEEPER_VARIABLE_EXPANSION_TOKEN));+ if (unsupportedKeys.length) {+ throw new SecretSyncError({+ secretKey: unsupportedKeys[0],+ shouldRetry: false,+ message: `${unsupportedKeys.length} secret ${+ unsupportedKeys.length === 1 ? "key contains" : "keys contain"+ } "${KEEPER_VARIABLE_EXPANSION_TOKEN}", which Keeper Commander expands as a variable in record titles: ${unsupportedKeys.join(+ ", "+ )}. Rename the ${unsupportedKeys.length === 1 ? "secret" : "secrets"} or adjust the key schema.`+ });+ }++ const { records, duplicates } = await listKeeperLoginRecords(connection.credentials, folderUid);++ for (const [key, { value }] of Object.entries(secretMap)) {+ const existing = records.get(key);++ try {+ if (!existing) {+ await createKeeperLoginRecord(connection.credentials, folderUid, key, value);+ } else if (existing.value !== value) {+ await updateKeeperLoginRecordValue(connection.credentials, existing.uid, value);+ }+ } catch (error) {+ throw new SecretSyncError({ error, secretKey: key });+ }+ }++ if (disableSecretDeletion) return;++ const staleRecords = [+ ...duplicates,+ ...Array.from(records.values()).filter((record) => !Object.hasOwn(secretMap, record.title))+ ];++ for (const record of staleRecords) {+ if (!matchesSchema(record.title, environment?.slug || "", keySchema)) {+ // eslint-disable-next-line no-continue+ continue;+ }++ try {+ await deleteKeeperRecord(connection.credentials, record.uid);+ } catch (error) {+ throw new SecretSyncError({ error, secretKey: record.title });+ }+ }+ },++ async getSecrets(secretSync: TKeeperSyncWithCredentials): Promise<TSecretMap> {+ const { records } = await listKeeperLoginRecords(+ secretSync.connection.credentials,+ secretSync.destinationConfig.folderUid+ );++ return Object.fromEntries(Array.from(records.values()).map((record) => [record.title, { value: record.value }]));+ },++ async removeSecrets(secretSync: TKeeperSyncWithCredentials, payload: TSecretSyncPayload) {+ const secretMap = payload.flatten();+ const {+ connection,+ destinationConfig: { folderUid }+ } = secretSync;++ const { records, duplicates } = await listKeeperLoginRecords(connection.credentials, folderUid);++ for (const record of [...records.values(), ...duplicates]) {+ if (!Object.hasOwn(secretMap, record.title)) {+ // eslint-disable-next-line no-continue+ continue;+ }++ try {+ await deleteKeeperRecord(connection.credentials, record.uid);+ } catch (error) {+ throw new SecretSyncError({ error, secretKey: record.title });+ }+ }+ }+};diff --git a/backend/src/services/secret-sync/keeper/keeper-sync-types.ts b/backend/src/services/secret-sync/keeper/keeper-sync-types.tsnew file mode 100644index 0000000000..612f687d40--- /dev/null+++ b/backend/src/services/secret-sync/keeper/keeper-sync-types.ts@@ -0,0 +1,41 @@+import z from "zod";++import { TKeeperConnection } from "@app/services/app-connection/keeper";++import { CreateKeeperSyncSchema, KeeperSyncListItemSchema, KeeperSyncSchema } from "./keeper-sync-schemas";++export type TKeeperSyncListItem = z.infer<typeof KeeperSyncListItemSchema>;++export type TKeeperSync = z.infer<typeof KeeperSyncSchema>;++export type TKeeperSyncInput = z.infer<typeof CreateKeeperSyncSchema>;++export type TKeeperSyncWithCredentials = TKeeperSync & {+ connection: TKeeperConnection;+};++export type TKeeperListEntry = {+ type?: string;+ uid?: string;+ record_uid?: string;+};++export type TKeeperListResponse = TKeeperListEntry[] | { records?: TKeeperListEntry[] };++export type TKeeperRecordField = {+ type?: string;+ value?: unknown[];+};++export type TKeeperRecord = {+ record_uid?: string;+ title?: string;+ type?: string;+ fields?: TKeeperRecordField[];+};++export type TKeeperLoginRecord = {+ uid: string;+ title: string;+ value: string;+};