-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh-key.ts
More file actions
173 lines (143 loc) · 4.89 KB
/
Copy pathssh-key.ts
File metadata and controls
173 lines (143 loc) · 4.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import {
CreatePlan,
DestroyPlan,
ModifyPlan,
ParameterChange,
Resource,
ResourceSettings,
getPty
} from 'codify-plugin-lib';
import { StringIndexedObject } from 'codify-schemas';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { codifySpawn } from '../../utils/codify-spawn.js';
import { FileUtils } from '../../utils/file-utils.js';
import Schema from './ssh-key-schema.json';
export type SshKeyType = 'ecdsa' | 'ecdsa-sk' | 'ed25519' | 'ed25519-sk' | 'rsa';
export interface SshKeyConfig extends StringIndexedObject {
keyType: SshKeyType;
comment?: string;
fileName: string;
bits?: number;
passphrase: string;
folder: string;
}
const SSH_KEYGEN_FINGERPRINT_REGEX = /^(\d+) (.*):(.*) (.*) \((.*)\)$/
export class SshKeyResource extends Resource<SshKeyConfig> {
getSettings(): ResourceSettings<SshKeyConfig> {
return {
id: 'ssh-key',
schema: Schema,
parameterSettings: {
comment: { canModify: true },
passphrase: { canModify: true, isSensitive: true },
folder: { type: 'directory', default: '~/.ssh' }
},
importAndDestroy:{
requiredParameters: ['fileName'],
defaultRefreshValues: {
passphrase: '',
}
},
transformation: {
to(input) {
if (!input.keyType) {
input.keyType = 'ed25519';
}
if (!input.fileName) {
input.fileName = `id_${input.keyType}`;
}
return input;
},
from: (output) => output,
},
allowMultiple: {
identifyingParameters: ['fileName'],
async findAllParameters() {
try {
const sshPublicKeys = await fs.readdir(path.join(os.homedir(), '.ssh'));
return sshPublicKeys.filter((p) => {
if (!p.endsWith('.pub')) {
return false;
}
// We only want public / private pairs.
const name = p.slice(0, - 4);
return sshPublicKeys.includes(name)
}).map((p) => ({ fileName: p.slice(0, - 4) }))
} catch {
return [];
}
}
}
}
}
override async refresh(parameters: Partial<SshKeyConfig>): Promise<Partial<SshKeyConfig> | null> {
const $ = getPty();
if (!(await FileUtils.dirExists(parameters.folder!))) {
return null;
}
const keyPath = path.join(parameters.folder!, parameters.fileName!);
if (!(await FileUtils.fileExists(keyPath))) {
return null;
}
const { data: existingKey } = await $.spawn(`ssh-keygen -l -f ${parameters.fileName}`, { cwd: parameters.folder! });
const [_, bits, __, ___, comment, type] = existingKey
.trim()
.match(SSH_KEYGEN_FINGERPRINT_REGEX) ?? [];
if (!bits || !type) {
console.error(`Unable to parse ssh keygen output: ${_}`)
return null;
}
const currentConfig: Partial<SshKeyConfig> = {
fileName: parameters.fileName,
passphrase: parameters.passphrase,
folder: parameters.folder!,
};
if (parameters.bits) {
currentConfig.bits = Number.parseInt(bits, 10);
}
if (parameters.keyType) {
currentConfig.keyType = type.toLowerCase() as SshKeyType;
}
if (parameters.comment) {
currentConfig.comment = comment;
}
return currentConfig;
}
override async create(plan: CreatePlan<SshKeyConfig>): Promise<void> {
const folderPath = path.resolve(os.homedir(), '.ssh')
if (!(await FileUtils.dirExists(folderPath))) {
await codifySpawn('mkdir .ssh', { cwd: os.homedir() })
await codifySpawn('chmod 700 .ssh', { cwd: os.homedir() })
}
const command = [
'ssh-keygen',
`-f "${plan.desiredConfig.fileName}"`,
`-t ${plan.desiredConfig.keyType}`,
`-P "${plan.desiredConfig.passphrase}"`
]
if (plan.desiredConfig.comment) {
command.push(`-C "${plan.desiredConfig.comment}"`);
}
if (plan.desiredConfig.bits) {
command.push(`-b ${plan.desiredConfig.bits}`);
}
await codifySpawn(command.join(' '), { cwd: plan.desiredConfig.folder })
}
override async modify(pc: ParameterChange<SshKeyConfig>, plan: ModifyPlan<SshKeyConfig>): Promise<void> {
if (pc.name === 'comment') {
await codifySpawn(`ssh-keygen -f ${plan.desiredConfig.fileName} -c -C "${pc.newValue}"`, { cwd: plan.desiredConfig.folder! })
return;
}
// Passphrase can't be called in stateless mode because we don't know what the previous password is
if (pc.name === 'passphrase') {
await codifySpawn(`ssh-keygen -f ${plan.desiredConfig.fileName} -N ${pc.newValue} -P ${pc.previousValue} -p`)
}
}
override async destroy(plan: DestroyPlan<SshKeyConfig>): Promise<void> {
const keyPath = path.join(plan.currentConfig.folder!, plan.currentConfig.fileName!);
await codifySpawn(`rm ${keyPath}`)
await codifySpawn(`rm ${keyPath}.pub`)
}
}