@jskit-ai/auth-provider-local-core 0.2.46 → 0.2.48

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - **Breaking, since 0.2.47 (JSKIT 0.2.111), which shipped it without this line:** every `auth.local.backend` gives `withRecords(callback)` beside `withTransaction(callback)`. It runs the callback on the same records outside a transaction, each call on its own, and answers what it answered; local auth reads each signed-in request's session and user through it, two statements a request in place of four (`BEGIN`, session, user, `COMMIT`). An application's own backend without it started and then failed every signed-in request with a 500 (`backend.withRecords is not a function`). Upgrading: add `withRecords` to the backend; one with no cheaper reads can give its `withTransaction`, as the file backend does (`@jskit-ai/auth-provider-local-db-core`'s reads without a transaction). An installed backend without `withRecords` or `withTransaction` now refuses to start, naming each missing method, what it must do and this fix.
5
6
  - `accountStateOf({ userId })` answers whether the local account `userId` names is `"active"` (with or without an authenticator), `"disabled"` or `"missing"`: one read of the account, beside `verifySecondFactorOf`, which refuses those accounts only when it checks a code. It checks no code, leaves the account's attempts and wait as they were, records no event and writes nothing; a missing `userId` is a `TypeError`. Unsupported, as every second-factor operation, on a production server without `AUTH_LOCAL_SECOND_FACTOR_KEY`.
6
7
  - `verifySecondFactorOf({ userId, proof })` checks an authenticator code or recovery code of the local account `userId` names, for the application, which decides whose and when (an API key's command asking for its creator's code, say). It is verifySecondFactor's own check: the same attempts, counted on the account's factor, so wrong codes through either make the account wait for both (five, then 30 seconds doubling to an hour, `AUTH_LOCAL_SIGN_IN_*`); the same once-only codes, so a code or recovery code accepted by one is refused by the other. It answers `{ verifiedAt, method, recoveryCodesLeft }` and marks no session. Refusals throw as verifySecondFactor's do: 404 `auth.local.secondFactor.accountNotFound` (new, message key `jskit.auth.local.secondFactor.accountNotFound`, "There is no such account.") for an id with no account, 403 `auth.local.secondFactor.accountDisabled` (new, message key `jskit.auth.local.secondFactor.accountDisabled`, "This account is disabled.") for a disabled account, even with its right code, 409 `notSetUp` for an account without a confirmed authenticator, 429 `locked` (with `Retry-After`) while it waits, 400 `codeInvalid`, `codeUsed`, `recoveryCodeInvalid` or `proofRequired`; a missing `userId` is a `TypeError`. Its outcome is a second-factor event as a session's is (`verified` with `method` and `recoveryCodesLeft`, or `failed` with its `reason`), marked `via: "application"` (new on `AuthLocalSecondFactorEvent`; a session's own events have none) with `ip` "", never a code; an unknown or disabled account and a missing factor record no event. The shared second-factor scenario runs it on the file backend and on `@jskit-ai/auth-provider-local-db-core`'s SQLite, MySQL and PostgreSQL.
7
8
  - Service keys: another application's server calls the app's bearer routes (`credentials: "bearer"`) with `Authorization: Bearer <key>` and `Act-As-User: <user id or email>` (an email only when exactly one enabled account has it, through the backend's new `users.findAllByEmail(email)`, which the file backend answers; more than one is refused as `auth.serviceKey.actAsAmbiguous`), and each call runs as exactly that user, with their rights, carrying the key's service user as `via`. A key is a sessions-store row of a dedicated service user with purpose `service-key` (`SERVICE_KEY_PURPOSE`), made by `createServiceKeyRecord({ userId, days? })` (365 days unless given, at most 3650) and written with the backend's `sessions.create`; no table or column changes. Revoking the row or disabling the service user ends it. A call without a key, with an unknown, revoked or expired key or a disabled key user, with a person's own sign-in token, without `Act-As-User`, naming an unknown or disabled user, or naming the key's own user is refused in words with its code (`auth.serviceKey.*`); none falls back to the key's user. A key never signs in a browser, and a cookie route ignores `Authorization`. `test/serviceKeys.test.js` proves each.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.46",
3
+ "version": "0.2.48",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -684,7 +684,9 @@ function createLocalFileBackend({ storeDir }) {
684
684
 
685
685
  return Object.freeze({
686
686
  storeDir: resolvedStoreDir,
687
- withTransaction
687
+ withTransaction,
688
+ // The files are read and written under the store's lock either way.
689
+ withRecords: withTransaction
688
690
  });
689
691
  }
690
692
 
@@ -209,9 +209,11 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
209
209
  await tx.sessions.touch(session.id, { lastSeenAt: new Date(now).toISOString(), ...requestClient(request) });
210
210
  }
211
211
 
212
+ // A request's session and user are read with no transaction around them: each read sees the latest rows, so a
213
+ // session revoked or an account disabled is refused from the next request on.
212
214
  async function resolveValidSessionByRefreshToken(refreshToken, request) {
213
215
  const tokenHash = sha256Base64url(refreshToken);
214
- return backend.withTransaction(async (tx) => {
216
+ return backend.withRecords(async (tx) => {
215
217
  const session = await tx.sessions.findByTokenHash(tokenHash);
216
218
  if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
217
219
  return null;
@@ -318,7 +320,7 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
318
320
  if (accessToken) {
319
321
  const payload = verifySignedToken(accessToken, config.sessionSecret);
320
322
  if (payload?.sid && payload?.sub) {
321
- const resolved = await backend.withTransaction(async (tx) => {
323
+ const resolved = await backend.withRecords(async (tx) => {
322
324
  const session = await tx.sessions.findById(String(payload.sid));
323
325
  if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
324
326
  return null;
@@ -24,6 +24,33 @@ import { createLoggedSignInEvents } from "../lib/sessions.js";
24
24
  // The emails each started auth service is still sending, by the service its setup gave out, for its shutdown.
25
25
  const deliveriesByService = new WeakMap();
26
26
 
27
+ // What each method local auth calls on an installed auth.local.backend must do, for the refusal that names one missing.
28
+ const BACKEND_METHODS = Object.freeze({
29
+ withTransaction: "withTransaction(callback) runs the callback in one transaction on the backend's records and " +
30
+ "answers what it answered.",
31
+ withRecords: "withRecords(callback) runs the callback on the same records outside a transaction, each call on its " +
32
+ "own, and answers what it answered: local auth reads each signed-in request's session and user through it since " +
33
+ "@jskit-ai/auth-provider-local-core 0.2.47 (JSKIT 0.2.111). A backend with no cheaper reads can give its " +
34
+ "withTransaction, as the file backend does."
35
+ });
36
+
37
+ /**
38
+ * Refuses, as the server starts, an installed auth.local.backend without a method local auth calls, which would
39
+ * otherwise fail at the first request that calls it: each signed-in request, for withRecords.
40
+ * @param {import("../types.js").AuthLocalBackend} backend
41
+ */
42
+ function requireBackendMethods(backend) {
43
+ // readable-check: allow method-probe - input validation: an application supplies its own auth.local.backend
44
+ const missing =Object.keys(BACKEND_METHODS).filter((name) => typeof backend[name] !== "function");
45
+ if (missing.length === 0) return;
46
+ throw new Error([
47
+ `The installed auth.local.backend has no ${missing.join(" and no ")}.`,
48
+ ...missing.map((name) => BACKEND_METHODS[name]),
49
+ `Add ${missing.length === 1 ? "it" : "them"} to the provider of auth.local.backend ` +
50
+ "(@jskit-ai/auth-provider-local-core's CHANGELOG says how)."
51
+ ].join(" "));
52
+ }
53
+
27
54
  /**
28
55
  * An installed email sender, sending as APP_ENV says (`deliverMessage`): production sends each email to its address;
29
56
  * staging only to STAGING_EMAIL_TO, passing the address it was for as `originalEmail`, or logs it when that is unset;
@@ -120,6 +147,7 @@ const AuthLocalProvider = defineProvider({
120
147
  { outputs }
121
148
  ) {
122
149
  const fileBackend = backend === null;
150
+ if (!fileBackend) requireBackendMethods(backend);
123
151
  const emailRecovery = recoverySender !== null;
124
152
  const emailConfirmationSender = confirmationSender !== null;
125
153
  const emailedChange = emailChangeSender !== null;
@@ -216,6 +216,9 @@
216
216
  * @typedef {object} AuthLocalBackend
217
217
  * @property {<T>(callback: (tx: AuthLocalBackendTransaction) => Promise<T>) => Promise<T>} withTransaction
218
218
  * Runs the callback in one transaction and answers what it answered.
219
+ * @property {<T>(callback: (records: AuthLocalBackendTransaction) => Promise<T>) => Promise<T>} withRecords
220
+ * Runs the callback on the same records outside a transaction, each call on its own, and answers what it answered:
221
+ * a request's authentication reads its session and its user this way, without a transaction's BEGIN and COMMIT.
219
222
  */
220
223
 
221
224
  /**
@@ -120,10 +120,12 @@ async function createStartedApp({
120
120
  logger = null,
121
121
  configureExtensions = null,
122
122
  signInEvents = null,
123
- emailChangeSender = null
123
+ emailChangeSender = null,
124
+ // The auth.local.backend to install: the file backend in the app's store directory unless a test gives its own.
125
+ installBackend = (storeDir) => createLocalFileBackend({ storeDir })
124
126
  } = {}) {
125
127
  const storeDir = await temporaryStoreDir("jskit-auth-local-");
126
- const backend = createLocalFileBackend({ storeDir });
128
+ const backend = installBackend(storeDir);
127
129
  const extensions = createAuthExtensions();
128
130
  const runtimeLogger = logger || {
129
131
  info() {},
@@ -463,6 +465,38 @@ test("local auth provider rejects dev login-as enablement in staging and product
463
465
  }
464
466
  });
465
467
 
468
+ // auth-provider-local-core 0.2.47 (JSKIT 0.2.111) made withRecords a method every auth.local.backend gives. An app's
469
+ // own backend without it started, and then every signed-in request failed ("backend.withRecords is not a function":
470
+ // 1,536 answers of 500 on one app); a backend without a method local auth calls now refuses to start, naming it, what
471
+ // it must do and the fix.
472
+ test("an installed auth.local.backend without withRecords or withTransaction refuses to start, naming each and what it must do", async () => {
473
+ const startup = async (omitted) => {
474
+ try {
475
+ await createStartedApp({
476
+ installBackend(storeDir) {
477
+ const backend = { ...createLocalFileBackend({ storeDir }) };
478
+ for (const name of omitted) delete backend[name];
479
+ return backend;
480
+ }
481
+ });
482
+ return "started";
483
+ } catch (error) {
484
+ return String(error.details?.cause?.message || error.message || "");
485
+ }
486
+ };
487
+ const withTransaction = "withTransaction(callback) runs the callback in one transaction on the backend's records " +
488
+ "and answers what it answered.";
489
+ const withRecords = "withRecords(callback) runs the callback on the same records outside a transaction, each call " +
490
+ "on its own, and answers what it answered: local auth reads each signed-in request's session and user through it " +
491
+ "since @jskit-ai/auth-provider-local-core 0.2.47 (JSKIT 0.2.111). A backend with no cheaper reads can give its " +
492
+ "withTransaction, as the file backend does.";
493
+ const fix = "to the provider of auth.local.backend (@jskit-ai/auth-provider-local-core's CHANGELOG says how).";
494
+ assert.equal(await startup(["withRecords"]), `The installed auth.local.backend has no withRecords. ${withRecords} Add it ${fix}`);
495
+ assert.equal(await startup(["withTransaction", "withRecords"]),
496
+ `The installed auth.local.backend has no withTransaction and no withRecords. ${withTransaction} ${withRecords} Add them ${fix}`);
497
+ assert.equal(await startup([]), "started", "a backend with both starts");
498
+ });
499
+
466
500
  test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to start, saying what to remove", async () => {
467
501
  await assert.rejects(
468
502
  () => createStartedApp({
@@ -21,15 +21,17 @@ async function startService(t) {
21
21
  }
22
22
  return tx.sessions[method](...args);
23
23
  }
24
+ const counted = (tx) => ({
25
+ ...tx,
26
+ sessions: Object.create(tx.sessions, {
27
+ findById: { value: (...args) => readSession(tx, "findById", args) },
28
+ findByTokenHash: { value: (...args) => readSession(tx, "findByTokenHash", args) }
29
+ })
30
+ });
24
31
  const backend = {
25
32
  ...files,
26
- withTransaction: (work) => files.withTransaction((tx) => work({
27
- ...tx,
28
- sessions: Object.create(tx.sessions, {
29
- findById: { value: (...args) => readSession(tx, "findById", args) },
30
- findByTokenHash: { value: (...args) => readSession(tx, "findByTokenHash", args) }
31
- })
32
- }))
33
+ withTransaction: (work) => files.withTransaction((tx) => work(counted(tx))),
34
+ withRecords: (work) => files.withRecords((tx) => work(counted(tx)))
33
35
  };
34
36
  const service = createLocalAuthService({ ...localServiceOptions(), backend });
35
37
  await service.register({ email: "ada@example.com", password: "correct horse" });