Lots of broken stuff

This commit is contained in:
EthanShoeDev
2025-09-08 04:07:12 -04:00
parent b3199ebd0d
commit f7d1d3b0f4
13 changed files with 2517 additions and 4781 deletions

View File

@@ -1,44 +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": {
"android": { "usesNonExemptEncryption": false
"package": "dev.fressh.app", }
"adaptiveIcon": { },
"foregroundImage": "./assets/images/adaptive-icon.png", "android": {
"backgroundColor": "#ffffff" "package": "dev.fressh.app",
}, "adaptiveIcon": {
"edgeToEdgeEnabled": true, "foregroundImage": "./assets/images/adaptive-icon.png",
"predictiveBackGestureEnabled": false "backgroundColor": "#ffffff"
}, },
"web": { "edgeToEdgeEnabled": true,
"output": "static", "predictiveBackGestureEnabled": false
"favicon": "./assets/images/favicon.png" },
}, "web": {
"plugins": [ "output": "static",
"expo-router", "favicon": "./assets/images/favicon.png"
[ },
"expo-splash-screen", "plugins": [
{ "expo-router",
"image": "./assets/images/splash-icon.png", [
"imageWidth": 200, "expo-splash-screen",
"resizeMode": "contain", {
"backgroundColor": "#ffffff" "image": "./assets/images/splash-icon.png",
} "imageWidth": 200,
] "resizeMode": "contain",
], "backgroundColor": "#ffffff"
"experiments": { }
"typedRoutes": true, ],
"reactCompiler": true "expo-secure-store"
} ],
} "experiments": {
"typedRoutes": true,
"reactCompiler": true
}
}
} }

View File

@@ -1,6 +1,6 @@
// https://docs.expo.dev/guides/using-eslint/ // https://docs.expo.dev/guides/using-eslint/
const { defineConfig } = require('eslint/config') const { defineConfig } = require('eslint/config');
const expoConfig = require('eslint-config-expo/flat') const expoConfig = require('eslint-config-expo/flat');
// const { config: epicConfig } = require('@epic-web/config/eslint') // const { config: epicConfig } = require('@epic-web/config/eslint')
module.exports = defineConfig([ module.exports = defineConfig([
@@ -9,4 +9,4 @@ module.exports = defineConfig([
{ {
ignores: ['dist/*'], ignores: ['dist/*'],
}, },
]) ]);

View File

@@ -15,10 +15,12 @@
"dependencies": { "dependencies": {
"@dylankenneally/react-native-ssh-sftp": "^1.5.20", "@dylankenneally/react-native-ssh-sftp": "^1.5.20",
"@expo/vector-icons": "^15.0.2", "@expo/vector-icons": "^15.0.2",
"@react-native-picker/picker": "2.11.1",
"@react-navigation/bottom-tabs": "^7.4.0", "@react-navigation/bottom-tabs": "^7.4.0",
"@react-navigation/elements": "^2.6.3", "@react-navigation/elements": "^2.6.3",
"@react-navigation/native": "^7.1.8", "@react-navigation/native": "^7.1.8",
"@tanstack/react-form": "^1.19.3", "@tanstack/react-form": "^1.19.3",
"@tanstack/react-query": "^5.87.1",
"expo": "~54.0.0-preview.12", "expo": "~54.0.0-preview.12",
"expo-constants": "~18.0.6", "expo-constants": "~18.0.6",
"expo-font": "~14.0.6", "expo-font": "~14.0.6",
@@ -26,6 +28,7 @@
"expo-image": "~3.0.5", "expo-image": "~3.0.5",
"expo-linking": "~8.0.6", "expo-linking": "~8.0.6",
"expo-router": "~6.0.0-preview.12", "expo-router": "~6.0.0-preview.12",
"expo-secure-store": "~15.0.6",
"expo-splash-screen": "~31.0.7", "expo-splash-screen": "~31.0.7",
"expo-status-bar": "~3.0.6", "expo-status-bar": "~3.0.6",
"expo-symbols": "~1.0.5", "expo-symbols": "~1.0.5",
@@ -37,8 +40,10 @@
"react-native-reanimated": "~4.0.2", "react-native-reanimated": "~4.0.2",
"react-native-safe-area-context": "~5.6.0", "react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.15.4", "react-native-screens": "~4.15.4",
"react-native-uuid": "^2.0.3",
"react-native-web": "~0.21.0", "react-native-web": "~0.21.0",
"react-native-worklets": "~0.4.2" "react-native-worklets": "~0.4.2",
"zod": "^4.1.5"
}, },
"devDependencies": { "devDependencies": {
"@epic-web/config": "^1.21.3", "@epic-web/config": "^1.21.3",

6252
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,15 @@
import defaultConfig from '@epic-web/config/prettier' import defaultConfig from '@epic-web/config/prettier';
// const defaultConfig = require('@epic-web/config/prettier') // const defaultConfig = require('@epic-web/config/prettier')
// Sometimes this plugin can remove imports that are in use. // Sometimes this plugin can remove imports that are in use.
// As a workaround we will only use this in the cli. (npm 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,
plugins: [ plugins: [
...(sortImports ? ['prettier-plugin-organize-imports'] : []), ...(sortImports ? ['prettier-plugin-organize-imports'] : []),
...(defaultConfig.plugins || []), ...(defaultConfig.plugins || []),
], ],
} };

View File

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

View File

@@ -1,126 +1,305 @@
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 { useStore } from '@tanstack/react-form'
import { useQuery } from '@tanstack/react-query'
import { useRouter } from 'expo-router' import { useRouter } from 'expo-router'
import { StyleSheet, Text, View } from 'react-native' import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { useFresshAppForm } from '../lib/app-form' import { useAppForm, withFieldGroup } from '../components/form-components'
import {
ConnectionDetails,
connectionDetailsSchema,
secretsManager,
} from '../lib/secrets-manager'
import { sshConnectionManager } from '../lib/ssh-connection-manager' import { sshConnectionManager } from '../lib/ssh-connection-manager'
const defaultValues: ConnectionDetails = {
host: 'test.rebex.net',
port: 22,
username: 'demo',
security: {
type: 'password',
password: 'password',
},
}
export default function Index() { export default function Index() {
const router = useRouter() const router = useRouter()
const connectionForm = useFresshAppForm({ const storedConnectionsQuery = useQuery(secretsManager.connections.query.list)
defaultValues: {
// host: '',
// port: 22,
// username: '',
// password: '',
// TODO: Remove this weird default
host: 'test.rebex.net',
port: 22,
username: 'demo',
password: 'password',
},
validators: {
// TODO: Add a zod validator here
// onChange: z.object({
// email: z.email(),
// }),
onSubmitAsync: async ({ value }) => {
console.log('Connecting to SSH server...')
const sshClientConnection = await SSHClient.connectWithPassword(
value.host,
value.port,
value.username,
value.password,
)
console.log('Connected to SSH server')
// sshClientConnection.on('Shell', (data) => { const preferredStoredConnection = storedConnectionsQuery.data?.firstConnection
// console.log(data) const connectionForm = useAppForm({
// }) // https://tanstack.com/form/latest/docs/framework/react/guides/async-initial-values
await sshClientConnection.startShell(PtyType.XTERM) defaultValues: preferredStoredConnection
// const sshConn = ? preferredStoredConnection.details
sshConnectionManager.addSession({ : defaultValues,
client: sshClientConnection, validators: {
}) onChange: connectionDetailsSchema,
router.push(`/shell`) onSubmitAsync: async ({ value }) => {
try {
console.log('Connecting to SSH server...')
const sshClientConnection = await (async () => {
if (value.security.type === 'password') {
return await SSHClient.connectWithPassword(
value.host,
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)
const sshConn = sshConnectionManager.addSession({
client: sshClientConnection,
})
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
}
}, },
}, },
}) })
const securityType = useStore(
connectionForm.store,
(state) => state.values.security.type,
)
return ( return (
<View style={styles.container}> <View style={styles.container}>
<View style={styles.card}> <ScrollView
<Text style={styles.title}>Connect to SSH Server</Text> contentContainerStyle={styles.scrollContent}
<Text style={styles.subtitle}>Enter your server credentials</Text> keyboardShouldPersistTaps="handled"
>
<View style={styles.header}>
<Text style={styles.appName}>fressh</Text>
<Text style={styles.appTagline}>A fast, friendly SSH client</Text>
</View>
<View style={styles.card}>
<Text style={styles.title}>Connect to SSH Server</Text>
<Text style={styles.subtitle}>Enter your server credentials</Text>
<connectionForm.AppForm> <connectionForm.AppForm>
<connectionForm.AppField name="host"> <connectionForm.AppField name="host">
{(field) => ( {(field) => (
<field.TextField <field.TextField
label="Host" label="Host"
placeholder="example.com or 192.168.0.10" placeholder="example.com or 192.168.0.10"
field={field} autoCapitalize="none"
autoCapitalize="none" autoCorrect={false}
autoCorrect={false} />
value={field.state.value} )}
onChangeText={field.handleChange} </connectionForm.AppField>
onBlur={field.handleBlur} <connectionForm.AppField name="port">
{(field) => <field.NumberField label="Port" placeholder="22" />}
</connectionForm.AppField>
<connectionForm.AppField name="username">
{(field) => (
<field.TextField
label="Username"
placeholder="root"
autoCapitalize="none"
autoCorrect={false}
/>
)}
</connectionForm.AppField>
<connectionForm.AppField name="security.type">
{(field) => (
<field.PickerField label="Security Type">
<Picker.Item label="Password" value="password" />
<Picker.Item label="Key" value="key" />
</field.PickerField>
)}
</connectionForm.AppField>
{securityType === 'password' ? (
<connectionForm.AppField name="security.password">
{(field) => (
<field.TextField
label="Password"
placeholder="••••••••"
secureTextEntry
/>
)}
</connectionForm.AppField>
) : (
<KeyPairSection
form={connectionForm}
fields={{
keyId: 'security.keyId',
type: 'security.type',
}}
/> />
)} )}
</connectionForm.AppField>
<connectionForm.AppField name="port">
{(field) => (
<field.NumberField
label="Port"
placeholder="22"
field={field}
value={field.state.value.toString()}
onChangeText={(text) => field.handleChange(Number(text))}
onBlur={field.handleBlur}
/>
)}
</connectionForm.AppField>
<connectionForm.AppField name="username">
{(field) => (
<field.TextField
label="Username"
placeholder="root"
field={field}
autoCapitalize="none"
autoCorrect={false}
value={field.state.value}
onChangeText={field.handleChange}
onBlur={field.handleBlur}
/>
)}
</connectionForm.AppField>
<connectionForm.AppField name="password">
{(field) => (
<field.TextField
label="Password"
placeholder="••••••••"
field={field}
secureTextEntry
value={field.state.value}
onChangeText={field.handleChange}
onBlur={field.handleBlur}
/>
)}
</connectionForm.AppField>
<View style={styles.actions}> <View style={styles.actions}>
<connectionForm.SubmitButton <connectionForm.SubmitButton
title="Connect" title="Connect"
onPress={() => { onPress={() => {
connectionForm.handleSubmit() connectionForm.handleSubmit()
}} }}
/> />
</View> </View>
</connectionForm.AppForm> </connectionForm.AppForm>
</View> </View>
<PreviousConnectionsSection
onSelect={(connection) => {
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> </View>
) )
} }
const KeyPairSection = withFieldGroup({
defaultValues: {
type: 'key',
keyId: '',
},
props: {},
render: function Render({ group }) {
const listPrivateKeysQuery = useQuery(secretsManager.keys.query.list)
return (
<group.AppField name="keyId">
{(field) =>
listPrivateKeysQuery.isLoading ? (
<Text style={styles.mutedText}>Loading keys...</Text>
) : listPrivateKeysQuery.isError ? (
<Text style={styles.errorText}>
Error: {listPrivateKeysQuery.error.message}
</Text>
) : (
<>
<field.PickerField label="Key">
{listPrivateKeysQuery.data?.keys.map((key) => (
<Picker.Item key={key.id} label={key.id} value={key.id} />
))}
</field.PickerField>
<Pressable
style={styles.secondaryButton}
onPress={async () => {
const newKeyPair =
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')
}}
>
<Text style={styles.secondaryButtonText}>
Generate New Key Pair
</Text>
</Pressable>
</>
)
}
</group.AppField>
)
},
})
function PreviousConnectionsSection(props: {
onSelect: (connection: ConnectionDetails) => void
}) {
const listConnectionsQuery = useQuery(secretsManager.connections.query.list)
return (
<View style={styles.listSection}>
<Text style={styles.listTitle}>Previous Connections</Text>
{listConnectionsQuery.isLoading ? (
<Text style={styles.mutedText}>Loading connections...</Text>
) : listConnectionsQuery.isError ? (
<Text style={styles.errorText}>Error loading connections</Text>
) : listConnectionsQuery.data?.manifest.connections.length ? (
<View style={styles.listContainer}>
{listConnectionsQuery.data?.manifest.connections.map((conn) => (
<ConnectionRow
key={conn.id}
id={conn.id}
onSelect={props.onSelect}
/>
))}
</View>
) : (
<Text style={styles.mutedText}>No saved connections yet</Text>
)}
</View>
)
}
function ConnectionRow(props: {
id: string
onSelect: (connection: ConnectionDetails) => void
}) {
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)
}}
disabled={!details}
>
<View style={styles.rowTextContainer}>
<Text style={styles.rowTitle}>
{details ? `${details.username}@${details.host}` : 'Loading...'}
</Text>
<Text style={styles.rowSubtitle}>
{details ? `Port ${details.port}${details.security.type}` : ''}
</Text>
</View>
<Text style={styles.rowChevron}></Text>
</Pressable>
)
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
@@ -128,6 +307,24 @@ const styles = StyleSheet.create({
backgroundColor: '#0B1324', backgroundColor: '#0B1324',
justifyContent: 'center', justifyContent: 'center',
}, },
scrollContent: {
paddingBottom: 32,
},
header: {
marginBottom: 16,
alignItems: 'center',
},
appName: {
fontSize: 28,
fontWeight: '800',
color: '#E5E7EB',
letterSpacing: 1,
},
appTagline: {
marginTop: 4,
fontSize: 13,
color: '#9AA0A6',
},
card: { card: {
backgroundColor: '#111B34', backgroundColor: '#111B34',
borderRadius: 16, borderRadius: 16,
@@ -175,6 +372,10 @@ const styles = StyleSheet.create({
actions: { actions: {
marginTop: 8, marginTop: 8,
}, },
mutedText: {
color: '#9AA0A6',
fontSize: 14,
},
submitButton: { submitButton: {
backgroundColor: '#2563EB', backgroundColor: '#2563EB',
borderRadius: 10, borderRadius: 10,
@@ -190,4 +391,61 @@ const styles = StyleSheet.create({
backgroundColor: '#3B82F6', backgroundColor: '#3B82F6',
opacity: 0.6, opacity: 0.6,
}, },
secondaryButton: {
backgroundColor: 'transparent',
borderWidth: 1,
borderColor: '#2A3655',
borderRadius: 10,
paddingVertical: 12,
alignItems: 'center',
marginTop: 8,
},
secondaryButtonText: {
color: '#C6CBD3',
fontWeight: '600',
fontSize: 14,
},
listSection: {
marginTop: 20,
},
listTitle: {
fontSize: 16,
fontWeight: '700',
color: '#E5E7EB',
marginBottom: 8,
},
listContainer: {
// Intentionally empty for RN compatibility
},
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: '#0E172B',
borderWidth: 1,
borderColor: '#2A3655',
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 12,
marginBottom: 8,
},
rowTextContainer: {
flex: 1,
marginRight: 12,
},
rowTitle: {
color: '#E5E7EB',
fontSize: 15,
fontWeight: '600',
},
rowSubtitle: {
color: '#9AA0A6',
marginTop: 2,
fontSize: 12,
},
rowChevron: {
color: '#9AA0A6',
fontSize: 22,
paddingHorizontal: 4,
},
}) })

View File

@@ -1,6 +1,7 @@
/** /**
* 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 { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { import {
Platform, Platform,
@@ -15,8 +16,7 @@ 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 { session: sessionId } = useLocalSearchParams<{ session: string }>() const { sessionId } = useLocalSearchParams<{ sessionId: string }>()
const sessionId = '123'
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('')
@@ -31,6 +31,19 @@ export default function Shell() {
// } // }
}, [setShellData, sshConn.client]) }, [setShellData, sshConn.client])
useEffect(() => {
return () => {
setTimeout(() => {
try {
sshConnectionManager.removeAndDisconnectSession({ sessionId })
console.log('Disconnected from SSH server')
} catch (error) {
console.error('Error disconnecting from SSH server', error)
}
}, 3_000)
}
}, [sessionId])
const scrollViewRef = useRef<ScrollView | null>(null) const scrollViewRef = useRef<ScrollView | null>(null)
useEffect(() => { useEffect(() => {

View File

@@ -1,25 +1,25 @@
import { AnyFieldApi } from '@tanstack/react-form' import { Picker } from '@react-native-picker/picker'
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native' import {
createFormHook,
createFormHookContexts,
useStore,
} from '@tanstack/react-form'
import {
Pressable,
StyleSheet,
Switch,
Text,
TextInput,
View,
} from 'react-native'
// https://tanstack.com/form/latest/docs/framework/react/quick-start function FieldInfo() {
export function TextField( const field = useFieldContext()
props: React.ComponentProps<typeof TextInput> & {
label?: string
field: AnyFieldApi
},
) {
const { label, field, style, ...rest } = props
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.inputGroup}> <View style={styles.fieldInfo}>
{label ? <Text style={styles.label}>{label}</Text> : null}
<TextInput
{...rest}
style={[styles.input, style]}
placeholderTextColor="#9AA0A6"
/>
{errorMessage ? ( {errorMessage ? (
<Text style={styles.errorText}>{String(errorMessage)}</Text> <Text style={styles.errorText}>{String(errorMessage)}</Text>
) : null} ) : null}
@@ -27,31 +27,95 @@ export function TextField(
) )
} }
export function NumberField( // https://tanstack.com/form/latest/docs/framework/react/quick-start
export function TextField(
props: React.ComponentProps<typeof TextInput> & { props: React.ComponentProps<typeof TextInput> & {
label?: string label?: string
field: AnyFieldApi
}, },
) { ) {
const { label, field, style, keyboardType, onChangeText, ...rest } = props const { label, style, ...rest } = props
const meta = field.state.meta const field = useFieldContext<string>()
const errorMessage = meta?.errors?.[0]
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}
<TextInput <TextInput
style={[styles.input, style]}
placeholderTextColor="#9AA0A6"
value={field.state.value}
onChangeText={field.handleChange}
onBlur={field.handleBlur}
{...rest} {...rest}
/>
<FieldInfo />
</View>
)
}
export function NumberField(
props: React.ComponentProps<typeof TextInput> & {
label?: string
},
) {
const { label, style, keyboardType, onChangeText, ...rest } = props
const field = useFieldContext<number>()
return (
<View style={styles.inputGroup}>
{label ? <Text style={styles.label}>{label}</Text> : null}
<TextInput
keyboardType={keyboardType ?? 'numeric'} keyboardType={keyboardType ?? 'numeric'}
style={[styles.input, style]} style={[styles.input, style]}
placeholderTextColor="#9AA0A6" placeholderTextColor="#9AA0A6"
onChangeText={(text) => { value={field.state.value.toString()}
if (onChangeText) onChangeText(text) onChangeText={(text) => field.handleChange(Number(text))}
}} onBlur={field.handleBlur}
{...rest}
/> />
{errorMessage ? ( <FieldInfo />
<Text style={styles.errorText}>{String(errorMessage)}</Text> </View>
) : null} )
}
export function SwitchField(
props: React.ComponentProps<typeof Switch> & {
label?: string
},
) {
const { label, style, ...rest } = props
const field = useFieldContext<boolean>()
return (
<View style={styles.inputGroup}>
{label ? <Text style={styles.label}>{label}</Text> : null}
<Switch
style={[styles.input, style]}
value={field.state.value}
onChange={(event) => field.handleChange(event.nativeEvent.value)}
onBlur={field.handleBlur}
{...rest}
/>
</View>
)
}
export function PickerField<T>(
props: React.ComponentProps<typeof Picker<T>> & {
label?: string
},
) {
const { label, style, ...rest } = props
const field = useFieldContext<T>()
return (
<View style={styles.inputGroup}>
{label ? <Text style={styles.label}>{label}</Text> : null}
<Picker<T>
selectedValue={field.state.value}
onValueChange={(itemValue) => field.handleChange(itemValue)}
{...rest}
>
{props.children}
</Picker>
<FieldInfo />
</View> </View>
) )
} }
@@ -62,6 +126,11 @@ export function SubmitButton(props: {
disabled?: boolean disabled?: boolean
}) { }) {
const { onPress, title = 'Connect', disabled } = props const { onPress, title = 'Connect', disabled } = props
const formContext = useFormContext()
const isSubmitting = useStore(
formContext.store,
(state) => state.isSubmitting,
)
return ( return (
<Pressable <Pressable
style={[ style={[
@@ -69,13 +138,34 @@ export function SubmitButton(props: {
disabled ? styles.buttonDisabled : undefined, disabled ? styles.buttonDisabled : undefined,
]} ]}
onPress={onPress} onPress={onPress}
disabled={disabled} disabled={disabled || isSubmitting}
> >
<Text style={styles.submitButtonText}>{title}</Text> <Text style={styles.submitButtonText}>
{isSubmitting ? 'Connecting...' : title}
</Text>
</Pressable> </Pressable>
) )
} }
const { fieldContext, formContext, useFieldContext, useFormContext } =
createFormHookContexts()
export { useFieldContext, useFormContext }
// https://tanstack.com/form/latest/docs/framework/react/quick-start
export const { useAppForm, withForm, withFieldGroup } = createFormHook({
fieldComponents: {
TextField,
NumberField,
PickerField,
SwitchField,
},
formComponents: {
SubmitButton,
},
fieldContext,
formContext,
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
inputGroup: { inputGroup: {
marginBottom: 12, marginBottom: 12,
@@ -116,4 +206,9 @@ const styles = StyleSheet.create({
backgroundColor: '#3B82F6', backgroundColor: '#3B82F6',
opacity: 0.6, opacity: 0.6,
}, },
fieldInfo: {
marginTop: 6,
color: '#FCA5A5',
fontSize: 12,
},
}) })

View File

@@ -1,20 +0,0 @@
import { createFormHook, createFormHookContexts } from '@tanstack/react-form'
import {
NumberField,
SubmitButton,
TextField,
} from '../components/form-components'
const { fieldContext, formContext } = createFormHookContexts()
// https://tanstack.com/form/latest/docs/framework/react/quick-start
export const { useAppForm: useFresshAppForm } = createFormHook({
fieldComponents: {
TextField,
NumberField,
},
formComponents: {
SubmitButton,
},
fieldContext,
formContext,
})

268
src/lib/secrets-manager.ts Normal file
View File

@@ -0,0 +1,268 @@
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
const keyManifestSchema = z.object({
manifestVersion: z.number().default(1),
keys: z.array(
z.object({
id: z.string(),
priority: z.number(),
createdAt: z.date(),
}),
),
})
async function getKeyManifest() {
const rawManifest = await SecureStore.getItemAsync(keys.manifestKey)
const manifest = rawManifest
? JSON.parse(rawManifest)
: {
manifestVersion: 1,
keys: [],
}
return keyManifestSchema.parse(manifest)
}
async function savePrivateKey(params: {
keyId: string
privateKey: string
priority: number
}) {
const manifest = await getKeyManifest()
const existingKey = manifest.keys.find((key) => key.id === params.keyId)
if (existingKey) throw new Error('Key already exists')
const newKey = {
id: params.keyId,
priority: params.priority,
createdAt: new Date(),
}
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] })
}
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 privateKey = await SecureStore.getItemAsync(
`${keys.storagePrefix}${keyId}`,
)
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 connections = {
storagePrefix: 'connection_',
manifestKey: 'connectionsManifest',
} as const
const connectionsManifestSchema = z.object({
manifestVersion: z.number().default(1),
connections: z.array(
z.object({
id: z.string(),
priority: z.number(),
createdAt: z.date(),
modifiedAt: z.date(),
}),
),
})
export const connectionDetailsSchema = z.object({
host: z.string().min(1),
port: z.number().min(1),
username: z.string().min(1),
security: z.discriminatedUnion('type', [
z.object({
type: z.literal('password'),
password: z.string().min(1),
}),
z.object({
type: z.literal('key'),
keyId: z.string().min(1),
}),
]),
})
export type ConnectionDetails = z.infer<typeof connectionDetailsSchema>
async function getConnectionManifest() {
const rawManifest = await SecureStore.getItemAsync(connections.manifestKey)
const manifest = rawManifest
? JSON.parse(rawManifest)
: {
manifestVersion: 1,
connections: [],
}
return connectionsManifestSchema.parse(manifest)
}
async function upsertConnection(params: {
id: string
details: ConnectionDetails
priority: number
}) {
const manifest = await getConnectionManifest()
const existingConnection = manifest.connections.find(
(connection) => connection.id === params.id,
)
const newConnection = existingConnection
? {
...existingConnection,
priority: params.priority,
modifiedAt: new Date(),
}
: {
id: params.id,
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
}
async function deleteConnection(id: string) {
const manifest = await getConnectionManifest()
const connection = manifest.connections.find(
(connection) => connection.id === id,
)
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] })
}
async function getConnection(id: string) {
const manifest = await getConnectionManifest()
const connection = manifest.connections.find(
(connection) => connection.id === id,
)
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 }
}
const connectionQueryKey = 'connections'
const listConnectionsQueryOptions = queryOptions({
queryKey: [connectionQueryKey],
queryFn: async () => {
const manifest = await getConnectionManifest()
const firstConnectionMeta = manifest.connections[0]
const firstConnection = firstConnectionMeta
? await getConnection(firstConnectionMeta.id)
: null
return {
manifest,
firstConnection,
}
},
})
const getConnectionQueryOptions = (id: string) =>
queryOptions({
queryKey: [connectionQueryKey, id],
queryFn: () => getConnection(id),
})
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'
async function generateKeyPair(params: {
type: SshPrivateKeyType
passphrase?: string
keySize?: number
comment?: string
}) {
const keyPair = await SSHClient.generateKeyPair(
params.type,
params.passphrase,
params.keySize,
params.comment,
)
return keyPair
}
export const secretsManager = {
keys: {
utils: {
getKeyManifest,
savePrivateKey,
getPrivateKey,
deletePrivateKey,
generateKeyPair,
},
query: {
list: listKeysQueryOptions,
},
},
connections: {
utils: {
upsertConnection,
deleteConnection,
},
query: {
list: listConnectionsQueryOptions,
get: getConnectionQueryOptions,
},
},
}

View File

@@ -1,4 +1,5 @@
import SSHClient from '@dylankenneally/react-native-ssh-sftp' import SSHClient from '@dylankenneally/react-native-ssh-sftp'
import uuid from 'react-native-uuid'
export type SSHConn = { export type SSHConn = {
client: SSHClient client: SSHClient
@@ -9,8 +10,7 @@ export type SSHConn = {
const sshConnections = new Map<string, SSHConn>() const sshConnections = new Map<string, SSHConn>()
function addSession(params: { client: SSHClient }) { function addSession(params: { client: SSHClient }) {
// const sessionId = crypto.randomUUID() const sessionId = uuid.v4()
const sessionId = '123'
const createdAt = new Date() const createdAt = new Date()
const sshConn: SSHConn = { const sshConn: SSHConn = {
client: params.client, client: params.client,
@@ -29,6 +29,7 @@ function getSession(params: { sessionId: string }) {
function removeAndDisconnectSession(params: { sessionId: string }) { function removeAndDisconnectSession(params: { sessionId: string }) {
const sshConn = getSession(params) const sshConn = getSession(params)
// sshConn.client.closeShell()
sshConn.client.disconnect() sshConn.client.disconnect()
sshConnections.delete(params.sessionId) sshConnections.delete(params.sessionId)
} }

3
src/lib/utils.ts Normal file
View File

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