Skip to content

Commit 24285e7

Browse files
committed
server: add fallback if it wasn't possible to read tokens file
1 parent 814bd86 commit 24285e7

File tree

1 file changed

+26
-16
lines changed

1 file changed

+26
-16
lines changed

server/index.js

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,27 @@ const { EventEmitter } = require("events");
3232

3333
async _loadTokens() {
3434
try {
35-
const data = await fs.readFile(
36-
this.config.tokens_store_path,
37-
"utf-8"
38-
);
39-
this.config.state.tokensList = JSON.parse(data) || {};
40-
this._cleanExpiredTokens();
35+
await fs.mkdir(".data", { recursive: true });
36+
37+
try {
38+
await fs.access(this.config.tokens_store_path);
39+
const data = await fs.readFile(
40+
this.config.tokens_store_path,
41+
"utf-8"
42+
);
43+
this.config.state.tokensList = JSON.parse(data) || {};
44+
this._cleanExpiredTokens();
45+
} catch {
46+
console.log(
47+
`[cap] Tokens file not found, creating a new empty one`
48+
);
49+
await fs.writeFile(this.config.tokens_store_path, "{}", "utf-8");
50+
this.config.state.tokensList = {};
51+
}
4152
} catch (error) {
53+
console.log(
54+
`[cap] Couldn't load or write tokens file, using empty state`
55+
);
4256
this.config.state.tokensList = {};
4357
}
4458
}
@@ -92,7 +106,9 @@ const { EventEmitter } = require("events");
92106
.toString("hex")
93107
.slice(0, (conf && conf.challengeSize) || 32),
94108
crypto
95-
.randomBytes(Math.ceil(((conf && conf.challengeDifficulty) || 4) / 2))
109+
.randomBytes(
110+
Math.ceil(((conf && conf.challengeDifficulty) || 4) / 2)
111+
)
96112
.toString("hex")
97113
.slice(0, (conf && conf.challengeDifficulty) || 4),
98114
]
@@ -143,10 +159,7 @@ const { EventEmitter } = require("events");
143159

144160
const vertoken = crypto.randomBytes(15).toString("hex");
145161
const expires = Date.now() + 20 * 60 * 1000;
146-
const hash = crypto
147-
.createHash("sha256")
148-
.update(vertoken)
149-
.digest("hex");
162+
const hash = crypto.createHash("sha256").update(vertoken).digest("hex");
150163
const id = crypto.randomBytes(8).toString("hex");
151164

152165
this.config.state.tokensList[`${id}:${hash}`] = expires;
@@ -164,10 +177,7 @@ const { EventEmitter } = require("events");
164177
this._cleanExpiredTokens();
165178

166179
const [id, vertoken] = token.split(":");
167-
const hash = crypto
168-
.createHash("sha256")
169-
.update(vertoken)
170-
.digest("hex");
180+
const hash = crypto.createHash("sha256").update(vertoken).digest("hex");
171181
const key = `${id}:${hash}`;
172182

173183
if (this.config.state.tokensList[key]) {
@@ -196,4 +206,4 @@ const { EventEmitter } = require("events");
196206
module.exports = factory(require, exports, module);
197207
}
198208
: define
199-
);
209+
);

0 commit comments

Comments
 (0)