@jskit-ai/auth-provider-local-core 0.2.32 → 0.2.34
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/package.json +6 -4
- package/src/server/lib/config.js +3 -0
- package/src/server/lib/fileBackend.js +33 -2
- package/src/server/lib/fileRecords.js +25 -0
- package/src/server/lib/passSignIn.js +58 -0
- package/src/server/lib/service.js +14 -0
- package/src/server/providers/AuthLocalProvider.js +9 -0
- package/src/server/types.js +14 -1
- package/test/passSignIn.test.js +121 -0
- package/test-support/passSignInScenario.js +111 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- The pass comes from `@jskit-ai/auth-pass/server`, a new dependency, instead of auth-core's removed `./server/passSignIn`; `AuthLocalPassIdentity` takes auth-pass's `AuthPass`. Pass sign-in behaves as before, with the same refusals and texts.
|
|
6
|
+
|
|
7
|
+
- One-time pass sign-in: with `AUTH_PASS_PUBLIC_KEY`, `AUTH_PASS_AUDIENCE` and `AUTH_PASS_RESOURCE` set, `signInWithPass({ pass })` checks a pass from `@jskit-ai/auth-core/server/passSignIn`, records it as used, and signs in the account the new `auth.local.pass-identity` capability names for it (`AuthLocalPassIdentity`, also `createLocalAuthService({ passIdentity })`); startup stops when the key is set and no mapping is installed. Each pass signs in once: the backend contract gains `passes.use({ id, expiresAt })` and `passes.deleteExpired(now)`, keyed by the hash of the pass's id and kept until 30 seconds after it expires, and the file backend keeps them in `passes.passwd`. Without the key, `signInWithPass` is refused as unsupported and nothing else changes.
|
|
5
8
|
- A dev sign-in (`devLoginAs`), a password sign-in, a recovery link's sign-in and a display-name change hold one database connection at a time. Each read or synchronized the application's profile inside local auth's transaction, and the profile projector (users-core's) reads and writes on a connection of its own, so one request held two pool connections, and as many such requests at once as the pool has connections each held one and waited for ever for another. The profile is now read or synchronized after local auth's transaction, as registration, OAuth sign-in and email confirmation already did; a dev sign-in finds its user in one transaction, reads the profile, and only then creates its session in another, so a user without a profile still gets none. Should synchronizing the profile fail after a sign-in's transaction committed, the sign-in still fails and its session is never handed out (it expires), as for a registration; a recovery link is then used up, and a changed display name stays changed until the next request's profile check synchronizes it.
|
|
6
9
|
- `AUTH_COOKIE_SAME_SITE=strict` makes every local auth cookie SameSite=Strict, and its clearing: the access, refresh, recovery and OAuth attempt cookies. Unset, blank or `lax` keeps them Lax, as before; any other value stops startup, naming the setting. OAuth sign-in works under `strict`: the provider's cross-site return only loads the login page, and the attempt cookie is read by that page's same-origin `POST /api/oauth/complete`. `resolveLocalAuthConfig()` returns `cookieSameSite`.
|
|
7
10
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.34",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
"./locales/en.json": "./locales/en.json"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
+
"@jskit-ai/auth-pass": "0.1.0",
|
|
15
16
|
"openid-client": "6.8.8"
|
|
16
17
|
},
|
|
17
18
|
"description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
|
|
@@ -52,7 +53,7 @@
|
|
|
52
53
|
},
|
|
53
54
|
{
|
|
54
55
|
"subpath": "./server/types",
|
|
55
|
-
"summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy, auth.local.recovery-sender, auth.local.confirmation-sender, auth.local.confirmation-mode
|
|
56
|
+
"summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy, auth.local.recovery-sender, auth.local.confirmation-sender, auth.local.confirmation-mode, auth.local.second-factor-events and auth.local.pass-identity capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
56
57
|
}
|
|
57
58
|
],
|
|
58
59
|
"extensionCapabilities": [
|
|
@@ -63,13 +64,14 @@
|
|
|
63
64
|
"auth.local.recovery-sender",
|
|
64
65
|
"auth.local.confirmation-sender",
|
|
65
66
|
"auth.local.confirmation-mode",
|
|
66
|
-
"auth.local.second-factor-events"
|
|
67
|
+
"auth.local.second-factor-events",
|
|
68
|
+
"auth.local.pass-identity"
|
|
67
69
|
]
|
|
68
70
|
}
|
|
69
71
|
}
|
|
70
72
|
},
|
|
71
73
|
"peerDependencies": {
|
|
72
|
-
"@jskit-ai/auth-core": "0.2.
|
|
74
|
+
"@jskit-ai/auth-core": "0.2.29",
|
|
73
75
|
"@jskit-ai/kernel": "0.2.26"
|
|
74
76
|
}
|
|
75
77
|
}
|
package/src/server/lib/config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parseBooleanFlag } from "@jskit-ai/auth-core/server/booleanFlag";
|
|
2
2
|
import { assertDevAuthPolicy, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
|
|
3
|
+
import { resolvePassSignInFromEnv } from "@jskit-ai/auth-pass/server";
|
|
3
4
|
import { randomBytes } from "node:crypto";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import path from "node:path";
|
|
@@ -233,6 +234,8 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
|
|
|
233
234
|
emailConfirmation: confirmationDelivery !== "off",
|
|
234
235
|
passwordMinLength: resolvePasswordMinLength(env),
|
|
235
236
|
signInThrottle: resolveSignInThrottle(env),
|
|
237
|
+
// The trusted issuer's key, audience and resource of one-time pass sign-in (AUTH_PASS_*), or null while it is off.
|
|
238
|
+
passSignIn: resolvePassSignInFromEnv(env),
|
|
236
239
|
devAuth
|
|
237
240
|
});
|
|
238
241
|
}
|
|
@@ -4,6 +4,7 @@ import { ConflictError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
|
4
4
|
import {
|
|
5
5
|
parseIdentities,
|
|
6
6
|
parseOAuthAttempts,
|
|
7
|
+
parsePasses,
|
|
7
8
|
parseRecovery,
|
|
8
9
|
parseRegistrations,
|
|
9
10
|
parseSecondFactors,
|
|
@@ -12,6 +13,7 @@ import {
|
|
|
12
13
|
parseUsers,
|
|
13
14
|
serializeIdentities,
|
|
14
15
|
serializeOAuthAttempts,
|
|
16
|
+
serializePasses,
|
|
15
17
|
serializeRecovery,
|
|
16
18
|
serializeRegistrations,
|
|
17
19
|
serializeSecondFactors,
|
|
@@ -28,6 +30,7 @@ const OAUTH_ATTEMPT_FILE = "oauth-attempts.passwd";
|
|
|
28
30
|
const SIGN_IN_FAILURE_FILE = "sign-in-failures.passwd";
|
|
29
31
|
const REGISTRATION_FILE = "registrations.passwd";
|
|
30
32
|
const SECOND_FACTOR_FILE = "second-factors.passwd";
|
|
33
|
+
const PASS_FILE = "passes.passwd";
|
|
31
34
|
const LOCK_FILE = "store.lock";
|
|
32
35
|
const JOURNAL_FILE = "transaction.journal";
|
|
33
36
|
const LOCK_STALE_MS = 30_000;
|
|
@@ -92,7 +95,8 @@ function parseJournal(content) {
|
|
|
92
95
|
OAUTH_ATTEMPT_FILE,
|
|
93
96
|
SIGN_IN_FAILURE_FILE,
|
|
94
97
|
REGISTRATION_FILE,
|
|
95
|
-
SECOND_FACTOR_FILE
|
|
98
|
+
SECOND_FACTOR_FILE,
|
|
99
|
+
PASS_FILE
|
|
96
100
|
];
|
|
97
101
|
if (!files.includes(name)) {
|
|
98
102
|
throw new Error("Invalid local auth transaction journal file.");
|
|
@@ -516,6 +520,26 @@ function createTx(state, touched) {
|
|
|
516
520
|
}
|
|
517
521
|
return count;
|
|
518
522
|
}
|
|
523
|
+
}),
|
|
524
|
+
passes: Object.freeze({
|
|
525
|
+
// The store lock holds every record until the transaction ends, so of two uses of one pass only the first records it.
|
|
526
|
+
async use({ id, expiresAt }) {
|
|
527
|
+
if (state.passes.some((record) => record.id === id)) {
|
|
528
|
+
return false;
|
|
529
|
+
}
|
|
530
|
+
state.passes.push({ id, expiresAt });
|
|
531
|
+
mark("passes");
|
|
532
|
+
return true;
|
|
533
|
+
},
|
|
534
|
+
async deleteExpired(now) {
|
|
535
|
+
const before = state.passes.length;
|
|
536
|
+
state.passes = state.passes.filter((record) => Date.parse(record.expiresAt) > Date.parse(now));
|
|
537
|
+
const count = before - state.passes.length;
|
|
538
|
+
if (count > 0) {
|
|
539
|
+
mark("passes");
|
|
540
|
+
}
|
|
541
|
+
return count;
|
|
542
|
+
}
|
|
519
543
|
})
|
|
520
544
|
});
|
|
521
545
|
}
|
|
@@ -536,7 +560,8 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
536
560
|
oauthAttempts: parseOAuthAttempts(await readText(path.join(resolvedStoreDir, OAUTH_ATTEMPT_FILE))),
|
|
537
561
|
signInFailures: parseSignInFailures(await readText(path.join(resolvedStoreDir, SIGN_IN_FAILURE_FILE))),
|
|
538
562
|
registrations: parseRegistrations(await readText(path.join(resolvedStoreDir, REGISTRATION_FILE))),
|
|
539
|
-
secondFactors: parseSecondFactors(await readText(path.join(resolvedStoreDir, SECOND_FACTOR_FILE)))
|
|
563
|
+
secondFactors: parseSecondFactors(await readText(path.join(resolvedStoreDir, SECOND_FACTOR_FILE))),
|
|
564
|
+
passes: parsePasses(await readText(path.join(resolvedStoreDir, PASS_FILE)))
|
|
540
565
|
};
|
|
541
566
|
const touched = new Set();
|
|
542
567
|
const result = await callback(createTx(state, touched));
|
|
@@ -589,6 +614,12 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
589
614
|
content: serializeSecondFactors(state.secondFactors)
|
|
590
615
|
});
|
|
591
616
|
}
|
|
617
|
+
if (touched.has("passes")) {
|
|
618
|
+
commitEntries.push({
|
|
619
|
+
name: PASS_FILE,
|
|
620
|
+
content: serializePasses(state.passes)
|
|
621
|
+
});
|
|
622
|
+
}
|
|
592
623
|
if (commitEntries.length > 0) {
|
|
593
624
|
await writeCommitJournal(resolvedStoreDir, commitEntries);
|
|
594
625
|
for (const entry of commitEntries) {
|
|
@@ -356,9 +356,33 @@ function serializeRegistrations(records) {
|
|
|
356
356
|
.join("\n") + (records.length > 0 ? "\n" : "");
|
|
357
357
|
}
|
|
358
358
|
|
|
359
|
+
// A used one-time pass: the hash of its id, and until when it is kept.
|
|
360
|
+
function parsePasses(content) {
|
|
361
|
+
const records = [];
|
|
362
|
+
for (const line of String(content || "").split("\n").filter(Boolean)) {
|
|
363
|
+
const parts = splitLine(line, "pass");
|
|
364
|
+
if (parts.length !== 4) {
|
|
365
|
+
throw new Error("Invalid pass record field count.");
|
|
366
|
+
}
|
|
367
|
+
records.push({
|
|
368
|
+
id: parts[2],
|
|
369
|
+
expiresAt: decodeField(parts[3])
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
return records;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function serializePasses(records) {
|
|
376
|
+
return [...records]
|
|
377
|
+
.sort((left, right) => String(left.id).localeCompare(String(right.id)))
|
|
378
|
+
.map((record) => ["pass", "v1", record.id, encodeField(record.expiresAt)].join(":"))
|
|
379
|
+
.join("\n") + (records.length > 0 ? "\n" : "");
|
|
380
|
+
}
|
|
381
|
+
|
|
359
382
|
export {
|
|
360
383
|
parseIdentities,
|
|
361
384
|
parseOAuthAttempts,
|
|
385
|
+
parsePasses,
|
|
362
386
|
parseRecovery,
|
|
363
387
|
parseRegistrations,
|
|
364
388
|
parseSecondFactors,
|
|
@@ -367,6 +391,7 @@ export {
|
|
|
367
391
|
parseUsers,
|
|
368
392
|
serializeIdentities,
|
|
369
393
|
serializeOAuthAttempts,
|
|
394
|
+
serializePasses,
|
|
370
395
|
serializeRecovery,
|
|
371
396
|
serializeRegistrations,
|
|
372
397
|
serializeSecondFactors,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { PASS_TEXTS, createPassError, verifyPass } from "@jskit-ai/auth-pass/server";
|
|
2
|
+
import { buildAuthPayload } from "./authPayloads.js";
|
|
3
|
+
import { sha256Base64url } from "./tokens.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The pass identity of a local auth service given none: it names no account, so every pass is refused as unmapped.
|
|
7
|
+
* The provider instead stops startup when AUTH_PASS_PUBLIC_KEY is set and no `auth.local.pass-identity` is installed.
|
|
8
|
+
* @type {import("../types.js").AuthLocalPassIdentity}
|
|
9
|
+
*/
|
|
10
|
+
async function noPassIdentities() {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Sign-in with a one-time signed pass (`@jskit-ai/auth-pass/server`), for a configuration whose passSignIn
|
|
16
|
+
* holds the issuer's key, audience and resource. A pass is checked, then recorded as used in the backend, so it signs
|
|
17
|
+
* in once however many servers share the backend's database, and then the application's pass identity names the
|
|
18
|
+
* account it signs in: one that is missing or disabled is refused as unmapped. The session is an ordinary one, as a
|
|
19
|
+
* password sign-in makes.
|
|
20
|
+
* @param {object} dependencies
|
|
21
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
22
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
23
|
+
* @param {import("../types.js").AuthLocalPassIdentity} dependencies.passIdentity The `auth.local.pass-identity`, or
|
|
24
|
+
* noPassIdentities.
|
|
25
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
26
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
27
|
+
*/
|
|
28
|
+
function createLocalPassSignIn({ backend, config, passIdentity, profileProjector, sessions }) {
|
|
29
|
+
const settings = config.passSignIn;
|
|
30
|
+
|
|
31
|
+
/** @param {{ pass: string }} input */
|
|
32
|
+
async function signInWithPass(input) {
|
|
33
|
+
const pass = verifyPass(input.pass, settings);
|
|
34
|
+
// Kept by the hash of its id, which the issuer chose, until the pass could no longer be used anyway. The expired
|
|
35
|
+
// ones go in a transaction of their own: in the same one, the range their delete locks would make two concurrent
|
|
36
|
+
// uses wait on each other's insert.
|
|
37
|
+
await backend.withTransaction((tx) => tx.passes.deleteExpired(new Date().toISOString()));
|
|
38
|
+
const firstUse = await backend.withTransaction((tx) =>
|
|
39
|
+
tx.passes.use({ id: sha256Base64url(pass.id), expiresAt: pass.usableUntil }));
|
|
40
|
+
if (!firstUse) {
|
|
41
|
+
throw createPassError(PASS_TEXTS.passReplayed);
|
|
42
|
+
}
|
|
43
|
+
const userId = await passIdentity(pass);
|
|
44
|
+
const user = userId ? await backend.withTransaction((tx) => tx.users.findById(userId)) : null;
|
|
45
|
+
if (!user || user.disabled) {
|
|
46
|
+
throw createPassError(PASS_TEXTS.passUnmapped);
|
|
47
|
+
}
|
|
48
|
+
const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user));
|
|
49
|
+
// After the transaction, as a password sign-in does: the profile projector works in transactions of its own.
|
|
50
|
+
return buildAuthPayload({ user, session, profileProjector });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
signInWithPass
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { createLocalPassSignIn, noPassIdentities };
|
|
@@ -7,6 +7,7 @@ import { PROVIDER_ID } from "./authPayloads.js";
|
|
|
7
7
|
import { confirmEveryRegistrationByLink, createLocalEmailConfirmation } from "./emailConfirmation.js";
|
|
8
8
|
import { createFirstAccountSetup } from "./firstAccountSetup.js";
|
|
9
9
|
import { createLocalOAuthFlows } from "./oauthFlows.js";
|
|
10
|
+
import { createLocalPassSignIn, noPassIdentities } from "./passSignIn.js";
|
|
10
11
|
import { createLocalPasswordFlows } from "./passwordFlows.js";
|
|
11
12
|
import { normalizePasswordStrategy } from "./passwords.js";
|
|
12
13
|
import { createLocalSecondFactor } from "./secondFactor.js";
|
|
@@ -25,6 +26,11 @@ const NO_SECOND_FACTOR = Object.freeze({
|
|
|
25
26
|
resetSecondFactor: () => throwUnsupportedAuthOperation("resetSecondFactor")
|
|
26
27
|
});
|
|
27
28
|
|
|
29
|
+
// Without AUTH_PASS_PUBLIC_KEY no pass signs anyone in.
|
|
30
|
+
const NO_PASS_SIGN_IN = Object.freeze({
|
|
31
|
+
signInWithPass: () => throwUnsupportedAuthOperation("signInWithPass")
|
|
32
|
+
});
|
|
33
|
+
|
|
28
34
|
/**
|
|
29
35
|
* The `auth.service` of local auth, from the collaborators its provider
|
|
30
36
|
* resolved once.
|
|
@@ -39,6 +45,8 @@ const NO_SECOND_FACTOR = Object.freeze({
|
|
|
39
45
|
* account's setup code, already started by the provider; by default, one that starts on first use.
|
|
40
46
|
* @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
|
|
41
47
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
48
|
+
* @param {import("../types.js").AuthLocalPassIdentity} [dependencies.passIdentity] The `auth.local.pass-identity`,
|
|
49
|
+
* which names the account a one-time pass signs in; by default none, so every pass is refused as unmapped.
|
|
42
50
|
* @param {import("../types.js").AuthLocalPasswordStrategy} dependencies.passwordStrategy The
|
|
43
51
|
* `auth.local.password-strategy`, or scryptPasswordStrategy.
|
|
44
52
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector The
|
|
@@ -56,6 +64,7 @@ function createLocalAuthService({
|
|
|
56
64
|
firstAccountSetup: givenFirstAccountSetup = null,
|
|
57
65
|
invitationContextResolver,
|
|
58
66
|
logger,
|
|
67
|
+
passIdentity = noPassIdentities,
|
|
59
68
|
passwordStrategy,
|
|
60
69
|
profileProjector,
|
|
61
70
|
recoverySender,
|
|
@@ -164,6 +173,10 @@ function createLocalAuthService({
|
|
|
164
173
|
? createLocalSecondFactor({ backend, config, logger, secondFactorEvents, sessions })
|
|
165
174
|
: NO_SECOND_FACTOR;
|
|
166
175
|
|
|
176
|
+
const passSignIn = config.passSignIn
|
|
177
|
+
? createLocalPassSignIn({ backend, config, passIdentity, profileProjector, sessions })
|
|
178
|
+
: NO_PASS_SIGN_IN;
|
|
179
|
+
|
|
167
180
|
function getCapabilities() {
|
|
168
181
|
if (firstAccountSetup.isWaiting()) {
|
|
169
182
|
return capabilitiesWaitingForFirstAccount;
|
|
@@ -210,6 +223,7 @@ function createLocalAuthService({
|
|
|
210
223
|
resendRegisterConfirmation,
|
|
211
224
|
confirmRegistration,
|
|
212
225
|
login: accounts.login,
|
|
226
|
+
signInWithPass: passSignIn.signInWithPass,
|
|
213
227
|
requestOtpLogin,
|
|
214
228
|
verifyOtpLogin,
|
|
215
229
|
writeOAuthStartCookies: oauthFlows.writeOAuthStartCookies,
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
} from "../lib/emailConfirmation.js";
|
|
14
14
|
import { createLocalFileBackend } from "../lib/fileBackend.js";
|
|
15
15
|
import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
|
|
16
|
+
import { noPassIdentities } from "../lib/passSignIn.js";
|
|
16
17
|
import { createLoggedRecoverySender, createSimulatedRecoverySender } from "../lib/passwordFlows.js";
|
|
17
18
|
import { scryptPasswordStrategy } from "../lib/passwords.js";
|
|
18
19
|
import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
|
|
@@ -30,6 +31,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
30
31
|
backend: "auth.local.backend",
|
|
31
32
|
confirmationMode: "auth.local.confirmation-mode",
|
|
32
33
|
confirmationSender: "auth.local.confirmation-sender",
|
|
34
|
+
passIdentity: "auth.local.pass-identity",
|
|
33
35
|
passwordStrategy: "auth.local.password-strategy",
|
|
34
36
|
profileProjector: "auth.profile.projector",
|
|
35
37
|
recoverySender: "auth.local.recovery-sender",
|
|
@@ -52,6 +54,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
52
54
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
|
|
53
55
|
* @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
|
|
54
56
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
57
|
+
* @param {import("../types.js").AuthLocalPassIdentity | null} dependencies.passIdentity The `auth.local.pass-identity`,
|
|
58
|
+
* when one is installed: required while AUTH_PASS_PUBLIC_KEY turns on pass sign-in.
|
|
55
59
|
* @param {import("../types.js").AuthLocalPasswordStrategy | null} dependencies.passwordStrategy The `auth.local.password-strategy`, when one is installed.
|
|
56
60
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
|
|
57
61
|
* @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
|
|
@@ -67,6 +71,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
67
71
|
env,
|
|
68
72
|
extensions,
|
|
69
73
|
logger,
|
|
74
|
+
passIdentity,
|
|
70
75
|
passwordStrategy,
|
|
71
76
|
profileProjector,
|
|
72
77
|
recoverySender,
|
|
@@ -78,6 +83,9 @@ const AuthLocalProvider = defineProvider({
|
|
|
78
83
|
const emailRecovery = recoverySender !== null;
|
|
79
84
|
const emailConfirmationSender = confirmationSender !== null;
|
|
80
85
|
const config = resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender });
|
|
86
|
+
if (config.passSignIn && passIdentity === null) {
|
|
87
|
+
throw new Error("AUTH_PASS_PUBLIC_KEY turns on one-time pass sign-in, and no auth.local.pass-identity is installed to name the account each pass signs in. Install one, or unset AUTH_PASS_PUBLIC_KEY.");
|
|
88
|
+
}
|
|
81
89
|
const localBackend = fileBackend ? createLocalFileBackend({ storeDir: config.storeDir }) : backend;
|
|
82
90
|
// A production server without accounts logs its setup code as it starts.
|
|
83
91
|
const firstAccountSetup = createFirstAccountSetup({ backend: localBackend, config, logger });
|
|
@@ -95,6 +103,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
95
103
|
firstAccountSetup,
|
|
96
104
|
invitationContextResolver: extensions.resolveInvitationContextResolver(),
|
|
97
105
|
logger,
|
|
106
|
+
passIdentity: passIdentity ?? noPassIdentities,
|
|
98
107
|
passwordStrategy: passwordStrategy ?? scryptPasswordStrategy,
|
|
99
108
|
profileProjector: profileProjector ?? noAppProfiles,
|
|
100
109
|
recoverySender: emailRecovery
|
package/src/server/types.js
CHANGED
|
@@ -68,6 +68,19 @@
|
|
|
68
68
|
* }} registrations Registrations waiting for their email to be confirmed, one per
|
|
69
69
|
* email; `save` replaces the email's registration. Saved only while
|
|
70
70
|
* AUTH_LOCAL_EMAIL_CONFIRMATION is on; a sign-in reads them whatever it says.
|
|
71
|
+
* @property {{
|
|
72
|
+
* use(input: { id: string, expiresAt: string }): Promise<boolean>,
|
|
73
|
+
* deleteExpired(now: string): Promise<number>
|
|
74
|
+
* }} passes The one-time passes already used, by the hash of each pass's id: `use` records one and answers true, or
|
|
75
|
+
* answers false when it was recorded before, also when another server recorded it at the same moment; a record is
|
|
76
|
+
* kept until `expiresAt` (its pass's `usableUntil`), and `deleteExpired` removes those whose time has come.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The `auth.local.pass-identity` capability: the application's mapping from a verified one-time pass
|
|
81
|
+
* (`@jskit-ai/auth-pass/server`) to the local account it signs in, by the account's id, or null when the
|
|
82
|
+
* pass's subject has none, which refuses the pass as unmapped. Required while AUTH_PASS_PUBLIC_KEY is set.
|
|
83
|
+
* @typedef {(pass: import("@jskit-ai/auth-pass/server").AuthPass) => Promise<string | null>} AuthLocalPassIdentity
|
|
71
84
|
*/
|
|
72
85
|
|
|
73
86
|
/**
|
|
@@ -140,7 +153,7 @@
|
|
|
140
153
|
/**
|
|
141
154
|
* The `auth.local.backend` capability: where local auth keeps its users,
|
|
142
155
|
* sessions, recovery tokens, linked identities, OAuth attempts, failed
|
|
143
|
-
* sign-ins, unconfirmed registrations and
|
|
156
|
+
* sign-ins, unconfirmed registrations, second factors and used one-time passes. Without
|
|
144
157
|
* one, local auth keeps them in files under AUTH_LOCAL_STORE_DIR;
|
|
145
158
|
* `@jskit-ai/auth-provider-local-db-core` provides one that keeps them in the
|
|
146
159
|
* database. Each backend implements this contract.
|
|
@@ -0,0 +1,121 @@
|
|
|
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 { createAuthExtensions } from "@jskit-ai/auth-core/server/authExtensions";
|
|
7
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
8
|
+
import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
9
|
+
import { AuthLocalProvider } from "../src/server/providers/AuthLocalProvider.js";
|
|
10
|
+
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
11
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
12
|
+
import { createPassIssuer, exercisePassSignIn, passIdentityByEmail, passwordlessAccount } from "../test-support/passSignInScenario.js";
|
|
13
|
+
|
|
14
|
+
async function temporaryStoreDir(t) {
|
|
15
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-pass-"));
|
|
16
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
17
|
+
return storeDir;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function startService(backend, issuer, env = issuer.env) {
|
|
21
|
+
return createLocalAuthService({ ...localServiceOptions({ env }), backend, passIdentity: passIdentityByEmail(backend) });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
test("a one-time pass signs its person in once, and every other pass is refused with its reason (file backend)", async (t) => {
|
|
25
|
+
const issuer = createPassIssuer();
|
|
26
|
+
const backend = createLocalFileBackend({ storeDir: await temporaryStoreDir(t) });
|
|
27
|
+
await exercisePassSignIn(startService(backend, issuer), { backend, issuer });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test("the file backend keeps used passes by their hash in its store, so another server on the store refuses them", async (t) => {
|
|
31
|
+
const issuer = createPassIssuer();
|
|
32
|
+
const storeDir = await temporaryStoreDir(t);
|
|
33
|
+
const first = createLocalFileBackend({ storeDir });
|
|
34
|
+
await first.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
|
|
35
|
+
const pass = issuer.pass("ada@example.com", { id: "pass-on-two-servers" });
|
|
36
|
+
|
|
37
|
+
assert.equal((await startService(first, issuer).signInWithPass({ pass })).actor.id, "usr_ada");
|
|
38
|
+
const stored = await fs.readFile(path.join(storeDir, "passes.passwd"), "utf8");
|
|
39
|
+
assert.match(stored, /^pass:v1:[\w-]{43}:[\w-]+\n$/u);
|
|
40
|
+
assert.doesNotMatch(stored, /pass-on-two-servers/u);
|
|
41
|
+
|
|
42
|
+
const second = createLocalFileBackend({ storeDir });
|
|
43
|
+
await assert.rejects(startService(second, issuer).signInWithPass({ pass }), { status: 401, code: "auth.pass.replayed" });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("used passes are forgotten once they could no longer be used, so the store holds only the last minutes' passes", async (t) => {
|
|
47
|
+
t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-13T10:00:00.000Z") });
|
|
48
|
+
const issuer = createPassIssuer();
|
|
49
|
+
const storeDir = await temporaryStoreDir(t);
|
|
50
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
51
|
+
await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
|
|
52
|
+
const service = startService(backend, issuer);
|
|
53
|
+
await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
|
|
54
|
+
await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
|
|
55
|
+
const lines = async () => (await fs.readFile(path.join(storeDir, "passes.passwd"), "utf8")).split("\n").filter(Boolean);
|
|
56
|
+
assert.equal((await lines()).length, 2);
|
|
57
|
+
|
|
58
|
+
// 60 seconds of life and 30 of clock skew later, the next use deletes them.
|
|
59
|
+
t.mock.timers.tick(90_000);
|
|
60
|
+
await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
|
|
61
|
+
assert.equal((await lines()).length, 1);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("without AUTH_PASS_PUBLIC_KEY, pass sign-in is not offered and a pass is refused as unsupported", async (t) => {
|
|
65
|
+
const issuer = createPassIssuer();
|
|
66
|
+
const backend = createLocalFileBackend({ storeDir: await temporaryStoreDir(t) });
|
|
67
|
+
const service = startService(backend, issuer, {});
|
|
68
|
+
await assert.rejects(async () => service.signInWithPass({ pass: issuer.pass("ada@example.com") }),
|
|
69
|
+
{ status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Local auth started as an application starts it, on the file store `storeDir`, with the env and capabilities given.
|
|
74
|
+
* @param {import("node:test").TestContext} t
|
|
75
|
+
* @param {string} storeDir
|
|
76
|
+
* @param {Record<string, string>} env
|
|
77
|
+
* @param {Record<string, unknown>} [capabilities]
|
|
78
|
+
*/
|
|
79
|
+
async function startProvider(t, storeDir, env, capabilities = {}) {
|
|
80
|
+
let authService = null;
|
|
81
|
+
const probe = defineProvider({
|
|
82
|
+
id: "test.auth.pass-probe",
|
|
83
|
+
requires: { service: "auth.service" },
|
|
84
|
+
setup({ service }) {
|
|
85
|
+
authService = service;
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
const runtime = createCapabilityRuntime({
|
|
90
|
+
inputs: {
|
|
91
|
+
"runtime.app-root": storeDir,
|
|
92
|
+
"runtime.env": { NODE_ENV: "test", AUTH_LOCAL_STORE_DIR: storeDir, APP_PUBLIC_URL: "http://localhost:5173", ...env },
|
|
93
|
+
"runtime.logger": silentLogger,
|
|
94
|
+
"auth.extensions": createAuthExtensions(),
|
|
95
|
+
...capabilities
|
|
96
|
+
},
|
|
97
|
+
providers: [AuthLocalProvider, probe]
|
|
98
|
+
});
|
|
99
|
+
await runtime.start();
|
|
100
|
+
t.after(() => runtime.shutdown());
|
|
101
|
+
return authService;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const startupError = (pattern) => (error) => pattern.test(String(error.details?.cause?.message || error.message));
|
|
105
|
+
|
|
106
|
+
test("with AUTH_PASS_PUBLIC_KEY set, startup needs its audience, resource and an auth.local.pass-identity, the mapping it signs in through", async (t) => {
|
|
107
|
+
const issuer = createPassIssuer();
|
|
108
|
+
const storeDir = await temporaryStoreDir(t);
|
|
109
|
+
await createLocalFileBackend({ storeDir }).withTransaction((tx) =>
|
|
110
|
+
tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
|
|
111
|
+
const unixUsers = { "auth.local.pass-identity": async (pass) => (pass.subject === "unix:ada" ? "usr_ada" : null) };
|
|
112
|
+
|
|
113
|
+
await assert.rejects(startProvider(t, storeDir, issuer.env),
|
|
114
|
+
startupError(/^AUTH_PASS_PUBLIC_KEY turns on one-time pass sign-in, and no auth\.local\.pass-identity is installed/u));
|
|
115
|
+
await assert.rejects(startProvider(t, storeDir, { ...issuer.env, AUTH_PASS_RESOURCE: "" }, unixUsers),
|
|
116
|
+
startupError(/AUTH_PASS_AUDIENCE and AUTH_PASS_RESOURCE are required/u));
|
|
117
|
+
|
|
118
|
+
const service = await startProvider(t, storeDir, issuer.env, unixUsers);
|
|
119
|
+
assert.equal((await service.signInWithPass({ pass: issuer.pass("unix:ada") })).actor.email, "ada@example.com");
|
|
120
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("unix:bob") }), { status: 403, code: "auth.pass.unmapped" });
|
|
121
|
+
});
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { generateKeyPairSync } from "node:crypto";
|
|
3
|
+
import { signPass } from "@jskit-ai/auth-pass/server";
|
|
4
|
+
import { NO_PASSWORD } from "../src/server/lib/accounts.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A pass issuer of the test's own: the env that makes local auth trust its key, for the application "editor" on the
|
|
8
|
+
* resource "machine-7", and the passes it signs.
|
|
9
|
+
*/
|
|
10
|
+
function createPassIssuer() {
|
|
11
|
+
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
|
|
12
|
+
return Object.freeze({
|
|
13
|
+
privateKey,
|
|
14
|
+
env: Object.freeze({
|
|
15
|
+
AUTH_PASS_PUBLIC_KEY: publicKey.export({ type: "spki", format: "der" }).toString("base64"),
|
|
16
|
+
AUTH_PASS_AUDIENCE: "editor",
|
|
17
|
+
AUTH_PASS_RESOURCE: "machine-7"
|
|
18
|
+
}),
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} subject
|
|
21
|
+
* @param {Partial<Parameters<typeof signPass>[0]>} [overrides]
|
|
22
|
+
*/
|
|
23
|
+
pass(subject, overrides = {}) {
|
|
24
|
+
return signPass({ privateKey, subject, audience: "editor", resource: "machine-7", ...overrides });
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The application's mapping in these tests: a pass's subject is the email of the account it signs in, and the
|
|
31
|
+
* subject "ghost" names an account id that does not exist.
|
|
32
|
+
* @param {import("../src/server/types.js").AuthLocalBackend} backend
|
|
33
|
+
* @returns {import("../src/server/types.js").AuthLocalPassIdentity}
|
|
34
|
+
*/
|
|
35
|
+
function passIdentityByEmail(backend) {
|
|
36
|
+
return async (pass) => {
|
|
37
|
+
if (pass.subject === "ghost") {
|
|
38
|
+
return "usr_missing";
|
|
39
|
+
}
|
|
40
|
+
const user = await backend.withTransaction((tx) => tx.users.findByEmail(pass.subject));
|
|
41
|
+
return user ? user.id : null;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* An account a pass signs in, as an application whose people sign in only with passes makes it: without a password.
|
|
47
|
+
* @param {{ id: string, email: string, displayName: string, disabled?: boolean }} account
|
|
48
|
+
*/
|
|
49
|
+
function passwordlessAccount({ id, email, displayName, disabled = false }) {
|
|
50
|
+
return { id, email, displayName, password: NO_PASSWORD, disabled };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sessionCookies(session) {
|
|
54
|
+
return { jskit_local_access_token: session.access_token, jskit_local_refresh_token: session.refresh_token };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const refused = (code, status = 401) => ({ status, code });
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Pass sign-in against any backend, for a service given the issuer's env and passIdentityByEmail: a pass signs its
|
|
61
|
+
* person in once, without a password, and every other pass is refused with its reason.
|
|
62
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthService} service
|
|
63
|
+
* @param {object} fixtures
|
|
64
|
+
* @param {import("../src/server/types.js").AuthLocalBackend} fixtures.backend
|
|
65
|
+
* @param {ReturnType<typeof createPassIssuer>} fixtures.issuer
|
|
66
|
+
*/
|
|
67
|
+
async function exercisePassSignIn(service, { backend, issuer }) {
|
|
68
|
+
await backend.withTransaction(async (tx) => {
|
|
69
|
+
await tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" }));
|
|
70
|
+
await tx.users.create(passwordlessAccount({ id: "usr_off", email: "off@example.com", displayName: "Off", disabled: true }));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// A pass signs its person in, with an ordinary session, though the account has no password.
|
|
74
|
+
const pass = issuer.pass("ada@example.com");
|
|
75
|
+
const signedIn = await service.signInWithPass({ pass });
|
|
76
|
+
assert.equal(signedIn.actor.id, "usr_ada");
|
|
77
|
+
assert.equal(signedIn.actor.email, "ada@example.com");
|
|
78
|
+
const authenticated = await service.authenticateRequest({ cookies: sessionCookies(signedIn.session) });
|
|
79
|
+
assert.equal(authenticated.authenticated, true);
|
|
80
|
+
assert.equal(authenticated.actor.id, "usr_ada");
|
|
81
|
+
|
|
82
|
+
// Only once.
|
|
83
|
+
await assert.rejects(service.signInWithPass({ pass }), refused("auth.pass.replayed"));
|
|
84
|
+
// Another pass for the same person signs in again.
|
|
85
|
+
assert.equal((await service.signInWithPass({ pass: issuer.pass("ada@example.com") })).actor.id, "usr_ada");
|
|
86
|
+
|
|
87
|
+
// A pass whose subject has no account, names an account that does not exist, or names a disabled one.
|
|
88
|
+
for (const subject of ["nobody@example.com", "ghost", "off@example.com"]) {
|
|
89
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass(subject) }), refused("auth.pass.unmapped", 403));
|
|
90
|
+
}
|
|
91
|
+
// An unmapped pass was used all the same: it is refused as replayed, even once its subject has an account.
|
|
92
|
+
const early = issuer.pass("late@example.com");
|
|
93
|
+
await assert.rejects(service.signInWithPass({ pass: early }), refused("auth.pass.unmapped", 403));
|
|
94
|
+
await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_late", email: "late@example.com", displayName: "Late" })));
|
|
95
|
+
await assert.rejects(service.signInWithPass({ pass: early }), refused("auth.pass.replayed"));
|
|
96
|
+
|
|
97
|
+
// A pass for another application or resource, signed by another key, expired, or not a pass at all.
|
|
98
|
+
const stranger = generateKeyPairSync("ed25519");
|
|
99
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("ada@example.com", { audience: "console" }) }),
|
|
100
|
+
refused("auth.pass.wrongAudience"));
|
|
101
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("ada@example.com", { resource: "machine-8" }) }),
|
|
102
|
+
refused("auth.pass.wrongResource"));
|
|
103
|
+
await assert.rejects(service.signInWithPass({ pass: signPass({
|
|
104
|
+
privateKey: stranger.privateKey, subject: "ada@example.com", audience: "editor", resource: "machine-7"
|
|
105
|
+
}) }), refused("auth.pass.badSignature"));
|
|
106
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("ada@example.com", { now: Date.now() - 91_000 }) }),
|
|
107
|
+
refused("auth.pass.expired"));
|
|
108
|
+
await assert.rejects(service.signInWithPass({ pass: "not a pass" }), refused("auth.pass.malformed"));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export { createPassIssuer, exercisePassSignIn, passIdentityByEmail, passwordlessAccount, sessionCookies };
|