(userOptions)
| 7 | import { createMiddleware } from "hono/factory"; |
| 8 | |
| 9 | export const capCheckpoint = (userOptions) => { |
| 10 | const options = { |
| 11 | token_validity_hours: 32, |
| 12 | tokens_store_path: ".data/middlewareTokens.json", |
| 13 | token_size: 16, // token size in bytes |
| 14 | verification_template_path: join( |
| 15 | dirname(fileURLToPath(import.meta.url)), |
| 16 | "./index.html", |
| 17 | ), |
| 18 | |
| 19 | ...userOptions, |
| 20 | }; |
| 21 | |
| 22 | const cap = new Cap({ |
| 23 | noFSState: true, |
| 24 | }); |
| 25 | |
| 26 | let tokensCache = null; |
| 27 | let cacheLastModified = 0; |
| 28 | |
| 29 | fs.mkdir(dirname(options.tokens_store_path), { recursive: true }); |
| 30 | |
| 31 | async function loadCustomTokens() { |
| 32 | try { |
| 33 | const stats = await fs.stat(options.tokens_store_path); |
| 34 | |
| 35 | if (tokensCache && stats.mtime.getTime() <= cacheLastModified) { |
| 36 | return tokensCache; |
| 37 | } |
| 38 | |
| 39 | tokensCache = JSON.parse( |
| 40 | await fs.readFile(options.tokens_store_path, "utf-8"), |
| 41 | ); |
| 42 | cacheLastModified = Date.now(); |
| 43 | |
| 44 | return tokensCache; |
| 45 | } catch { |
| 46 | tokensCache = {}; |
| 47 | cacheLastModified = Date.now(); |
| 48 | |
| 49 | return tokensCache; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | async function saveCustomTokens(tokens) { |
| 54 | await fs.writeFile(options.tokens_store_path, JSON.stringify(tokens)); |
| 55 | tokensCache = tokens; |
| 56 | cacheLastModified = Date.now(); |
| 57 | } |
| 58 | |
| 59 | async function storeCustomToken(token) { |
| 60 | const tokens = await loadCustomTokens(); |
| 61 | |
| 62 | tokens[token] = Date.now() + options.token_validity_hours * 60 * 60 * 1000; |
| 63 | await saveCustomTokens(tokens); |
| 64 | return token; |
| 65 | } |
| 66 |
no test coverage detected