@dskhys/mf-scraper 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +484 -0
- package/dist/aggregation.test.d.ts +2 -0
- package/dist/aggregation.test.d.ts.map +1 -0
- package/dist/aggregation.test.js +202 -0
- package/dist/aggregation.test.js.map +1 -0
- package/dist/api.d.ts +26 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +64 -0
- package/dist/api.js.map +1 -0
- package/dist/assign-ids.d.ts +8 -0
- package/dist/assign-ids.d.ts.map +1 -0
- package/dist/assign-ids.js +26 -0
- package/dist/assign-ids.js.map +1 -0
- package/dist/assign-ids.test.d.ts +2 -0
- package/dist/assign-ids.test.d.ts.map +1 -0
- package/dist/assign-ids.test.js +146 -0
- package/dist/assign-ids.test.js.map +1 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +58 -0
- package/dist/config.js.map +1 -0
- package/dist/e2e.test.d.ts +7 -0
- package/dist/e2e.test.d.ts.map +1 -0
- package/dist/e2e.test.js +132 -0
- package/dist/e2e.test.js.map +1 -0
- package/dist/encrypt.d.ts +29 -0
- package/dist/encrypt.d.ts.map +1 -0
- package/dist/encrypt.js +62 -0
- package/dist/encrypt.js.map +1 -0
- package/dist/encrypt.test.d.ts +2 -0
- package/dist/encrypt.test.d.ts.map +1 -0
- package/dist/encrypt.test.js +100 -0
- package/dist/encrypt.test.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +153 -0
- package/dist/index.js.map +1 -0
- package/dist/login.d.ts +11 -0
- package/dist/login.d.ts.map +1 -0
- package/dist/login.js +73 -0
- package/dist/login.js.map +1 -0
- package/dist/scraper.d.ts +40 -0
- package/dist/scraper.d.ts.map +1 -0
- package/dist/scraper.js +231 -0
- package/dist/scraper.js.map +1 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +29 -0
- package/scripts/generate-version.js +64 -0
- package/src/aggregation.test.ts +248 -0
- package/src/api.ts +89 -0
- package/src/assign-ids.test.ts +158 -0
- package/src/assign-ids.ts +32 -0
- package/src/config.ts +79 -0
- package/src/e2e.test.ts +163 -0
- package/src/encrypt.test.ts +139 -0
- package/src/encrypt.ts +91 -0
- package/src/index.ts +180 -0
- package/src/login.ts +88 -0
- package/src/scraper.ts +317 -0
- package/src/version.ts +8 -0
- package/tsconfig.json +19 -0
- package/vitest.config.ts +8 -0
package/src/api.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type EncryptedData, encryptedToBase64 } from './encrypt.js';
|
|
2
|
+
|
|
3
|
+
interface LoginResponse {
|
|
4
|
+
accessToken: string;
|
|
5
|
+
refreshToken: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface ApiClientOptions {
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
username: string;
|
|
11
|
+
password: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* APIクライアント
|
|
16
|
+
*/
|
|
17
|
+
export class ApiClient {
|
|
18
|
+
private baseUrl: string;
|
|
19
|
+
private username: string;
|
|
20
|
+
private password: string;
|
|
21
|
+
private accessToken: string | null = null;
|
|
22
|
+
|
|
23
|
+
constructor(options: ApiClientOptions) {
|
|
24
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, ''); // 末尾のスラッシュを削除
|
|
25
|
+
this.username = options.username;
|
|
26
|
+
this.password = options.password;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* APIサーバーにログイン
|
|
31
|
+
*/
|
|
32
|
+
async login(): Promise<void> {
|
|
33
|
+
const response = await fetch(`${this.baseUrl}/api/auth/login`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: {
|
|
36
|
+
'Content-Type': 'application/json',
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify({
|
|
39
|
+
email: this.username,
|
|
40
|
+
password: this.password,
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
const text = await response.text();
|
|
46
|
+
throw new Error(`ログイン失敗: ${response.status} ${text}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const data = (await response.json()) as LoginResponse;
|
|
50
|
+
this.accessToken = data.accessToken;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 暗号化ポートフォリオデータを送信
|
|
55
|
+
*/
|
|
56
|
+
async sendEncryptedPortfolio(
|
|
57
|
+
encryptedData: EncryptedData,
|
|
58
|
+
scrapedAt: string
|
|
59
|
+
): Promise<void> {
|
|
60
|
+
if (!this.accessToken) {
|
|
61
|
+
throw new Error('ログインが必要です');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const base64Data = encryptedToBase64(encryptedData);
|
|
65
|
+
console.log(base64Data);
|
|
66
|
+
|
|
67
|
+
const response = await fetch(
|
|
68
|
+
`${this.baseUrl}/api/portfolio/encrypted`,
|
|
69
|
+
{
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers: {
|
|
72
|
+
'Content-Type': 'application/json',
|
|
73
|
+
Authorization: `Bearer ${this.accessToken}`,
|
|
74
|
+
},
|
|
75
|
+
body: JSON.stringify({
|
|
76
|
+
iv: base64Data.iv,
|
|
77
|
+
data: base64Data.encryptedData,
|
|
78
|
+
tag: base64Data.authTag,
|
|
79
|
+
scrapedAt,
|
|
80
|
+
}),
|
|
81
|
+
}
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
const text = await response.text();
|
|
86
|
+
throw new Error(`データ送信失敗: ${response.status} ${text}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { assignIds } from './assign-ids.js';
|
|
3
|
+
import type { MFStock } from './scraper.js';
|
|
4
|
+
|
|
5
|
+
describe('assignIds', () => {
|
|
6
|
+
it('シンプルなケース:重複なし', () => {
|
|
7
|
+
const stocks: MFStock[] = [
|
|
8
|
+
{
|
|
9
|
+
id: '',
|
|
10
|
+
name: 'Apple',
|
|
11
|
+
account: 'SBI',
|
|
12
|
+
units: 10,
|
|
13
|
+
averageCost: 150,
|
|
14
|
+
currentPrice: 160,
|
|
15
|
+
value: 1600,
|
|
16
|
+
profitLoss: 100,
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
id: '',
|
|
20
|
+
name: 'Google',
|
|
21
|
+
account: 'SBI',
|
|
22
|
+
units: 5,
|
|
23
|
+
averageCost: 100,
|
|
24
|
+
currentPrice: 120,
|
|
25
|
+
value: 600,
|
|
26
|
+
profitLoss: 100,
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const result = assignIds(stocks);
|
|
31
|
+
|
|
32
|
+
expect(result[0].id).toBe('Apple_SBI');
|
|
33
|
+
expect(result[1].id).toBe('Google_SBI');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('同一銘柄・同一金融機関の場合、_2, _3 をつける', () => {
|
|
37
|
+
const stocks: MFStock[] = [
|
|
38
|
+
{
|
|
39
|
+
id: '',
|
|
40
|
+
name: 'Apple',
|
|
41
|
+
account: 'SBI',
|
|
42
|
+
units: 10,
|
|
43
|
+
averageCost: 150,
|
|
44
|
+
currentPrice: 160,
|
|
45
|
+
value: 1600,
|
|
46
|
+
profitLoss: 100,
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: '',
|
|
50
|
+
name: 'Apple',
|
|
51
|
+
account: 'SBI',
|
|
52
|
+
units: 5,
|
|
53
|
+
averageCost: 155,
|
|
54
|
+
currentPrice: 160,
|
|
55
|
+
value: 800,
|
|
56
|
+
profitLoss: 25,
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: '',
|
|
60
|
+
name: 'Apple',
|
|
61
|
+
account: 'SBI',
|
|
62
|
+
units: 3,
|
|
63
|
+
averageCost: 145,
|
|
64
|
+
currentPrice: 160,
|
|
65
|
+
value: 480,
|
|
66
|
+
profitLoss: 45,
|
|
67
|
+
},
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
const result = assignIds(stocks);
|
|
71
|
+
|
|
72
|
+
expect(result[0].id).toBe('Apple_SBI');
|
|
73
|
+
expect(result[1].id).toBe('Apple_SBI_2');
|
|
74
|
+
expect(result[2].id).toBe('Apple_SBI_3');
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('異なる金融機関の同一銘柄は異なる ID になる', () => {
|
|
78
|
+
const stocks: MFStock[] = [
|
|
79
|
+
{
|
|
80
|
+
id: '',
|
|
81
|
+
name: 'Apple',
|
|
82
|
+
account: 'SBI',
|
|
83
|
+
units: 10,
|
|
84
|
+
averageCost: 150,
|
|
85
|
+
currentPrice: 160,
|
|
86
|
+
value: 1600,
|
|
87
|
+
profitLoss: 100,
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: '',
|
|
91
|
+
name: 'Apple',
|
|
92
|
+
account: '楽天',
|
|
93
|
+
units: 5,
|
|
94
|
+
averageCost: 155,
|
|
95
|
+
currentPrice: 160,
|
|
96
|
+
value: 800,
|
|
97
|
+
profitLoss: 25,
|
|
98
|
+
},
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
const result = assignIds(stocks);
|
|
102
|
+
|
|
103
|
+
expect(result[0].id).toBe('Apple_SBI');
|
|
104
|
+
expect(result[1].id).toBe('Apple_楽天');
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('複雑なケース:複数の銘柄・複数の金融機関・一部重複', () => {
|
|
108
|
+
const stocks: MFStock[] = [
|
|
109
|
+
{
|
|
110
|
+
id: '',
|
|
111
|
+
name: 'Apple',
|
|
112
|
+
account: 'SBI',
|
|
113
|
+
units: 10,
|
|
114
|
+
averageCost: 150,
|
|
115
|
+
currentPrice: 160,
|
|
116
|
+
value: 1600,
|
|
117
|
+
profitLoss: 100,
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
id: '',
|
|
121
|
+
name: 'Google',
|
|
122
|
+
account: 'SBI',
|
|
123
|
+
units: 5,
|
|
124
|
+
averageCost: 100,
|
|
125
|
+
currentPrice: 120,
|
|
126
|
+
value: 600,
|
|
127
|
+
profitLoss: 100,
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
id: '',
|
|
131
|
+
name: 'Apple',
|
|
132
|
+
account: 'SBI',
|
|
133
|
+
units: 5,
|
|
134
|
+
averageCost: 155,
|
|
135
|
+
currentPrice: 160,
|
|
136
|
+
value: 800,
|
|
137
|
+
profitLoss: 25,
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
id: '',
|
|
141
|
+
name: 'Apple',
|
|
142
|
+
account: '楽天',
|
|
143
|
+
units: 3,
|
|
144
|
+
averageCost: 145,
|
|
145
|
+
currentPrice: 160,
|
|
146
|
+
value: 480,
|
|
147
|
+
profitLoss: 45,
|
|
148
|
+
},
|
|
149
|
+
];
|
|
150
|
+
|
|
151
|
+
const result = assignIds(stocks);
|
|
152
|
+
|
|
153
|
+
expect(result[0].id).toBe('Apple_SBI');
|
|
154
|
+
expect(result[1].id).toBe('Google_SBI');
|
|
155
|
+
expect(result[2].id).toBe('Apple_SBI_2');
|
|
156
|
+
expect(result[3].id).toBe('Apple_楽天');
|
|
157
|
+
});
|
|
158
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { MFStock } from './scraper.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* MFStock に ID を割り当てる
|
|
5
|
+
* 銘柄名_金融機関名 の形式でID を生成
|
|
6
|
+
* 同じ組み合わせがある場合は _2, _3 などをつける
|
|
7
|
+
*/
|
|
8
|
+
export const assignIds = (stocks: Omit<MFStock, 'id'>[]): MFStock[] => {
|
|
9
|
+
const idMap = new Map<string, number>();
|
|
10
|
+
const result: MFStock[] = [];
|
|
11
|
+
|
|
12
|
+
for (const stock of stocks) {
|
|
13
|
+
const baseKey = `${stock.name}_${stock.account}`;
|
|
14
|
+
|
|
15
|
+
// 出現回数をカウント
|
|
16
|
+
const count = idMap.get(baseKey) ?? 0;
|
|
17
|
+
idMap.set(baseKey, count + 1);
|
|
18
|
+
|
|
19
|
+
// ID を生成
|
|
20
|
+
let id = baseKey;
|
|
21
|
+
if (count > 0) {
|
|
22
|
+
id = `${baseKey}_${count + 1}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
result.push({
|
|
26
|
+
...stock,
|
|
27
|
+
id,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return result;
|
|
32
|
+
};
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export interface Config {
|
|
6
|
+
encryptionKey: string;
|
|
7
|
+
apiUrl: string;
|
|
8
|
+
apiUsername: string;
|
|
9
|
+
apiPassword: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const CONFIG_DIR = path.join(os.homedir(), '.config', 'mf-scraper');
|
|
13
|
+
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
14
|
+
const AUTH_FILE = path.join(CONFIG_DIR, 'auth.json');
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 設定ディレクトリを初期化
|
|
18
|
+
*/
|
|
19
|
+
export const ensureConfigDir = (): void => {
|
|
20
|
+
if (!fs.existsSync(CONFIG_DIR)) {
|
|
21
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 設定ファイルを読み込み
|
|
27
|
+
*/
|
|
28
|
+
export const loadConfig = (): Config => {
|
|
29
|
+
if (!fs.existsSync(CONFIG_FILE)) {
|
|
30
|
+
throw new Error(
|
|
31
|
+
`設定ファイルが見つかりません: ${CONFIG_FILE}\n` +
|
|
32
|
+
'以下の形式で設定ファイルを作成してください:\n' +
|
|
33
|
+
JSON.stringify(
|
|
34
|
+
{
|
|
35
|
+
encryptionKey: 'Base64エンコードされた32バイトのキー',
|
|
36
|
+
apiUrl: 'https://api.example.com',
|
|
37
|
+
apiUsername: 'APIサーバーのユーザー名',
|
|
38
|
+
apiPassword: 'APIサーバーのパスワード',
|
|
39
|
+
},
|
|
40
|
+
null,
|
|
41
|
+
2
|
|
42
|
+
)
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const content = fs.readFileSync(CONFIG_FILE, 'utf-8');
|
|
47
|
+
const config = JSON.parse(content) as Config;
|
|
48
|
+
|
|
49
|
+
// バリデーション
|
|
50
|
+
if (!config.encryptionKey) {
|
|
51
|
+
throw new Error('設定ファイルにencryptionKeyがありません');
|
|
52
|
+
}
|
|
53
|
+
if (!config.apiUrl) {
|
|
54
|
+
throw new Error('設定ファイルにapiUrlがありません');
|
|
55
|
+
}
|
|
56
|
+
if (!config.apiUsername) {
|
|
57
|
+
throw new Error('設定ファイルにapiUsernameがありません');
|
|
58
|
+
}
|
|
59
|
+
if (!config.apiPassword) {
|
|
60
|
+
throw new Error('設定ファイルにapiPasswordがありません');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return config;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 認証ファイルのパスを取得
|
|
68
|
+
*/
|
|
69
|
+
export const getAuthFilePath = (): string => AUTH_FILE;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 認証ファイルが存在するか確認
|
|
73
|
+
*/
|
|
74
|
+
export const hasAuthFile = (): boolean => fs.existsSync(AUTH_FILE);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 設定ディレクトリのパスを取得
|
|
78
|
+
*/
|
|
79
|
+
export const getConfigDir = (): string => CONFIG_DIR;
|
package/src/e2e.test.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mf-scraper エンドツーエンドテスト
|
|
3
|
+
*
|
|
4
|
+
* 実際のマネーフォワードなしで、モック環境で動作確認
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it } from 'vitest';
|
|
8
|
+
import { decrypt, type EncryptedData, encrypt } from './encrypt.js';
|
|
9
|
+
|
|
10
|
+
describe('end-to-end encryption flow', () => {
|
|
11
|
+
const testKey =
|
|
12
|
+
'4ffa6b761c44097af8962f53b347651960ff98ea53aa916718ffae00c45a3663';
|
|
13
|
+
|
|
14
|
+
const mockPortfolioData = {
|
|
15
|
+
stocks: [
|
|
16
|
+
{
|
|
17
|
+
name: 'Apple Inc.',
|
|
18
|
+
units: 100,
|
|
19
|
+
averageCost: 120.5,
|
|
20
|
+
currentPrice: 175.3,
|
|
21
|
+
value: 17530,
|
|
22
|
+
profitLoss: 5480,
|
|
23
|
+
account: 'NISA',
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: 'ソフトバンクグループ',
|
|
27
|
+
units: 50,
|
|
28
|
+
averageCost: 2400,
|
|
29
|
+
currentPrice: 2850,
|
|
30
|
+
value: 142500,
|
|
31
|
+
profitLoss: 22500,
|
|
32
|
+
account: '特定',
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
scrapedAt: new Date().toISOString(),
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
it('バッチ側: データを暗号化', () => {
|
|
39
|
+
const json = JSON.stringify(mockPortfolioData);
|
|
40
|
+
const keyBuffer = Buffer.from(testKey, 'hex');
|
|
41
|
+
|
|
42
|
+
const { iv, encrypted, authTag } = encrypt(json, keyBuffer);
|
|
43
|
+
|
|
44
|
+
// 各要素が正しく生成されたか確認
|
|
45
|
+
expect(iv).toBeInstanceOf(Buffer);
|
|
46
|
+
expect(iv.length).toBe(12); // 12 bytes IV
|
|
47
|
+
expect(encrypted).toBeInstanceOf(Buffer);
|
|
48
|
+
expect(encrypted.length).toBeGreaterThan(0);
|
|
49
|
+
expect(authTag).toBeInstanceOf(Buffer);
|
|
50
|
+
expect(authTag.length).toBe(16); // 16 bytes auth tag
|
|
51
|
+
|
|
52
|
+
console.log('✅ 暗号化成功');
|
|
53
|
+
console.log(` IV: ${iv.toString('base64')}`);
|
|
54
|
+
console.log(` 暗号文長: ${encrypted.length} bytes`);
|
|
55
|
+
console.log(` 認証タグ: ${authTag.toString('base64')}`);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('バッチ側: APIに送信するデータを生成', () => {
|
|
59
|
+
const json = JSON.stringify(mockPortfolioData);
|
|
60
|
+
const keyBuffer = Buffer.from(testKey, 'hex');
|
|
61
|
+
const { iv, encrypted, authTag } = encrypt(json, keyBuffer);
|
|
62
|
+
|
|
63
|
+
// API送信形式に変換
|
|
64
|
+
const apiPayload = {
|
|
65
|
+
iv: iv.toString('base64'),
|
|
66
|
+
encryptedData: encrypted.toString('base64'),
|
|
67
|
+
authTag: authTag.toString('base64'),
|
|
68
|
+
scrapedAt: mockPortfolioData.scrapedAt,
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// JSONで送信可能か確認
|
|
72
|
+
const json_serialized = JSON.stringify(apiPayload);
|
|
73
|
+
expect(() => JSON.parse(json_serialized)).not.toThrow();
|
|
74
|
+
|
|
75
|
+
console.log('✅ API送信形式を生成');
|
|
76
|
+
console.log(` ペイロードサイズ: ${json_serialized.length} bytes`);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('クライアント側: APIから受け取ったデータを復号', () => {
|
|
80
|
+
const json = JSON.stringify(mockPortfolioData);
|
|
81
|
+
const keyBuffer = Buffer.from(testKey, 'hex');
|
|
82
|
+
|
|
83
|
+
// バッチ側で暗号化
|
|
84
|
+
const encryptedData = encrypt(json, keyBuffer);
|
|
85
|
+
|
|
86
|
+
// クライアント側で復号(Web Crypto API)
|
|
87
|
+
// 注: Node.js環境なのでWeb Crypto APIではなく、同等の処理をテスト
|
|
88
|
+
const decrypted = decrypt(encryptedData, keyBuffer);
|
|
89
|
+
expect(decrypted).toBe(json);
|
|
90
|
+
|
|
91
|
+
const parsed = JSON.parse(decrypted);
|
|
92
|
+
expect(parsed).toEqual(mockPortfolioData);
|
|
93
|
+
|
|
94
|
+
console.log('✅ クライアント側の復号成功');
|
|
95
|
+
console.log(` 復号後の銘柄数: ${parsed.stocks.length}`);
|
|
96
|
+
console.log(` 復号後の日時: ${parsed.scrapedAt}`);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('データ改ざん検出テスト', () => {
|
|
100
|
+
const json = JSON.stringify(mockPortfolioData);
|
|
101
|
+
const keyBuffer = Buffer.from(testKey, 'hex');
|
|
102
|
+
const encryptedData = encrypt(json, keyBuffer);
|
|
103
|
+
|
|
104
|
+
// 認証タグを改ざん
|
|
105
|
+
const tamperedAuthTag = Buffer.alloc(encryptedData.authTag.length);
|
|
106
|
+
encryptedData.authTag.copy(tamperedAuthTag);
|
|
107
|
+
tamperedAuthTag[0] ^= 0xff; // 最初のバイトをフリップ
|
|
108
|
+
|
|
109
|
+
// 改ざんされたデータで復号しようとする
|
|
110
|
+
const tamperedData: EncryptedData = {
|
|
111
|
+
...encryptedData,
|
|
112
|
+
authTag: tamperedAuthTag,
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
expect(() => {
|
|
116
|
+
decrypt(tamperedData, keyBuffer);
|
|
117
|
+
}).toThrow();
|
|
118
|
+
|
|
119
|
+
console.log('✅ 改ざんが正しく検出されました');
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('システム全体のフロー: バッチ → API → クライアント', () => {
|
|
123
|
+
// 1. バッチ側:データ暗号化
|
|
124
|
+
const json = JSON.stringify(mockPortfolioData);
|
|
125
|
+
const keyBuffer = Buffer.from(testKey, 'hex');
|
|
126
|
+
const encryptedData = encrypt(json, keyBuffer);
|
|
127
|
+
|
|
128
|
+
// 2. API経由での送受信をシミュレート(検証のため変数使用)
|
|
129
|
+
const apiData = {
|
|
130
|
+
iv: encryptedData.iv.toString('base64'),
|
|
131
|
+
encryptedData: encryptedData.encrypted.toString('base64'),
|
|
132
|
+
authTag: encryptedData.authTag.toString('base64'),
|
|
133
|
+
scrapedAt: mockPortfolioData.scrapedAt,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// 3. クライアント側:データ受け取り
|
|
137
|
+
// API形式(Base64)をBuffer形式に戻す
|
|
138
|
+
const bufferData = {
|
|
139
|
+
iv: Buffer.from(apiData.iv, 'base64'),
|
|
140
|
+
encrypted: Buffer.from(apiData.encryptedData, 'base64'),
|
|
141
|
+
authTag: Buffer.from(apiData.authTag, 'base64'),
|
|
142
|
+
};
|
|
143
|
+
const decrypted = decrypt(bufferData, keyBuffer);
|
|
144
|
+
|
|
145
|
+
const result = JSON.parse(decrypted);
|
|
146
|
+
|
|
147
|
+
// 4. 検証
|
|
148
|
+
expect(result.stocks.length).toBe(2);
|
|
149
|
+
expect(result.stocks[0].name).toBe('Apple Inc.');
|
|
150
|
+
expect(result.stocks[0].value).toBe(17530);
|
|
151
|
+
expect(result.stocks[1].name).toBe('ソフトバンクグループ');
|
|
152
|
+
expect(result.stocks[1].profitLoss).toBe(22500);
|
|
153
|
+
expect(result.scrapedAt).toBe(mockPortfolioData.scrapedAt);
|
|
154
|
+
|
|
155
|
+
console.log('✅ エンドツーエンドフロー完成');
|
|
156
|
+
console.log(
|
|
157
|
+
` 暗号化: ${json.length} bytes → ${encryptedData.encrypted.length} bytes`
|
|
158
|
+
);
|
|
159
|
+
console.log(
|
|
160
|
+
` 圧縮率: ${((encryptedData.encrypted.length / json.length) * 100).toFixed(1)}%`
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
decrypt,
|
|
4
|
+
type EncryptedData,
|
|
5
|
+
encrypt,
|
|
6
|
+
encryptedToBase64,
|
|
7
|
+
} from './encrypt.js';
|
|
8
|
+
|
|
9
|
+
describe('encrypt', () => {
|
|
10
|
+
// 32バイトのテスト用キー
|
|
11
|
+
const testKey = Buffer.from('0123456789abcdef0123456789abcdef');
|
|
12
|
+
|
|
13
|
+
describe('encrypt', () => {
|
|
14
|
+
it('文字列を暗号化できる', () => {
|
|
15
|
+
const plaintext = 'Hello, World!';
|
|
16
|
+
const result = encrypt(plaintext, testKey);
|
|
17
|
+
|
|
18
|
+
expect(result.iv).toBeInstanceOf(Buffer);
|
|
19
|
+
expect(result.encrypted).toBeInstanceOf(Buffer);
|
|
20
|
+
expect(result.authTag).toBeInstanceOf(Buffer);
|
|
21
|
+
expect(result.iv.length).toBe(12);
|
|
22
|
+
expect(result.authTag.length).toBe(16);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('同じ平文でも毎回異なるIVが生成される', () => {
|
|
26
|
+
const plaintext = 'Same text';
|
|
27
|
+
const result1 = encrypt(plaintext, testKey);
|
|
28
|
+
const result2 = encrypt(plaintext, testKey);
|
|
29
|
+
|
|
30
|
+
expect(result1.iv.toString('hex')).not.toBe(
|
|
31
|
+
result2.iv.toString('hex')
|
|
32
|
+
);
|
|
33
|
+
expect(result1.encrypted.toString('hex')).not.toBe(
|
|
34
|
+
result2.encrypted.toString('hex')
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('キーが32バイトでない場合はエラー', () => {
|
|
39
|
+
const invalidKey = Buffer.from('short');
|
|
40
|
+
expect(() => encrypt('test', invalidKey)).toThrow(
|
|
41
|
+
'暗号化キーは32バイトである必要があります'
|
|
42
|
+
);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('JSON文字列を暗号化できる', () => {
|
|
46
|
+
const data = {
|
|
47
|
+
stocks: [
|
|
48
|
+
{ name: 'テスト株', value: 10000 },
|
|
49
|
+
{ name: 'サンプル', value: 20000 },
|
|
50
|
+
],
|
|
51
|
+
scrapedAt: '2026-01-13T07:00:00.000Z',
|
|
52
|
+
};
|
|
53
|
+
const plaintext = JSON.stringify(data);
|
|
54
|
+
const result = encrypt(plaintext, testKey);
|
|
55
|
+
|
|
56
|
+
expect(result.iv).toBeInstanceOf(Buffer);
|
|
57
|
+
expect(result.encrypted).toBeInstanceOf(Buffer);
|
|
58
|
+
expect(result.authTag).toBeInstanceOf(Buffer);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe('decrypt', () => {
|
|
63
|
+
it('暗号化したデータを復号できる', () => {
|
|
64
|
+
const plaintext = 'Hello, World!';
|
|
65
|
+
const encrypted = encrypt(plaintext, testKey);
|
|
66
|
+
const decrypted = decrypt(encrypted, testKey);
|
|
67
|
+
|
|
68
|
+
expect(decrypted).toBe(plaintext);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('JSON文字列を復号してパースできる', () => {
|
|
72
|
+
const data = {
|
|
73
|
+
stocks: [
|
|
74
|
+
{ name: 'テスト株', value: 10000 },
|
|
75
|
+
{ name: 'サンプル', value: 20000 },
|
|
76
|
+
],
|
|
77
|
+
scrapedAt: '2026-01-13T07:00:00.000Z',
|
|
78
|
+
};
|
|
79
|
+
const plaintext = JSON.stringify(data);
|
|
80
|
+
const encrypted = encrypt(plaintext, testKey);
|
|
81
|
+
const decrypted = decrypt(encrypted, testKey);
|
|
82
|
+
const parsed = JSON.parse(decrypted);
|
|
83
|
+
|
|
84
|
+
expect(parsed).toEqual(data);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('不正なキーでは復号できない', () => {
|
|
88
|
+
const plaintext = 'Secret data';
|
|
89
|
+
const encrypted = encrypt(plaintext, testKey);
|
|
90
|
+
|
|
91
|
+
const wrongKey = Buffer.from('abcdef0123456789abcdef0123456789');
|
|
92
|
+
|
|
93
|
+
expect(() => decrypt(encrypted, wrongKey)).toThrow();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('改ざんされたデータは復号できない', () => {
|
|
97
|
+
const plaintext = 'Original data';
|
|
98
|
+
const encrypted = encrypt(plaintext, testKey);
|
|
99
|
+
|
|
100
|
+
// 認証タグを改ざん
|
|
101
|
+
const tampered: EncryptedData = {
|
|
102
|
+
...encrypted,
|
|
103
|
+
authTag: Buffer.alloc(16, 0),
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
expect(() => decrypt(tampered, testKey)).toThrow();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('キーが32バイトでない場合はエラー', () => {
|
|
110
|
+
const invalidKey = Buffer.from('short');
|
|
111
|
+
const encrypted = encrypt('test', testKey);
|
|
112
|
+
|
|
113
|
+
expect(() => decrypt(encrypted, invalidKey)).toThrow(
|
|
114
|
+
'暗号化キーは32バイトである必要があります'
|
|
115
|
+
);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
describe('encryptedToBase64', () => {
|
|
120
|
+
it('暗号化データをBase64に変換できる', () => {
|
|
121
|
+
const plaintext = 'Test data';
|
|
122
|
+
const encrypted = encrypt(plaintext, testKey);
|
|
123
|
+
const base64 = encryptedToBase64(encrypted);
|
|
124
|
+
|
|
125
|
+
expect(typeof base64.iv).toBe('string');
|
|
126
|
+
expect(typeof base64.encryptedData).toBe('string');
|
|
127
|
+
expect(typeof base64.authTag).toBe('string');
|
|
128
|
+
|
|
129
|
+
// Base64であることを確認
|
|
130
|
+
expect(Buffer.from(base64.iv, 'base64')).toEqual(encrypted.iv);
|
|
131
|
+
expect(Buffer.from(base64.encryptedData, 'base64')).toEqual(
|
|
132
|
+
encrypted.encrypted
|
|
133
|
+
);
|
|
134
|
+
expect(Buffer.from(base64.authTag, 'base64')).toEqual(
|
|
135
|
+
encrypted.authTag
|
|
136
|
+
);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
});
|