@softure-ai/auth 0.1.11 → 0.1.13
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 +27 -0
- package/README.md +65 -9
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +1 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +26 -1
- package/dist/options.js.map +1 -1
- package/dist/proxy/index.d.ts +11 -0
- package/dist/proxy/index.d.ts.map +1 -1
- package/dist/proxy/index.js +11 -3
- package/dist/proxy/index.js.map +1 -1
- package/dist/scripts/index.d.ts +1 -0
- package/dist/scripts/index.d.ts.map +1 -1
- package/dist/scripts/index.js +4 -2
- package/dist/scripts/index.js.map +1 -1
- package/dist/scripts/seed-account.d.ts +19 -0
- package/dist/scripts/seed-account.d.ts.map +1 -0
- package/dist/scripts/seed-account.js +95 -0
- package/dist/scripts/seed-account.js.map +1 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/only-account.d.ts +21 -0
- package/dist/server/only-account.d.ts.map +1 -0
- package/dist/server/only-account.js +34 -0
- package/dist/server/only-account.js.map +1 -0
- package/dist/testing/account.d.ts +27 -5
- package/dist/testing/account.d.ts.map +1 -1
- package/dist/testing/account.js +42 -7
- package/dist/testing/account.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js.map +1 -1
- package/module.json +1 -1
- package/package.json +4 -4
- package/src/index.ts +10 -9
- package/src/options.ts +26 -1
- package/src/proxy/index.ts +21 -3
- package/src/scripts/index.ts +4 -2
- package/src/scripts/seed-account.ts +108 -0
- package/src/server/index.ts +7 -0
- package/src/server/only-account.ts +50 -0
- package/src/testing/account.ts +72 -12
- package/src/testing/index.ts +1 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// The one account a local tool acts for (a stdio MCP server, a measurement or seed script): the
|
|
2
|
+
// account an environment variable names, else the only account in the database. Never the first of
|
|
3
|
+
// several: that could be another person's data.
|
|
4
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
5
|
+
import type { Queryable } from "@softure-ai/db";
|
|
6
|
+
import { eq } from "drizzle-orm";
|
|
7
|
+
import { users } from "../schema.js";
|
|
8
|
+
|
|
9
|
+
const UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
10
|
+
|
|
11
|
+
export type OnlyAccountErrorCode = "auth.account_unknown" | "auth.no_account" | "auth.account_ambiguous";
|
|
12
|
+
|
|
13
|
+
/** Why there is no account to use, with a line for the person running the tool. */
|
|
14
|
+
export type OnlyAccountError = Err<OnlyAccountErrorCode> & { readonly message: string };
|
|
15
|
+
|
|
16
|
+
export type OnlyAccountResult = Ok<string> | OnlyAccountError;
|
|
17
|
+
|
|
18
|
+
export interface ResolveOnlyAccountOptions {
|
|
19
|
+
readonly db: Queryable;
|
|
20
|
+
/** The variable that may name the account's id, e.g. `MCP_USER_ID`. */
|
|
21
|
+
readonly envName: string;
|
|
22
|
+
/** Default: `process.env`. */
|
|
23
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The id of the account `envName` names (it must exist), or, when the variable is empty or unset,
|
|
28
|
+
* of the only account. Refuses an unknown id, an empty database and several accounts with none named.
|
|
29
|
+
*/
|
|
30
|
+
export async function resolveOnlyAccount(options: ResolveOnlyAccountOptions): Promise<OnlyAccountResult> {
|
|
31
|
+
const { db, envName } = options;
|
|
32
|
+
const requested = (options.env ?? process.env)[envName]?.trim() ?? "";
|
|
33
|
+
if (requested !== "") {
|
|
34
|
+
const unknown = refuse("auth.account_unknown", `${envName} names no account`);
|
|
35
|
+
// Checked before the query: Postgres rejects a malformed uuid with an error, not an empty result.
|
|
36
|
+
if (!UUID_SHAPE.test(requested)) return unknown;
|
|
37
|
+
const [found] = await db.select({ id: users.id }).from(users).where(eq(users.id, requested)).limit(1);
|
|
38
|
+
return found === undefined ? unknown : ok(found.id);
|
|
39
|
+
}
|
|
40
|
+
const [only, second] = await db.select({ id: users.id }).from(users).limit(2);
|
|
41
|
+
if (only === undefined) return refuse("auth.no_account", "the database has no account");
|
|
42
|
+
if (second !== undefined) {
|
|
43
|
+
return refuse("auth.account_ambiguous", `the database has several accounts; set ${envName} to the id of the one to use`);
|
|
44
|
+
}
|
|
45
|
+
return ok(only.id);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function refuse(code: OnlyAccountErrorCode, message: string): OnlyAccountError {
|
|
49
|
+
return { ...err(code), message };
|
|
50
|
+
}
|
package/src/testing/account.ts
CHANGED
|
@@ -1,43 +1,103 @@
|
|
|
1
|
-
// An account written straight to auth's tables, hashed the way registration hashes it. No
|
|
2
|
-
//
|
|
1
|
+
// An account written straight to auth's tables, hashed the way registration hashes it. No session
|
|
2
|
+
// is opened: the test signs in through the login form. The app's `onRegistered` hook runs only on
|
|
3
|
+
// request (`runHooks`), so fixture rows the app's hooks write (a profile, an entitlement) exist too.
|
|
3
4
|
import type { Queryable } from "@softure-ai/db";
|
|
4
5
|
import type { AuthUser } from "../contract.js";
|
|
5
6
|
import { DEFAULT_SCRYPT_COST, type ScryptParams } from "../options.js";
|
|
6
7
|
import { userRoles, users } from "../schema.js";
|
|
7
|
-
import {
|
|
8
|
+
import { getAuthOptions } from "../server/options.js";
|
|
9
|
+
import { hashPassword, isPasswordHash } from "../server/password.js";
|
|
10
|
+
import type { AuthContext } from "../server/sessions.js";
|
|
8
11
|
import { parseEmail } from "../server/validation.js";
|
|
9
12
|
|
|
10
13
|
/** Auth's own hash parameters when the app sets none (`password.scrypt` in `auth({ ... })`). */
|
|
11
14
|
const DEFAULT_SCRYPT: ScryptParams = { cost: DEFAULT_SCRYPT_COST, blockSize: 8, parallelization: 1 };
|
|
12
15
|
|
|
13
|
-
|
|
16
|
+
/** One hash per password and parameters for the whole test run: scrypt is the slow part of a big suite's setup. */
|
|
17
|
+
const hashCache = new Map<string, Promise<string>>();
|
|
18
|
+
|
|
19
|
+
interface TestAccountBase {
|
|
14
20
|
readonly email: string;
|
|
15
|
-
|
|
21
|
+
/** The row's id (a uuid); the database draws one when absent. */
|
|
22
|
+
readonly id?: string;
|
|
23
|
+
/** `created_at` and `password_changed_at`; now when absent. */
|
|
24
|
+
readonly createdAt?: Date;
|
|
16
25
|
/** Rows of `auth.user_roles`, e.g. `["admin"]`. */
|
|
17
26
|
readonly roles?: readonly string[];
|
|
18
|
-
/**
|
|
27
|
+
/** Run the app's `onRegistered` hook in the account's transaction. Needs a module context as the first argument. */
|
|
28
|
+
readonly runHooks?: boolean;
|
|
29
|
+
/** `event.fields` for the hook, as the register form would send the app's `registrationFields`. */
|
|
30
|
+
readonly fields?: Readonly<Record<string, string>>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** An account with a password, hashed here (once per password and parameters). */
|
|
34
|
+
export interface TestAccountInput extends TestAccountBase {
|
|
35
|
+
readonly password: string;
|
|
36
|
+
/** Hash parameters; the app's (`getAuthOptions(config).password.scrypt`) when a module context is given, else auth's default. */
|
|
19
37
|
readonly scrypt?: ScryptParams;
|
|
38
|
+
readonly passwordHash?: never;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** An account with a ready hash, stored as is. */
|
|
42
|
+
export interface TestAccountHashInput extends TestAccountBase {
|
|
43
|
+
/** A ready hash from `hashPassword`, stored as is: nothing is hashed. */
|
|
44
|
+
readonly passwordHash: string;
|
|
45
|
+
readonly password?: never;
|
|
46
|
+
readonly scrypt?: never;
|
|
20
47
|
}
|
|
21
48
|
|
|
22
49
|
/**
|
|
23
50
|
* Creates an account and its roles in one transaction and returns it. The email is normalized as
|
|
24
|
-
* registration normalizes it. An invalid or taken email
|
|
51
|
+
* registration normalizes it. An invalid or taken email, a malformed `passwordHash` or a hook that
|
|
52
|
+
* throws rolls everything back and throws: in test setup it is a bug of the test.
|
|
25
53
|
*/
|
|
26
|
-
export async function createTestAccount(
|
|
54
|
+
export async function createTestAccount(target: Queryable | AuthContext, input: TestAccountInput | TestAccountHashInput): Promise<AuthUser> {
|
|
55
|
+
const ctx = isModuleContext(target) ? target : null;
|
|
56
|
+
const db = isModuleContext(target) ? target.db : target;
|
|
27
57
|
const email = parseEmail(input.email);
|
|
28
58
|
if (!email.ok) throw new Error(`createTestAccount: "${input.email}" is not a valid email`);
|
|
29
|
-
|
|
30
|
-
|
|
59
|
+
if (input.runHooks === true && ctx === null) {
|
|
60
|
+
throw new Error("createTestAccount: runHooks needs a module context ({ db, clock, config }) instead of a database");
|
|
61
|
+
}
|
|
62
|
+
const passwordHash = await readPasswordHash(input, email.value, ctx);
|
|
63
|
+
const now = input.createdAt ?? new Date();
|
|
31
64
|
|
|
32
65
|
return db.transaction(async (tx) => {
|
|
33
66
|
const [row] = await tx
|
|
34
67
|
.insert(users)
|
|
35
|
-
.values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
|
|
68
|
+
.values({ ...(input.id === undefined ? {} : { id: input.id }), email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
|
|
36
69
|
.onConflictDoNothing({ target: users.email })
|
|
37
70
|
.returning();
|
|
38
71
|
if (row === undefined) throw new Error(`createTestAccount: an account with the email "${email.value}" already exists`);
|
|
39
72
|
const roles = input.roles ?? [];
|
|
40
73
|
if (roles.length > 0) await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
|
|
41
|
-
|
|
74
|
+
const user = { id: row.id, email: row.email, createdAt: row.createdAt };
|
|
75
|
+
if (input.runHooks === true && ctx !== null) {
|
|
76
|
+
const options = getAuthOptions(ctx.config);
|
|
77
|
+
const consent = options.requireConsent ? { acceptedAt: now } : null;
|
|
78
|
+
await options.onRegistered?.({ user, consent, fields: input.fields ?? {} }, { ...ctx, db: tx });
|
|
79
|
+
}
|
|
80
|
+
return user;
|
|
42
81
|
});
|
|
43
82
|
}
|
|
83
|
+
|
|
84
|
+
async function readPasswordHash(input: TestAccountInput | TestAccountHashInput, email: string, ctx: AuthContext | null): Promise<string> {
|
|
85
|
+
if (input.passwordHash !== undefined) {
|
|
86
|
+
if (!isPasswordHash(input.passwordHash)) throw new Error(`createTestAccount: the passwordHash for "${email}" is not a hash from hashPassword`);
|
|
87
|
+
return input.passwordHash;
|
|
88
|
+
}
|
|
89
|
+
const scrypt = input.scrypt ?? (ctx === null ? DEFAULT_SCRYPT : getAuthOptions(ctx.config).password.scrypt);
|
|
90
|
+
const key = JSON.stringify([scrypt.cost, scrypt.blockSize, scrypt.parallelization, input.password]);
|
|
91
|
+
let hash = hashCache.get(key);
|
|
92
|
+
if (hash === undefined) {
|
|
93
|
+
hash = hashPassword(input.password, scrypt);
|
|
94
|
+
hashCache.set(key, hash);
|
|
95
|
+
// A failed hash is not kept, so the next call tries again.
|
|
96
|
+
void hash.catch(() => hashCache.delete(key));
|
|
97
|
+
}
|
|
98
|
+
return hash;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function isModuleContext(target: Queryable | AuthContext): target is AuthContext {
|
|
102
|
+
return "config" in target && "clock" in target && "db" in target;
|
|
103
|
+
}
|
package/src/testing/index.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Test helpers of @softure-ai/auth: accounts created directly in the database, for tests that need
|
|
2
2
|
// a user but are not about registration. Server-only; never imported by the module's runtime code.
|
|
3
|
-
export { createTestAccount, type TestAccountInput } from "./account.js";
|
|
3
|
+
export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
|