Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 8 additions & 26 deletions packages/insomnia/src/account/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ export async function absorbKey(sessionId: string, key: string) {
getUserProfile({ sessionId: sessionIdResolved }),
getEncryptionKeys({ sessionId: sessionIdResolved }),
]);
const {
public_key: publicKey,
enc_private_key: encPrivateKey,
enc_symmetric_key: encSymmetricKey,
} = keys;
const { public_key: publicKey, enc_private_key: encPrivateKey, enc_symmetric_key: encSymmetricKey } = keys;
const { email, id: accountId, first_name: firstName, last_name: lastName } = profile;
const symmetricKeyStr = crypt.decryptAES(key, JSON.parse(encSymmetricKey));

Expand Down Expand Up @@ -67,7 +63,7 @@ export async function getPrivateKey() {
}

export async function getCurrentSessionId() {
const { id } = await services.userSession.getOrCreate();
const { id } = await services.userSession.get();
return id;
}

Expand Down Expand Up @@ -122,42 +118,28 @@ export async function setSessionData(
lastName,
};

const userData = await services.userSession.getOrCreate();
await services.userSession.update(userData, sessionData);
await services.userSession.update(sessionData);

return sessionData;
}

/** Update the session data with vault salt and vault key */
export async function setVaultSessionData(vaultSalt: string, vaultKey: string) {
const userData = await services.userSession.getOrCreate();
await services.userSession.update(userData, { vaultSalt, vaultKey });
await services.userSession.update({ vaultSalt, vaultKey });
}

// ~~~~~~~~~~~~~~~~ //
// Helper Functions //
// ~~~~~~~~~~~~~~~~ //

export async function getUserSession(): Promise<SessionData> {
const userData = await services.userSession.getOrCreate();
const userData = await services.userSession.get();

return userData;
}

async function _unsetSessionData() {
await services.userSession.getOrCreate();
await services.userSession.update(await services.userSession.getOrCreate(), {
id: '',
accountId: '',
email: '',
firstName: '',
lastName: '',
symmetricKey: {} as JsonWebKey,
publicKey: {} as JsonWebKey,
encPrivateKey: {} as crypt.AESMessage,
vaultSalt: '',
vaultKey: '',
});
await services.userSession.remove();
}

/**
Expand Down Expand Up @@ -272,12 +254,12 @@ export async function migrateFromLocalStorage() {
try {
const sessionData = JSON.parse(session) as SessionData;

const currentUserSession = await services.userSession.getOrCreate();
const currentUserSession = await services.userSession.get();

if (currentUserSession.id) {
console.warn('Session already exists, skipping migration');
} else {
await services.userSession.update(currentUserSession, sessionData);
await services.userSession.update(sessionData);
}
} catch (e) {
console.error('Failed to parse session data', e);
Expand Down
2 changes: 1 addition & 1 deletion packages/insomnia/src/common/__tests__/har.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { getRenderedRequestAndContext } from '../render';
describe('export', () => {
beforeEach(async () => {
await db.init({ inMemoryOnly: true }, true);
await services.project.all();
await services.project.list();
await services.settings.getOrCreate();
});

Expand Down
1 change: 0 additions & 1 deletion packages/insomnia/src/common/__tests__/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const reqGroupBuilder = createBuilder(requestGroupModelSchema);

describe('render tests', () => {
beforeEach(async () => {
await services.project.all();
await services.settings.getOrCreate();
envBuilder.reset();
reqGroupBuilder.reset();
Expand Down
5 changes: 2 additions & 3 deletions packages/insomnia/src/common/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ export const importResourcesToNewWorkspace = async ({
}): Promise<Workspace> => {
invariant(resourceCacheItem, 'No resources to import');

const project = await services.project.getById(projectId);
const project = await services.project.get(projectId);
invariant(project, 'Project not found');

const resources = resourceCacheItem.resources;
Expand Down Expand Up @@ -766,8 +766,7 @@ export async function findExistingImportedSpec(
}
| undefined
> {
const allProjects = await services.project.all();
const filteredProjects = organizationId ? allProjects.filter(p => p.parentId === organizationId) : allProjects;
const filteredProjects = await services.project.list({ organizationId });

// match active project first, then look in rest
const projectIds = new Set<string>();
Expand Down
2 changes: 1 addition & 1 deletion packages/insomnia/src/common/organization-storage-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function fetchAndCacheOrganizationStorageRule(
}
}

const { id: sessionId } = await services.userSession.getOrCreate();
const { id: sessionId } = await services.userSession.get();

return await getOrganizationStorageRule({
organizationId,
Expand Down
2 changes: 1 addition & 1 deletion packages/insomnia/src/entry.main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ async function _createModelInstances() {
await services.stats.get();
await services.settings.getOrCreate();
try {
const scratchpadProject = await services.project.getById(models.project.SCRATCHPAD_PROJECT_ID);
const scratchpadProject = await services.project.get(models.project.SCRATCHPAD_PROJECT_ID);
const scratchPad = await services.workspace.getById(models.workspace.SCRATCHPAD_WORKSPACE_ID);
if (!scratchpadProject) {
console.log('[main] Initializing Scratch Pad Project');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import { services } from '~/insomnia-data';
// @vitest-environment jsdom
describe('Request Model - Comprehensive Tests', () => {
beforeEach(async () => {
await services.project.all();
await services.settings.getOrCreate();

// Create test project for all tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import * as mcpResponseService from './mcp-response';
import * as mockRouteService from './mock-route';
import * as mockServerService from './mock-server';
import * as oAuth2TokenService from './o-auth-2-token';
import * as organizationService from './organization';
import * as pluginDataService from './plugin-data';
import * as projectService from './project';
import * as protoDirectoryService from './proto-directory';
Expand Down Expand Up @@ -59,6 +60,7 @@ export const servicesNodeImpl = {
mcpRequest: mcpRequestService,
mcpResponse: mcpResponseService,
oAuth2Token: oAuth2TokenService,
organization: organizationService,
pluginData: pluginDataService,
protoDirectory: protoDirectoryService,
protoFile: protoFileService,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { getOrganizations, type Organization } from 'insomnia-api';

import { models } from '~/insomnia-data';

import * as userSessionService from './user-session';

function sortOrganizations(accountId: string, organizations: Organization[]): Organization[] {
const home = organizations.find(
organization =>
models.organization.isPersonalOrganization(organization) &&
models.organization.isOwnerOfOrganization({
organization,
accountId,
}),
);
const myOrgs = organizations
.filter(
organization =>
!models.organization.isPersonalOrganization(organization) &&
models.organization.isOwnerOfOrganization({
organization,
accountId,
}),
)
.sort((a, b) => a.name.localeCompare(b.name));
const notMyOrgs = organizations
.filter(
organization =>
!models.organization.isOwnerOfOrganization({
organization,
accountId,
}),
)
.sort((a, b) => a.name.localeCompare(b.name));
return [...(home ? [home] : []), ...myOrgs, ...notMyOrgs];
}

/**
* List organizations from the Insomnia cloud API.
*/
export async function list(): Promise<Organization[]> {
const { id: sessionId, accountId } = await userSessionService.get();

if (!sessionId || !accountId) {
return [];
}

const result = await getOrganizations({ sessionId });
const organizations = result?.organizations ?? [];

return sortOrganizations(accountId, organizations);
Comment thread
ZxBing0066 marked this conversation as resolved.
}

/**
* Get a single organization by ID.
*/
export async function get(id: string): Promise<Organization | undefined> {
const all = await list();
return all.find(org => org.id === id);
}
48 changes: 30 additions & 18 deletions packages/insomnia/src/insomnia-data/node-src/services/project.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Project } from '~/insomnia-data';
import type { Project, Query } from '~/insomnia-data';
import { database as db, models } from '~/insomnia-data';

const { type } = models.project;
Expand All @@ -7,30 +7,42 @@ export function create(patch: Partial<Project> = {}) {
return db.docCreate<Project>(type, patch);
}

export function getById(_id: string) {
return db.findOne<Project>(type, { _id });
export function list(options?: { gitRepositoryIds?: string[]; organizationId?: string }) {
const query: Query<Project> = {};
if (options?.organizationId) {
query.parentId = options.organizationId;
}
if (options?.gitRepositoryIds) {
const queryIds = options.gitRepositoryIds.flatMap(id => models.project.getQueryableGitRepositoryIds(id));
query.gitRepositoryId = { $in: queryIds };
}
return db.find<Project>(type, query);
}

export function getByRemoteId(remoteId: string) {
return db.findOne<Project>(type, { remoteId });
}

export function getAllByGitRepositoryIds(gitRepositoryIds: string[]) {
const queryIds = gitRepositoryIds.flatMap(id => models.project.getQueryableGitRepositoryIds(id));
return db.find<Project>(type, {
gitRepositoryId: { $in: queryIds },
});
export function get(id: string) {
return db.findOne<Project>(type, { _id: id });
}

export function remove(project: Project) {
return db.remove(project);
export function getByRemoteId(remoteId: string) {
return db.findOne<Project>(type, { remoteId });
}

export function update(project: Project, patch: Partial<Project>) {
const getProjectByIdOrProject = async (idOrProject: string | Project) => {
const project = typeof idOrProject === 'string' ? await get(idOrProject) : idOrProject;
if (!project) {
throw new Error(
`Project not found: ${typeof idOrProject === 'string' ? idOrProject : `_id=${idOrProject._id}, name=${idOrProject.name}`}`,
);
}
return project;
};

export async function update(idOrProject: string | Project, patch: Partial<Project>) {
const project = await getProjectByIdOrProject(idOrProject);
return db.docUpdate(project, patch);
}

export async function all() {
const projects = await db.find<Project>(type);
return projects;
export async function remove(idOrProject: string | Project) {
const project = await getProjectByIdOrProject(idOrProject);
return db.remove(project);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,23 @@ import { database as db, models } from '~/insomnia-data';

const { type } = models.userSession;

export async function all() {
let userList = await db.find<UserSession>(type);
export async function get() {
const result = await db.findOne<UserSession>(type);

if (userList?.length === 0) {
userList = [await getOrCreate()];
if (!result) {
const user = await db.docCreate<UserSession>(type);
return user;
}

return userList;
}

async function create() {
const user = await db.docCreate<UserSession>(type);
return user;
}

export async function update(user: UserSession, patch: Partial<UserSession>) {
const updatedUser = await db.docUpdate<UserSession>(user, patch);
return updatedUser;
return result;
}

export async function patch(patch: Partial<UserSession>) {
const user = await getOrCreate();
export async function update(patch: Partial<UserSession>) {
const user = await get();
const updatedUser = await db.docUpdate<UserSession>(user, patch);
return updatedUser;
}

export async function getOrCreate() {
const result = await db.findOne<UserSession>(type);

if (!result) {
return await create();
}
return result;
}

export async function get() {
return getOrCreate();
export async function remove() {
const user = await get();
await db.remove(user);
Comment thread
ZxBing0066 marked this conversation as resolved.
}
10 changes: 5 additions & 5 deletions packages/insomnia/src/main/__tests__/sync-initialization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ vi.mock('~/insomnia-data', () => ({
getById: vi.fn(),
},
project: {
getById: vi.fn(),
get: vi.fn(),
},
userSession: {
getOrCreate: vi.fn(),
get: vi.fn(),
},
workspaceMeta: {
getOrCreateByParentId: vi.fn(),
Expand Down Expand Up @@ -68,8 +68,8 @@ describe('sync-initialization', () => {
vi.clearAllMocks();

vi.mocked(services.workspace.getById).mockResolvedValue(workspace);
vi.mocked(services.project.getById).mockResolvedValue(project);
vi.mocked(services.userSession.getOrCreate).mockResolvedValue({ id: 'sess_123' } as any);
vi.mocked(services.project.get).mockResolvedValue(project);
vi.mocked(services.userSession.get).mockResolvedValue({ id: 'sess_123' } as any);
vi.mocked(services.workspaceMeta.getOrCreateByParentId).mockResolvedValue({ gitRepositoryId: null } as any);
vi.mocked(services.environment.getOrCreateForParentId).mockResolvedValue({} as any);
vi.mocked(services.cookieJar.getOrCreateForParentId).mockResolvedValue({} as any);
Expand All @@ -83,7 +83,7 @@ describe('sync-initialization', () => {
});

it('returns early when initializing a workspace backend project without a session', async () => {
vi.mocked(services.userSession.getOrCreate).mockResolvedValue({ id: null } as any);
vi.mocked(services.userSession.get).mockResolvedValue({ id: null } as any);

await initializeWorkspaceBackendProject({ workspaceId: workspace._id });

Expand Down
4 changes: 2 additions & 2 deletions packages/insomnia/src/main/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export async function trackSegmentEvent(event: SegmentEvent, properties?: Record
return;
}
const settings = await services.settings.getOrCreate();
const userSession = await services.userSession.getOrCreate();
const userSession = await services.userSession.get();
if (!userSession?.hashedAccountId) {
userSession.hashedAccountId = userSession?.accountId ? hashString(userSession.accountId) : '';
}
Expand Down Expand Up @@ -142,7 +142,7 @@ export async function trackPageView(name: string) {
return;
}
const settings = await services.settings.getOrCreate();
const userSession = await services.userSession.getOrCreate();
const userSession = await services.userSession.get();
if (!userSession?.hashedAccountId) {
userSession.hashedAccountId = userSession?.accountId ? hashString(userSession.accountId) : '';
}
Expand Down
Loading
Loading