1 import { IPv4, IPv6, parse, subnetMatch } from 'ipaddr.js'
2 import { CONFIG } from '../initializers/config'
3 import { UserModel } from '../models/user/user'
5 const isCidr = require('is-cidr')
7 export type SignupMode = 'direct-registration' | 'request-registration'
9 async function isSignupAllowed (options: {
10 signupMode: SignupMode
12 ip: string // For plugins
14 }): Promise<{ allowed: boolean, errorMessage?: string }> {
15 const { signupMode } = options
17 if (CONFIG.SIGNUP.ENABLED === false) {
18 return { allowed: false }
21 if (signupMode === 'direct-registration' && CONFIG.SIGNUP.REQUIRES_APPROVAL === true) {
22 return { allowed: false }
25 // No limit and signup is enabled
26 if (CONFIG.SIGNUP.LIMIT === -1) {
27 return { allowed: true }
30 const totalUsers = await UserModel.countTotal()
32 return { allowed: totalUsers < CONFIG.SIGNUP.LIMIT }
35 function isSignupAllowedForCurrentIP (ip: string) {
38 const addr = parse(ip)
39 const excludeList = [ 'blacklist' ]
42 // if there is a valid, non-empty whitelist, we exclude all unknown addresses too
43 if (CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr(cidr)).length > 0) {
44 excludeList.push('unknown')
47 if (addr.kind() === 'ipv4') {
48 const addrV4 = IPv4.parse(ip)
50 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v4(cidr))
51 .map(cidr => IPv4.parseCIDR(cidr)),
52 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v4(cidr))
53 .map(cidr => IPv4.parseCIDR(cidr))
55 matched = subnetMatch(addrV4, rangeList, 'unknown')
56 } else if (addr.kind() === 'ipv6') {
57 const addrV6 = IPv6.parse(ip)
59 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v6(cidr))
60 .map(cidr => IPv6.parseCIDR(cidr)),
61 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v6(cidr))
62 .map(cidr => IPv6.parseCIDR(cidr))
64 matched = subnetMatch(addrV6, rangeList, 'unknown')
67 return !excludeList.includes(matched)
70 // ---------------------------------------------------------------------------
74 isSignupAllowedForCurrentIP