@jskit-ai/auth-provider-local-db-core 0.1.142 → 0.1.143

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.
@@ -0,0 +1,41 @@
1
+ const USERS_TABLE = "auth_local_users";
2
+ const IDENTITIES_TABLE = "auth_local_identities";
3
+ const OAUTH_ATTEMPTS_TABLE = "auth_local_oauth_attempts";
4
+
5
+ exports.up = async function up(knex) {
6
+ if (!(await knex.schema.hasTable(IDENTITIES_TABLE))) {
7
+ await knex.schema.createTable(IDENTITIES_TABLE, (table) => {
8
+ table.string("user_id", 80).notNullable();
9
+ table.string("provider", 32).notNullable();
10
+ table.string("provider_subject", 255).notNullable();
11
+ table.string("email", 320).notNullable();
12
+ table.timestamp("created_at").notNullable();
13
+ table.primary(["provider", "provider_subject"], "pk_auth_local_identities");
14
+ table.index(["user_id"], "idx_auth_local_identities_user");
15
+ table.foreign(["user_id"], "fk_auth_local_identities_user").references(["id"]).inTable(USERS_TABLE).onUpdate("RESTRICT").onDelete("CASCADE");
16
+ });
17
+ }
18
+
19
+ // One pending provider sign-in or link, keyed by the hash of the starting
20
+ // browser's cookie; it is deleted when used and expires after ten minutes.
21
+ if (!(await knex.schema.hasTable(OAUTH_ATTEMPTS_TABLE))) {
22
+ await knex.schema.createTable(OAUTH_ATTEMPTS_TABLE, (table) => {
23
+ table.string("browser_key_hash", 128).primary();
24
+ table.string("provider", 32).notNullable();
25
+ table.string("intent", 16).notNullable();
26
+ table.string("user_id", 80).nullable();
27
+ table.string("state", 128).notNullable();
28
+ table.string("nonce", 128).notNullable();
29
+ table.string("code_verifier", 128).notNullable();
30
+ table.text("return_to").notNullable();
31
+ table.timestamp("expires_at").notNullable();
32
+ table.timestamp("created_at").notNullable();
33
+ table.index(["expires_at"], "idx_auth_local_oauth_attempts_expires");
34
+ });
35
+ }
36
+ };
37
+
38
+ exports.down = async function down(knex) {
39
+ await knex.schema.dropTableIfExists(OAUTH_ATTEMPTS_TABLE);
40
+ await knex.schema.dropTableIfExists(IDENTITIES_TABLE);
41
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-db-core",
3
- "version": "0.1.142",
3
+ "version": "0.1.143",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -10,7 +10,7 @@
10
10
  "./server/lib/index": "./src/server/lib/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/auth-provider-local-core": "0.2.1",
13
+ "@jskit-ai/auth-provider-local-core": "0.2.2",
14
14
  "@jskit-ai/database-runtime": "0.1.250"
15
15
  },
16
16
  "peerDependencies": {
@@ -52,6 +52,12 @@
52
52
  },
53
53
  {
54
54
  "tableName": "auth_local_recovery"
55
+ },
56
+ {
57
+ "tableName": "auth_local_identities"
58
+ },
59
+ {
60
+ "tableName": "auth_local_oauth_attempts"
55
61
  }
56
62
  ]
57
63
  }
@@ -3,7 +3,9 @@ import { isDuplicateEntryError } from "@jskit-ai/database-runtime/shared/duplica
3
3
  const TABLES = Object.freeze({
4
4
  users: "auth_local_users",
5
5
  sessions: "auth_local_sessions",
6
- recovery: "auth_local_recovery"
6
+ recovery: "auth_local_recovery",
7
+ identities: "auth_local_identities",
8
+ oauthAttempts: "auth_local_oauth_attempts"
7
9
  });
8
10
 
9
11
  function nowIso() {
@@ -95,6 +97,37 @@ function mapRecovery(row) {
95
97
  };
96
98
  }
97
99
 
100
+ function mapIdentity(row) {
101
+ if (!row) {
102
+ return null;
103
+ }
104
+ return {
105
+ userId: String(row.user_id || ""),
106
+ provider: String(row.provider || ""),
107
+ providerSubject: String(row.provider_subject || ""),
108
+ email: String(row.email || ""),
109
+ createdAt: readDateTime(row.created_at)
110
+ };
111
+ }
112
+
113
+ function mapOAuthAttempt(row) {
114
+ if (!row) {
115
+ return null;
116
+ }
117
+ return {
118
+ browserKeyHash: String(row.browser_key_hash || ""),
119
+ provider: String(row.provider || ""),
120
+ intent: String(row.intent || ""),
121
+ userId: String(row.user_id || ""),
122
+ state: String(row.state || ""),
123
+ nonce: String(row.nonce || ""),
124
+ codeVerifier: String(row.code_verifier || ""),
125
+ returnTo: String(row.return_to || ""),
126
+ createdAt: readDateTime(row.created_at),
127
+ expiresAt: readDateTime(row.expires_at)
128
+ };
129
+ }
130
+
98
131
  function userInsert(input = {}) {
99
132
  const createdAt = requiredDateTime(input.createdAt);
100
133
  return {
@@ -269,6 +302,69 @@ function createLocalDbBackend({ knex, transactionManager } = {}) {
269
302
  });
270
303
  return Number(count || 0);
271
304
  }
305
+ }),
306
+ identities: Object.freeze({
307
+ async create(input) {
308
+ const row = {
309
+ user_id: String(input.userId || ""),
310
+ provider: String(input.provider || ""),
311
+ provider_subject: String(input.providerSubject || ""),
312
+ email: String(input.email || ""),
313
+ created_at: requiredDateTime(input.createdAt)
314
+ };
315
+ await table(client, TABLES.identities).insert(row);
316
+ return mapIdentity(row);
317
+ },
318
+ async findByProviderSubject(provider, providerSubject) {
319
+ return mapIdentity(await table(client, TABLES.identities)
320
+ .where({ provider: String(provider || ""), provider_subject: String(providerSubject || "") })
321
+ .first());
322
+ },
323
+ async listForUser(userId) {
324
+ const rows = await table(client, TABLES.identities).where({ user_id: String(userId || "") });
325
+ return rows.map(mapIdentity);
326
+ },
327
+ async deleteForUser(userId, provider) {
328
+ const count = await table(client, TABLES.identities)
329
+ .where({ user_id: String(userId || ""), provider: String(provider || "") })
330
+ .delete();
331
+ return Number(count || 0);
332
+ }
333
+ }),
334
+ oauthAttempts: Object.freeze({
335
+ async create(input) {
336
+ const row = {
337
+ browser_key_hash: String(input.browserKeyHash || ""),
338
+ provider: String(input.provider || ""),
339
+ intent: String(input.intent || ""),
340
+ user_id: input.userId ? String(input.userId) : null,
341
+ state: String(input.state || ""),
342
+ nonce: String(input.nonce || ""),
343
+ code_verifier: String(input.codeVerifier || ""),
344
+ return_to: String(input.returnTo || ""),
345
+ expires_at: requiredDateTime(input.expiresAt),
346
+ created_at: requiredDateTime(input.createdAt)
347
+ };
348
+ await table(client, TABLES.oauthAttempts).insert(row);
349
+ return mapOAuthAttempt(row);
350
+ },
351
+ // Only the request whose delete removes the row gets the attempt, so
352
+ // concurrent callbacks on several servers cannot both use it.
353
+ async take(browserKeyHash) {
354
+ const where = { browser_key_hash: String(browserKeyHash || "") };
355
+ const row = await table(client, TABLES.oauthAttempts).where(where).first();
356
+ if (!row) {
357
+ return null;
358
+ }
359
+ const count = await table(client, TABLES.oauthAttempts).where(where).delete();
360
+ return Number(count || 0) === 1 ? mapOAuthAttempt(row) : null;
361
+ },
362
+ async deleteExpired(now) {
363
+ const count = await table(client, TABLES.oauthAttempts)
364
+ .where("expires_at", "<=", requiredDateTime(now))
365
+ .delete();
366
+ return Number(count || 0);
367
+ }
272
368
  })
273
369
  });
274
370
  }
@@ -0,0 +1,95 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import createKnex from "knex";
4
+ import initialMigration from "../migrations/auth_local_db_initial.cjs";
5
+ import oauthMigration from "../migrations/auth_local_db_oauth.cjs";
6
+ import { createLocalDbBackend, LOCAL_AUTH_DB_TABLES } from "../src/server/lib/index.js";
7
+ import {
8
+ ATTEMPT_COOKIE,
9
+ approveAtProvider,
10
+ createService,
11
+ oidcProviderEntry,
12
+ sessionCookies,
13
+ startOidcProvider
14
+ } from "../../auth-provider-local-core/test-support/oauthHarness.js";
15
+
16
+ async function databaseBackend(t) {
17
+ const knex = createKnex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
18
+ t.after(() => knex.destroy());
19
+ await knex.raw("PRAGMA foreign_keys = ON");
20
+ await initialMigration.up(knex);
21
+ await oauthMigration.up(knex);
22
+ const backend = createLocalDbBackend({
23
+ knex,
24
+ transactionManager: { inTransaction: (work) => knex.transaction(work) }
25
+ });
26
+ return { knex, backend };
27
+ }
28
+
29
+ test("provider sign-in and linking store identities and single-use attempts in the database", async (t) => {
30
+ const issuer = await startOidcProvider();
31
+ t.after(() => issuer.close());
32
+ const { knex, backend } = await databaseBackend(t);
33
+ const service = createService({ backend, oauthProviders: [oidcProviderEntry(issuer)] });
34
+
35
+ const { input, request } = await approveAtProvider(service);
36
+ assert.equal((await knex(LOCAL_AUTH_DB_TABLES.oauthAttempts).count({ count: "*" }))[0].count, 1);
37
+ const result = await service.oauthComplete(input, request);
38
+ assert.equal((await knex(LOCAL_AUTH_DB_TABLES.oauthAttempts).count({ count: "*" }))[0].count, 0);
39
+ await assert.rejects(service.oauthComplete(input, request), { code: "auth.local.oauth.expired" });
40
+
41
+ const user = await knex(LOCAL_AUTH_DB_TABLES.users).where({ email: issuer.account.email }).first();
42
+ assert.equal(user.password_hash, "", "a provider-created account has no password");
43
+ assert.deepEqual(
44
+ await knex(LOCAL_AUTH_DB_TABLES.identities).select("user_id", "provider", "provider_subject", "email"),
45
+ [{ user_id: user.id, provider: "google", provider_subject: issuer.account.sub, email: issuer.account.email }]
46
+ );
47
+
48
+ const status = await service.getSecurityStatus({ cookies: sessionCookies(result.session) });
49
+ assert.deepEqual(status.authMethods.map(({ id, enabled }) => [id, enabled]), [["password", false], ["oauth:google", true]]);
50
+ await assert.rejects(service.unlinkProvider({ cookies: sessionCookies(result.session) }, { provider: "google" }), {
51
+ code: "auth.local.oauth.lastMethod"
52
+ });
53
+
54
+ // Deleting the user removes its identities with it.
55
+ await knex(LOCAL_AUTH_DB_TABLES.users).where({ id: user.id }).delete();
56
+ assert.equal((await knex(LOCAL_AUTH_DB_TABLES.identities).count({ count: "*" }))[0].count, 0);
57
+ });
58
+
59
+ test("concurrent callbacks with one attempt complete at most once", async (t) => {
60
+ const { backend } = await databaseBackend(t);
61
+ const attempt = {
62
+ browserKeyHash: "browser-key-hash",
63
+ provider: "google",
64
+ intent: "login",
65
+ userId: "",
66
+ state: "state",
67
+ nonce: "nonce",
68
+ codeVerifier: "verifier",
69
+ returnTo: "/",
70
+ expiresAt: new Date(Date.now() + 60_000).toISOString()
71
+ };
72
+ await backend.withTransaction((tx) => tx.oauthAttempts.create(attempt));
73
+ const taken = await Promise.all([1, 2, 3].map(() => backend.withTransaction((tx) => tx.oauthAttempts.take(attempt.browserKeyHash))));
74
+ assert.equal(taken.filter(Boolean).length, 1);
75
+ assert.equal(taken.find(Boolean).state, "state");
76
+ assert.equal(taken.find(Boolean).userId, "");
77
+
78
+ await backend.withTransaction(async (tx) => {
79
+ await tx.oauthAttempts.create({ ...attempt, browserKeyHash: "old", expiresAt: new Date(Date.now() - 1000).toISOString() });
80
+ await tx.oauthAttempts.create({ ...attempt, browserKeyHash: "fresh" });
81
+ assert.equal(await tx.oauthAttempts.deleteExpired(new Date().toISOString()), 1);
82
+ assert.equal(await tx.oauthAttempts.take("old"), null);
83
+ });
84
+ });
85
+
86
+ test("an attempt cookie from another browser finds nothing", async (t) => {
87
+ const issuer = await startOidcProvider();
88
+ t.after(() => issuer.close());
89
+ const { backend } = await databaseBackend(t);
90
+ const service = createService({ backend, oauthProviders: [oidcProviderEntry(issuer)] });
91
+ const { input } = await approveAtProvider(service);
92
+ await assert.rejects(service.oauthComplete(input, { cookies: { [ATTEMPT_COOKIE]: "forged-browser-key" } }), {
93
+ code: "auth.local.oauth.expired"
94
+ });
95
+ });
@@ -477,7 +477,9 @@ test("package metadata declares portable local auth DB migrations without instal
477
477
  [
478
478
  LOCAL_AUTH_DB_TABLES.users,
479
479
  LOCAL_AUTH_DB_TABLES.sessions,
480
- LOCAL_AUTH_DB_TABLES.recovery
480
+ LOCAL_AUTH_DB_TABLES.recovery,
481
+ LOCAL_AUTH_DB_TABLES.identities,
482
+ LOCAL_AUTH_DB_TABLES.oauthAttempts
481
483
  ]
482
484
  );
483
485
  });