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": { "editor.codeActionsOnSave": {
"source.organizeImports": "never",
"source.fixAll": "explicit", "source.fixAll": "explicit",
"source.organizeImports": "explicit",
"source.sortMembers": "explicit" "source.sortMembers": "explicit"
} },
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
} }

View File

@@ -1,48 +1,48 @@
{ {
"expo": { "expo": {
"name": "fressh", "name": "fressh",
"slug": "fressh", "slug": "fressh",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/images/icon.png", "icon": "./assets/images/icon.png",
"scheme": "fressh", "scheme": "fressh",
"userInterfaceStyle": "automatic", "userInterfaceStyle": "automatic",
"newArchEnabled": true, "newArchEnabled": true,
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true,
"config": { "config": {
"usesNonExemptEncryption": false "usesNonExemptEncryption": false
} }
}, },
"android": { "android": {
"package": "dev.fressh.app", "package": "dev.fressh.app",
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/images/adaptive-icon.png", "foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"edgeToEdgeEnabled": true, "edgeToEdgeEnabled": true,
"predictiveBackGestureEnabled": false "predictiveBackGestureEnabled": false
}, },
"web": { "web": {
"output": "static", "output": "static",
"favicon": "./assets/images/favicon.png" "favicon": "./assets/images/favicon.png"
}, },
"plugins": [ "plugins": [
"expo-router", "expo-router",
[ [
"expo-splash-screen", "expo-splash-screen",
{ {
"image": "./assets/images/splash-icon.png", "image": "./assets/images/splash-icon.png",
"imageWidth": 200, "imageWidth": 200,
"resizeMode": "contain", "resizeMode": "contain",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
} }
], ],
"expo-secure-store" "expo-secure-store"
], ],
"experiments": { "experiments": {
"typedRoutes": true, "typedRoutes": true,
"reactCompiler": true "reactCompiler": true
} }
} }
} }

View File

@@ -1,12 +1,27 @@
// https://docs.expo.dev/guides/using-eslint/ // https://docs.expo.dev/guides/using-eslint/
const { defineConfig } = require('eslint/config'); import { createRequire } from 'node:module';
const expoConfig = require('eslint-config-expo/flat'); import { config as epicConfig } from '@epic-web/config/eslint';
// const { config: epicConfig } = require('@epic-web/config/eslint') import { defineConfig } from 'eslint/config';
module.exports = defineConfig([ const require = createRequire(import.meta.url);
expoConfig,
// ...epicConfig, 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", "name": "fressh",
"main": "expo-router/entry", "main": "expo-router/entry",
"version": "1.0.0", "version": "1.0.0",
"type": "module",
"scripts": { "scripts": {
"start": "expo start", "start": "expo start",
"reset-project": "node ./scripts/reset-project.js", "reset-project": "node ./scripts/reset-project.js",
@@ -9,8 +10,10 @@
"ios": "expo run:ios", "ios": "expo run:ios",
"web": "expo start --web", "web": "expo start --web",
"lint": "expo lint", "lint": "expo lint",
"format": "SORT_IMPORTS=true prettier . --write", "fmt": "SORT_IMPORTS=true prettier . --write",
"typecheck": "tsc" "typecheck": "tsc",
"validate": "run-p -l fmt lint typecheck",
"update:all": "pnpm dlx npm-check-updates --interactive --format group"
}, },
"dependencies": { "dependencies": {
"@dylankenneally/react-native-ssh-sftp": "^1.5.20", "@dylankenneally/react-native-ssh-sftp": "^1.5.20",
@@ -50,8 +53,9 @@
"@types/react": "~19.1.0", "@types/react": "~19.1.0",
"eslint": "^9.25.0", "eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0", "eslint-config-expo": "~10.0.0",
"jiti": "^2.5.1",
"npm-run-all": "^4.1.5",
"prettier": "^3.6.2", "prettier": "^3.6.2",
"prettier-plugin-organize-imports": "^4.2.0",
"tsx": "^4.20.5", "tsx": "^4.20.5",
"typescript": "~5.9.2" "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 nodeLinker: hoisted
onlyBuiltDependencies: onlyBuiltDependencies:
- esbuild
- unrs-resolver - unrs-resolver

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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