@vue-skuilder/express 0.2.25 → 0.2.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.development +4 -0
- package/dist/couchdb/identityAssertion.d.ts +49 -0
- package/dist/couchdb/identityAssertion.d.ts.map +1 -0
- package/dist/couchdb/identityAssertion.js +90 -0
- package/dist/couchdb/identityAssertion.js.map +1 -0
- package/dist/couchdb/sessionCookie.d.ts +28 -0
- package/dist/couchdb/sessionCookie.d.ts.map +1 -0
- package/dist/couchdb/sessionCookie.js +101 -0
- package/dist/couchdb/sessionCookie.js.map +1 -0
- package/dist/couchdb/userDesignDocs.d.ts +3 -1
- package/dist/couchdb/userDesignDocs.d.ts.map +1 -1
- package/dist/couchdb/userDesignDocs.js +7 -5
- package/dist/couchdb/userDesignDocs.js.map +1 -1
- package/dist/couchdb/userLookup.d.ts +6 -0
- package/dist/couchdb/userLookup.d.ts.map +1 -1
- package/dist/couchdb/userLookup.js +29 -2
- package/dist/couchdb/userLookup.js.map +1 -1
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/auth.js +124 -14
- package/dist/routes/auth.js.map +1 -1
- package/dist/utils/email.d.ts +11 -0
- package/dist/utils/email.d.ts.map +1 -0
- package/dist/utils/email.js +13 -0
- package/dist/utils/email.js.map +1 -0
- package/package.json +4 -4
- package/src/couchdb/identityAssertion.ts +163 -0
- package/src/couchdb/sessionCookie.ts +135 -0
- package/src/couchdb/userDesignDocs.ts +7 -5
- package/src/couchdb/userLookup.ts +29 -2
- package/src/routes/auth.ts +130 -14
- package/src/utils/email.ts +12 -0
|
@@ -3,6 +3,7 @@ import type { CouchDbUserDoc } from '@vue-skuilder/db';
|
|
|
3
3
|
import { getCouchDB } from './index.js';
|
|
4
4
|
import logger from '../logger.js';
|
|
5
5
|
import { isNanoError } from '../utils/types.js';
|
|
6
|
+
import { normalizeEmail } from '../utils/email.js';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* User lookup utilities for authentication flows.
|
|
@@ -79,7 +80,7 @@ export async function findUserByEmail(
|
|
|
79
80
|
const usersDB = getUsersDB();
|
|
80
81
|
|
|
81
82
|
const result = await usersDB.view('users', 'by_email', {
|
|
82
|
-
key: email,
|
|
83
|
+
key: normalizeEmail(email),
|
|
83
84
|
include_docs: true,
|
|
84
85
|
limit: 1,
|
|
85
86
|
});
|
|
@@ -99,6 +100,32 @@ export async function findUserByEmail(
|
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Usernames of every account (verified or not) that has this email on its
|
|
105
|
+
* _users doc, capped at `limit`. Used by login resolution, where the password
|
|
106
|
+
* check — not verification — is what proves ownership.
|
|
107
|
+
*/
|
|
108
|
+
export async function findUsernamesByEmail(email: string, limit = 3): Promise<string[]> {
|
|
109
|
+
try {
|
|
110
|
+
const usersDB = getUsersDB();
|
|
111
|
+
const result = await usersDB.view('users', 'by_email', {
|
|
112
|
+
key: normalizeEmail(email),
|
|
113
|
+
include_docs: true,
|
|
114
|
+
limit,
|
|
115
|
+
});
|
|
116
|
+
return result.rows
|
|
117
|
+
.map((row) => (row.doc as CouchDbUserDoc | undefined)?.name)
|
|
118
|
+
.filter((name): name is string => typeof name === 'string');
|
|
119
|
+
} catch (error: unknown) {
|
|
120
|
+
if (isNanoError(error) && error.statusCode === 404) {
|
|
121
|
+
logger.warn('Design doc or view not found for email lookup');
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
logger.error(`Error finding usernames by email ${email}:`, error);
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
102
129
|
/**
|
|
103
130
|
* Find a *verified* user by email using the by_verified_email view.
|
|
104
131
|
* Used to enforce the "at most one verified account per email" invariant.
|
|
@@ -112,7 +139,7 @@ export async function findVerifiedUserByEmail(
|
|
|
112
139
|
const usersDB = getUsersDB();
|
|
113
140
|
|
|
114
141
|
const result = await usersDB.view('users', 'by_verified_email', {
|
|
115
|
-
key: email,
|
|
142
|
+
key: normalizeEmail(email),
|
|
116
143
|
include_docs: true,
|
|
117
144
|
reduce: false,
|
|
118
145
|
limit: 1,
|
package/src/routes/auth.ts
CHANGED
|
@@ -6,11 +6,16 @@ import {
|
|
|
6
6
|
findUserByToken,
|
|
7
7
|
findUserByEmail,
|
|
8
8
|
findVerifiedUserByEmail,
|
|
9
|
+
findUsernamesByEmail,
|
|
9
10
|
updateUserDoc,
|
|
10
11
|
} from '../couchdb/userLookup.js';
|
|
11
12
|
import { generateSecureToken, getTokenExpiry, isTokenExpired } from '../utils/tokens.js';
|
|
12
13
|
import { sendVerificationEmail, sendPasswordResetEmail } from '../services/email.js';
|
|
13
14
|
import { verifyCredentials } from '../couchdb/authentication.js';
|
|
15
|
+
import { normalizeEmail } from '../utils/email.js';
|
|
16
|
+
import { resolveAssertedIdentity } from '../couchdb/identityAssertion.js';
|
|
17
|
+
import { mintAuthSessionCookie } from '../couchdb/sessionCookie.js';
|
|
18
|
+
import crypto from 'crypto';
|
|
14
19
|
import logger from '../logger.js';
|
|
15
20
|
|
|
16
21
|
interface CouchSession {
|
|
@@ -72,7 +77,7 @@ router.post('/send-verification', (req: Request, res: Response) => {
|
|
|
72
77
|
// Use the provided email if present; otherwise fall back to the address
|
|
73
78
|
// already on the _users doc — the single source of truth. (CONFIG.email was
|
|
74
79
|
// a second, divergent copy; it has been retired.)
|
|
75
|
-
let email = providedEmail;
|
|
80
|
+
let email = typeof providedEmail === 'string' ? normalizeEmail(providedEmail) : providedEmail;
|
|
76
81
|
if (!email) {
|
|
77
82
|
email = userDoc.email;
|
|
78
83
|
if (!email) {
|
|
@@ -101,7 +106,7 @@ router.post('/send-verification', (req: Request, res: Response) => {
|
|
|
101
106
|
// When the address came from a lookup rather than the request body, keep
|
|
102
107
|
// the original fill-if-absent behaviour.
|
|
103
108
|
if (providedEmail) {
|
|
104
|
-
userDoc.email =
|
|
109
|
+
userDoc.email = email as string;
|
|
105
110
|
} else if (email && !userDoc.email) {
|
|
106
111
|
userDoc.email = email as string;
|
|
107
112
|
}
|
|
@@ -267,16 +272,44 @@ router.post('/resolve-login', (req: Request, res: Response) => {
|
|
|
267
272
|
.json({ ok: false, error: 'Identifier and password required' });
|
|
268
273
|
}
|
|
269
274
|
|
|
270
|
-
// Resolve email → username; a username passes through as-is.
|
|
271
|
-
//
|
|
272
|
-
//
|
|
273
|
-
|
|
275
|
+
// Resolve email → username; a username passes through as-is.
|
|
276
|
+
//
|
|
277
|
+
// For an email identifier, candidates are tried in order until one
|
|
278
|
+
// authenticates:
|
|
279
|
+
// 1. the account that has *verified* this email (it may have a legacy
|
|
280
|
+
// non-email username),
|
|
281
|
+
// 2. the normalized email itself — accounts created with the email as
|
|
282
|
+
// their username (stored normalized), which may be unverified,
|
|
283
|
+
// 3. accounts with this email saved but *unverified* (legacy
|
|
284
|
+
// username + email signups that never clicked the link). Safe: the
|
|
285
|
+
// password check, not verification, is what proves ownership here,
|
|
286
|
+
// 4. the raw identifier, for any legacy username containing '@' that
|
|
287
|
+
// predates normalization.
|
|
288
|
+
// A verified-email owner and an email-named account can coexist (the
|
|
289
|
+
// latter is blocked from verifying — see /verify), so falling through
|
|
290
|
+
// past (1) is required. Every failure returns the same 401, but not in
|
|
291
|
+
// uniform time: the candidate count, and whether each candidate is a real
|
|
292
|
+
// account (couch hashes for real users, fast-fails unknown ones), vary.
|
|
293
|
+
// Same class of timing signal the single-candidate version had.
|
|
294
|
+
const candidates: string[] = [];
|
|
274
295
|
if (typeof identifier === 'string' && identifier.includes('@')) {
|
|
275
|
-
const
|
|
276
|
-
|
|
296
|
+
const normalized = normalizeEmail(identifier);
|
|
297
|
+
const verifiedUser = await findVerifiedUserByEmail(normalized);
|
|
298
|
+
if (verifiedUser?.name) candidates.push(verifiedUser.name);
|
|
299
|
+
candidates.push(normalized);
|
|
300
|
+
candidates.push(...(await findUsernamesByEmail(normalized)));
|
|
301
|
+
}
|
|
302
|
+
candidates.push(identifier);
|
|
303
|
+
|
|
304
|
+
let username: string | null = null;
|
|
305
|
+
for (const candidate of new Set(candidates)) {
|
|
306
|
+
if (await verifyCredentials(candidate, password)) {
|
|
307
|
+
username = candidate;
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
277
310
|
}
|
|
278
311
|
|
|
279
|
-
if (!
|
|
312
|
+
if (!username) {
|
|
280
313
|
return res.status(401).json({ ok: false, error: 'Invalid credentials' });
|
|
281
314
|
}
|
|
282
315
|
|
|
@@ -299,14 +332,23 @@ router.post('/resolve-login', (req: Request, res: Response) => {
|
|
|
299
332
|
router.post('/request-reset', (req: Request, res: Response) => {
|
|
300
333
|
void (async () => {
|
|
301
334
|
try {
|
|
302
|
-
const { email, origin } = req.body;
|
|
335
|
+
const { email: rawEmail, origin } = req.body;
|
|
303
336
|
|
|
304
|
-
if (!
|
|
337
|
+
if (!rawEmail || typeof rawEmail !== 'string') {
|
|
305
338
|
return res.status(400).json({ ok: false, error: 'Email required' });
|
|
306
339
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
340
|
+
const email = normalizeEmail(rawEmail);
|
|
341
|
+
|
|
342
|
+
// Find user by email (using design doc view). Fallback: an account whose
|
|
343
|
+
// *username* is this email but which never got an email persisted (the
|
|
344
|
+
// address is only written by /send-verification, which is best-effort at
|
|
345
|
+
// signup). Only when the doc has no email at all — if the owner has since
|
|
346
|
+
// set a different address, the username-address is not theirs to trust.
|
|
347
|
+
let userDoc = await findUserByEmail(email);
|
|
348
|
+
if (!userDoc) {
|
|
349
|
+
const byName = await findUserByUsername(email);
|
|
350
|
+
if (byName && !byName.email) userDoc = byName;
|
|
351
|
+
}
|
|
310
352
|
if (!userDoc) {
|
|
311
353
|
// Don't reveal whether email exists (security best practice)
|
|
312
354
|
logger.warn(`Password reset requested for non-existent email: ${email}`);
|
|
@@ -565,4 +607,78 @@ router.post('/permissions', (req: Request, res: Response) => {
|
|
|
565
607
|
})();
|
|
566
608
|
});
|
|
567
609
|
|
|
610
|
+
/**
|
|
611
|
+
* POST /auth/assert-identity
|
|
612
|
+
* Server-to-server: a trusted caller (e.g. a backend that has verified a
|
|
613
|
+
* Google ID token) asserts that a person controls an email address. Resolves,
|
|
614
|
+
* links or creates the account under the rules in couchdb/identityAssertion.ts
|
|
615
|
+
* and returns a freshly minted CouchDB session cookie for it, which the caller
|
|
616
|
+
* forwards to the browser.
|
|
617
|
+
*
|
|
618
|
+
* Disabled (404) unless IDENTITY_ASSERTION_SECRET is set. Authenticated by
|
|
619
|
+
* `Authorization: Bearer <IDENTITY_ASSERTION_SECRET>`; this route mints
|
|
620
|
+
* sessions for arbitrary accounts, so the secret is as sensitive as the
|
|
621
|
+
* CouchDB admin password.
|
|
622
|
+
*
|
|
623
|
+
* Body params:
|
|
624
|
+
* - email: string (required)
|
|
625
|
+
* - provider: string (required) - e.g. 'google'
|
|
626
|
+
* - authoritative: boolean (required) - whether the provider is
|
|
627
|
+
* authoritative for this address; linking an existing account requires it
|
|
628
|
+
*
|
|
629
|
+
* Responses:
|
|
630
|
+
* - 200 { ok, username, outcome: 'existing'|'linked'|'created', cookie: { name, value, maxAge } }
|
|
631
|
+
* - 403 { ok: false, code } - privileged_account | link_requires_authoritative
|
|
632
|
+
* - 409 { ok: false, code: 'username_conflict' }
|
|
633
|
+
*/
|
|
634
|
+
router.post('/assert-identity', (req: Request, res: Response) => {
|
|
635
|
+
void (async () => {
|
|
636
|
+
const secret = process.env.IDENTITY_ASSERTION_SECRET;
|
|
637
|
+
if (!secret) {
|
|
638
|
+
return res.status(404).json({ ok: false, error: 'Not found' });
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// Compare digests, not the raw header: equal-length, and an early-exit
|
|
642
|
+
// mismatch reveals nothing about the secret itself.
|
|
643
|
+
const digest = (v: string) => crypto.createHash('sha256').update(v).digest('hex');
|
|
644
|
+
if (digest(req.headers.authorization ?? '') !== digest(`Bearer ${secret}`)) {
|
|
645
|
+
logger.warn('Unauthorized assert-identity request');
|
|
646
|
+
return res.status(401).json({ ok: false, error: 'Unauthorized' });
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const { email, provider, authoritative } = req.body ?? {};
|
|
650
|
+
if (
|
|
651
|
+
typeof email !== 'string' ||
|
|
652
|
+
!email.includes('@') ||
|
|
653
|
+
typeof provider !== 'string' ||
|
|
654
|
+
!provider ||
|
|
655
|
+
typeof authoritative !== 'boolean'
|
|
656
|
+
) {
|
|
657
|
+
return res.status(400).json({
|
|
658
|
+
ok: false,
|
|
659
|
+
error: 'Required: email (string), provider (string), authoritative (boolean)',
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
try {
|
|
664
|
+
const resolution = await resolveAssertedIdentity({ email, provider, authoritative });
|
|
665
|
+
if (!resolution.ok) {
|
|
666
|
+
const status = resolution.code === 'username_conflict' ? 409 : 403;
|
|
667
|
+
return res.status(status).json({ ok: false, code: resolution.code });
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const cookie = await mintAuthSessionCookie(resolution.username);
|
|
671
|
+
res.json({
|
|
672
|
+
ok: true,
|
|
673
|
+
username: resolution.username,
|
|
674
|
+
outcome: resolution.outcome,
|
|
675
|
+
cookie,
|
|
676
|
+
});
|
|
677
|
+
} catch (error) {
|
|
678
|
+
logger.error('Error asserting identity:', error);
|
|
679
|
+
res.status(500).json({ ok: false, error: 'Failed to assert identity' });
|
|
680
|
+
}
|
|
681
|
+
})();
|
|
682
|
+
});
|
|
683
|
+
|
|
568
684
|
export default router;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical form of an email address for storage and lookup: trimmed and
|
|
3
|
+
* lowercased.
|
|
4
|
+
*
|
|
5
|
+
* RFC 5321 technically allows a case-sensitive local part, but no mainstream
|
|
6
|
+
* provider treats it that way, and case drift ("Foo@x.com" vs "foo@x.com")
|
|
7
|
+
* otherwise causes missed lookups and duplicate accounts. Deliberately does
|
|
8
|
+
* NOT strip dots or +tags — those are distinct addresses at many providers.
|
|
9
|
+
*/
|
|
10
|
+
export function normalizeEmail(email: string): string {
|
|
11
|
+
return email.trim().toLowerCase();
|
|
12
|
+
}
|