-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathinvites.js
More file actions
181 lines (155 loc) · 4.1 KB
/
invites.js
File metadata and controls
181 lines (155 loc) · 4.1 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/**
* Invite code management for invite-only registration
* Stores codes in /data/.server/invites.json
*/
import { promises as fs } from 'fs';
import { join } from 'path';
import crypto from 'crypto';
import { getDataRoot } from '../utils/url.js';
const INVITES_DIR = '.server';
const INVITES_FILE = 'invites.json';
/**
* Get path to invites file
*/
function getInvitesPath() {
return join(getDataRoot(), INVITES_DIR, INVITES_FILE);
}
/**
* Ensure .server directory exists
*/
async function ensureServerDir() {
const dirPath = join(getDataRoot(), INVITES_DIR);
try {
await fs.mkdir(dirPath, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
/**
* Load all invites from storage
* @returns {Promise<object>} Map of code -> invite data
*/
export async function loadInvites() {
try {
const data = await fs.readFile(getInvitesPath(), 'utf-8');
return JSON.parse(data);
} catch (err) {
if (err.code === 'ENOENT') {
return {};
}
throw err;
}
}
/**
* Save invites to storage
* @param {object} invites - Map of code -> invite data
*/
async function saveInvites(invites) {
await ensureServerDir();
await fs.writeFile(getInvitesPath(), JSON.stringify(invites, null, 2));
}
/**
* Generate a random invite code
* @returns {string} 8-character uppercase alphanumeric code
*/
function generateCode() {
const bytes = crypto.randomBytes(6);
// Base64 encode and take first 8 chars, uppercase, remove ambiguous chars
return bytes.toString('base64')
.replace(/[+/=]/g, '')
.substring(0, 8)
.toUpperCase()
.replace(/O/g, '0')
.replace(/I/g, '1')
.replace(/L/g, '1');
}
/**
* Create a new invite code
* @param {object} options
* @param {number} options.maxUses - Maximum number of uses (default 1)
* @param {string} options.note - Optional note/description
* @returns {Promise<{code: string, invite: object}>}
*/
export async function createInvite({ maxUses = 1, note = '' } = {}) {
const invites = await loadInvites();
// Generate unique code
let code;
do {
code = generateCode();
} while (invites[code]);
const invite = {
created: new Date().toISOString(),
maxUses,
uses: 0,
note
};
invites[code] = invite;
await saveInvites(invites);
return { code, invite };
}
/**
* List all invite codes
* @returns {Promise<Array<{code: string, ...invite}>>}
*/
export async function listInvites() {
const invites = await loadInvites();
return Object.entries(invites).map(([code, invite]) => ({
code,
...invite
}));
}
/**
* Revoke (delete) an invite code
* @param {string} code - The invite code to revoke
* @returns {Promise<boolean>} True if code existed and was deleted
*/
export async function revokeInvite(code) {
const invites = await loadInvites();
const upperCode = code.toUpperCase();
if (!invites[upperCode]) {
return false;
}
delete invites[upperCode];
await saveInvites(invites);
return true;
}
/**
* Validate and consume an invite code
* @param {string} code - The invite code to validate
* @returns {Promise<{valid: boolean, error?: string}>}
*/
export async function validateInvite(code) {
if (!code || typeof code !== 'string') {
return { valid: false, error: 'Invite code required' };
}
const invites = await loadInvites();
const upperCode = code.toUpperCase().trim();
const invite = invites[upperCode];
if (!invite) {
return { valid: false, error: 'Invalid invite code' };
}
if (invite.uses >= invite.maxUses) {
return { valid: false, error: 'Invite code has been fully used' };
}
// Consume one use
invite.uses += 1;
await saveInvites(invites);
return { valid: true };
}
/**
* Check if an invite code is valid without consuming it
* @param {string} code - The invite code to check
* @returns {Promise<boolean>}
*/
export async function isValidInvite(code) {
if (!code || typeof code !== 'string') {
return false;
}
const invites = await loadInvites();
const upperCode = code.toUpperCase().trim();
const invite = invites[upperCode];
if (!invite) {
return false;
}
return invite.uses < invite.maxUses;
}