Files
cli/src/command/jwks.ts
2026-01-25 02:56:56 +08:00

74 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { generate } from '@kevisual/auth'
import { program, Command } from '@/program.ts';
import fs from 'node:fs';
import path from 'node:path';
export const getPath = async (dir: string) => {
const JWKS_PATH = path.join(dir, 'jwks.json');
const PRIVATE_JWK_PATH = path.join(dir, 'privateKey.json');
const PRIVATE_KEY_PATH = path.join(dir, 'privateKey.txt');
const PUBLIC_KEY_PATH = path.join(dir, 'publicKey.txt');
return {
JWKS_PATH,
PRIVATE_JWK_PATH,
PRIVATE_KEY_PATH,
PUBLIC_KEY_PATH,
}
}
const jwksCmd = new Command('jwks')
.description('JWKS 相关命令')
.action(async (opts) => {
});
const jwksGenerate = new Command('generate')
.alias('gen')
.option('-d , --dir <dir>', '指定保存目录,默认当前目录下 jwt 文件夹', 'jwt')
.description('生成 JWKS 密钥对')
.action(async (opts) => {
const dir = path.isAbsolute(opts.dir) ? opts.dir : path.join(process.cwd(), opts.dir);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const { JWKS_PATH, PRIVATE_JWK_PATH, PRIVATE_KEY_PATH, PUBLIC_KEY_PATH } = await getPath(dir);
const { jwks, privateJWK, privatePEM, publicPEM } = await generate();
fs.writeFileSync(PUBLIC_KEY_PATH, publicPEM);
fs.writeFileSync(PRIVATE_KEY_PATH, privatePEM);
fs.writeFileSync(PRIVATE_JWK_PATH, JSON.stringify(privateJWK, null, 2));
fs.writeFileSync(JWKS_PATH, JSON.stringify(jwks, null, 2));
console.log(`Keys have been saved to directory: ${dir}`);
});
jwksCmd.addCommand(jwksGenerate);
const getJWKS = new Command('get')
.description('获取 JWKS 内容')
.option('-d , --dir <dir>', '指定 JWKS 所在目录,默认当前目录下 jwt 文件夹', 'jwt')
.option('-t, --type <type>', '指定获取类型jwks 或 privateJWK', 'jwks')
.action(async (opts) => {
const dir = path.isAbsolute(opts.dir) ? opts.dir : path.join(process.cwd(), opts.dir);
const { JWKS_PATH, PRIVATE_JWK_PATH } = await getPath(dir);
const type = opts.type || 'jwks';
if (type !== 'jwks') {
if (!fs.existsSync(PRIVATE_JWK_PATH)) {
console.error(`Private JWK file not found in directory: ${dir}`);
return;
}
const privateJWKContent = fs.readFileSync(PRIVATE_JWK_PATH, 'utf-8');
console.log('Private JWK:\n');
console.log(privateJWKContent);
return;
}
if (!fs.existsSync(JWKS_PATH)) {
console.error(`JWKS file not found in directory: ${dir}`);
return;
}
const jwksContent = fs.readFileSync(JWKS_PATH, 'utf-8');
console.log('PublicJWKS:\n');
console.log(jwksContent);
});
jwksCmd.addCommand(getJWKS);
program.addCommand(jwksCmd);