1 import { UserModel } from '../models/account/user'
2 import * as ipaddr from 'ipaddr.js'
3 import { CONFIG } from '../initializers/config'
5 const isCidr = require('is-cidr')
7 async function isSignupAllowed (): Promise<{ allowed: boolean, errorMessage?: string }> {
8 if (CONFIG.SIGNUP.ENABLED === false) {
9 return { allowed: false }
12 // No limit and signup is enabled
13 if (CONFIG.SIGNUP.LIMIT === -1) {
14 return { allowed: true }
17 const totalUsers = await UserModel.countTotal()
19 return { allowed: totalUsers < CONFIG.SIGNUP.LIMIT }
22 function isSignupAllowedForCurrentIP (ip: string) {
23 const addr = ipaddr.parse(ip)
24 let excludeList = [ 'blacklist' ]
27 // if there is a valid, non-empty whitelist, we exclude all unknown adresses too
28 if (CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr(cidr)).length > 0) {
29 excludeList.push('unknown')
32 if (addr.kind() === 'ipv4') {
33 const addrV4 = ipaddr.IPv4.parse(ip)
35 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v4(cidr))
36 .map(cidr => ipaddr.IPv4.parseCIDR(cidr)),
37 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v4(cidr))
38 .map(cidr => ipaddr.IPv4.parseCIDR(cidr))
40 matched = ipaddr.subnetMatch(addrV4, rangeList, 'unknown')
41 } else if (addr.kind() === 'ipv6') {
42 const addrV6 = ipaddr.IPv6.parse(ip)
44 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v6(cidr))
45 .map(cidr => ipaddr.IPv6.parseCIDR(cidr)),
46 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v6(cidr))
47 .map(cidr => ipaddr.IPv6.parseCIDR(cidr))
49 matched = ipaddr.subnetMatch(addrV6, rangeList, 'unknown')
52 return !excludeList.includes(matched)
55 // ---------------------------------------------------------------------------
59 isSignupAllowedForCurrentIP