-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathaccounts.js
More file actions
317 lines (272 loc) · 8.89 KB
/
Copy pathaccounts.js
File metadata and controls
317 lines (272 loc) · 8.89 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/**
* Account management for the Identity Provider
* Handles user accounts with username/password authentication
* Email is optional - internally uses username@jss if not provided
*/
import bcrypt from 'bcrypt';
import crypto from 'crypto';
import fs from 'fs-extra';
import path from 'path';
// Internal domain for generated emails
const INTERNAL_DOMAIN = 'jss';
/**
* Get accounts directory (computed dynamically to support changing DATA_ROOT)
*/
function getAccountsDir() {
const dataRoot = process.env.DATA_ROOT || './data';
return path.join(dataRoot, '.idp', 'accounts');
}
function getUsernameIndexPath() {
return path.join(getAccountsDir(), '_username_index.json');
}
function getEmailIndexPath() {
return path.join(getAccountsDir(), '_email_index.json');
}
function getWebIdIndexPath() {
return path.join(getAccountsDir(), '_webid_index.json');
}
const SALT_ROUNDS = 10;
/**
* Initialize the accounts directory
*/
async function ensureDir() {
await fs.ensureDir(getAccountsDir());
}
/**
* Load an index file
*/
async function loadIndex(indexPath) {
try {
return await fs.readJson(indexPath);
} catch (err) {
if (err.code === 'ENOENT') return {};
throw err;
}
}
/**
* Save an index file
*/
async function saveIndex(indexPath, index) {
await fs.writeJson(indexPath, index, { spaces: 2 });
}
/**
* Create a new user account
* @param {object} options - Account options
* @param {string} options.username - Username (typically same as podName)
* @param {string} options.password - Plain text password
* @param {string} options.webId - User's WebID URI
* @param {string} options.podName - Pod name
* @param {string} [options.email] - Optional email (defaults to username@jss)
* @returns {Promise<object>} - Created account (without password)
*/
export async function createAccount({ username, password, webId, podName, email }) {
await ensureDir();
const normalizedUsername = username.toLowerCase().trim();
// Use provided email or generate internal one
const normalizedEmail = email
? email.toLowerCase().trim()
: `${normalizedUsername}@${INTERNAL_DOMAIN}`;
// Check username uniqueness
const existingByUsername = await findByUsername(normalizedUsername);
if (existingByUsername) {
throw new Error('Username already taken');
}
// Check email uniqueness (if real email provided)
if (email) {
const existingByEmail = await findByEmail(normalizedEmail);
if (existingByEmail) {
throw new Error('Email already registered');
}
}
// Check webId uniqueness
const existingByWebId = await findByWebId(webId);
if (existingByWebId) {
throw new Error('WebID already has an account');
}
// Generate account ID and hash password
const id = crypto.randomUUID();
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
const account = {
id,
username: normalizedUsername,
email: normalizedEmail,
passwordHash,
webId,
podName,
createdAt: new Date().toISOString(),
lastLogin: null,
};
// Save account
const accountPath = path.join(getAccountsDir(), `${id}.json`);
await fs.writeJson(accountPath, account, { spaces: 2 });
// Update username index
const usernameIndex = await loadIndex(getUsernameIndexPath());
usernameIndex[normalizedUsername] = id;
await saveIndex(getUsernameIndexPath(), usernameIndex);
// Update email index
const emailIndex = await loadIndex(getEmailIndexPath());
emailIndex[normalizedEmail] = id;
await saveIndex(getEmailIndexPath(), emailIndex);
// Update webId index
const webIdIndex = await loadIndex(getWebIdIndexPath());
webIdIndex[webId] = id;
await saveIndex(getWebIdIndexPath(), webIdIndex);
// Return account without password hash
const { passwordHash: _, ...safeAccount } = account;
return safeAccount;
}
/**
* Authenticate a user with username/email and password
* @param {string} identifier - Username or email
* @param {string} password - Plain text password
* @returns {Promise<object|null>} - Account if valid, null if invalid
*/
export async function authenticate(identifier, password) {
// Try to find by username first, then by email
let account = await findByUsername(identifier);
if (!account) {
account = await findByEmail(identifier);
}
if (!account) return null;
const valid = await bcrypt.compare(password, account.passwordHash);
if (!valid) return null;
// Update last login
account.lastLogin = new Date().toISOString();
const accountPath = path.join(getAccountsDir(), `${account.id}.json`);
await fs.writeJson(accountPath, account, { spaces: 2 });
// Return account without password hash
const { passwordHash: _, ...safeAccount } = account;
return safeAccount;
}
/**
* Find an account by ID
* @param {string} id - Account ID
* @returns {Promise<object|null>} - Account or null
*/
export async function findById(id) {
try {
const accountPath = path.join(getAccountsDir(), `${id}.json`);
return await fs.readJson(accountPath);
} catch (err) {
if (err.code === 'ENOENT') return null;
throw err;
}
}
/**
* Find an account by username
* @param {string} username - Username
* @returns {Promise<object|null>} - Account or null
*/
export async function findByUsername(username) {
const normalizedUsername = username.toLowerCase().trim();
const usernameIndex = await loadIndex(getUsernameIndexPath());
const id = usernameIndex[normalizedUsername];
if (!id) return null;
return findById(id);
}
/**
* Find an account by email
* @param {string} email - User email
* @returns {Promise<object|null>} - Account or null
*/
export async function findByEmail(email) {
const normalizedEmail = email.toLowerCase().trim();
const emailIndex = await loadIndex(getEmailIndexPath());
const id = emailIndex[normalizedEmail];
if (!id) return null;
return findById(id);
}
/**
* Find an account by WebID
* @param {string} webId - User WebID
* @returns {Promise<object|null>} - Account or null
*/
export async function findByWebId(webId) {
const webIdIndex = await loadIndex(getWebIdIndexPath());
const id = webIdIndex[webId];
if (!id) return null;
return findById(id);
}
/**
* Update account password
* @param {string} id - Account ID
* @param {string} newPassword - New plain text password
*/
export async function updatePassword(id, newPassword) {
const account = await findById(id);
if (!account) {
throw new Error('Account not found');
}
account.passwordHash = await bcrypt.hash(newPassword, SALT_ROUNDS);
account.passwordChangedAt = new Date().toISOString();
const accountPath = path.join(getAccountsDir(), `${id}.json`);
await fs.writeJson(accountPath, account, { spaces: 2 });
}
/**
* Delete an account
* @param {string} id - Account ID
*/
export async function deleteAccount(id) {
const account = await findById(id);
if (!account) return;
// Remove from indexes
if (account.username) {
const usernameIndex = await loadIndex(getUsernameIndexPath());
delete usernameIndex[account.username];
await saveIndex(getUsernameIndexPath(), usernameIndex);
}
const emailIndex = await loadIndex(getEmailIndexPath());
delete emailIndex[account.email];
await saveIndex(getEmailIndexPath(), emailIndex);
const webIdIndex = await loadIndex(getWebIdIndexPath());
delete webIdIndex[account.webId];
await saveIndex(getWebIdIndexPath(), webIdIndex);
// Delete account file
const accountPath = path.join(getAccountsDir(), `${id}.json`);
await fs.remove(accountPath);
}
/**
* Get account for oidc-provider's findAccount
* This is the interface oidc-provider expects
* @param {string} id - Account ID
* @returns {Promise<object|undefined>} - Account interface for oidc-provider
*/
export async function getAccountForProvider(id) {
const account = await findById(id);
if (!account) return undefined;
return {
accountId: id,
/**
* Return claims for the token
* @param {string} use - 'id_token' or 'userinfo'
* @param {string} scope - Requested scopes
* @param {object} claims - Requested claims
* @param {string[]} rejected - Rejected claims
*/
async claims(use, scope, claims, rejected) {
const result = {
sub: id,
};
// Always include webid for Solid-OIDC
result.webid = account.webId;
// Handle scope being a string, array, Set, or object with keys
const hasScope = (s) => {
if (typeof scope === 'string') return scope.includes(s);
if (Array.isArray(scope)) return scope.includes(s);
if (scope instanceof Set) return scope.has(s);
if (scope && typeof scope === 'object') return s in scope || Object.keys(scope).includes(s);
return false;
};
// Profile scope
if (hasScope('profile')) {
result.name = account.podName;
}
// Email scope
if (hasScope('email')) {
result.email = account.email;
result.email_verified = false; // We don't have email verification yet
}
return result;
},
};
}