@jskit-ai/auth-provider-local-core 0.2.39 → 0.2.41

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,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A provider sign-in started from an invitation (`oauthStart({ provider, returnTo, invitationToken })`) keeps the token with its attempt (a thirteenth field of `oauth-attempts.passwd`; twelve-field records still read) and, at the end, resolves it through the invitation context resolver for the signed-in account and hands the result to profile synchronization (`source` and `invitation`), as a registration's invitation is handed on. An invitation the resolver refuses never fails the sign-in, which continues as one without; a failure that is not a refusal is logged.
6
+ - The password lockout names the email address, never an account: 429 `auth.local.login.locked` says "Password sign-in for this email address is paused for N minute(s) after too many failed attempts. Try again after that." (it said "Too many failed sign-ins for this account."). An address without an account waits the same way. Code, params (`count`, `retryAfterSeconds`) and `Retry-After` are unchanged.
5
7
  - **Breaking:** the local file auth backend in staging and production needs `AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK=true`, in place of `AUTH_LOCAL_FILE_PRODUCTION_ACK`, which it always needed in staging too; a server with the old variable set refuses to start, naming the new one. The resolved configuration (`resolveLocalAuthConfig`) names whether it runs in staging or production `isStagingOrProduction`, in place of `isDeployed`.
6
8
  - Email change: the signed-in person asks for a new email with their password (`requestEmailChange(request, { email, password })`), or the application asks for an account it chose, such as an operator's change for a person who lost their old address (`requestEmailChangeForUser({ userId, email })`, who may ask being the application's decision). The account keeps the address as its waiting change (`pendingEmail`) and the new address is sent a link to `/auth/email-change?token=`, signed with the session secret and working for a day; a newer request replaces the waiting change, so an earlier link stops working. Using it (`confirmEmailChange({ token })`) changes the email, which the link proves, ends the password resets sent to the old address and sends the old address a notice; the account's sessions stay signed in. Refusals: `auth.local.emailChange.passwordInvalid` (400), `sameEmail` (400), `emailTaken` (409, also when an account took the address since the link was sent), `linkInvalid` (400, a used, replaced, expired or altered link) and `accountNotFound` (404), each with its message key under `jskit.auth.local.emailChange`. The links and notices go through the new optional `auth.local.email-change-sender` capability (`AuthLocalEmailChangeSender`: `{ type: "confirmation", email, currentEmail, confirmationUrl }` or `{ type: "notice", email, newEmail }`) after the request has answered, through the local deliveries, and send as `APP_ENV` says, like the recovery and confirmation senders (production to each address, staging only to `STAGING_EMAIL_TO` with `originalEmail`, development and test to the log). Without one, development and test log them (`createLoggedEmailChangeSender`, new), and a staging or production server has no email change (`features.emailChange` false, the operations `AUTH_OPERATION_UNSUPPORTED`). A sender needs `APP_PUBLIC_URL`, which its links name.
7
9
  - Upgrading: `createLocalAuthService()` takes `emailChangeSender`, and `resolveLocalAuthConfig()` takes `emailChangeSender: true` when one is installed (`config.emailChangeDelivery` is `email`, `dev-log` or `off`); a custom `auth.local.backend` keeps a user's `pendingEmail` and implements `users.updatePendingEmail(userId, pendingEmail)` and `users.updateEmail(userId, email)`, which refuses an email another account has with `auth.local.accounts.exists` and clears the waiting change. The file backend adds `pendingEmail` to each line of `users.passwd` and reads the lines it wrote before as having none.
package/locales/en.json CHANGED
@@ -32,7 +32,7 @@
32
32
  "codeInvalid": "That is not this app's setup code. Copy it again from the server's log or its hosting service."
33
33
  },
34
34
  "login": {
35
- "locked": "Too many failed sign-ins for this account. Try again in {count} minute. | Too many failed sign-ins for this account. Try again in {count} minutes.",
35
+ "locked": "Password sign-in for this email address is paused for {count} minute after too many failed attempts. Try again after that. | Password sign-in for this email address is paused for {count} minutes after too many failed attempts. Try again after that.",
36
36
  "disabled": "This account is disabled."
37
37
  },
38
38
  "recovery": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.39",
3
+ "version": "0.2.41",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -12,7 +12,7 @@
12
12
  "./locales/en.json": "./locales/en.json"
13
13
  },
14
14
  "dependencies": {
15
- "@jskit-ai/auth-pass": "0.1.3",
15
+ "@jskit-ai/auth-pass": "0.1.5",
16
16
  "openid-client": "6.8.8"
17
17
  },
18
18
  "description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
@@ -73,7 +73,7 @@
73
73
  }
74
74
  },
75
75
  "peerDependencies": {
76
- "@jskit-ai/auth-core": "0.2.33",
77
- "@jskit-ai/kernel": "0.2.29"
76
+ "@jskit-ai/auth-core": "0.2.35",
77
+ "@jskit-ai/kernel": "0.2.31"
78
78
  }
79
79
  }
@@ -193,7 +193,8 @@ function parseOAuthAttempts(content) {
193
193
  const attempts = [];
194
194
  for (const line of String(content || "").split("\n").filter(Boolean)) {
195
195
  const parts = splitLine(line, "oauth_attempt");
196
- if (parts.length !== 12) {
196
+ // Twelve fields, or thirteen since an attempt keeps the invitation its sign-in started from.
197
+ if (parts.length !== 12 && parts.length !== 13) {
197
198
  throw new Error("Invalid OAuth attempt record field count.");
198
199
  }
199
200
  attempts.push({
@@ -206,7 +207,8 @@ function parseOAuthAttempts(content) {
206
207
  codeVerifier: parts[8],
207
208
  returnTo: decodeField(parts[9]),
208
209
  createdAt: decodeField(parts[10]),
209
- expiresAt: decodeField(parts[11])
210
+ expiresAt: decodeField(parts[11]),
211
+ invitationToken: decodeField(parts[12])
210
212
  });
211
213
  }
212
214
  return attempts;
@@ -228,7 +230,8 @@ function serializeOAuthAttempts(attempts) {
228
230
  attempt.codeVerifier,
229
231
  encodeField(attempt.returnTo),
230
232
  encodeField(attempt.createdAt),
231
- encodeField(attempt.expiresAt)
233
+ encodeField(attempt.expiresAt),
234
+ encodeField(attempt.invitationToken)
232
235
  ].join(":")
233
236
  )
234
237
  .join("\n") + (attempts.length > 0 ? "\n" : "");
@@ -18,6 +18,7 @@ const OAUTH_REDIRECT_PATH = "/auth/login";
18
18
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
19
19
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
20
20
  * @param {import("../types.js").AuthLocalFirstAccountSetup} dependencies.firstAccountSetup
21
+ * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
21
22
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
22
23
  * @param {Map<string, import("../types.js").AuthLocalOAuthProvider>} dependencies.oauthProvidersById
23
24
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
@@ -28,6 +29,7 @@ function createLocalOAuthFlows({
28
29
  backend,
29
30
  config,
30
31
  firstAccountSetup,
32
+ invitationContextResolver,
31
33
  logger,
32
34
  oauthProvidersById,
33
35
  profileProjector,
@@ -50,9 +52,10 @@ function createLocalOAuthFlows({
50
52
 
51
53
  /**
52
54
  * The attempt (state, nonce, PKCE verifier) is stored server-side under the
53
- * hash of a random key that only the starting browser holds in a cookie.
55
+ * hash of a random key that only the starting browser holds in a cookie. A
56
+ * sign-in started from an invitation keeps its token, for the sign-in's end.
54
57
  */
55
- async function beginOAuthAttempt(provider, { intent, userId = "", returnTo }) {
58
+ async function beginOAuthAttempt(provider, { intent, userId = "", returnTo, invitationToken = "" }) {
56
59
  const browserKey = randomToken(32);
57
60
  const attempt = {
58
61
  browserKeyHash: sha256Base64url(browserKey),
@@ -63,6 +66,7 @@ function createLocalOAuthFlows({
63
66
  nonce: randomToken(32),
64
67
  codeVerifier: randomToken(32),
65
68
  returnTo: normalizeReturnToPath(returnTo, { fallback: "/", allowedOrigins: [appOrigin] }),
69
+ invitationToken: String(invitationToken || "").trim(),
66
70
  expiresAt: isoFromNow(OAUTH_ATTEMPT_TTL_SECONDS)
67
71
  };
68
72
  const url = await oauthClients.authorizationUrl(provider, { ...attempt, redirectUri: oauthRedirectUri });
@@ -74,7 +78,11 @@ function createLocalOAuthFlows({
74
78
  }
75
79
 
76
80
  async function oauthStart(input) {
77
- return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "login", returnTo: input.returnTo });
81
+ return beginOAuthAttempt(requireOAuthProvider(input.provider), {
82
+ intent: "login",
83
+ returnTo: input.returnTo,
84
+ invitationToken: input.invitationToken
85
+ });
78
86
  }
79
87
 
80
88
  async function startProviderLink(request, input) {
@@ -97,12 +105,34 @@ function createLocalOAuthFlows({
97
105
  }
98
106
  }
99
107
 
108
+ /**
109
+ * The invitation a sign-in started from, as the invitation context resolver resolves it for the account, or null.
110
+ * An invitation never fails a sign-in: one it refuses (used, expired, withdrawn, for another address) is none.
111
+ * @param {string} token
112
+ * @param {string} email
113
+ */
114
+ async function signInInvitation(token, email) {
115
+ if (!token) {
116
+ return null;
117
+ }
118
+ try {
119
+ return await invitationContextResolver.resolveInvitationContext({ token, email });
120
+ } catch (error) {
121
+ // A refusal (4xx) is expected; anything else is worth a look.
122
+ if (!(error?.statusCode >= 400 && error.statusCode < 500)) {
123
+ logger.warn({ error }, "The invitation a provider sign-in started from could not be read; it signs in without it.");
124
+ }
125
+ return null;
126
+ }
127
+ }
128
+
100
129
  /**
101
130
  * Subject first, then a verified email that matches an existing user, then a
102
- * new user created like register; profile sync then provisions it as usual.
131
+ * new user created like register; profile sync then provisions it as usual,
132
+ * told of the invitation the sign-in started from.
103
133
  * The sign-in, and the refusal of a disabled account, are sign-in events.
104
134
  */
105
- async function signInWithOAuthIdentity(identity, request) {
135
+ async function signInWithOAuthIdentity(identity, request, invitationToken = "") {
106
136
  await firstAccountSetup.start();
107
137
  const result = await backend.withTransaction(async (tx) => {
108
138
  const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
@@ -143,8 +173,10 @@ function createLocalOAuthFlows({
143
173
  firstAccountSetup.accountCreated();
144
174
  }
145
175
  sessions.recordSignInEvent("signedIn", { ...method, userId: result.user.id, email: result.user.email }, request);
176
+ const invitation = await signInInvitation(invitationToken, result.user.email);
177
+ const profileOptions = invitation ? { source: invitation.source || "workspace-invite", invitation } : {};
146
178
  return {
147
- ...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
179
+ ...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector, profileOptions })),
148
180
  registered: result.registered
149
181
  };
150
182
  }
@@ -208,7 +240,7 @@ function createLocalOAuthFlows({
208
240
  const identity = await oauthClients.verifiedIdentity(provider, { callbackUrl, attempt });
209
241
  const result = attempt.intent === "link"
210
242
  ? await linkOAuthIdentity(request, attempt, identity, provider)
211
- : await signInWithOAuthIdentity(identity, request);
243
+ : await signInWithOAuthIdentity(identity, request, attempt.invitationToken);
212
244
  return { ...result, provider: provider.id, returnTo: attempt.returnTo };
213
245
  }
214
246
 
@@ -188,6 +188,7 @@ function createLocalAuthService({
188
188
  backend,
189
189
  config,
190
190
  firstAccountSetup,
191
+ invitationContextResolver,
191
192
  logger,
192
193
  oauthProvidersById,
193
194
  profileProjector,
@@ -120,14 +120,16 @@ function waitParams(waitMs) {
120
120
  }
121
121
 
122
122
  /**
123
- * The refusal of a sign-in while its account waits, with the minutes to wait;
124
- * Retry-After gives the exact seconds.
123
+ * The refusal of a password sign-in while its email address waits, with the minutes to wait; Retry-After gives the
124
+ * exact seconds. It names the email address, never an account: an address with no account waits the same, so the
125
+ * refusal does not tell whether one exists. The sign-in page adds the other ways forward it offers.
125
126
  * @param {number} waitMs
126
127
  */
127
128
  function signInLockedError(waitMs) {
128
129
  const params = waitParams(waitMs);
129
130
  const unit = params.count === 1 ? "minute" : "minutes";
130
- return new AppError(429, `Too many failed sign-ins for this account. Try again in ${params.count} ${unit}.`, {
131
+ const message = `Password sign-in for this email address is paused for ${params.count} ${unit} after too many failed attempts. Try again after that.`;
132
+ return new AppError(429, message, {
131
133
  code: "auth.local.login.locked",
132
134
  params,
133
135
  headers: { "retry-after": String(params.retryAfterSeconds) }
@@ -0,0 +1,111 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
7
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
8
+ import { createLocalFileBackend } from "../src/server/lib/index.js";
9
+ import { parseOAuthAttempts, serializeOAuthAttempts } from "../src/server/lib/fileRecords.js";
10
+ import { approveAtProvider, createService, oidcProviderEntry, startOidcProvider } from "../test-support/oauthHarness.js";
11
+
12
+ /**
13
+ * A Google sign-in over the file backend whose invitation context resolver answers `resolve(input)`, and whose
14
+ * profile sync records what each sign-in tells it.
15
+ */
16
+ async function invitationSetup(t, resolve) {
17
+ const issuer = await startOidcProvider();
18
+ t.after(() => issuer.close());
19
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-oauth-invite-"));
20
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
21
+ const synced = [];
22
+ const resolved = [];
23
+ const warnings = [];
24
+ const service = createService({
25
+ backend: createLocalFileBackend({ storeDir }),
26
+ oauthProviders: [oidcProviderEntry(issuer)],
27
+ profileProjector: {
28
+ async syncIdentityProfile(profile, options) {
29
+ synced.push({ email: profile.email, options });
30
+ return null;
31
+ },
32
+ async findByIdentity() {
33
+ return null;
34
+ }
35
+ },
36
+ invitationContextResolver: {
37
+ async resolveInvitationContext(input) {
38
+ resolved.push(input);
39
+ return resolve(input);
40
+ }
41
+ },
42
+ logger: { ...silentLogger, warn: (_details, message) => warnings.push(message) }
43
+ });
44
+ const signIn = async (invitationToken) => {
45
+ const { input, request } = await approveAtProvider(service, { invitationToken });
46
+ return service.oauthComplete(input, request);
47
+ };
48
+ return { issuer, storeDir, service, synced, resolved, warnings, signIn };
49
+ }
50
+
51
+ test("a provider sign-in started from an invitation keeps it to the end and gives profile sync the resolved invitation", async (t) => {
52
+ const invitation = { token: "invite-token", source: "workspace-invite", workspaceId: "3", email: "invited@example.com" };
53
+ const { issuer, storeDir, service, synced, resolved } = await invitationSetup(t, ({ token }) => ({ ...invitation, token }));
54
+
55
+ const { input, request } = await approveAtProvider(service, { invitationToken: " invite-token " });
56
+ const attempts = parseOAuthAttempts(await fs.readFile(path.join(storeDir, "oauth-attempts.passwd"), "utf8"));
57
+ assert.equal(attempts[0].invitationToken, "invite-token", "the attempt keeps the invitation across the provider's round trip");
58
+ const result = await service.oauthComplete(input, request);
59
+
60
+ assert.equal(result.actor.email, issuer.account.email);
61
+ assert.equal(result.returnTo, "/home");
62
+ assert.deepEqual(resolved, [{ token: "invite-token", email: issuer.account.email }]);
63
+ assert.deepEqual(synced, [{ email: issuer.account.email, options: { source: "workspace-invite", invitation } }]);
64
+
65
+ // A sign-in from no invitation asks the resolver nothing and tells profile sync nothing.
66
+ const { input: again, request: againRequest } = await approveAtProvider(service);
67
+ await service.oauthComplete(again, againRequest);
68
+ assert.equal(resolved.length, 1);
69
+ assert.deepEqual(synced[1], { email: issuer.account.email, options: {} });
70
+ });
71
+
72
+ test("an invitation the app refuses, or cannot read, never fails a provider sign-in, which goes on without it", async (t) => {
73
+ const { issuer, synced, warnings, signIn } = await invitationSetup(t, ({ token }) => {
74
+ if (token === "expired") {
75
+ throw new AppError(409, "This invitation has expired.", { code: "workspaces.invite.expired" });
76
+ }
77
+ throw new Error("The invitations store is unavailable.");
78
+ });
79
+
80
+ for (const token of ["expired", "unreadable"]) {
81
+ const result = await signIn(token);
82
+ assert.equal(result.actor.email, issuer.account.email, token);
83
+ assert.equal(result.session.purpose, "normal", token);
84
+ }
85
+
86
+ assert.deepEqual(synced.map(({ options }) => options), [{}, {}], "profile sync provisions as for no invitation");
87
+ assert.deepEqual(warnings, ["The invitation a provider sign-in started from could not be read; it signs in without it."],
88
+ "only the failure that is not a refusal is logged");
89
+ });
90
+
91
+ test("an OAuth attempt record written before attempts kept an invitation still reads, as one without", () => {
92
+ const attempt = {
93
+ browserKeyHash: "hash",
94
+ provider: "google",
95
+ intent: "login",
96
+ userId: "",
97
+ state: "state",
98
+ nonce: "nonce",
99
+ codeVerifier: "verifier",
100
+ returnTo: "/invite?token=a:b",
101
+ createdAt: "2026-11-20T10:00:00.000Z",
102
+ expiresAt: "2026-11-20T10:10:00.000Z",
103
+ invitationToken: "token:with:colons"
104
+ };
105
+ const line = serializeOAuthAttempts([attempt]);
106
+ assert.deepEqual(parseOAuthAttempts(line), [attempt]);
107
+
108
+ const twelveFields = `${line.trimEnd().split(":").slice(0, 12).join(":")}\n`;
109
+ assert.deepEqual(parseOAuthAttempts(twelveFields), [{ ...attempt, invitationToken: "" }]);
110
+ assert.throws(() => parseOAuthAttempts(`${line.trimEnd()}:extra\n`), /Invalid OAuth attempt record field count\./u);
111
+ });
@@ -132,15 +132,19 @@ function oidcProviderEntry(issuer, { id = "google", label = "Google" } = {}) {
132
132
  * @param {import("../src/server/types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup]
133
133
  * @param {Record<string, string>} [dependencies.env] Environment values over the test ones, such as another
134
134
  * APP_PUBLIC_URL.
135
+ * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} [dependencies.invitationContextResolver]
136
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} [dependencies.logger]
135
137
  */
136
- function createService({ backend, oauthProviders, profileProjector, firstAccountSetup, env = {} }) {
138
+ function createService({ backend, oauthProviders, profileProjector, firstAccountSetup, env = {}, invitationContextResolver, logger }) {
137
139
  const options = localServiceOptions({ env: { APP_PUBLIC_URL: APP_URL, ...env } });
138
140
  return createLocalAuthService({
139
141
  ...options,
140
142
  backend,
141
143
  config: { ...options.config, oauthProviders, oauthEnabled: oauthProviders.length > 0 },
142
144
  profileProjector,
143
- firstAccountSetup
145
+ firstAccountSetup,
146
+ ...(invitationContextResolver && { invitationContextResolver }),
147
+ ...(logger && { logger })
144
148
  });
145
149
  }
146
150
 
@@ -153,10 +157,10 @@ function sessionCookies(session) {
153
157
  * the provider approve it, and returns the callback input and browser request.
154
158
  * @param {ReturnType<typeof createService>} service
155
159
  */
156
- async function approveAtProvider(service, { provider = "google", returnTo = "/home", cookies = {}, link = false } = {}) {
160
+ async function approveAtProvider(service, { provider = "google", returnTo = "/home", cookies = {}, link = false, invitationToken } = {}) {
157
161
  const started = link
158
162
  ? await service.startProviderLink({ cookies }, { provider, returnTo })
159
- : await service.oauthStart({ provider, returnTo });
163
+ : await service.oauthStart({ provider, returnTo, ...(invitationToken && { invitationToken }) });
160
164
  const callback = await followAuthorization(started.url, { redirectPrefix: REDIRECT_URI });
161
165
  return {
162
166
  started,
@@ -14,6 +14,9 @@ function lockedFor(seconds) {
14
14
  assert.equal(error.code, "auth.local.login.locked");
15
15
  assert.deepEqual(error.params, { count: Math.ceil(seconds / 60), retryAfterSeconds: seconds });
16
16
  assert.equal(error.headers["retry-after"], String(seconds));
17
+ const minutes = Math.ceil(seconds / 60);
18
+ assert.equal(error.message, `Password sign-in for this email address is paused for ${minutes} minute${minutes === 1 ? "" : "s"} ` +
19
+ "after too many failed attempts. Try again after that.", "it names the address, never an account");
17
20
  return true;
18
21
  };
19
22
  }