@tylix/auth 1.4.0 → 2.0.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.
Files changed (65) hide show
  1. package/README.md +284 -14
  2. package/package.json +95 -9
  3. package/src/client/client.d.ts +14 -0
  4. package/src/client/client.js +83 -0
  5. package/src/cookies/authCookies.d.ts +8 -6
  6. package/src/cookies/authCookies.js +43 -28
  7. package/src/core/crypto.js +143 -0
  8. package/src/core/keys.js +83 -0
  9. package/src/core/seal.js +43 -0
  10. package/src/generators/AuthGenerator.d.ts +9 -3
  11. package/src/generators/AuthGenerator.js +16 -4
  12. package/src/generators/templates/auth-controller-ts.tyx +401 -98
  13. package/src/generators/templates/auth-controller.tyx +384 -96
  14. package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
  15. package/src/generators/templates/auth-session-migration.tyx +32 -0
  16. package/src/generators/templates/auth-session-model-ts.tyx +53 -0
  17. package/src/generators/templates/auth-session-model.tyx +34 -0
  18. package/src/generators/templates/auth-validator-ts.tyx +17 -0
  19. package/src/generators/templates/auth-validator.tyx +17 -0
  20. package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
  21. package/src/generators/templates/oauth-account-migration.tyx +27 -0
  22. package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
  23. package/src/generators/templates/oauth-account-model.tyx +45 -0
  24. package/src/generators/templates/password-reset-model-ts.tyx +26 -4
  25. package/src/generators/templates/password-reset-model.tyx +26 -4
  26. package/src/generators/templates/reset-password-view.html +30 -3
  27. package/src/generators/templates/verify-email-view.html +30 -3
  28. package/src/http/cookies.js +91 -0
  29. package/src/http/origin.js +68 -0
  30. package/src/http/request.js +179 -0
  31. package/src/index.d.ts +9 -1
  32. package/src/index.js +5 -0
  33. package/src/integrations/h3.d.ts +6 -0
  34. package/src/integrations/h3.js +70 -0
  35. package/src/integrations/hono.d.ts +6 -0
  36. package/src/integrations/hono.js +36 -0
  37. package/src/integrations/next.d.ts +16 -0
  38. package/src/integrations/next.js +36 -0
  39. package/src/integrations/node.d.ts +7 -0
  40. package/src/integrations/node.js +87 -0
  41. package/src/integrations/routes.js +92 -0
  42. package/src/integrations/sveltekit.d.ts +5 -0
  43. package/src/integrations/sveltekit.js +52 -0
  44. package/src/integrations/web.js +69 -0
  45. package/src/mfa/totp.js +150 -0
  46. package/src/oauth/oauth.js +142 -0
  47. package/src/oauth/providers.js +112 -0
  48. package/src/password/hashPassword.d.ts +5 -1
  49. package/src/password/hashPassword.js +96 -30
  50. package/src/password/index.d.ts +2 -0
  51. package/src/password/index.js +2 -0
  52. package/src/password/policy.js +108 -0
  53. package/src/rateLimiter/loginRateLimiter.js +16 -6
  54. package/src/ratelimit/limiter.js +129 -0
  55. package/src/session/adapters/keyValue.js +87 -0
  56. package/src/session/adapters/memory.js +38 -0
  57. package/src/session/adapters/model.js +97 -0
  58. package/src/session/adapters/prisma.js +67 -0
  59. package/src/session/adapters/sql.js +128 -0
  60. package/src/session/createAuth.js +420 -0
  61. package/src/token/jwt.js +144 -0
  62. package/src/token/signToken.js +41 -22
  63. package/src/tylix/accessTokens.js +61 -0
  64. package/src/web.d.ts +359 -0
  65. package/src/web.js +47 -0
@@ -0,0 +1,97 @@
1
+ // Sessions through a Tylix ORM model (or anything with the same static
2
+ // API: create, query().where().first()/get(), updateWhere, delete).
3
+ // The table is created by the "create_auth_sessions_table" migration
4
+ // that `tylix make:auth` writes. Times are ISO strings in the table.
5
+ //
6
+ // Rotation is a compare-and-swap through updateWhere().
7
+
8
+ const TIME_FIELDS = { rotatedAt: 'rotated_at', lastUsedAt: 'last_used_at', expiresAt: 'expires_at', idleExpiresAt: 'idle_expires_at' }
9
+ const OTHER_FIELDS = { tokenHash: 'token_hash', prevTokenHash: 'prev_token_hash', ip: 'ip', userAgent: 'user_agent' }
10
+
11
+ const iso = (ms) => (ms == null ? null : new Date(ms).toISOString())
12
+ const ms = (value) => (value == null || value === '' ? null : new Date(value).getTime())
13
+
14
+ export function modelAdapter(Model) {
15
+ if (!Model || typeof Model.updateWhere !== 'function' || typeof Model.query !== 'function') {
16
+ throw new TypeError('modelAdapter needs a Tylix ORM model class (with query() and updateWhere()).')
17
+ }
18
+
19
+ const fromRow = (row) =>
20
+ row && {
21
+ id: row.sid,
22
+ userId: row.user_id,
23
+ tokenHash: row.token_hash,
24
+ prevTokenHash: row.prev_token_hash ?? null,
25
+ rotatedAt: ms(row.rotated_at),
26
+ createdAt: ms(row.created_at) ?? Date.now(),
27
+ lastUsedAt: ms(row.last_used_at),
28
+ expiresAt: ms(row.expires_at),
29
+ idleExpiresAt: ms(row.idle_expires_at),
30
+ persistent: row.persistent === true || row.persistent === 1 || row.persistent === '1' || row.persistent === 'true',
31
+ ip: row.ip ?? null,
32
+ userAgent: row.user_agent ?? null,
33
+ data: row.data == null || row.data === '' ? null : typeof row.data === 'string' ? JSON.parse(row.data) : row.data,
34
+ _rowId: row.id,
35
+ }
36
+
37
+ const strip = (record) => {
38
+ if (!record) return null
39
+ const { _rowId, ...rest } = record
40
+ return rest
41
+ }
42
+
43
+ async function findRow(id) {
44
+ if (typeof id !== 'string' || id.length === 0) return null
45
+ return Model.query().where('sid', id).first()
46
+ }
47
+
48
+ return {
49
+ async create(record) {
50
+ await Model.create({
51
+ sid: record.id,
52
+ user_id: record.userId,
53
+ token_hash: record.tokenHash,
54
+ prev_token_hash: record.prevTokenHash,
55
+ rotated_at: iso(record.rotatedAt),
56
+ last_used_at: iso(record.lastUsedAt),
57
+ expires_at: iso(record.expiresAt),
58
+ idle_expires_at: iso(record.idleExpiresAt),
59
+ persistent: record.persistent ? 1 : 0,
60
+ ip: record.ip,
61
+ user_agent: record.userAgent,
62
+ data: record.data == null ? null : JSON.stringify(record.data),
63
+ })
64
+ },
65
+ async get(id) {
66
+ return strip(fromRow(await findRow(id)))
67
+ },
68
+ async update(id, patch, { expectTokenHash } = {}) {
69
+ const values = {}
70
+ for (const [field, value] of Object.entries(patch)) {
71
+ if (TIME_FIELDS[field]) values[TIME_FIELDS[field]] = iso(value)
72
+ else if (OTHER_FIELDS[field]) values[OTHER_FIELDS[field]] = value
73
+ else if (field === 'data') values.data = value == null ? null : JSON.stringify(value)
74
+ }
75
+ if (Object.keys(values).length === 0) return false
76
+ const where = expectTokenHash === undefined ? { sid: id } : { sid: id, token_hash: expectTokenHash }
77
+ return (await Model.updateWhere(where, values)) === 1
78
+ },
79
+ async delete(id) {
80
+ const row = await findRow(id)
81
+ if (row) await Model.delete(row.id)
82
+ },
83
+ async deleteByUser(userId, { exceptId } = {}) {
84
+ const rows = await Model.query().where('user_id', userId).get()
85
+ let count = 0
86
+ for (const row of rows) {
87
+ if (row.sid === exceptId) continue
88
+ await Model.delete(row.id)
89
+ count++
90
+ }
91
+ return count
92
+ },
93
+ async listByUser(userId) {
94
+ return (await Model.query().where('user_id', userId).get()).map((row) => strip(fromRow(row)))
95
+ },
96
+ }
97
+ }
@@ -0,0 +1,67 @@
1
+ // Sessions through Prisma. Add this model to schema.prisma:
2
+ //
3
+ // model AuthSession {
4
+ // id String @id
5
+ // userId String
6
+ // tokenHash String
7
+ // prevTokenHash String?
8
+ // rotatedAt BigInt?
9
+ // createdAt BigInt
10
+ // lastUsedAt BigInt
11
+ // expiresAt BigInt
12
+ // idleExpiresAt BigInt?
13
+ // persistent Boolean
14
+ // ip String?
15
+ // userAgent String?
16
+ // data String?
17
+ // @@index([userId])
18
+ // }
19
+ //
20
+ // prismaAdapter(prisma.authSession)
21
+
22
+ const FIELDS = ['tokenHash', 'prevTokenHash', 'rotatedAt', 'lastUsedAt', 'idleExpiresAt', 'expiresAt', 'data', 'ip', 'userAgent']
23
+ const TIMES = ['rotatedAt', 'createdAt', 'lastUsedAt', 'expiresAt', 'idleExpiresAt']
24
+
25
+ export function prismaAdapter(delegate) {
26
+ if (!delegate || typeof delegate.findUnique !== 'function') throw new TypeError('prismaAdapter needs a Prisma model delegate, e.g. prisma.authSession')
27
+
28
+ const toDb = (record) => {
29
+ const out = { ...record, userId: String(record.userId) }
30
+ for (const k of TIMES) if (out[k] != null) out[k] = BigInt(out[k])
31
+ if ('data' in out) out.data = out.data == null ? null : JSON.stringify(out.data)
32
+ return out
33
+ }
34
+ const fromDb = (row) => {
35
+ if (!row) return null
36
+ const out = { ...row }
37
+ for (const k of TIMES) if (out[k] != null) out[k] = Number(out[k])
38
+ out.data = row.data == null ? null : JSON.parse(row.data)
39
+ return out
40
+ }
41
+
42
+ return {
43
+ async create(record) {
44
+ await delegate.create({ data: toDb(record) })
45
+ },
46
+ async get(id) {
47
+ return fromDb(await delegate.findUnique({ where: { id } }))
48
+ },
49
+ async update(id, patch, { expectTokenHash } = {}) {
50
+ const data = toDb(Object.fromEntries(Object.entries(patch).filter(([k]) => FIELDS.includes(k))))
51
+ delete data.userId
52
+ const where = expectTokenHash === undefined ? { id } : { id, tokenHash: expectTokenHash }
53
+ const { count } = await delegate.updateMany({ where, data })
54
+ return count === 1
55
+ },
56
+ async delete(id) {
57
+ await delegate.deleteMany({ where: { id } })
58
+ },
59
+ async deleteByUser(userId, { exceptId } = {}) {
60
+ const where = { userId: String(userId), ...(exceptId ? { NOT: { id: exceptId } } : {}) }
61
+ return (await delegate.deleteMany({ where })).count
62
+ },
63
+ async listByUser(userId) {
64
+ return (await delegate.findMany({ where: { userId: String(userId) } })).map(fromDb)
65
+ },
66
+ }
67
+ }
@@ -0,0 +1,128 @@
1
+ // Sessions in a SQL table, through any driver. You pass one function that
2
+ // runs a parameterised statement and resolves rows (for SELECT) or the
3
+ // number of affected rows (for UPDATE/DELETE):
4
+ //
5
+ // sqlAdapter({ dialect: 'postgres', query: async (sql, params) => ... })
6
+ //
7
+ // Placeholders are written for the dialect ($1 for postgres, ? otherwise).
8
+ // The table (see `createTableSql`) stores times as epoch milliseconds, so
9
+ // every database compares them the same way.
10
+ //
11
+ // Rotation is a real compare-and-swap (UPDATE ... WHERE token_hash = ?).
12
+
13
+ const COLUMNS = [
14
+ 'id', 'user_id', 'token_hash', 'prev_token_hash', 'rotated_at', 'created_at', 'last_used_at',
15
+ 'expires_at', 'idle_expires_at', 'persistent', 'ip', 'user_agent', 'data',
16
+ ]
17
+
18
+ const FIELD_TO_COLUMN = {
19
+ tokenHash: 'token_hash',
20
+ prevTokenHash: 'prev_token_hash',
21
+ rotatedAt: 'rotated_at',
22
+ lastUsedAt: 'last_used_at',
23
+ idleExpiresAt: 'idle_expires_at',
24
+ expiresAt: 'expires_at',
25
+ data: 'data',
26
+ ip: 'ip',
27
+ userAgent: 'user_agent',
28
+ }
29
+
30
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/
31
+
32
+ export function createTableSql({ table = 'auth_sessions', dialect = 'postgres' } = {}) {
33
+ const big = dialect === 'sqlite' ? 'INTEGER' : 'BIGINT'
34
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
35
+ return [
36
+ `CREATE TABLE IF NOT EXISTS ${table} (
37
+ id ${dialect === 'mysql' ? 'VARCHAR(32)' : 'TEXT'} PRIMARY KEY,
38
+ user_id ${text} NOT NULL,
39
+ token_hash ${text} NOT NULL,
40
+ prev_token_hash ${text},
41
+ rotated_at ${big},
42
+ created_at ${big} NOT NULL,
43
+ last_used_at ${big} NOT NULL,
44
+ expires_at ${big} NOT NULL,
45
+ idle_expires_at ${big},
46
+ persistent ${dialect === 'postgres' ? 'BOOLEAN' : 'INTEGER'} NOT NULL,
47
+ ip ${text},
48
+ user_agent ${dialect === 'mysql' ? 'VARCHAR(512)' : 'TEXT'},
49
+ data TEXT
50
+ )`,
51
+ `CREATE INDEX ${dialect === 'mysql' ? '' : 'IF NOT EXISTS '}${table}_user_id_idx ON ${table} (user_id)`,
52
+ ]
53
+ }
54
+
55
+ export function sqlAdapter({ query, dialect = 'postgres', table = 'auth_sessions' }) {
56
+ if (typeof query !== 'function') throw new TypeError('sqlAdapter needs query(sql, params)')
57
+ if (!IDENTIFIER.test(table)) throw new TypeError(`Invalid table name ${JSON.stringify(table)}`)
58
+ const ph = (n) => (dialect === 'postgres' ? `$${n}` : '?')
59
+
60
+ const toRow = (r) => [
61
+ r.id, String(r.userId), r.tokenHash, r.prevTokenHash ?? null, r.rotatedAt ?? null, r.createdAt, r.lastUsedAt,
62
+ r.expiresAt, r.idleExpiresAt ?? null, dialect === 'postgres' ? Boolean(r.persistent) : r.persistent ? 1 : 0,
63
+ r.ip ?? null, r.userAgent ?? null, r.data == null ? null : JSON.stringify(r.data),
64
+ ]
65
+ const num = (v) => (v == null ? null : Number(v))
66
+ const fromRow = (row) =>
67
+ row && {
68
+ id: row.id,
69
+ userId: row.user_id,
70
+ tokenHash: row.token_hash,
71
+ prevTokenHash: row.prev_token_hash ?? null,
72
+ rotatedAt: num(row.rotated_at),
73
+ createdAt: num(row.created_at),
74
+ lastUsedAt: num(row.last_used_at),
75
+ expiresAt: num(row.expires_at),
76
+ idleExpiresAt: num(row.idle_expires_at),
77
+ persistent: Boolean(row.persistent),
78
+ ip: row.ip ?? null,
79
+ userAgent: row.user_agent ?? null,
80
+ data: row.data == null ? null : typeof row.data === 'string' ? JSON.parse(row.data) : row.data,
81
+ }
82
+ const rows = async (sql, params) => {
83
+ const result = await query(sql, params)
84
+ return Array.isArray(result) ? result : (result?.rows ?? [])
85
+ }
86
+ const affected = async (sql, params) => {
87
+ const result = await query(sql, params)
88
+ if (typeof result === 'number') return result
89
+ return Number(result?.rowCount ?? result?.affectedRows ?? result?.changes ?? result?.[0]?.affectedRows ?? 0)
90
+ }
91
+
92
+ return {
93
+ async create(record) {
94
+ await query(`INSERT INTO ${table} (${COLUMNS.join(', ')}) VALUES (${COLUMNS.map((_, i) => ph(i + 1)).join(', ')})`, toRow(record))
95
+ },
96
+ async get(id) {
97
+ return fromRow((await rows(`SELECT * FROM ${table} WHERE id = ${ph(1)}`, [id]))[0]) ?? null
98
+ },
99
+ async update(id, patch, { expectTokenHash } = {}) {
100
+ const sets = []
101
+ const params = []
102
+ for (const [field, value] of Object.entries(patch)) {
103
+ const column = FIELD_TO_COLUMN[field]
104
+ if (!column) continue
105
+ params.push(field === 'data' ? (value == null ? null : JSON.stringify(value)) : value)
106
+ sets.push(`${column} = ${ph(params.length)}`)
107
+ }
108
+ if (sets.length === 0) return false
109
+ params.push(id)
110
+ let sql = `UPDATE ${table} SET ${sets.join(', ')} WHERE id = ${ph(params.length)}`
111
+ if (expectTokenHash !== undefined) {
112
+ params.push(expectTokenHash)
113
+ sql += ` AND token_hash = ${ph(params.length)}`
114
+ }
115
+ return (await affected(sql, params)) === 1
116
+ },
117
+ async delete(id) {
118
+ await query(`DELETE FROM ${table} WHERE id = ${ph(1)}`, [id])
119
+ },
120
+ async deleteByUser(userId, { exceptId } = {}) {
121
+ if (exceptId) return affected(`DELETE FROM ${table} WHERE user_id = ${ph(1)} AND id <> ${ph(2)}`, [String(userId), exceptId])
122
+ return affected(`DELETE FROM ${table} WHERE user_id = ${ph(1)}`, [String(userId)])
123
+ },
124
+ async listByUser(userId) {
125
+ return (await rows(`SELECT * FROM ${table} WHERE user_id = ${ph(1)}`, [String(userId)])).map(fromRow)
126
+ },
127
+ }
128
+ }