@meith/accounts 0.16.0

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/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@meith/accounts",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/accounts"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "files": [
14
+ "src",
15
+ "!src/**/*.test.*",
16
+ "!src/**/*.type-test.*"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "hash-wasm": "^4.12.0",
23
+ "@meith/i18n": "0.16.0"
24
+ }
25
+ }
@@ -0,0 +1,127 @@
1
+ import { ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+
4
+ import { foldIdentifier } from './case-fold'
5
+
6
+ export const BAN_FILTER_TYPES = ['username', 'email', 'ip'] as const
7
+ export type BanFilterType = (typeof BAN_FILTER_TYPES)[number]
8
+
9
+ export interface BanFilter {
10
+ readonly id: number
11
+ readonly type: BanFilterType
12
+ readonly pattern: string
13
+ }
14
+
15
+ export interface BanFilterSubject {
16
+ readonly username?: string | undefined
17
+ readonly email?: string | undefined
18
+ readonly ip?: string | undefined
19
+ }
20
+
21
+ export const BAN_FILTER_PATTERN_MAX = 200
22
+ export const BAN_FILTER_WILDCARD_MAX = 20
23
+
24
+ function preparedPattern(type: BanFilterType, pattern: string): string {
25
+ return type === 'ip' ? pattern.trim() : foldIdentifier(pattern)
26
+ }
27
+
28
+ function wildcards(pattern: string): number {
29
+ let count = 0
30
+ for (const char of pattern) {
31
+ if (char === '*' || char === '?') count += 1
32
+ }
33
+ return count
34
+ }
35
+
36
+ function tooLong(pattern: string): boolean {
37
+ return [...pattern].length > BAN_FILTER_PATTERN_MAX
38
+ }
39
+
40
+ function tooWild(pattern: string): boolean {
41
+ return wildcards(pattern) > BAN_FILTER_WILDCARD_MAX
42
+ }
43
+
44
+ function globMatches(pattern: string, value: string): boolean {
45
+ const p = [...pattern]
46
+ const v = [...value]
47
+
48
+ let pi = 0
49
+ let vi = 0
50
+ let star = -1
51
+ let resume = 0
52
+
53
+ while (vi < v.length) {
54
+ if (pi < p.length && (p[pi] === '?' || p[pi] === v[vi])) {
55
+ pi += 1
56
+ vi += 1
57
+ } else if (pi < p.length && p[pi] === '*') {
58
+ star = pi
59
+ resume = vi
60
+ pi += 1
61
+ } else if (star !== -1) {
62
+ resume += 1
63
+ pi = star + 1
64
+ vi = resume
65
+ } else {
66
+ return false
67
+ }
68
+ }
69
+
70
+ while (pi < p.length && p[pi] === '*') pi += 1
71
+
72
+ return pi === p.length
73
+ }
74
+
75
+ export function assertUsableFilter(type: BanFilterType, pattern: string): void {
76
+ const trimmed = pattern.trim()
77
+
78
+ if (trimmed === '') {
79
+ throw new ValidationError(msg('error.accounts.ban-filter-needs-pattern'))
80
+ }
81
+
82
+ if (/^\*+$/.test(trimmed)) {
83
+ throw new ValidationError(
84
+ `"${trimmed}" would match every ${type} and lock everyone out. ` +
85
+ 'Use the registration settings to close signups instead.',
86
+ )
87
+ }
88
+
89
+ if (!(BAN_FILTER_TYPES as readonly string[]).includes(type)) {
90
+ throw new ValidationError(`Unknown ban filter type: ${type}`)
91
+ }
92
+
93
+ const prepared = preparedPattern(type, pattern)
94
+
95
+ if (tooLong(prepared)) {
96
+ throw new ValidationError(
97
+ msg('error.accounts.ban-filter-pattern-long', { max: BAN_FILTER_PATTERN_MAX }),
98
+ )
99
+ }
100
+
101
+ if (tooWild(prepared)) {
102
+ throw new ValidationError(
103
+ msg('error.accounts.ban-filter-too-many-wildcards', { max: BAN_FILTER_WILDCARD_MAX }),
104
+ )
105
+ }
106
+ }
107
+
108
+ function subjectValue(type: BanFilterType, subject: BanFilterSubject): string | undefined {
109
+ if (type === 'username') return subject.username ? foldIdentifier(subject.username) : undefined
110
+ if (type === 'email') return subject.email ? foldIdentifier(subject.email) : undefined
111
+ return subject.ip?.trim()
112
+ }
113
+
114
+ export function matchBanFilter(
115
+ filters: readonly BanFilter[],
116
+ subject: BanFilterSubject,
117
+ ): BanFilter | null {
118
+ for (const filter of filters) {
119
+ const value = subjectValue(filter.type, subject)
120
+ if (value === undefined || value === '') continue
121
+
122
+ const pattern = preparedPattern(filter.type, filter.pattern)
123
+ if (tooLong(pattern) || tooWild(pattern)) continue
124
+ if (globMatches(pattern, value)) return filter
125
+ }
126
+ return null
127
+ }
@@ -0,0 +1,71 @@
1
+ import { ForbiddenError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+
4
+ import type { BanRecord, BanRepository, Clock } from './ports'
5
+
6
+ export interface BanServiceDeps {
7
+ readonly bans: BanRepository
8
+ readonly clock?: Clock
9
+ readonly bannedGroupId: number
10
+ }
11
+
12
+ export interface BanInput {
13
+ readonly userId: number
14
+ readonly bannedByUserId?: number | undefined
15
+ readonly reason?: string | undefined
16
+ readonly publicReason?: string | undefined
17
+ readonly expiresAt?: Date | undefined
18
+ }
19
+
20
+ export class BanService {
21
+ private readonly now: () => Date
22
+
23
+ constructor(private readonly deps: BanServiceDeps) {
24
+ this.now = deps.clock ?? (() => new Date())
25
+ }
26
+
27
+ async ban(input: BanInput): Promise<BanRecord> {
28
+ const now = this.now()
29
+
30
+ if (input.expiresAt !== undefined && input.expiresAt <= now) {
31
+ throw new ValidationError(msg('error.accounts.ban-expire-past'))
32
+ }
33
+
34
+ const existing = await this.deps.bans.findActive(input.userId)
35
+ if (existing) {
36
+ throw new ValidationError(msg('error.accounts.user-already-banned-lift-existing'))
37
+ }
38
+
39
+ return this.deps.bans.create({
40
+ userId: input.userId,
41
+ bannedByUserId: input.bannedByUserId ?? null,
42
+ reason: input.reason ?? null,
43
+ publicReason: input.publicReason ?? null,
44
+ expiresAt: input.expiresAt ?? null,
45
+ bannedGroupId: this.deps.bannedGroupId,
46
+ now,
47
+ })
48
+ }
49
+
50
+ async lift(userId: number): Promise<void> {
51
+ const active = await this.deps.bans.findActive(userId)
52
+ if (!active) throw new ValidationError(msg('error.accounts.user-banned'))
53
+
54
+ await this.deps.bans.lift(active.id, this.now())
55
+ }
56
+
57
+ async expireDue(limit = 200): Promise<number> {
58
+ return this.deps.bans.expireDue(this.now(), limit)
59
+ }
60
+
61
+ async assertNotBanned(userId: number): Promise<void> {
62
+ const active = await this.deps.bans.findActive(userId)
63
+ if (!active) return
64
+
65
+ throw new ForbiddenError(
66
+ active.publicReason
67
+ ? `This account is banned: ${active.publicReason}`
68
+ : 'This account is banned.',
69
+ )
70
+ }
71
+ }
@@ -0,0 +1,3 @@
1
+ export function foldIdentifier(value: string): string {
2
+ return value.trim().toLowerCase()
3
+ }
@@ -0,0 +1,17 @@
1
+ import type { SessionRecord } from './ports'
2
+
3
+ export const CREDENTIAL_PROOF_TTL_MS = 10 * 60 * 1_000
4
+
5
+ export function hasFreshCredentialProof(
6
+ session: SessionRecord,
7
+ userId: number,
8
+ now: Date,
9
+ ): boolean {
10
+ if (session.userId !== userId) return false
11
+ if (session.revokedAt !== null || session.supersededBySessionId !== null) return false
12
+ if (session.expiresAt.getTime() <= now.getTime()) return false
13
+ if (session.credentialProvedAt === null) return false
14
+
15
+ const age = now.getTime() - session.credentialProvedAt.getTime()
16
+ return age >= 0 && age <= CREDENTIAL_PROOF_TTL_MS
17
+ }
@@ -0,0 +1,53 @@
1
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
2
+
3
+ export function encodeBase64Url(bytes: Uint8Array): string {
4
+ let out = ''
5
+
6
+ for (let index = 0; index < bytes.length; index += 3) {
7
+ const a = bytes[index]!
8
+ const b = bytes[index + 1]
9
+ const c = bytes[index + 2]
10
+
11
+ out += ALPHABET[a >> 2]
12
+ out += ALPHABET[((a & 0b11) << 4) | ((b ?? 0) >> 4)]
13
+ if (b === undefined) break
14
+ out += ALPHABET[((b & 0b1111) << 2) | ((c ?? 0) >> 6)]
15
+ if (c === undefined) break
16
+ out += ALPHABET[c & 0b111111]
17
+ }
18
+
19
+ return out
20
+ }
21
+
22
+ export function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {
23
+ const clean = value.replace(/[=\s]/g, '')
24
+ const bytes: number[] = []
25
+
26
+ let buffer = 0
27
+ let bits = 0
28
+
29
+ for (const character of clean) {
30
+ const digit = ALPHABET.indexOf(character === '+' ? '-' : character === '/' ? '_' : character)
31
+ if (digit < 0) throw new Error('not base64url')
32
+
33
+ buffer = (buffer << 6) | digit
34
+ bits += 6
35
+
36
+ if (bits >= 8) {
37
+ bits -= 8
38
+ bytes.push((buffer >> bits) & 0xff)
39
+ }
40
+ }
41
+
42
+ return Uint8Array.from(bytes)
43
+ }
44
+
45
+ export function decodeBase64UrlText(value: string): string {
46
+ return new TextDecoder().decode(decodeBase64Url(value))
47
+ }
48
+
49
+ export function randomBase64Url(byteLength: number): string {
50
+ const bytes = new Uint8Array(byteLength)
51
+ crypto.getRandomValues(bytes)
52
+ return encodeBase64Url(bytes)
53
+ }
@@ -0,0 +1,127 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto'
2
+
3
+ import { bcryptVerify } from 'hash-wasm'
4
+
5
+ export const MYBB_PREFIX = 'mybb$'
6
+ export const PHPBB_PREFIX = 'phpbb$'
7
+
8
+ export interface LegacyMybbHash {
9
+ readonly salt: string
10
+ readonly hash: string
11
+ }
12
+
13
+ function md5(value: string | Buffer): Buffer {
14
+ return createHash('md5').update(value).digest()
15
+ }
16
+
17
+ function md5Hex(value: string): string {
18
+ return createHash('md5').update(value, 'utf8').digest('hex')
19
+ }
20
+
21
+ export function parseMybbHash(stored: string): LegacyMybbHash | null {
22
+ if (!stored.startsWith(MYBB_PREFIX)) return null
23
+
24
+ const rest = stored.slice(MYBB_PREFIX.length)
25
+ const separator = rest.indexOf('$')
26
+ if (separator === -1) return null
27
+
28
+ const salt = rest.slice(0, separator)
29
+ const hash = rest.slice(separator + 1)
30
+
31
+ if (salt.length === 0) return null
32
+ if (!/^[0-9a-f]{32}$/i.test(hash)) return null
33
+
34
+ return { salt, hash }
35
+ }
36
+
37
+ export function isLegacyHash(stored: string | null | undefined): boolean {
38
+ return (
39
+ typeof stored === 'string' &&
40
+ (stored.startsWith(MYBB_PREFIX) || stored.startsWith(PHPBB_PREFIX))
41
+ )
42
+ }
43
+
44
+ export function verifyMybbPassword(password: string, stored: string): boolean {
45
+ const parsed = parseMybbHash(stored)
46
+ if (parsed === null) return false
47
+
48
+ const computed = md5Hex(md5Hex(parsed.salt) + md5Hex(password))
49
+ return constantTimeEqual(computed, parsed.hash.toLowerCase())
50
+ }
51
+
52
+ const ITOA64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
53
+
54
+ function phpassEncode64(input: Buffer, count: number): string {
55
+ let output = ''
56
+ let i = 0
57
+ while (i < count) {
58
+ let value = input[i]!
59
+ i += 1
60
+ output += ITOA64[value & 0x3f]
61
+ if (i < count) value |= input[i]! << 8
62
+ output += ITOA64[(value >> 6) & 0x3f]
63
+ if (i >= count) break
64
+ i += 1
65
+ if (i < count) value |= input[i]! << 16
66
+ output += ITOA64[(value >> 12) & 0x3f]
67
+ if (i >= count) break
68
+ i += 1
69
+ output += ITOA64[(value >> 18) & 0x3f]
70
+ }
71
+ return output
72
+ }
73
+
74
+ function verifyPhpassHash(password: string, stored: string): boolean {
75
+ if (stored.length !== 34) return false
76
+
77
+ const countLog2 = ITOA64.indexOf(stored[3]!)
78
+ if (countLog2 < 7 || countLog2 > 30) return false
79
+
80
+ const salt = stored.slice(4, 12)
81
+ if (salt.length !== 8) return false
82
+
83
+ const rounds = 1 << countLog2
84
+ let hash = md5(salt + password)
85
+ for (let i = 0; i < rounds; i += 1) {
86
+ hash = md5(Buffer.concat([hash, Buffer.from(password, 'utf8')]))
87
+ }
88
+
89
+ return constantTimeEqual(stored.slice(0, 12) + phpassEncode64(hash, 16), stored)
90
+ }
91
+
92
+ export async function verifyPhpbbPassword(password: string, stored: string): Promise<boolean> {
93
+ if (!stored.startsWith(PHPBB_PREFIX)) return false
94
+ const hash = stored.slice(PHPBB_PREFIX.length)
95
+
96
+ if (/^\$2[abxy]\$/.test(hash)) {
97
+ try {
98
+ return await bcryptVerify({ password, hash: `$2a$${hash.slice(4)}` })
99
+ } catch {
100
+ return false
101
+ }
102
+ }
103
+
104
+ if (hash.startsWith('$H$') || hash.startsWith('$P$')) {
105
+ return verifyPhpassHash(password, hash)
106
+ }
107
+
108
+ if (/^[0-9a-f]{32}$/i.test(hash)) {
109
+ return constantTimeEqual(md5Hex(password), hash.toLowerCase())
110
+ }
111
+
112
+ return false
113
+ }
114
+
115
+ export function verifyLegacyPassword(password: string, stored: string): Promise<boolean> {
116
+ if (stored.startsWith(MYBB_PREFIX)) {
117
+ return Promise.resolve(verifyMybbPassword(password, stored))
118
+ }
119
+ return verifyPhpbbPassword(password, stored)
120
+ }
121
+
122
+ function constantTimeEqual(a: string, b: string): boolean {
123
+ const left = Buffer.from(a, 'utf8')
124
+ const right = Buffer.from(b, 'utf8')
125
+ if (left.length !== right.length) return false
126
+ return timingSafeEqual(left, right)
127
+ }
@@ -0,0 +1,92 @@
1
+ import { argon2id, argon2Verify } from 'hash-wasm'
2
+
3
+ import { isLegacyHash, verifyLegacyPassword } from './legacy'
4
+
5
+ export interface PasswordPolicy {
6
+ readonly memorySize: number
7
+ readonly iterations: number
8
+ readonly parallelism: number
9
+ }
10
+
11
+ export const CURRENT_PASSWORD_POLICY: PasswordPolicy = {
12
+ memorySize: 19456,
13
+ iterations: 2,
14
+ parallelism: 1,
15
+ }
16
+
17
+ const SALT_BYTES = 16
18
+ const HASH_BYTES = 32
19
+
20
+ export async function hashPassword(
21
+ password: string,
22
+ policy: PasswordPolicy = CURRENT_PASSWORD_POLICY,
23
+ ): Promise<string> {
24
+ if (password.length === 0) {
25
+ throw new Error('Refusing to hash an empty password.')
26
+ }
27
+ const salt = randomBytes(SALT_BYTES)
28
+ return argon2id({
29
+ password,
30
+ salt,
31
+ memorySize: policy.memorySize,
32
+ iterations: policy.iterations,
33
+ parallelism: policy.parallelism,
34
+ hashLength: HASH_BYTES,
35
+ outputType: 'encoded',
36
+ })
37
+ }
38
+
39
+ export async function verifyPassword(
40
+ password: string,
41
+ encodedHash: string | null | undefined,
42
+ ): Promise<boolean> {
43
+ if (!encodedHash) return false
44
+
45
+ if (isLegacyHash(encodedHash)) return verifyLegacyPassword(password, encodedHash)
46
+
47
+ try {
48
+ return await argon2Verify({ password, hash: encodedHash })
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ export interface Argon2Params {
55
+ readonly algo: 'argon2id' | 'argon2i' | 'argon2d'
56
+ readonly memorySize: number
57
+ readonly iterations: number
58
+ readonly parallelism: number
59
+ }
60
+
61
+ const PHC = /^\$(argon2id|argon2i|argon2d)\$v=19\$m=(\d+),t=(\d+),p=(\d+)\$/
62
+
63
+ export function parseArgon2Params(encodedHash: string): Argon2Params | null {
64
+ const m = PHC.exec(encodedHash)
65
+ if (!m) return null
66
+ return {
67
+ algo: m[1] as Argon2Params['algo'],
68
+ memorySize: Number(m[2]),
69
+ iterations: Number(m[3]),
70
+ parallelism: Number(m[4]),
71
+ }
72
+ }
73
+
74
+ export function needsRehash(
75
+ encodedHash: string,
76
+ policy: PasswordPolicy = CURRENT_PASSWORD_POLICY,
77
+ ): boolean {
78
+ const p = parseArgon2Params(encodedHash)
79
+ if (p === null) return true
80
+ if (p.algo !== 'argon2id') return true
81
+ return (
82
+ p.memorySize < policy.memorySize ||
83
+ p.iterations < policy.iterations ||
84
+ p.parallelism < policy.parallelism
85
+ )
86
+ }
87
+
88
+ function randomBytes(n: number): Uint8Array {
89
+ const bytes = new Uint8Array(n)
90
+ crypto.getRandomValues(bytes)
91
+ return bytes
92
+ }