Improve lint anf fmt cmds

This commit is contained in:
EthanShoeDev
2025-09-09 21:21:12 -04:00
parent f7d1d3b0f4
commit 638cfc49cb
15 changed files with 5266 additions and 1992 deletions

View File

@@ -1,7 +1,9 @@
{
"editor.codeActionsOnSave": {
"source.organizeImports": "never",
"source.fixAll": "explicit",
"source.organizeImports": "explicit",
"source.sortMembers": "explicit"
}
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}

View File

@@ -1,12 +1,27 @@
// https://docs.expo.dev/guides/using-eslint/
const { defineConfig } = require('eslint/config');
const expoConfig = require('eslint-config-expo/flat');
// const { config: epicConfig } = require('@epic-web/config/eslint')
import { createRequire } from 'node:module';
import { config as epicConfig } from '@epic-web/config/eslint';
import { defineConfig } from 'eslint/config';
module.exports = defineConfig([
expoConfig,
// ...epicConfig,
const require = createRequire(import.meta.url);
const expoConfig = require('eslint-config-expo/flat');
// // Both epic and expo define a 'import' plugin (though not the same package)
// // We need to pick one or they will conflict.
const stripImportPlugin = (config) => {
if (!config?.plugins?.['import']) return config;
const { import: _removed, ...rest } = config.plugins;
return {
...config,
plugins: rest,
};
};
export default defineConfig([
...expoConfig,
...epicConfig.map(stripImportPlugin),
{
ignores: ['dist/*'],
ignores: ['dist'],
},
]);

View File

@@ -2,6 +2,7 @@
"name": "fressh",
"main": "expo-router/entry",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
@@ -9,8 +10,10 @@
"ios": "expo run:ios",
"web": "expo start --web",
"lint": "expo lint",
"format": "SORT_IMPORTS=true prettier . --write",
"typecheck": "tsc"
"fmt": "SORT_IMPORTS=true prettier . --write",
"typecheck": "tsc",
"validate": "run-p -l fmt lint typecheck",
"update:all": "pnpm dlx npm-check-updates --interactive --format group"
},
"dependencies": {
"@dylankenneally/react-native-ssh-sftp": "^1.5.20",
@@ -50,8 +53,9 @@
"@types/react": "~19.1.0",
"eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0",
"jiti": "^2.5.1",
"npm-run-all": "^4.1.5",
"prettier": "^3.6.2",
"prettier-plugin-organize-imports": "^4.2.0",
"tsx": "^4.20.5",
"typescript": "~5.9.2"
}

6636
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
nodeLinker: hoisted
onlyBuiltDependencies:
- esbuild
- unrs-resolver

View File

@@ -1,15 +1,14 @@
import defaultConfig from '@epic-web/config/prettier';
// const defaultConfig = require('@epic-web/config/prettier')
// Sometimes this plugin can remove imports that are in use.
// As a workaround we will only use this in the cli. (npm run fmt)
const sortImports = process.env.SORT_IMPORTS === 'true';
// Sometimes this plugin can remove imports that are being edited.
// As a workaround we will only use this in the cli. (pnpm run fmt)
// const sortImports = process.env.SORT_IMPORTS === "true";
/** @type {import("prettier").Options} */
export default {
...defaultConfig,
semi: true,
plugins: [
...(sortImports ? ['prettier-plugin-organize-imports'] : []),
// ...(sortImports ? ["prettier-plugin-organize-imports"] : []),
...(defaultConfig.plugins || []),
],
};

View File

@@ -1,11 +1,11 @@
import { QueryClientProvider } from '@tanstack/react-query'
import { Stack } from 'expo-router'
import { queryClient } from '../lib/utils'
import { QueryClientProvider } from '@tanstack/react-query';
import { Stack } from 'expo-router';
import { queryClient } from '../lib/utils';
export default function RootLayout() {
return (
<QueryClientProvider client={queryClient}>
<Stack screenOptions={{ headerShown: false }} />
</QueryClientProvider>
)
);
}

View File

@@ -1,16 +1,16 @@
import SSHClient, { PtyType } from '@dylankenneally/react-native-ssh-sftp'
import { Picker } from '@react-native-picker/picker'
import { useStore } from '@tanstack/react-form'
import { useQuery } from '@tanstack/react-query'
import { useRouter } from 'expo-router'
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { useAppForm, withFieldGroup } from '../components/form-components'
import SSHClient, { PtyType } from '@dylankenneally/react-native-ssh-sftp';
import { Picker } from '@react-native-picker/picker';
import { useStore } from '@tanstack/react-form';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { useAppForm, withFieldGroup } from '../components/form-components';
import {
ConnectionDetails,
type ConnectionDetails,
connectionDetailsSchema,
secretsManager,
} from '../lib/secrets-manager'
import { sshConnectionManager } from '../lib/ssh-connection-manager'
} from '../lib/secrets-manager';
import { sshConnectionManager } from '../lib/ssh-connection-manager';
const defaultValues: ConnectionDetails = {
host: 'test.rebex.net',
@@ -20,13 +20,16 @@ const defaultValues: ConnectionDetails = {
type: 'password',
password: 'password',
},
}
};
export default function Index() {
const router = useRouter()
const storedConnectionsQuery = useQuery(secretsManager.connections.query.list)
const router = useRouter();
const storedConnectionsQuery = useQuery(
secretsManager.connections.query.list,
);
const preferredStoredConnection = storedConnectionsQuery.data?.firstConnection
const preferredStoredConnection =
storedConnectionsQuery.data?.firstConnection;
const connectionForm = useAppForm({
// https://tanstack.com/form/latest/docs/framework/react/guides/async-initial-values
defaultValues: preferredStoredConnection
@@ -36,7 +39,7 @@ export default function Index() {
onChange: connectionDetailsSchema,
onSubmitAsync: async ({ value }) => {
try {
console.log('Connecting to SSH server...')
console.log('Connecting to SSH server...');
const sshClientConnection = await (async () => {
if (value.security.type === 'password') {
return await SSHClient.connectWithPassword(
@@ -44,47 +47,52 @@ export default function Index() {
value.port,
value.username,
value.security.password,
)
);
}
const privateKey = await secretsManager.keys.utils.getPrivateKey(
value.security.keyId,
)
);
return await SSHClient.connectWithKey(
value.host,
value.port,
value.username,
privateKey.privateKey,
)
})()
);
})();
await secretsManager.connections.utils.upsertConnection({
id: 'default',
details: value,
priority: 0,
})
await sshClientConnection.startShell(PtyType.XTERM)
});
await sshClientConnection.startShell(PtyType.XTERM);
const sshConn = sshConnectionManager.addSession({
client: sshClientConnection,
})
console.log('Connected to SSH server', sshConn.sessionId)
});
console.log('Connected to SSH server', sshConn.sessionId);
router.push({
pathname: '/shell',
params: {
sessionId: sshConn.sessionId,
},
})
});
} catch (error) {
console.error('Error connecting to SSH server', error)
throw error
console.error('Error connecting to SSH server', error);
throw error;
}
},
},
})
});
const securityType = useStore(
connectionForm.store,
(state) => state.values.security.type,
)
);
const isSubmitting = useStore(
connectionForm.store,
(state) => state.isSubmitting,
);
return (
<View style={styles.container}>
@@ -156,7 +164,8 @@ export default function Index() {
<connectionForm.SubmitButton
title="Connect"
onPress={() => {
connectionForm.handleSubmit()
if (isSubmitting) return;
void connectionForm.handleSubmit();
}}
/>
</View>
@@ -164,31 +173,33 @@ export default function Index() {
</View>
<PreviousConnectionsSection
onSelect={(connection) => {
connectionForm.setFieldValue('host', connection.host)
connectionForm.setFieldValue('port', connection.port)
connectionForm.setFieldValue('username', connection.username)
connectionForm.setFieldValue('host', connection.host);
connectionForm.setFieldValue('port', connection.port);
connectionForm.setFieldValue('username', connection.username);
connectionForm.setFieldValue(
'security.type',
connection.security.type,
)
);
if (connection.security.type === 'password') {
connectionForm.setFieldValue(
'security.password',
connection.security.password,
)
);
} else {
connectionForm.setFieldValue(
'security.keyId',
connection.security.keyId,
)
);
}
}}
/>
</ScrollView>
</View>
)
);
}
// Yes, HOCs are weird. Its what the docs recommend.
// https://tanstack.com/form/v1/docs/framework/react/guides/form-composition#withform-faq
const KeyPairSection = withFieldGroup({
defaultValues: {
type: 'key',
@@ -196,7 +207,7 @@ const KeyPairSection = withFieldGroup({
},
props: {},
render: function Render({ group }) {
const listPrivateKeysQuery = useQuery(secretsManager.keys.query.list)
const listPrivateKeysQuery = useQuery(secretsManager.keys.query.list);
return (
<group.AppField name="keyId">
@@ -221,14 +232,14 @@ const KeyPairSection = withFieldGroup({
await secretsManager.keys.utils.generateKeyPair({
type: 'rsa',
keySize: 4096,
})
});
await secretsManager.keys.utils.savePrivateKey({
keyId: 'default',
privateKey: newKeyPair.privateKey,
priority: 0,
})
field.handleChange('default')
console.log('New key pair generated and saved')
});
field.handleChange('default');
console.log('New key pair generated and saved');
}}
>
<Text style={styles.secondaryButtonText}>
@@ -239,14 +250,14 @@ const KeyPairSection = withFieldGroup({
)
}
</group.AppField>
)
);
},
})
});
function PreviousConnectionsSection(props: {
onSelect: (connection: ConnectionDetails) => void
onSelect: (connection: ConnectionDetails) => void;
}) {
const listConnectionsQuery = useQuery(secretsManager.connections.query.list)
const listConnectionsQuery = useQuery(secretsManager.connections.query.list);
return (
<View style={styles.listSection}>
@@ -269,21 +280,21 @@ function PreviousConnectionsSection(props: {
<Text style={styles.mutedText}>No saved connections yet</Text>
)}
</View>
)
);
}
function ConnectionRow(props: {
id: string
onSelect: (connection: ConnectionDetails) => void
id: string;
onSelect: (connection: ConnectionDetails) => void;
}) {
const detailsQuery = useQuery(secretsManager.connections.query.get(props.id))
const details = detailsQuery.data?.details
const detailsQuery = useQuery(secretsManager.connections.query.get(props.id));
const details = detailsQuery.data?.details;
return (
<Pressable
style={styles.row}
onPress={() => {
if (details) props.onSelect(details)
if (details) props.onSelect(details);
}}
disabled={!details}
>
@@ -297,7 +308,7 @@ function ConnectionRow(props: {
</View>
<Text style={styles.rowChevron}></Text>
</Pressable>
)
);
}
const styles = StyleSheet.create({
@@ -448,4 +459,4 @@ const styles = StyleSheet.create({
fontSize: 22,
paddingHorizontal: 4,
},
})
});

View File

@@ -1,8 +1,8 @@
/**
* This is the page that is shown after an ssh connection
*/
import { useLocalSearchParams } from 'expo-router'
import { useEffect, useRef, useState } from 'react'
import { useLocalSearchParams } from 'expo-router';
import { useEffect, useRef, useState } from 'react';
import {
Platform,
Pressable,
@@ -11,45 +11,45 @@ import {
Text,
TextInput,
View,
} from 'react-native'
import { sshConnectionManager } from '../lib/ssh-connection-manager'
} from 'react-native';
import { sshConnectionManager } from '../lib/ssh-connection-manager';
export default function Shell() {
// https://docs.expo.dev/router/reference/url-parameters/
const { sessionId } = useLocalSearchParams<{ sessionId: string }>()
const sshConn = sshConnectionManager.getSession({ sessionId }) // this throws if the session is not found
const { sessionId } = useLocalSearchParams<{ sessionId: string }>();
const sshConn = sshConnectionManager.getSession({ sessionId }); // this throws if the session is not found
const [shellData, setShellData] = useState('')
const [shellData, setShellData] = useState('');
useEffect(() => {
sshConn.client.on('Shell', (data) => {
console.log('Received data (on Shell):', data)
setShellData((prev) => prev + data)
})
console.log('Received data (on Shell):', data);
setShellData((prev) => prev + data);
});
// return () => {
// sshConn.client.off('Shell')
// }
}, [setShellData, sshConn.client])
}, [setShellData, sshConn.client]);
useEffect(() => {
return () => {
setTimeout(() => {
try {
sshConnectionManager.removeAndDisconnectSession({ sessionId })
console.log('Disconnected from SSH server')
sshConnectionManager.removeAndDisconnectSession({ sessionId });
console.log('Disconnected from SSH server');
} catch (error) {
console.error('Error disconnecting from SSH server', error)
console.error('Error disconnecting from SSH server', error);
}
}, 3_000)
}
}, [sessionId])
}, 3_000);
};
}, [sessionId]);
const scrollViewRef = useRef<ScrollView | null>(null)
const scrollViewRef = useRef<ScrollView | null>(null);
useEffect(() => {
// Auto-scroll to bottom when new data arrives
scrollViewRef.current?.scrollToEnd({ animated: true })
}, [shellData])
scrollViewRef.current?.scrollToEnd({ animated: true });
}, [shellData]);
return (
<View style={styles.container}>
@@ -66,22 +66,24 @@ export default function Shell() {
</ScrollView>
</View>
<CommandInput
executeCommand={(command) => {
console.log('Executing command:', command)
sshConn.client.writeToShell(command + '\n')
executeCommand={async (command) => {
console.log('Executing command:', command);
await sshConn.client.writeToShell(command + '\n');
}}
/>
</View>
)
);
}
function CommandInput(props: { executeCommand: (command: string) => void }) {
const [command, setCommand] = useState('')
function CommandInput(props: {
executeCommand: (command: string) => Promise<void>;
}) {
const [command, setCommand] = useState('');
function handleExecute() {
if (!command.trim()) return
props.executeCommand(command)
setCommand('')
async function handleExecute() {
if (!command.trim()) return;
await props.executeCommand(command);
setCommand('');
}
return (
@@ -101,7 +103,7 @@ function CommandInput(props: { executeCommand: (command: string) => void }) {
<Text style={styles.executeButtonText}>Execute</Text>
</Pressable>
</View>
)
);
}
const styles = StyleSheet.create({
@@ -172,4 +174,4 @@ const styles = StyleSheet.create({
fontWeight: '700',
fontSize: 14,
},
})
});

View File

@@ -1,9 +1,9 @@
import { Picker } from '@react-native-picker/picker'
import { Picker } from '@react-native-picker/picker';
import {
createFormHook,
createFormHookContexts,
useStore,
} from '@tanstack/react-form'
} from '@tanstack/react-form';
import {
Pressable,
StyleSheet,
@@ -11,12 +11,12 @@ import {
Text,
TextInput,
View,
} from 'react-native'
} from 'react-native';
function FieldInfo() {
const field = useFieldContext()
const meta = field.state.meta
const errorMessage = meta?.errors?.[0] // TODO: typesafe errors
const field = useFieldContext();
const meta = field.state.meta;
const errorMessage = meta?.errors?.[0]; // TODO: typesafe errors
return (
<View style={styles.fieldInfo}>
@@ -24,17 +24,17 @@ function FieldInfo() {
<Text style={styles.errorText}>{String(errorMessage)}</Text>
) : null}
</View>
)
);
}
// https://tanstack.com/form/latest/docs/framework/react/quick-start
export function TextField(
props: React.ComponentProps<typeof TextInput> & {
label?: string
label?: string;
},
) {
const { label, style, ...rest } = props
const field = useFieldContext<string>()
const { label, style, ...rest } = props;
const field = useFieldContext<string>();
return (
<View style={styles.inputGroup}>
@@ -49,16 +49,16 @@ export function TextField(
/>
<FieldInfo />
</View>
)
);
}
export function NumberField(
props: React.ComponentProps<typeof TextInput> & {
label?: string
label?: string;
},
) {
const { label, style, keyboardType, onChangeText, ...rest } = props
const field = useFieldContext<number>()
const { label, style, keyboardType, onChangeText, ...rest } = props;
const field = useFieldContext<number>();
return (
<View style={styles.inputGroup}>
{label ? <Text style={styles.label}>{label}</Text> : null}
@@ -73,16 +73,16 @@ export function NumberField(
/>
<FieldInfo />
</View>
)
);
}
export function SwitchField(
props: React.ComponentProps<typeof Switch> & {
label?: string
label?: string;
},
) {
const { label, style, ...rest } = props
const field = useFieldContext<boolean>()
const { label, style, ...rest } = props;
const field = useFieldContext<boolean>();
return (
<View style={styles.inputGroup}>
@@ -95,16 +95,16 @@ export function SwitchField(
{...rest}
/>
</View>
)
);
}
export function PickerField<T>(
props: React.ComponentProps<typeof Picker<T>> & {
label?: string
label?: string;
},
) {
const { label, style, ...rest } = props
const field = useFieldContext<T>()
const { label, style, ...rest } = props;
const field = useFieldContext<T>();
return (
<View style={styles.inputGroup}>
{label ? <Text style={styles.label}>{label}</Text> : null}
@@ -117,20 +117,20 @@ export function PickerField<T>(
</Picker>
<FieldInfo />
</View>
)
);
}
export function SubmitButton(props: {
onPress?: () => void
title?: string
disabled?: boolean
onPress?: () => void;
title?: string;
disabled?: boolean;
}) {
const { onPress, title = 'Connect', disabled } = props
const formContext = useFormContext()
const { onPress, title = 'Connect', disabled } = props;
const formContext = useFormContext();
const isSubmitting = useStore(
formContext.store,
(state) => state.isSubmitting,
)
);
return (
<Pressable
style={[
@@ -144,13 +144,13 @@ export function SubmitButton(props: {
{isSubmitting ? 'Connecting...' : title}
</Text>
</Pressable>
)
);
}
const { fieldContext, formContext, useFieldContext, useFormContext } =
createFormHookContexts()
createFormHookContexts();
export { useFieldContext, useFormContext }
export { useFieldContext, useFormContext };
// https://tanstack.com/form/latest/docs/framework/react/quick-start
export const { useAppForm, withForm, withFieldGroup } = createFormHook({
fieldComponents: {
@@ -164,7 +164,7 @@ export const { useAppForm, withForm, withFieldGroup } = createFormHook({
},
fieldContext,
formContext,
})
});
const styles = StyleSheet.create({
inputGroup: {
@@ -211,4 +211,4 @@ const styles = StyleSheet.create({
color: '#FCA5A5',
fontSize: 12,
},
})
});

View File

@@ -1,13 +1,13 @@
import SSHClient from '@dylankenneally/react-native-ssh-sftp'
import { queryOptions } from '@tanstack/react-query'
import * as SecureStore from 'expo-secure-store'
import * as z from 'zod'
import { queryClient } from './utils'
import SSHClient from '@dylankenneally/react-native-ssh-sftp';
import { queryOptions } from '@tanstack/react-query';
import * as SecureStore from 'expo-secure-store';
import * as z from 'zod';
import { queryClient } from './utils';
const keys = {
storagePrefix: 'privateKey_',
manifestKey: 'privateKeysManifest',
} as const
} as const;
const keyManifestSchema = z.object({
manifestVersion: z.number().default(1),
@@ -18,73 +18,73 @@ const keyManifestSchema = z.object({
createdAt: z.date(),
}),
),
})
});
async function getKeyManifest() {
const rawManifest = await SecureStore.getItemAsync(keys.manifestKey)
const rawManifest = await SecureStore.getItemAsync(keys.manifestKey);
const manifest = rawManifest
? JSON.parse(rawManifest)
: {
manifestVersion: 1,
keys: [],
}
return keyManifestSchema.parse(manifest)
};
return keyManifestSchema.parse(manifest);
}
async function savePrivateKey(params: {
keyId: string
privateKey: string
priority: number
keyId: string;
privateKey: string;
priority: number;
}) {
const manifest = await getKeyManifest()
const manifest = await getKeyManifest();
const existingKey = manifest.keys.find((key) => key.id === params.keyId)
const existingKey = manifest.keys.find((key) => key.id === params.keyId);
if (existingKey) throw new Error('Key already exists')
if (existingKey) throw new Error('Key already exists');
const newKey = {
id: params.keyId,
priority: params.priority,
createdAt: new Date(),
}
};
manifest.keys.push(newKey)
manifest.keys.push(newKey);
await SecureStore.setItemAsync(
`${keys.storagePrefix}${params.keyId}`,
params.privateKey,
)
await SecureStore.setItemAsync(keys.manifestKey, JSON.stringify(manifest))
queryClient.invalidateQueries({ queryKey: [keyQueryKey] })
);
await SecureStore.setItemAsync(keys.manifestKey, JSON.stringify(manifest));
await queryClient.invalidateQueries({ queryKey: [keyQueryKey] });
}
async function getPrivateKey(keyId: string) {
const manifest = await getKeyManifest()
const key = manifest.keys.find((key) => key.id === keyId)
if (!key) throw new Error('Key not found')
const manifest = await getKeyManifest();
const key = manifest.keys.find((key) => key.id === keyId);
if (!key) throw new Error('Key not found');
const privateKey = await SecureStore.getItemAsync(
`${keys.storagePrefix}${keyId}`,
)
if (!privateKey) throw new Error('Key not found')
);
if (!privateKey) throw new Error('Key not found');
return {
...key,
privateKey,
}
};
}
async function deletePrivateKey(keyId: string) {
const manifest = await getKeyManifest()
const key = manifest.keys.find((key) => key.id === keyId)
if (!key) throw new Error('Key not found')
manifest.keys = manifest.keys.filter((key) => key.id !== keyId)
await SecureStore.setItemAsync(keys.manifestKey, JSON.stringify(manifest))
await SecureStore.deleteItemAsync(`${keys.storagePrefix}${keyId}`)
queryClient.invalidateQueries({ queryKey: [keyQueryKey] })
const manifest = await getKeyManifest();
const key = manifest.keys.find((key) => key.id === keyId);
if (!key) throw new Error('Key not found');
manifest.keys = manifest.keys.filter((key) => key.id !== keyId);
await SecureStore.setItemAsync(keys.manifestKey, JSON.stringify(manifest));
await SecureStore.deleteItemAsync(`${keys.storagePrefix}${keyId}`);
await queryClient.invalidateQueries({ queryKey: [keyQueryKey] });
}
const connections = {
storagePrefix: 'connection_',
manifestKey: 'connectionsManifest',
} as const
} as const;
const connectionsManifestSchema = z.object({
manifestVersion: z.number().default(1),
@@ -96,7 +96,7 @@ const connectionsManifestSchema = z.object({
modifiedAt: z.date(),
}),
),
})
});
export const connectionDetailsSchema = z.object({
host: z.string().min(1),
@@ -112,30 +112,30 @@ export const connectionDetailsSchema = z.object({
keyId: z.string().min(1),
}),
]),
})
});
export type ConnectionDetails = z.infer<typeof connectionDetailsSchema>
export type ConnectionDetails = z.infer<typeof connectionDetailsSchema>;
async function getConnectionManifest() {
const rawManifest = await SecureStore.getItemAsync(connections.manifestKey)
const rawManifest = await SecureStore.getItemAsync(connections.manifestKey);
const manifest = rawManifest
? JSON.parse(rawManifest)
: {
manifestVersion: 1,
connections: [],
}
return connectionsManifestSchema.parse(manifest)
};
return connectionsManifestSchema.parse(manifest);
}
async function upsertConnection(params: {
id: string
details: ConnectionDetails
priority: number
id: string;
details: ConnectionDetails;
priority: number;
}) {
const manifest = await getConnectionManifest()
const manifest = await getConnectionManifest();
const existingConnection = manifest.connections.find(
(connection) => connection.id === params.id,
)
);
const newConnection = existingConnection
? {
@@ -148,98 +148,98 @@ async function upsertConnection(params: {
priority: params.priority,
createdAt: new Date(),
modifiedAt: new Date(),
}
};
await SecureStore.setItemAsync(
connections.manifestKey,
JSON.stringify(manifest),
)
);
await SecureStore.setItemAsync(
`${connections.storagePrefix}${params.id}`,
JSON.stringify(params.details),
)
queryClient.invalidateQueries({ queryKey: [connectionQueryKey] })
return existingConnection ?? newConnection
);
await queryClient.invalidateQueries({ queryKey: [connectionQueryKey] });
return existingConnection ?? newConnection;
}
async function deleteConnection(id: string) {
const manifest = await getConnectionManifest()
const manifest = await getConnectionManifest();
const connection = manifest.connections.find(
(connection) => connection.id === id,
)
if (!connection) throw new Error('Connection not found')
);
if (!connection) throw new Error('Connection not found');
manifest.connections = manifest.connections.filter(
(connection) => connection.id !== id,
)
);
await SecureStore.setItemAsync(
connections.manifestKey,
JSON.stringify(manifest),
)
await SecureStore.deleteItemAsync(`${connections.storagePrefix}${id}`)
queryClient.invalidateQueries({ queryKey: [connectionQueryKey] })
);
await SecureStore.deleteItemAsync(`${connections.storagePrefix}${id}`);
await queryClient.invalidateQueries({ queryKey: [connectionQueryKey] });
}
async function getConnection(id: string) {
const manifest = await getConnectionManifest()
const manifest = await getConnectionManifest();
const connection = manifest.connections.find(
(connection) => connection.id === id,
)
if (!connection) throw new Error('Connection not found')
);
if (!connection) throw new Error('Connection not found');
const detailsString = await SecureStore.getItemAsync(
`${connections.storagePrefix}${id}`,
)
if (!detailsString) throw new Error('Connection details not found')
const detailsJson = JSON.parse(detailsString)
const details = connectionDetailsSchema.parse(detailsJson)
return { ...connection, details }
);
if (!detailsString) throw new Error('Connection details not found');
const detailsJson = JSON.parse(detailsString);
const details = connectionDetailsSchema.parse(detailsJson);
return { ...connection, details };
}
const connectionQueryKey = 'connections'
const connectionQueryKey = 'connections';
const listConnectionsQueryOptions = queryOptions({
queryKey: [connectionQueryKey],
queryFn: async () => {
const manifest = await getConnectionManifest()
const firstConnectionMeta = manifest.connections[0]
const manifest = await getConnectionManifest();
const firstConnectionMeta = manifest.connections[0];
const firstConnection = firstConnectionMeta
? await getConnection(firstConnectionMeta.id)
: null
: null;
return {
manifest,
firstConnection,
}
};
},
})
});
const getConnectionQueryOptions = (id: string) =>
queryOptions({
queryKey: [connectionQueryKey, id],
queryFn: () => getConnection(id),
})
});
const keyQueryKey = 'keys'
const keyQueryKey = 'keys';
const listKeysQueryOptions = queryOptions({
queryKey: [keyQueryKey],
queryFn: getKeyManifest,
})
});
// https://github.com/dylankenneally/react-native-ssh-sftp/blob/ea55436d8d40378a8f9dabb95b463739ffb219fa/android/src/main/java/me/keeex/rnssh/RNSshClientModule.java#L101-L119
export type SshPrivateKeyType = 'dsa' | 'rsa' | 'ecdsa' | 'ed25519' | 'ed448'
export type SshPrivateKeyType = 'dsa' | 'rsa' | 'ecdsa' | 'ed25519' | 'ed448';
async function generateKeyPair(params: {
type: SshPrivateKeyType
passphrase?: string
keySize?: number
comment?: string
type: SshPrivateKeyType;
passphrase?: string;
keySize?: number;
comment?: string;
}) {
const keyPair = await SSHClient.generateKeyPair(
params.type,
params.passphrase,
params.keySize,
params.comment,
)
return keyPair
);
return keyPair;
}
export const secretsManager = {
@@ -265,4 +265,4 @@ export const secretsManager = {
get: getConnectionQueryOptions,
},
},
}
};

View File

@@ -1,41 +1,41 @@
import SSHClient from '@dylankenneally/react-native-ssh-sftp'
import uuid from 'react-native-uuid'
import type SSHClient from '@dylankenneally/react-native-ssh-sftp';
import uuid from 'react-native-uuid';
export type SSHConn = {
client: SSHClient
sessionId: string
createdAt: Date
}
client: SSHClient;
sessionId: string;
createdAt: Date;
};
const sshConnections = new Map<string, SSHConn>()
const sshConnections = new Map<string, SSHConn>();
function addSession(params: { client: SSHClient }) {
const sessionId = uuid.v4()
const createdAt = new Date()
const sessionId = uuid.v4();
const createdAt = new Date();
const sshConn: SSHConn = {
client: params.client,
sessionId,
createdAt,
}
sshConnections.set(sessionId, sshConn)
return sshConn
};
sshConnections.set(sessionId, sshConn);
return sshConn;
}
function getSession(params: { sessionId: string }) {
const sshConn = sshConnections.get(params.sessionId)
if (!sshConn) throw new Error('Session not found')
return sshConn
const sshConn = sshConnections.get(params.sessionId);
if (!sshConn) throw new Error('Session not found');
return sshConn;
}
function removeAndDisconnectSession(params: { sessionId: string }) {
const sshConn = getSession(params)
const sshConn = getSession(params);
// sshConn.client.closeShell()
sshConn.client.disconnect()
sshConnections.delete(params.sessionId)
sshConn.client.disconnect();
sshConnections.delete(params.sessionId);
}
export const sshConnectionManager = {
addSession,
getSession,
removeAndDisconnectSession,
}
};

View File

@@ -1,3 +1,3 @@
import { QueryClient } from '@tanstack/react-query'
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient()
export const queryClient = new QueryClient();

View File

@@ -6,5 +6,11 @@
"@/*": ["./*"]
}
},
"include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"]
"include": [
"**/*.ts",
"**/*.tsx",
".expo/types/**/*.ts",
"expo-env.d.ts",
"eslint.config.js"
]
}