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
import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
import { TDeleteTokenForUserDALDTO } from "./auth-token-types";
export type TTokenDALFactory = ReturnType<typeof tokenDALFactory>;
export const tokenDALFactory = (db: TDbClient) => {
const authOrm = ormify(db, TableName.AuthTokens);
const findOneTokenSession = async (
filter: Partial<TAuthTokenSessions>,
tx?: Knex,
{ readFromPrimary = false }: { readFromPrimary?: boolean } = {}
): Promise<TAuthTokenSessions | undefined> => {
try {
const reader = tx || (readFromPrimary ? db : db.replicaNode());
const doc = await reader(TableName.AuthTokenSession).where(filter).first();
return doc;
} catch (error) {
throw new DatabaseError({ error, name: "FindOneTokenSession" });
}
};
const deleteTokenForUser = async ({
userId,
type,
orgId
}: TDeleteTokenForUserDALDTO): Promise<TAuthTokens[] | undefined> => {
try {
const doc = await db(TableName.AuthTokens).where({ userId, type, orgId }).delete().returning("*");
return doc;
} catch (error) {
throw new DatabaseError({ error, name: "DeleteTokenForUser" });
}
};
// Bulk-deletes tokens for many (type, userId, orgId) tuples in a single query.
// Used to refresh a batch of tokens without opening one transaction per user.
// Note: tuples with a null orgId are not matched (composite IN ignores NULL rows).
const deleteTokensForUsers = async (
tuples: { type: string; userId: string; orgId: string }[],
tx?: Knex
): Promise<void> => {
if (!tuples.length) return;
try {
await (tx || db)(TableName.AuthTokens)
.whereIn(
["type", "userId", "orgId"],
tuples.map(({ type, userId, orgId }) => [type, userId, orgId])
)
.delete();
} catch (error) {
throw new DatabaseError({ error, name: "DeleteTokensForUsers" });
}
};
const decrementTriesField = async ({ userId, type }: TDeleteTokenForUserDALDTO): Promise<void> => {
try {
await db(TableName.AuthTokens).where({ userId, type }).decrement("triesLeft", 1);
} catch (error) {
throw new DatabaseError({ error, name: "DecrementTriesField" });
}
};
const findTokenSessions = async (filter: Partial<TAuthTokenSessions>, tx?: Knex) => {
try {
const sessions = await (tx || db.replicaNode())(TableName.AuthTokenSession)
.where(filter)
.orderBy("lastUsed", "desc");
return sessions;
} catch (error) {
throw new DatabaseError({ name: "Find all token session", error });
}
};
const insertTokenSession = async (
userId: string,
ip: string,
userAgent: string,
tx?: Knex
): Promise<TAuthTokenSessions | undefined> => {
try {
const [session] = await (tx || db)(TableName.AuthTokenSession)
.insert({
userId,
ip,
userAgent,
accessVersion: 1,
refreshVersion: 1,
lastUsed: new Date()
})
.returning("*");
return session;
} catch (error) {
throw new DatabaseError({ error, name: "InsertTokenSession" });
}
};
const incrementTokenSessionVersion = async (
userId: string,
sessionId: string
): Promise<TAuthTokenSessions | undefined> => {
try {
const [session] = await db(TableName.AuthTokenSession)
.where({ userId, id: sessionId })
.increment("accessVersion", 1)
.increment("refreshVersion", 1)
.returning("*");
return session;
} catch (error) {
throw new DatabaseError({ error, name: "IncrementTokenSessionVersion" });
}
};
const incrementRefreshVersion = async (
sessionId: string,
userId: string,
tx?: Knex
): Promise<{ refreshVersion: number; id: string } | undefined> => {
try {
const [session] = await (tx || db)(TableName.AuthTokenSession)
.where({ id: sessionId, userId })
.increment("refreshVersion", 1)
.update({ lastUsed: new Date() })
.returning(["refreshVersion", "id"]);
return session;
} catch (error) {
throw new DatabaseError({ error, name: "IncrementRefreshVersion" });
}
};
const deleteTokenSession = async (filter: Partial<TAuthTokenSessions>, tx?: Knex) => {
try {
const sessions = await (tx || db)(TableName.AuthTokenSession).where(filter).del().returning("*");
return sessions;
} catch (error) {
throw new DatabaseError({ name: "Delete token session", error });
}
};
return {
...authOrm,
findTokenSessions,
deleteTokenForUser,
deleteTokensForUsers,
decrementTriesField,
findOneTokenSession,
insertTokenSession,
incrementTokenSessionVersion,
incrementRefreshVersion,
deleteTokenSession
};
};