File size: 3,262 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as fs from 'fs';
import * as path from 'path';
import pino, { Logger } from 'pino';
import { AuthStrategy, Client } from 'whatsapp-web.js';

async function isValidPath(path: string) {
  try {
    await fs.promises.access(path);
    return true;
  } catch {
    return false;
  }
}

export class LocalAuth implements AuthStrategy {
  private readonly logger: Logger;

  private client: Client;
  private readonly clientId: string;
  private readonly dataPath: string;
  private readonly rmMaxRetries: number;

  private userDataDir: string;

  setup(client: Client) {
    this.client = client;
  }

  constructor({ clientId, dataPath, rmMaxRetries, logger }) {
    const idRegex = /^[-_\w]+$/i;
    if (clientId && !idRegex.test(clientId)) {
      throw new Error(
        'Invalid clientId. Only alphanumeric characters, underscores and hyphens are allowed.',
      );
    }

    this.dataPath = path.resolve(dataPath || './.wwebjs_auth/');
    this.clientId = clientId;
    this.rmMaxRetries = rmMaxRetries ?? 4;
    this.logger = logger || pino({ name: LocalAuth.name });
  }

  async beforeBrowserInitialized() {
    // @ts-ignore
    const puppeteerOpts = this.client.options.puppeteer;
    const sessionDirName = this.clientId
      ? `session-${this.clientId}`
      : 'session';
    const dirPath = path.join(this.dataPath, sessionDirName);

    if (puppeteerOpts.userDataDir && puppeteerOpts.userDataDir !== dirPath) {
      throw new Error(
        'LocalAuth is not compatible with a user-supplied userDataDir.',
      );
    }

    fs.mkdirSync(dirPath, { recursive: true });

    // @ts-ignore
    this.client.options.puppeteer = {
      ...puppeteerOpts,
      userDataDir: dirPath,
    };

    this.userDataDir = dirPath;
    await this.removeSingletonFiles(dirPath);
  }

  /**
   * Find in direction Singleton* files and try to remove it
   * Fix for SingletonLock and other files
   */
  private async removeSingletonFiles(dir: string) {
    const files = await fs.promises.readdir(dir);
    for (const file of files) {
      if (file.startsWith('Singleton')) {
        const filePath = path.join(dir, file);
        try {
          await fs.promises.rm(filePath, {
            maxRetries: this.rmMaxRetries,
            recursive: true,
            force: true,
          });
        } catch (err) {
          this.logger.error(err, `Error deleting: ${filePath}`);
        }
      }
    }
  }

  async logout() {
    if (this.userDataDir) {
      await this.removePathSilently(this.userDataDir);
    }
  }

  private async removePathSilently(path: string) {
    const exists = await isValidPath(path);
    if (!exists) {
      return;
    }

    try {
      await fs.promises.rm(path, {
        maxRetries: this.rmMaxRetries,
        recursive: true,
        force: true,
      });
    } catch (err) {
      this.logger.error(err, `Error deleting: ${path}`);
    }
  }

  async afterBrowserInitialized() {
    return;
  }

  async onAuthenticationNeeded() {
    return {
      failed: false,
      restart: false,
      failureEventPayload: undefined,
    };
  }

  async getAuthEventPayload() {
    return;
  }

  async afterAuthReady() {
    return;
  }

  async disconnect() {
    return;
  }

  async destroy() {
    return;
  }
}