@jskit-ai/auth-provider-local-db-core 0.1.188 → 0.1.190
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/CHANGELOG.md +3 -0
- package/migrations/auth_local_db_sessions_metadata.cjs +29 -0
- package/migrations/auth_local_db_users_disabled_message.cjs +21 -0
- package/migrations/auth_local_db_users_pending_email.cjs +20 -0
- package/package.json +4 -4
- package/src/server/lib/dbBackend.js +94 -3
- package/src/server/lib/localAuthResources.js +15 -1
- package/test/emailChange.test.js +24 -0
- package/test/localAuthRecords.mysql.test.js +11 -6
- package/test/ownerApis.test.js +53 -2
- package/test/providerRuntime.test.js +2 -2
- package/test/sessionMetadata.test.js +72 -0
- package/test/support/localAuthRuntime.js +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A user's waiting email change, in the new nullable column `auth_local_users.pending_email` (migration `auth_local_db_users_pending_email`; run `npm run db:migrate`), behind the backend contract's `pendingEmail`, `users.updatePendingEmail` and `users.updateEmail`. Changing the email clears the waiting change and sets `email_verified_at`, which the link sent to the address proves; an email another account has is refused with `auth.local.accounts.exists`.
|
|
6
|
+
- Sessions keep where and when they were last seen, in the new nullable columns `auth_local_sessions.ip`, `user_agent` and `last_seen_at` (migration `auth_local_db_sessions_metadata`; run `npm run db:migrate`), behind the backend contract's session fields and `sessions.touch`. `auth.local.sessions.listForUser(userId, options)` answers an account's sessions that are neither revoked nor expired, the newest first, every one of them in one read, each with `ip`, `userAgent` and `lastSeenAt`, and refuses a missing id with a `TypeError`: for an application's list of a person's sessions, its own or an operator's.
|
|
7
|
+
- `auth.local.accounts` can disable an account and enable it again: `disable(userId, { message }, options)` refuses every sign-in and session of the account from its next request, and a sign-in that proves who it is (the right password, a linked provider or a one-time pass) is refused with 403 `auth.local.login.disabled` and `message`, at most 500 characters, as its text, or "This account is disabled." without one; `enable(userId, options)` lets it sign in again and clears the message. Both answer the account, now with `disabledMessage` ("" when it has none), or null when there is no such account, and refuse a missing id, or a message that is not text of at most 500 characters, with a `TypeError`. Neither revokes sessions (`auth.local.sessions.revokeForUser` does). Until now nothing set `disabled`. Upgrading: run `npm run db:migrate` for the new migration `auth_local_db_users_disabled_message`, which adds the nullable `auth_local_users.disabled_message` column.
|
|
5
8
|
- Its tests name `APP_ENV`, which local auth now reads in place of `NODE_ENV`.
|
|
6
9
|
- A new account keeps the `emailVerifiedAt` it is created with (`users.create`), as local sign-in's email confirmation now gives it; without one it stays empty, as before.
|
|
7
10
|
- Used one-time passes in the database: the table `auth_local_used_passes` (the hash of each pass's id, until it expires), created by the new migration `auth_local_db_used_passes`, behind the backend contract's `passes` collection, so a pass one server accepted is refused by every server on the database. Two first uses at once both find no row, and the later one's duplicate entry runs its transaction again, which finds it. `LOCAL_AUTH_DB_TABLES.passes` names the table, which the package owns.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Where and when each session was last seen: the address and browser of the request that signed it in, then of
|
|
2
|
+
// one that found it more than five minutes after it was last seen. Null when unknown, as for sessions from before.
|
|
3
|
+
const SESSIONS_TABLE = "auth_local_sessions";
|
|
4
|
+
const IP_MAX_LENGTH = 64;
|
|
5
|
+
const USER_AGENT_MAX_LENGTH = 512;
|
|
6
|
+
|
|
7
|
+
const COLUMNS = Object.freeze([
|
|
8
|
+
["ip", (table) => table.string("ip", IP_MAX_LENGTH).nullable()],
|
|
9
|
+
["user_agent", (table) => table.string("user_agent", USER_AGENT_MAX_LENGTH).nullable()],
|
|
10
|
+
["last_seen_at", (table) => table.timestamp("last_seen_at").nullable()]
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
exports.up = async function up(knex) {
|
|
14
|
+
for (const [name, add] of COLUMNS) {
|
|
15
|
+
if (!(await knex.schema.hasColumn(SESSIONS_TABLE, name))) {
|
|
16
|
+
await knex.schema.alterTable(SESSIONS_TABLE, add);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
exports.down = async function down(knex) {
|
|
22
|
+
for (const [name] of COLUMNS) {
|
|
23
|
+
if (await knex.schema.hasColumn(SESSIONS_TABLE, name)) {
|
|
24
|
+
await knex.schema.alterTable(SESSIONS_TABLE, (table) => {
|
|
25
|
+
table.dropColumn(name);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// What a disabled account's sign-in is told, as the application wrote it when it
|
|
2
|
+
// disabled the account through auth.local.accounts' disable; null when it gave none.
|
|
3
|
+
const USERS_TABLE = "auth_local_users";
|
|
4
|
+
const COLUMN_NAME = "disabled_message";
|
|
5
|
+
const MESSAGE_MAX_LENGTH = 500;
|
|
6
|
+
|
|
7
|
+
exports.up = async function up(knex) {
|
|
8
|
+
if (!(await knex.schema.hasColumn(USERS_TABLE, COLUMN_NAME))) {
|
|
9
|
+
await knex.schema.alterTable(USERS_TABLE, (table) => {
|
|
10
|
+
table.string(COLUMN_NAME, MESSAGE_MAX_LENGTH).nullable();
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
exports.down = async function down(knex) {
|
|
16
|
+
if (await knex.schema.hasColumn(USERS_TABLE, COLUMN_NAME)) {
|
|
17
|
+
await knex.schema.alterTable(USERS_TABLE, (table) => {
|
|
18
|
+
table.dropColumn(COLUMN_NAME);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The address an account's email change waits to confirm, until the link sent to it is used; null when none waits.
|
|
2
|
+
const USERS_TABLE = "auth_local_users";
|
|
3
|
+
const COLUMN_NAME = "pending_email";
|
|
4
|
+
const EMAIL_MAX_LENGTH = 320;
|
|
5
|
+
|
|
6
|
+
exports.up = async function up(knex) {
|
|
7
|
+
if (!(await knex.schema.hasColumn(USERS_TABLE, COLUMN_NAME))) {
|
|
8
|
+
await knex.schema.alterTable(USERS_TABLE, (table) => {
|
|
9
|
+
table.string(COLUMN_NAME, EMAIL_MAX_LENGTH).nullable();
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
exports.down = async function down(knex) {
|
|
15
|
+
if (await knex.schema.hasColumn(USERS_TABLE, COLUMN_NAME)) {
|
|
16
|
+
await knex.schema.alterTable(USERS_TABLE, (table) => {
|
|
17
|
+
table.dropColumn(COLUMN_NAME);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-db-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.190",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -11,14 +11,14 @@
|
|
|
11
11
|
"./server/types": "./src/server/types.js"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@jskit-ai/auth-provider-local-core": "0.2.
|
|
14
|
+
"@jskit-ai/auth-provider-local-core": "0.2.37",
|
|
15
15
|
"@jskit-ai/resource-core": "0.1.218"
|
|
16
16
|
},
|
|
17
17
|
"peerDependencies": {
|
|
18
|
-
"@jskit-ai/auth-core": "0.2.
|
|
18
|
+
"@jskit-ai/auth-core": "0.2.31",
|
|
19
19
|
"@jskit-ai/database-runtime": "0.1.276",
|
|
20
20
|
"@jskit-ai/kernel": "0.2.27",
|
|
21
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
21
|
+
"@jskit-ai/resource-runtime": "0.2.38"
|
|
22
22
|
},
|
|
23
23
|
"description": "Database-backed local auth storage backend for JSKIT local auth.",
|
|
24
24
|
"jskit": {
|
|
@@ -50,6 +50,27 @@ function requireIdPrefix(idPrefix) {
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
// What a disabled account's sign-in is told is at most this long, as its column keeps it.
|
|
54
|
+
const DISABLED_MESSAGE_MAX_LENGTH = 500;
|
|
55
|
+
|
|
56
|
+
// The account an owner call changes: a call without one is a mistake, never "no such account".
|
|
57
|
+
function requireUserId(userId, method) {
|
|
58
|
+
if (!text(userId).trim()) {
|
|
59
|
+
throw new TypeError(`auth.local.accounts.${method}() takes the id of the account it changes.`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The message a disabled account's sign-in is told, or null for none (local sign-in then says the account is disabled).
|
|
64
|
+
function storedDisabledMessage(message) {
|
|
65
|
+
if (message === undefined || message === null) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (typeof message !== "string" || message.length > DISABLED_MESSAGE_MAX_LENGTH) {
|
|
69
|
+
throw new TypeError(`auth.local.accounts.disable() takes a message of at most ${DISABLED_MESSAGE_MAX_LENGTH} characters.`);
|
|
70
|
+
}
|
|
71
|
+
return message.trim() ? message : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
53
74
|
function readPassword(record) {
|
|
54
75
|
return {
|
|
55
76
|
algorithm: text(record.passwordAlgorithm),
|
|
@@ -80,7 +101,9 @@ function mapUser(record) {
|
|
|
80
101
|
createdAt: readDateTime(record.createdAt),
|
|
81
102
|
updatedAt: readDateTime(record.updatedAt),
|
|
82
103
|
emailVerifiedAt: readDateTime(record.emailVerifiedAt),
|
|
83
|
-
disabled: record.disabled === true || record.disabled === 1 || record.disabled === "1"
|
|
104
|
+
disabled: record.disabled === true || record.disabled === 1 || record.disabled === "1",
|
|
105
|
+
disabledMessage: text(record.disabledMessage),
|
|
106
|
+
pendingEmail: text(record.pendingEmail)
|
|
84
107
|
};
|
|
85
108
|
}
|
|
86
109
|
|
|
@@ -96,7 +119,10 @@ function mapSession(record) {
|
|
|
96
119
|
createdAt: readDateTime(record.createdAt),
|
|
97
120
|
expiresAt: readDateTime(record.expiresAt),
|
|
98
121
|
revokedAt: readDateTime(record.revokedAt),
|
|
99
|
-
secondFactorAt: readDateTime(record.secondFactorAt)
|
|
122
|
+
secondFactorAt: readDateTime(record.secondFactorAt),
|
|
123
|
+
ip: text(record.ip),
|
|
124
|
+
userAgent: text(record.userAgent),
|
|
125
|
+
lastSeenAt: readDateTime(record.lastSeenAt)
|
|
100
126
|
};
|
|
101
127
|
}
|
|
102
128
|
|
|
@@ -197,6 +223,9 @@ function sessionRecord(input = {}) {
|
|
|
197
223
|
expiresAt: requiredDateTime(input.expiresAt),
|
|
198
224
|
revokedAt: optionalDateTime(input.revokedAt),
|
|
199
225
|
secondFactorAt: optionalDateTime(input.secondFactorAt),
|
|
226
|
+
ip: input.ip ? String(input.ip) : null,
|
|
227
|
+
userAgent: input.userAgent ? String(input.userAgent) : null,
|
|
228
|
+
lastSeenAt: optionalDateTime(input.lastSeenAt),
|
|
200
229
|
createdAt,
|
|
201
230
|
updatedAt: requiredDateTime(input.updatedAt, createdAt)
|
|
202
231
|
};
|
|
@@ -276,6 +305,35 @@ function userRecords(users, options) {
|
|
|
276
305
|
}
|
|
277
306
|
await users.patch(id, { emailVerifiedAt: requiredDateTime() }, { ...options, onlyIf: { emailVerifiedAt: null }, missing: "skip", returning: "none" });
|
|
278
307
|
return mapUser(await users.get(id, {}, { ...options, missing: "skip" }));
|
|
308
|
+
},
|
|
309
|
+
// Every sign-in and session of a disabled account is refused; a sign-in that proves who it is is told the message.
|
|
310
|
+
async disable(userId, { message } = {}) {
|
|
311
|
+
requireUserId(userId, "disable");
|
|
312
|
+
const changes = { disabled: true, disabledMessage: storedDisabledMessage(message), updatedAt: requiredDateTime() };
|
|
313
|
+
return mapUser(await patchExisting(users, userId, changes, options));
|
|
314
|
+
},
|
|
315
|
+
async enable(userId) {
|
|
316
|
+
requireUserId(userId, "enable");
|
|
317
|
+
const changes = { disabled: false, disabledMessage: null, updatedAt: requiredDateTime() };
|
|
318
|
+
return mapUser(await patchExisting(users, userId, changes, options));
|
|
319
|
+
},
|
|
320
|
+
// The address the account's email change waits to confirm; "" clears it.
|
|
321
|
+
async updatePendingEmail(userId, pendingEmail) {
|
|
322
|
+
const changes = { pendingEmail: text(pendingEmail) || null, updatedAt: requiredDateTime() };
|
|
323
|
+
return mapUser(await patchExisting(users, userId, changes, options));
|
|
324
|
+
},
|
|
325
|
+
// The email changes to an address its link proved, confirmed from now; another account's email is refused.
|
|
326
|
+
async updateEmail(userId, email) {
|
|
327
|
+
const now = requiredDateTime();
|
|
328
|
+
const changes = { email: text(email), pendingEmail: null, emailVerifiedAt: now, updatedAt: now };
|
|
329
|
+
try {
|
|
330
|
+
return mapUser(await patchExisting(users, userId, changes, options));
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (isDuplicateEntryError(error)) {
|
|
333
|
+
throw new ConflictError("An account with this id or email already exists.", { code: "auth.local.accounts.exists", cause: error });
|
|
334
|
+
}
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
279
337
|
}
|
|
280
338
|
});
|
|
281
339
|
}
|
|
@@ -358,6 +416,33 @@ function sessionRecords(sessions, options) {
|
|
|
358
416
|
{ secondFactorAt: null, updatedAt: requiredDateTime() },
|
|
359
417
|
{ ...options, returning: "count" }
|
|
360
418
|
);
|
|
419
|
+
},
|
|
420
|
+
// The session seen again: when, and from where when the request said; a missing one changes nothing.
|
|
421
|
+
async touch(sessionId, { lastSeenAt, ip, userAgent } = {}) {
|
|
422
|
+
const id = text(sessionId);
|
|
423
|
+
if (!id) {
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const changes = { lastSeenAt: requiredDateTime(lastSeenAt) };
|
|
427
|
+
if (ip) {
|
|
428
|
+
changes.ip = String(ip);
|
|
429
|
+
}
|
|
430
|
+
if (userAgent) {
|
|
431
|
+
changes.userAgent = String(userAgent);
|
|
432
|
+
}
|
|
433
|
+
await sessions.patch(id, changes, { ...options, missing: "skip", returning: "none" });
|
|
434
|
+
},
|
|
435
|
+
// Every session of the user that is neither revoked nor expired, the newest first.
|
|
436
|
+
async listForUser(userId) {
|
|
437
|
+
const owner = text(userId);
|
|
438
|
+
if (!owner.trim()) {
|
|
439
|
+
throw new TypeError("auth.local.sessions.listForUser() takes the id of the account whose sessions it lists.");
|
|
440
|
+
}
|
|
441
|
+
const records = await sessions.queryAll({
|
|
442
|
+
filters: { userId: owner, notRevoked: true, expiresAfter: requiredDateTime() },
|
|
443
|
+
sort: ["-createdAt", "-id"]
|
|
444
|
+
}, options);
|
|
445
|
+
return records.map(mapSession);
|
|
361
446
|
}
|
|
362
447
|
});
|
|
363
448
|
}
|
|
@@ -591,7 +676,10 @@ function createLocalDbOwners({ resources, identities, context }) {
|
|
|
591
676
|
findByEmail: (email, options = {}) => records(options).users.findByEmail(normalizeEmail(email)),
|
|
592
677
|
updatePassword: (userId, passwordRecord, options = {}) => records(options).users.updatePassword(userId, passwordRecord),
|
|
593
678
|
updateProfile: (userId, updates, options = {}) => records(options).users.updateProfile(userId, updates),
|
|
594
|
-
markEmailVerified: (userId, options = {}) => records(options).users.markEmailVerified(userId)
|
|
679
|
+
markEmailVerified: (userId, options = {}) => records(options).users.markEmailVerified(userId),
|
|
680
|
+
// Refuses the account's sign-ins and sessions until enable; a sign-in that proves who it is is told the message.
|
|
681
|
+
disable: (userId, { message } = {}, options = {}) => records(options).users.disable(userId, { message }),
|
|
682
|
+
enable: (userId, options = {}) => records(options).users.enable(userId)
|
|
595
683
|
});
|
|
596
684
|
const sessions = Object.freeze({
|
|
597
685
|
create: (input, options = {}) => records(options).sessions.create(input),
|
|
@@ -600,6 +688,9 @@ function createLocalDbOwners({ resources, identities, context }) {
|
|
|
600
688
|
revoke: (sessionId, options = {}) => records(options).sessions.revoke(sessionId),
|
|
601
689
|
// options.exceptSessionId keeps that session.
|
|
602
690
|
revokeForUser: (userId, { exceptSessionId, ...options } = {}) => records(options).sessions.revokeForUser(userId, { exceptSessionId }),
|
|
691
|
+
// The account's live sessions, the newest first, each with where (ip, userAgent) and when (lastSeenAt) it was
|
|
692
|
+
// last seen.
|
|
693
|
+
listForUser: (userId, options = {}) => records(options).sessions.listForUser(userId),
|
|
603
694
|
deleteExpired: (now, options = {}) => records(options).sessions.deleteExpired(now)
|
|
604
695
|
});
|
|
605
696
|
const recovery = Object.freeze({
|
|
@@ -29,6 +29,11 @@ function hasSecondFactorAt(query, _proved, { column }) {
|
|
|
29
29
|
query.whereNotNull(column("secondFactorAt"));
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// Sessions nobody ended.
|
|
33
|
+
function hasNoRevokedAt(query, _notRevoked, { column }) {
|
|
34
|
+
query.whereNull(column("revokedAt"));
|
|
35
|
+
}
|
|
36
|
+
|
|
32
37
|
// auth_local_users: one row per local account, keyed by its text id.
|
|
33
38
|
const localAuthUserResource = defineTableResource({
|
|
34
39
|
name: "localAuthUsers",
|
|
@@ -39,9 +44,11 @@ const localAuthUserResource = defineTableResource({
|
|
|
39
44
|
displayName: text,
|
|
40
45
|
...password,
|
|
41
46
|
disabled: { type: "boolean" },
|
|
47
|
+
disabledMessage: { ...text, nullable: true },
|
|
42
48
|
createdAt: dateTime,
|
|
43
49
|
updatedAt: dateTime,
|
|
44
|
-
emailVerifiedAt: optionalDateTime
|
|
50
|
+
emailVerifiedAt: optionalDateTime,
|
|
51
|
+
pendingEmail: { ...text, nullable: true }
|
|
45
52
|
}
|
|
46
53
|
});
|
|
47
54
|
|
|
@@ -58,6 +65,10 @@ const localAuthSessionResource = defineTableResource({
|
|
|
58
65
|
expiresAt: dateTime,
|
|
59
66
|
revokedAt: optionalDateTime,
|
|
60
67
|
secondFactorAt: optionalDateTime,
|
|
68
|
+
// Where and when the session was last seen: null when unknown.
|
|
69
|
+
ip: { ...text, nullable: true },
|
|
70
|
+
userAgent: { ...text, nullable: true },
|
|
71
|
+
lastSeenAt: optionalDateTime,
|
|
61
72
|
createdAt: dateTime,
|
|
62
73
|
updatedAt: dateTime
|
|
63
74
|
},
|
|
@@ -65,6 +76,9 @@ const localAuthSessionResource = defineTableResource({
|
|
|
65
76
|
// Every session of a user but one.
|
|
66
77
|
exceptId: { type: "string", actualField: "id", filterOperator: "!=" },
|
|
67
78
|
expiresAtOrBefore,
|
|
79
|
+
// Sessions that have not expired by then.
|
|
80
|
+
expiresAfter: { type: "dateTime", actualField: "expiresAt", filterOperator: ">" },
|
|
81
|
+
notRevoked: { type: "boolean", applyFilter: hasNoRevokedAt },
|
|
68
82
|
secondFactorProved: { type: "boolean", applyFilter: hasSecondFactorAt }
|
|
69
83
|
}
|
|
70
84
|
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import pendingEmailMigration from "../migrations/auth_local_db_users_pending_email.cjs";
|
|
4
|
+
import { exerciseEmailChange } from "../../auth-provider-local-core/test-support/emailChangeScenario.js";
|
|
5
|
+
import { openSqliteLocalAuth } from "./support/localAuthRuntime.js";
|
|
6
|
+
|
|
7
|
+
test("an account's email changes once the link sent to the new address is used, and the old address is told (database backend)", async (t) => {
|
|
8
|
+
const { accounts, backend, knex } = await openSqliteLocalAuth(t);
|
|
9
|
+
// The migration runs again on a database that has its column, as a rerun deploy does.
|
|
10
|
+
await pendingEmailMigration.up(knex);
|
|
11
|
+
const { adaId, bobId } = await exerciseEmailChange(t, backend);
|
|
12
|
+
// The link proved the new address, so it is confirmed from when it was used; the account whose change was refused
|
|
13
|
+
// keeps its own confirmation, which registering without a link never gave.
|
|
14
|
+
const ada = await accounts.findById(adaId);
|
|
15
|
+
assert.deepEqual([ada.email, ada.pendingEmail, ada.emailVerifiedAt], ["ada.second@example.com", "", "2026-11-15T09:00:00.000Z"]);
|
|
16
|
+
const bob = await accounts.findById(bobId);
|
|
17
|
+
assert.deepEqual([bob.email, bob.pendingEmail, bob.emailVerifiedAt], ["bob@example.com", "carol@example.com", ""]);
|
|
18
|
+
|
|
19
|
+
// The migration's down drops the column, and up adds it again.
|
|
20
|
+
await pendingEmailMigration.down(knex);
|
|
21
|
+
assert.equal(await knex.schema.hasColumn("auth_local_users", "pending_email"), false);
|
|
22
|
+
await pendingEmailMigration.up(knex);
|
|
23
|
+
assert.equal(await knex.schema.hasColumn("auth_local_users", "pending_email"), true);
|
|
24
|
+
});
|
|
@@ -17,8 +17,8 @@ const NEXT_PASSWORD = Object.freeze({ algorithm: "scrypt", version: "2", salt: "
|
|
|
17
17
|
const NO_PASSWORD = Object.freeze({ algorithm: "", version: "", salt: "", hash: "" });
|
|
18
18
|
const CREATED = "2026-11-01T08:00:00.000Z";
|
|
19
19
|
const ISO_SECONDS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.000Z$/u;
|
|
20
|
-
const ACCOUNT_KEYS = ["id", "email", "displayName", "password", "createdAt", "updatedAt", "emailVerifiedAt", "disabled"];
|
|
21
|
-
const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt", "secondFactorAt"];
|
|
20
|
+
const ACCOUNT_KEYS = ["id", "email", "displayName", "password", "createdAt", "updatedAt", "emailVerifiedAt", "disabled", "disabledMessage", "pendingEmail"];
|
|
21
|
+
const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt", "secondFactorAt", "ip", "userAgent", "lastSeenAt"];
|
|
22
22
|
const RECOVERY_KEYS = ["id", "userId", "tokenHash", "createdAt", "expiresAt", "usedAt"];
|
|
23
23
|
|
|
24
24
|
/** The current second, as the second-precision timestamps keep it. */
|
|
@@ -60,7 +60,9 @@ test("accounts: create answers the account it wrote, reads find it by id and ema
|
|
|
60
60
|
createdAt: "2026-11-01T08:00:00.123Z",
|
|
61
61
|
updatedAt: "2026-11-01T08:00:00.123Z",
|
|
62
62
|
emailVerifiedAt: "",
|
|
63
|
-
disabled: false
|
|
63
|
+
disabled: false,
|
|
64
|
+
disabledMessage: "",
|
|
65
|
+
pendingEmail: ""
|
|
64
66
|
}, "create answers what it wrote, to the millisecond, and updatedAt defaults to createdAt");
|
|
65
67
|
|
|
66
68
|
const before = thisSecond();
|
|
@@ -154,7 +156,10 @@ test("sessions: create, reads, revoke once, revoke a user's live sessions but on
|
|
|
154
156
|
createdAt: CREATED,
|
|
155
157
|
expiresAt: "2026-12-01T00:00:00.000Z",
|
|
156
158
|
revokedAt: "",
|
|
157
|
-
secondFactorAt: ""
|
|
159
|
+
secondFactorAt: "",
|
|
160
|
+
ip: "",
|
|
161
|
+
userAgent: "",
|
|
162
|
+
lastSeenAt: ""
|
|
158
163
|
}, "a session without a purpose is a normal one");
|
|
159
164
|
const preview = await backend.withTransaction((tx) => tx.sessions.create(session("ses_two", "usr_ada", "2026-12-01T00:00:00.000Z", { purpose: "dev-auth" })));
|
|
160
165
|
assert.equal(preview.purpose, "dev-auth");
|
|
@@ -413,8 +418,8 @@ test("concurrent failed sign-ins for one email each count: find holds the email'
|
|
|
413
418
|
test("the owner APIs answer as the backend does and join a caller's transaction, whose rollback undoes their writes", async (context) => {
|
|
414
419
|
requireTestDatabase(process.env);
|
|
415
420
|
const { accounts, sessions, recovery, backend, inCallerTransaction } = await openLocalAuthDatabase(context, "da_local_owners");
|
|
416
|
-
assert.deepEqual(Object.keys(accounts), ["create", "findById", "findByEmail", "updatePassword", "updateProfile", "markEmailVerified"]);
|
|
417
|
-
assert.deepEqual(Object.keys(sessions), ["create", "update", "revoke", "revokeForUser", "deleteExpired"]);
|
|
421
|
+
assert.deepEqual(Object.keys(accounts), ["create", "findById", "findByEmail", "updatePassword", "updateProfile", "markEmailVerified", "disable", "enable"]);
|
|
422
|
+
assert.deepEqual(Object.keys(sessions), ["create", "update", "revoke", "revokeForUser", "listForUser", "deleteExpired"]);
|
|
418
423
|
assert.deepEqual(Object.keys(recovery), ["create", "findByTokenHash", "consume", "consumeForUser"]);
|
|
419
424
|
|
|
420
425
|
const created = await accounts.create(account("usr_ada", "ada@example.com"));
|
package/test/ownerApis.test.js
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import test from "node:test";
|
|
3
|
+
import disabledMessageMigration from "../migrations/auth_local_db_users_disabled_message.cjs";
|
|
3
4
|
import emailVerifiedMigration from "../migrations/auth_local_db_users_email_verified.cjs";
|
|
4
|
-
import { hashPassword } from "@jskit-ai/auth-provider-local-core/server/lib/index";
|
|
5
|
+
import { createLocalAuthService, hashPassword } from "@jskit-ai/auth-provider-local-core/server/lib/index";
|
|
5
6
|
import { LOCAL_AUTH_DB_TABLES } from "../src/server/lib/index.js";
|
|
6
7
|
import { openSqliteLocalAuth } from "./support/localAuthRuntime.js";
|
|
8
|
+
import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
|
|
9
|
+
import { sessionCookies } from "../../auth-provider-local-core/test-support/passSignInScenario.js";
|
|
7
10
|
|
|
8
11
|
// The owner APIs as an application feature requires them, over a migrated database.
|
|
9
12
|
async function ownerApis(t) {
|
|
10
13
|
const records = await openSqliteLocalAuth(t);
|
|
11
|
-
// The email proof's
|
|
14
|
+
// The email proof's and the disabled message's migrations run again on a database that has their columns, as a rerun
|
|
15
|
+
// deploy does.
|
|
12
16
|
await emailVerifiedMigration.up(records.knex);
|
|
17
|
+
await disabledMessageMigration.up(records.knex);
|
|
13
18
|
return records;
|
|
14
19
|
}
|
|
15
20
|
|
|
@@ -52,6 +57,52 @@ test("accounts keep and find an email as local sign-in does, and are found by id
|
|
|
52
57
|
assert.equal(await accounts.findById("usr_missing"), null);
|
|
53
58
|
});
|
|
54
59
|
|
|
60
|
+
test("disable refuses the account's sign-ins with its message until enable, in the caller's transaction or on its own", async (t) => {
|
|
61
|
+
const { accounts, backend, inCallerTransaction } = await ownerApis(t);
|
|
62
|
+
const service = createLocalAuthService({ ...localServiceOptions(), backend });
|
|
63
|
+
await accounts.create({
|
|
64
|
+
id: "usr_off", email: "off@example.com", displayName: "Off", password: await hashPassword("off password value")
|
|
65
|
+
});
|
|
66
|
+
const signIn = (password = "off password value") => service.login({ email: "off@example.com", password });
|
|
67
|
+
const signedIn = await signIn();
|
|
68
|
+
const suspended = "This account is suspended until 14 Dec. We've emailed you why.";
|
|
69
|
+
|
|
70
|
+
await assert.rejects(inCallerTransaction(async (options) => {
|
|
71
|
+
assert.equal((await accounts.disable("usr_off", { message: suspended }, options)).disabled, true);
|
|
72
|
+
throw new Error("Abort the suspension");
|
|
73
|
+
}), /Abort the suspension/u);
|
|
74
|
+
assert.equal((await accounts.findById("usr_off")).disabled, false, "The rolled-back suspension is gone");
|
|
75
|
+
|
|
76
|
+
const disabled = await accounts.disable("usr_off", { message: suspended });
|
|
77
|
+
assert.equal(disabled.disabled, true);
|
|
78
|
+
assert.equal(disabled.disabledMessage, suspended);
|
|
79
|
+
assert.deepEqual(await accounts.findById("usr_off"), disabled);
|
|
80
|
+
await assert.rejects(signIn(), { status: 403, code: "auth.local.login.disabled", message: suspended });
|
|
81
|
+
// A wrong password learns nothing: it is an ordinary failed sign-in.
|
|
82
|
+
await assert.rejects(signIn("a wrong password"), { status: 401, code: "auth.login.invalidCredentials" });
|
|
83
|
+
// The account's sessions stop working at its next request.
|
|
84
|
+
assert.equal((await service.authenticateRequest({ cookies: sessionCookies(signedIn.session) })).authenticated, false);
|
|
85
|
+
|
|
86
|
+
// Without a message, the refusal says plainly that the account is disabled.
|
|
87
|
+
assert.equal((await accounts.disable("usr_off")).disabledMessage, "");
|
|
88
|
+
await assert.rejects(signIn(), { status: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
|
|
89
|
+
|
|
90
|
+
const enabled = await accounts.enable("usr_off");
|
|
91
|
+
assert.equal(enabled.disabled, false);
|
|
92
|
+
assert.equal(enabled.disabledMessage, "");
|
|
93
|
+
assert.equal((await signIn()).actor.email, "off@example.com");
|
|
94
|
+
|
|
95
|
+
// A missing account changes nothing; a missing id or a message that is not text of at most 500 characters is refused.
|
|
96
|
+
assert.equal(await accounts.disable("usr_missing", { message: suspended }), null);
|
|
97
|
+
assert.equal(await accounts.enable("usr_missing"), null);
|
|
98
|
+
const refused = { name: "TypeError" };
|
|
99
|
+
await assert.rejects(accounts.disable("", { message: suspended }), refused);
|
|
100
|
+
await assert.rejects(accounts.enable(" "), refused);
|
|
101
|
+
await assert.rejects(accounts.disable("usr_off", { message: 42 }), refused);
|
|
102
|
+
await assert.rejects(accounts.disable("usr_off", { message: "x".repeat(501) }), refused);
|
|
103
|
+
assert.equal((await accounts.findById("usr_off")).disabled, false, "A refused disable changes nothing");
|
|
104
|
+
});
|
|
105
|
+
|
|
55
106
|
test("sessions.update changes a session's purpose and expiry only, in the caller's transaction or on its own", async (t) => {
|
|
56
107
|
const { accounts, sessions, inCallerTransaction } = await ownerApis(t);
|
|
57
108
|
await accounts.create({
|
|
@@ -349,7 +349,7 @@ test("local auth DB backend works with custom password strategy", async (t) => {
|
|
|
349
349
|
assert.equal(login.actor.email, "strategy-db@example.com");
|
|
350
350
|
});
|
|
351
351
|
|
|
352
|
-
test("local auth service
|
|
352
|
+
test("local auth service tells a disabled DB-backed account's right password that it is disabled", async (t) => {
|
|
353
353
|
const { backend } = await createDbBackendFixture(t);
|
|
354
354
|
const password = await hashPassword("disabled password value");
|
|
355
355
|
await backend.withTransaction((tx) =>
|
|
@@ -369,7 +369,7 @@ test("local auth service rejects disabled DB-backed users", async (t) => {
|
|
|
369
369
|
email: "disabled@example.com",
|
|
370
370
|
password: "disabled password value"
|
|
371
371
|
}),
|
|
372
|
-
|
|
372
|
+
{ status: 403, code: "auth.local.login.disabled", message: "This account is disabled." }
|
|
373
373
|
);
|
|
374
374
|
});
|
|
375
375
|
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { createLocalAuthService, hashPassword } from "@jskit-ai/auth-provider-local-core/server/lib/index";
|
|
4
|
+
import sessionsMetadataMigration from "../migrations/auth_local_db_sessions_metadata.cjs";
|
|
5
|
+
import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
|
|
6
|
+
import { exerciseSessionMetadata, requestFrom } from "../../auth-provider-local-core/test-support/sessionMetadataScenario.js";
|
|
7
|
+
import { openSqliteLocalAuth } from "./support/localAuthRuntime.js";
|
|
8
|
+
|
|
9
|
+
const PASSWORD = "listed password value";
|
|
10
|
+
const BROWSER = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
|
|
11
|
+
|
|
12
|
+
test("a session keeps where and when it was last seen, at most every five minutes (database backend)", async (t) => {
|
|
13
|
+
const { backend, knex } = await openSqliteLocalAuth(t);
|
|
14
|
+
// The migration runs again on a database that has its columns, as a rerun deploy does.
|
|
15
|
+
await sessionsMetadataMigration.up(knex);
|
|
16
|
+
await exerciseSessionMetadata(t, { service: createLocalAuthService({ ...localServiceOptions(), backend }), backend });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("sessions.listForUser answers the account's live sessions, newest first, in one read whatever their number", async (t) => {
|
|
20
|
+
const { accounts, backend, knex, sessions } = await openSqliteLocalAuth(t);
|
|
21
|
+
const service = createLocalAuthService({ ...localServiceOptions(), backend });
|
|
22
|
+
const password = await hashPassword(PASSWORD);
|
|
23
|
+
await accounts.create({ id: "usr_list", email: "list@example.com", displayName: "List", password });
|
|
24
|
+
await accounts.create({ id: "usr_other", email: "other@example.com", displayName: "Other", password });
|
|
25
|
+
const start = Date.parse("2026-11-15T09:00:00.000Z");
|
|
26
|
+
t.mock.timers.enable({ apis: ["Date"], now: start });
|
|
27
|
+
const signIn = async (email, ip) => {
|
|
28
|
+
t.mock.timers.tick(1000);
|
|
29
|
+
const answer = await service.authenticateRequest({
|
|
30
|
+
cookies: {
|
|
31
|
+
jskit_local_access_token: (await service.login({ email, password: PASSWORD }, requestFrom(ip, BROWSER))).session.access_token
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
return answer.sessionId;
|
|
35
|
+
};
|
|
36
|
+
const first = await signIn("list@example.com", "203.0.113.1");
|
|
37
|
+
const ended = await signIn("list@example.com", "203.0.113.2");
|
|
38
|
+
const latest = await signIn("list@example.com", "203.0.113.3");
|
|
39
|
+
await signIn("other@example.com", "198.51.100.1");
|
|
40
|
+
await sessions.revoke(ended);
|
|
41
|
+
await sessions.create({ id: "ses_expired", userId: "usr_list", tokenHash: "hash-expired", purpose: "normal", expiresAt: new Date(start).toISOString() });
|
|
42
|
+
|
|
43
|
+
const listed = await sessions.listForUser("usr_list");
|
|
44
|
+
assert.deepEqual(listed.map(({ id, ip, userAgent }) => ({ id, ip, userAgent })), [
|
|
45
|
+
{ id: latest, ip: "203.0.113.3", userAgent: BROWSER },
|
|
46
|
+
{ id: first, ip: "203.0.113.1", userAgent: BROWSER }
|
|
47
|
+
], "Only the account's own sessions that are neither ended nor expired");
|
|
48
|
+
assert.equal(listed[0].lastSeenAt, new Date(start + 3000).toISOString());
|
|
49
|
+
assert.deepEqual(await sessions.listForUser("usr_missing"), []);
|
|
50
|
+
await assert.rejects(sessions.listForUser(""), { name: "TypeError" });
|
|
51
|
+
|
|
52
|
+
// The read is one statement whether the account has two sessions or sixty.
|
|
53
|
+
const statements = async () => {
|
|
54
|
+
let count = 0;
|
|
55
|
+
const onQuery = () => { count += 1; };
|
|
56
|
+
knex.on("query", onQuery);
|
|
57
|
+
try {
|
|
58
|
+
const listed = await sessions.listForUser("usr_list");
|
|
59
|
+
return { sessions: listed.length, statements: count };
|
|
60
|
+
} finally {
|
|
61
|
+
knex.off("query", onQuery);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const few = await statements();
|
|
65
|
+
for (let index = 0; index < 58; index += 1) {
|
|
66
|
+
await sessions.create({ id: `ses_many_${index}`, userId: "usr_list", tokenHash: `hash-many-${index}`, purpose: "normal",
|
|
67
|
+
expiresAt: "2026-12-15T09:00:00.000Z" });
|
|
68
|
+
}
|
|
69
|
+
const many = await statements();
|
|
70
|
+
assert.deepEqual([few.sessions, many.sessions], [2, 60]);
|
|
71
|
+
assert.equal(many.statements, few.statements);
|
|
72
|
+
});
|
|
@@ -6,8 +6,11 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
|
|
|
6
6
|
import initialMigration from "../../migrations/auth_local_db_initial.cjs";
|
|
7
7
|
import oauthMigration from "../../migrations/auth_local_db_oauth.cjs";
|
|
8
8
|
import protectionMigration from "../../migrations/auth_local_db_protection.cjs";
|
|
9
|
+
import sessionsMetadataMigration from "../../migrations/auth_local_db_sessions_metadata.cjs";
|
|
9
10
|
import usedPassesMigration from "../../migrations/auth_local_db_used_passes.cjs";
|
|
11
|
+
import disabledMessageMigration from "../../migrations/auth_local_db_users_disabled_message.cjs";
|
|
10
12
|
import emailVerifiedMigration from "../../migrations/auth_local_db_users_email_verified.cjs";
|
|
13
|
+
import pendingEmailMigration from "../../migrations/auth_local_db_users_pending_email.cjs";
|
|
11
14
|
import secondFactorsMigration from "../../migrations/auth_local_db_users_second_factors.cjs";
|
|
12
15
|
import { AuthLocalDatabaseBackendProvider } from "../../src/server/providers/AuthLocalDatabaseBackendProvider.js";
|
|
13
16
|
|
|
@@ -16,8 +19,11 @@ const LOCAL_AUTH_MIGRATIONS = Object.freeze([
|
|
|
16
19
|
initialMigration,
|
|
17
20
|
oauthMigration,
|
|
18
21
|
protectionMigration,
|
|
22
|
+
sessionsMetadataMigration,
|
|
19
23
|
usedPassesMigration,
|
|
24
|
+
disabledMessageMigration,
|
|
20
25
|
emailVerifiedMigration,
|
|
26
|
+
pendingEmailMigration,
|
|
21
27
|
secondFactorsMigration
|
|
22
28
|
]);
|
|
23
29
|
|