-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli-node.ts
84 lines (75 loc) · 1.94 KB
/
cli-node.ts
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
import "./polyfill-node";
import process from "node:process";
import { TinyCli, TinyCliParseError, arg } from "@hiogawa/tiny-cli";
import { formatError } from "@hiogawa/utils";
import { version } from "../package.json";
const cli = new TinyCli({
program: "tiny-jwt",
version,
});
//
// keygen
//
const keygenFns: Record<string, () => Promise<unknown>> = {
HS256: async () => {
const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-256" },
true,
["sign", "verify"]
);
const jwk = await crypto.subtle.exportKey("jwk", key);
return jwk;
},
ES256: async () => {
const keyPair = await crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" },
true,
["sign", "verify"]
);
const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);
const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
return { privateKey, publicKey };
},
A256GCM: async () => {
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const jwk = await crypto.subtle.exportKey("jwk", key);
return jwk;
},
};
cli.defineCommand(
{
name: "keygen",
args: {
algorithm: arg.string(Object.keys(keygenFns).join(", "), {
positional: true,
}),
},
},
async ({ args }) => {
const keygenFn = keygenFns[args.algorithm];
if (!keygenFn) {
throw new TinyCliParseError("unsupported algorithm: " + args.algorithm);
}
const result = await keygenFn();
console.log(JSON.stringify(result, null, 2));
}
);
//
// main
//
async function main() {
try {
await cli.parse(process.argv.slice(2));
} catch (e) {
console.log(formatError(e, { noColor: !process.stdout.isTTY }));
if (e instanceof TinyCliParseError) {
console.log("See '--help' for more info.\n\n" + cli.help());
}
process.exit(1);
}
}
main();