@dskhys/mf-scraper 0.0.1 → 0.1.0

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.
Files changed (65) hide show
  1. package/README.md +452 -484
  2. package/dist/api.js +6 -32
  3. package/dist/assign-ids.js +0 -1
  4. package/dist/config.js +6 -9
  5. package/dist/encrypt.js +0 -1
  6. package/dist/index.js +10 -14
  7. package/dist/login.js +2 -1
  8. package/dist/scraper.js +37 -40
  9. package/package.json +27 -12
  10. package/dist/aggregation.test.d.ts +0 -2
  11. package/dist/aggregation.test.d.ts.map +0 -1
  12. package/dist/aggregation.test.js +0 -202
  13. package/dist/aggregation.test.js.map +0 -1
  14. package/dist/api.d.ts +0 -26
  15. package/dist/api.d.ts.map +0 -1
  16. package/dist/api.js.map +0 -1
  17. package/dist/assign-ids.d.ts +0 -8
  18. package/dist/assign-ids.d.ts.map +0 -1
  19. package/dist/assign-ids.js.map +0 -1
  20. package/dist/assign-ids.test.d.ts +0 -2
  21. package/dist/assign-ids.test.d.ts.map +0 -1
  22. package/dist/assign-ids.test.js +0 -146
  23. package/dist/assign-ids.test.js.map +0 -1
  24. package/dist/config.d.ts +0 -27
  25. package/dist/config.d.ts.map +0 -1
  26. package/dist/config.js.map +0 -1
  27. package/dist/e2e.test.d.ts +0 -7
  28. package/dist/e2e.test.d.ts.map +0 -1
  29. package/dist/e2e.test.js +0 -132
  30. package/dist/e2e.test.js.map +0 -1
  31. package/dist/encrypt.d.ts +0 -29
  32. package/dist/encrypt.d.ts.map +0 -1
  33. package/dist/encrypt.js.map +0 -1
  34. package/dist/encrypt.test.d.ts +0 -2
  35. package/dist/encrypt.test.d.ts.map +0 -1
  36. package/dist/encrypt.test.js +0 -100
  37. package/dist/encrypt.test.js.map +0 -1
  38. package/dist/index.d.ts +0 -12
  39. package/dist/index.d.ts.map +0 -1
  40. package/dist/index.js.map +0 -1
  41. package/dist/login.d.ts +0 -11
  42. package/dist/login.d.ts.map +0 -1
  43. package/dist/login.js.map +0 -1
  44. package/dist/scraper.d.ts +0 -40
  45. package/dist/scraper.d.ts.map +0 -1
  46. package/dist/scraper.js.map +0 -1
  47. package/dist/version.d.ts +0 -8
  48. package/dist/version.d.ts.map +0 -1
  49. package/dist/version.js +0 -8
  50. package/dist/version.js.map +0 -1
  51. package/scripts/generate-version.js +0 -64
  52. package/src/aggregation.test.ts +0 -248
  53. package/src/api.ts +0 -89
  54. package/src/assign-ids.test.ts +0 -158
  55. package/src/assign-ids.ts +0 -32
  56. package/src/config.ts +0 -79
  57. package/src/e2e.test.ts +0 -163
  58. package/src/encrypt.test.ts +0 -139
  59. package/src/encrypt.ts +0 -91
  60. package/src/index.ts +0 -180
  61. package/src/login.ts +0 -88
  62. package/src/scraper.ts +0 -317
  63. package/src/version.ts +0 -8
  64. package/tsconfig.json +0 -19
  65. package/vitest.config.ts +0 -8
package/src/config.ts DELETED
@@ -1,79 +0,0 @@
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 DELETED
@@ -1,163 +0,0 @@
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
- });
@@ -1,139 +0,0 @@
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
- });
package/src/encrypt.ts DELETED
@@ -1,91 +0,0 @@
1
- import * as crypto from 'node:crypto';
2
-
3
- const ALGORITHM = 'aes-256-gcm';
4
- const IV_LENGTH = 12;
5
- const TAG_LENGTH = 16;
6
-
7
- export interface EncryptedData {
8
- iv: Buffer;
9
- encrypted: Buffer;
10
- authTag: Buffer;
11
- }
12
-
13
- export interface EncryptedDataBase64 {
14
- iv: string;
15
- encryptedData: string;
16
- authTag: string;
17
- }
18
-
19
- /**
20
- * データを AES-256-GCM で暗号化
21
- * @param plaintext 平文データ
22
- * @param key 暗号化キー(Buffer, 32バイト)
23
- * @returns 暗号化データ(Buffer)
24
- */
25
- export const encrypt = (plaintext: string, key: Buffer): EncryptedData => {
26
- if (key.length !== 32) {
27
- throw new Error(
28
- `暗号化キーは32バイトである必要があります(現在: ${key.length}バイト)`
29
- );
30
- }
31
-
32
- // ランダムなIVを生成
33
- const iv = crypto.randomBytes(IV_LENGTH);
34
-
35
- // 暗号化
36
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv, {
37
- authTagLength: TAG_LENGTH,
38
- });
39
-
40
- const encrypted = Buffer.concat([
41
- cipher.update(plaintext, 'utf8'),
42
- cipher.final(),
43
- ]);
44
-
45
- const authTag = cipher.getAuthTag();
46
-
47
- return {
48
- iv,
49
- encrypted,
50
- authTag,
51
- };
52
- };
53
-
54
- /**
55
- * 暗号化データをBase64エンコード(API送信用)
56
- */
57
- export const encryptedToBase64 = (
58
- encrypted: EncryptedData
59
- ): EncryptedDataBase64 => {
60
- return {
61
- iv: encrypted.iv.toString('base64'),
62
- encryptedData: encrypted.encrypted.toString('base64'),
63
- authTag: encrypted.authTag.toString('base64'),
64
- };
65
- };
66
-
67
- /**
68
- * AES-256-GCM で暗号化されたデータを復号
69
- * @param encrypted 暗号化データ(Buffer)
70
- * @param key 暗号化キー(Buffer, 32バイト)
71
- * @returns 復号された平文
72
- */
73
- export const decrypt = (encrypted: EncryptedData, key: Buffer): string => {
74
- if (key.length !== 32) {
75
- throw new Error(
76
- `暗号化キーは32バイトである必要があります(現在: ${key.length}バイト)`
77
- );
78
- }
79
-
80
- const decipher = crypto.createDecipheriv(ALGORITHM, key, encrypted.iv, {
81
- authTagLength: TAG_LENGTH,
82
- });
83
- decipher.setAuthTag(encrypted.authTag);
84
-
85
- const decrypted = Buffer.concat([
86
- decipher.update(encrypted.encrypted),
87
- decipher.final(),
88
- ]);
89
-
90
- return decrypted.toString('utf8');
91
- };
package/src/index.ts DELETED
@@ -1,180 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * mf-scraper メインエントリポイント
5
- *
6
- * サブコマンド:
7
- * - mf-scraper : ポートフォリオスクレイピングを実行
8
- * - mf-scraper login : マネーフォワードにログイン
9
- * - mf-scraper --help/-h : ヘルプを表示
10
- * - mf-scraper --version/-v : バージョンを表示
11
- */
12
-
13
- import * as fs from 'node:fs';
14
- import { ApiClient } from './api.js';
15
- import { getAuthFilePath, loadConfig } from './config.js';
16
- import { encrypt } from './encrypt.js';
17
- import { login } from './login.js';
18
- import {
19
- checkLoginStatus,
20
- createContextWithSession,
21
- launchBrowser,
22
- scrapePortfolio,
23
- } from './scraper.js';
24
- import { VERSION } from './version.js';
25
-
26
- const printHelp = (): void => {
27
- console.log(`
28
- === mf-scraper ===
29
-
30
- MoneyForward からポートフォリオデータをスクレイピングして、
31
- APIサーバーに送信するバッチアプリケーション
32
-
33
- 【使用方法】
34
-
35
- mf-scraper ポートフォリオをスクレイピング
36
- mf-scraper login マネーフォワードにログイン(初回必須)
37
- mf-scraper --help このヘルプを表示
38
- mf-scraper --version バージョン情報を表示
39
-
40
- 【セットアップ手順】
41
-
42
- 1. 設定ファイルを作成
43
- ~/.config/mf-scraper/config.json
44
-
45
- 2. マネーフォワードにログイン
46
- mf-scraper login
47
- ブラウザが開くので、手動でログインしてください。
48
-
49
- 3. スクレイピングを実行
50
- mf-scraper
51
-
52
- 【クロンジョブでの定期実行】
53
-
54
- 毎日午前 3 時に実行する場合:
55
- 0 3 * * * /usr/local/bin/mf-scraper
56
-
57
- 【トラブルシューティング】
58
-
59
- セッションが期限切れの場合:
60
- mf-scraper login
61
-
62
- Playwright ブラウザをリセット:
63
- rm -rf ~/.cache/ms-playwright
64
- mf-scraper
65
- `);
66
- };
67
-
68
- const printVersion = (): void => {
69
- console.log(`mf-scraper ${VERSION}`);
70
- };
71
-
72
- const scrape = async (): Promise<void> => {
73
- console.log('=== mf-scraper ===');
74
- console.log(`実行日時: ${new Date().toISOString()}\n`);
75
-
76
- // 1. 設定ファイルの読み込み
77
- console.log('設定ファイルを読み込み中...');
78
- const config = loadConfig();
79
- console.log(`APIサーバー: ${config.apiUrl}\n`);
80
-
81
- // 2. セッションファイルの確認
82
- const authFilePath = getAuthFilePath();
83
- if (!fs.existsSync(authFilePath)) {
84
- console.error('エラー: セッションファイルが見つかりません。');
85
- console.error(
86
- '先に `mf-scraper login` を実行してログインしてください。'
87
- );
88
- process.exit(1);
89
- }
90
-
91
- // 3. APIサーバーへのログイン
92
- console.log('APIサーバーにログイン中...');
93
- const apiClient = new ApiClient({
94
- baseUrl: config.apiUrl,
95
- username: config.apiUsername,
96
- password: config.apiPassword,
97
- });
98
- await apiClient.login();
99
- console.log('APIサーバーへのログイン成功\n');
100
-
101
- // 4. ブラウザ起動とスクレイピング
102
- console.log('ブラウザを起動中...');
103
- const browser = await launchBrowser();
104
-
105
- try {
106
- const context = await createContextWithSession(browser);
107
- const page = await context.newPage();
108
-
109
- // ログイン状態確認
110
- console.log('マネーフォワードのログイン状態を確認中...');
111
- const isLoggedIn = await checkLoginStatus(page);
112
-
113
- if (!isLoggedIn) {
114
- console.error('エラー: マネーフォワードにログインしていません。');
115
- console.error('セッションが期限切れの可能性があります。');
116
- console.error('`mf-scraper login` で再ログインしてください。');
117
- process.exit(1);
118
- }
119
- console.log('ログイン状態OK\n');
120
-
121
- // スクレイピング実行
122
- console.log('ポートフォリオデータを取得中...');
123
- const portfolioData = await scrapePortfolio(page);
124
- console.log(`取得銘柄数: ${portfolioData.stocks.length}`);
125
- console.log(`取得日時: ${portfolioData.scrapedAt}\n`);
126
-
127
- // 5. データ暗号化
128
- console.log('データを暗号化中...');
129
- const dataJson = JSON.stringify(portfolioData);
130
- const encryptionKey = Buffer.from(config.encryptionKey, 'hex');
131
- const encryptedData = encrypt(dataJson, encryptionKey);
132
- console.log('暗号化完了\n');
133
-
134
- // 6. APIサーバーへ送信
135
- console.log('APIサーバーへ送信中...');
136
- await apiClient.sendEncryptedPortfolio(
137
- encryptedData,
138
- portfolioData.scrapedAt
139
- );
140
- console.log('送信完了!\n');
141
-
142
- console.log('=== 処理完了 ===');
143
- } finally {
144
- await browser.close();
145
- }
146
- };
147
-
148
- const main = async (): Promise<void> => {
149
- const args = process.argv.slice(2);
150
- const command = args[0];
151
-
152
- switch (command) {
153
- case 'login':
154
- await login();
155
- break;
156
- case '--help':
157
- case '-h':
158
- case 'help':
159
- printHelp();
160
- break;
161
- case '--version':
162
- case '-v':
163
- printVersion();
164
- break;
165
- case undefined:
166
- // デフォルト: スクレイピング実行
167
- await scrape();
168
- break;
169
- default:
170
- console.error(`エラー: 不明なコマンド '${command}'`);
171
- console.error('ヘルプを表示: mf-scraper --help');
172
- process.exit(1);
173
- }
174
- };
175
-
176
- // エラーハンドリング
177
- main().catch((error) => {
178
- console.error('致命的なエラー:', error);
179
- process.exit(1);
180
- });