@softure-ai/auth 0.2.5 → 0.2.7
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 +59 -0
- package/README.md +113 -15
- package/dist/contract.d.ts +11 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js.map +1 -1
- package/dist/index.d.ts +72 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -4
- package/dist/index.js.map +1 -1
- package/dist/messages/en.d.ts +10 -0
- package/dist/messages/en.d.ts.map +1 -1
- package/dist/messages/en.js +10 -0
- package/dist/messages/en.js.map +1 -1
- package/dist/messages/index.d.ts +28 -2
- package/dist/messages/index.d.ts.map +1 -1
- package/dist/messages/index.js +13 -3
- package/dist/messages/index.js.map +1 -1
- package/dist/next/actions.d.ts +5 -0
- package/dist/next/actions.d.ts.map +1 -1
- package/dist/next/actions.js +26 -15
- package/dist/next/actions.js.map +1 -1
- package/dist/next/index.d.ts +2 -1
- package/dist/next/index.d.ts.map +1 -1
- package/dist/next/index.js +2 -1
- package/dist/next/index.js.map +1 -1
- package/dist/next/oidc-cookie.d.ts +7 -0
- package/dist/next/oidc-cookie.d.ts.map +1 -0
- package/dist/next/oidc-cookie.js +25 -0
- package/dist/next/oidc-cookie.js.map +1 -0
- package/dist/next/oidc-login-url.d.ts +4 -0
- package/dist/next/oidc-login-url.d.ts.map +1 -0
- package/dist/next/oidc-login-url.js +13 -0
- package/dist/next/oidc-login-url.js.map +1 -0
- package/dist/next/oidc-route.d.ts +7 -0
- package/dist/next/oidc-route.d.ts.map +1 -0
- package/dist/next/oidc-route.js +48 -0
- package/dist/next/oidc-route.js.map +1 -0
- package/dist/next/pages.d.ts +5 -0
- package/dist/next/pages.d.ts.map +1 -1
- package/dist/next/pages.js +19 -4
- package/dist/next/pages.js.map +1 -1
- package/dist/next/params.d.ts +2 -0
- package/dist/next/params.d.ts.map +1 -1
- package/dist/next/params.js +2 -0
- package/dist/next/params.js.map +1 -1
- package/dist/next/previous-session.d.ts +6 -0
- package/dist/next/previous-session.d.ts.map +1 -0
- package/dist/next/previous-session.js +23 -0
- package/dist/next/previous-session.js.map +1 -0
- package/dist/options.d.ts +99 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +80 -0
- package/dist/options.js.map +1 -1
- package/dist/proxy/index.d.ts.map +1 -1
- package/dist/proxy/index.js +3 -1
- package/dist/proxy/index.js.map +1 -1
- package/dist/schema.d.ts +323 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +26 -3
- package/dist/schema.js.map +1 -1
- package/dist/server/change-password.d.ts +1 -1
- package/dist/server/change-password.d.ts.map +1 -1
- package/dist/server/change-password.js +3 -0
- package/dist/server/change-password.js.map +1 -1
- package/dist/server/health.d.ts.map +1 -1
- package/dist/server/health.js +2 -0
- package/dist/server/health.js.map +1 -1
- 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/login.d.ts +1 -1
- package/dist/server/login.d.ts.map +1 -1
- package/dist/server/login.js +4 -2
- package/dist/server/login.js.map +1 -1
- package/dist/server/oidc/accounts.d.ts +14 -0
- package/dist/server/oidc/accounts.d.ts.map +1 -0
- package/dist/server/oidc/accounts.js +79 -0
- package/dist/server/oidc/accounts.js.map +1 -0
- package/dist/server/oidc/context.d.ts +37 -0
- package/dist/server/oidc/context.d.ts.map +1 -0
- package/dist/server/oidc/context.js +34 -0
- package/dist/server/oidc/context.js.map +1 -0
- package/dist/server/oidc/discovery.d.ts +24 -0
- package/dist/server/oidc/discovery.d.ts.map +1 -0
- package/dist/server/oidc/discovery.js +109 -0
- package/dist/server/oidc/discovery.js.map +1 -0
- package/dist/server/oidc/flow.d.ts +49 -0
- package/dist/server/oidc/flow.d.ts.map +1 -0
- package/dist/server/oidc/flow.js +168 -0
- package/dist/server/oidc/flow.js.map +1 -0
- package/dist/server/oidc/id-token.d.ts +45 -0
- package/dist/server/oidc/id-token.d.ts.map +1 -0
- package/dist/server/oidc/id-token.js +122 -0
- package/dist/server/oidc/id-token.js.map +1 -0
- package/dist/server/oidc/index.d.ts +4 -0
- package/dist/server/oidc/index.d.ts.map +1 -0
- package/dist/server/oidc/index.js +4 -0
- package/dist/server/oidc/index.js.map +1 -0
- package/dist/server/oidc/token-request.d.ts +13 -0
- package/dist/server/oidc/token-request.d.ts.map +1 -0
- package/dist/server/oidc/token-request.js +49 -0
- package/dist/server/oidc/token-request.js.map +1 -0
- package/dist/server/password-reset.d.ts +1 -1
- package/dist/server/password-reset.d.ts.map +1 -1
- package/dist/server/password-reset.js +7 -7
- package/dist/server/password-reset.js.map +1 -1
- package/dist/server/privacy.d.ts +10 -0
- package/dist/server/privacy.d.ts.map +1 -1
- package/dist/server/privacy.js +18 -6
- package/dist/server/privacy.js.map +1 -1
- package/dist/server/rate-limits.d.ts +4 -1
- package/dist/server/rate-limits.d.ts.map +1 -1
- package/dist/server/rate-limits.js +10 -3
- package/dist/server/rate-limits.js.map +1 -1
- package/dist/server/register.js +2 -2
- package/dist/server/register.js.map +1 -1
- package/dist/server/sessions.js +2 -2
- package/dist/server/sessions.js.map +1 -1
- package/dist/server/switches.d.ts +1 -1
- package/dist/server/switches.d.ts.map +1 -1
- package/dist/server/switches.js +3 -1
- package/dist/server/switches.js.map +1 -1
- package/dist/testing/account.js +2 -2
- package/dist/testing/account.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +3 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/oidc-provider.d.ts +68 -0
- package/dist/testing/oidc-provider.d.ts.map +1 -0
- package/dist/testing/oidc-provider.js +185 -0
- package/dist/testing/oidc-provider.js.map +1 -0
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.d.ts.map +1 -1
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -1
- package/dist/ui/oidc-sign-in.d.ts +25 -0
- package/dist/ui/oidc-sign-in.d.ts.map +1 -0
- package/dist/ui/oidc-sign-in.js +19 -0
- package/dist/ui/oidc-sign-in.js.map +1 -0
- package/migrations/0005_create_identities_and_oidc_states.sql +34 -0
- package/migrations/0006_add_users_display_name.sql +8 -0
- package/module.json +3 -2
- package/package.json +2 -2
- package/src/contract.ts +16 -1
- package/src/index.ts +20 -5
- package/src/messages/en.ts +10 -0
- package/src/messages/index.ts +29 -4
- package/src/next/actions.ts +23 -14
- package/src/next/index.ts +2 -0
- package/src/next/oidc-cookie.ts +31 -0
- package/src/next/oidc-login-url.ts +14 -0
- package/src/next/oidc-route.ts +48 -0
- package/src/next/pages.tsx +38 -11
- package/src/next/params.ts +3 -0
- package/src/next/previous-session.ts +23 -0
- package/src/options.ts +86 -1
- package/src/proxy/index.ts +3 -1
- package/src/schema.ts +33 -3
- package/src/server/change-password.ts +3 -0
- package/src/server/health.ts +2 -0
- package/src/server/index.ts +17 -0
- package/src/server/login.ts +3 -2
- package/src/server/oidc/accounts.ts +92 -0
- package/src/server/oidc/context.ts +56 -0
- package/src/server/oidc/discovery.ts +133 -0
- package/src/server/oidc/flow.ts +196 -0
- package/src/server/oidc/id-token.ts +143 -0
- package/src/server/oidc/index.ts +14 -0
- package/src/server/oidc/token-request.ts +59 -0
- package/src/server/password-reset.ts +7 -7
- package/src/server/privacy.ts +28 -6
- package/src/server/rate-limits.ts +11 -3
- package/src/server/register.ts +2 -2
- package/src/server/sessions.ts +2 -2
- package/src/server/switches.ts +2 -1
- package/src/testing/account.ts +2 -2
- package/src/testing/index.ts +10 -1
- package/src/testing/oidc-provider.ts +254 -0
- package/src/ui/index.ts +1 -0
- package/src/ui/oidc-sign-in.tsx +61 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// The ID token (OpenID Connect Core §3.1.3.7): a JWS in compact form, signed with RS256 or ES256 (no `none`, no
|
|
2
|
+
// HMAC), checked against the issuer's key and the claims the sign-in expects. Nothing in the token is trusted before
|
|
3
|
+
// its signature is.
|
|
4
|
+
import { timingSafeEqual, verify, type KeyObject } from "node:crypto";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { passed, refused, type Checked } from "./context.js";
|
|
7
|
+
|
|
8
|
+
/** Clock skew tolerated between this server and the provider. */
|
|
9
|
+
const SKEW_SECONDS = 60;
|
|
10
|
+
const MAX_TOKEN_LENGTH = 16_384;
|
|
11
|
+
/** The longest display name kept, in characters (code points); `auth.users.display_name` checks the same bound. */
|
|
12
|
+
export const MAX_DISPLAY_NAME_LENGTH = 200;
|
|
13
|
+
const SEGMENT = /^[A-Za-z0-9_-]+$/;
|
|
14
|
+
|
|
15
|
+
const ALGORITHMS = { RS256: "RSA", ES256: "EC" } as const;
|
|
16
|
+
export type IdTokenAlgorithm = keyof typeof ALGORITHMS;
|
|
17
|
+
|
|
18
|
+
const headerSchema = z.object({ alg: z.string(), kid: z.string().max(256).optional() });
|
|
19
|
+
|
|
20
|
+
const claimsSchema = z.object({
|
|
21
|
+
iss: z.string(),
|
|
22
|
+
sub: z.string().min(1).max(255),
|
|
23
|
+
aud: z.union([z.string(), z.array(z.string()).min(1).max(20)]),
|
|
24
|
+
azp: z.string().optional(),
|
|
25
|
+
exp: z.number(),
|
|
26
|
+
iat: z.number(),
|
|
27
|
+
nonce: z.string().optional(),
|
|
28
|
+
email: z.string().max(254).optional(),
|
|
29
|
+
// Most providers send a boolean; some send the string.
|
|
30
|
+
email_verified: z.union([z.boolean(), z.enum(["true", "false"]).transform((value) => value === "true")]).optional(),
|
|
31
|
+
hd: z.string().max(253).optional(),
|
|
32
|
+
// Profile claims are best effort: a malformed one is dropped, never a reason to refuse the sign-in.
|
|
33
|
+
name: z.unknown().optional(),
|
|
34
|
+
given_name: z.unknown().optional(),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export interface DecodedIdToken {
|
|
38
|
+
readonly algorithm: IdTokenAlgorithm;
|
|
39
|
+
readonly keyType: "RSA" | "EC";
|
|
40
|
+
readonly kid: string | undefined;
|
|
41
|
+
readonly signingInput: string;
|
|
42
|
+
readonly signature: Buffer;
|
|
43
|
+
readonly payload: unknown;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The token's parts, or the reason (for the log) it is not a JWS this module accepts. */
|
|
47
|
+
export function decodeIdToken(token: string): Checked<DecodedIdToken> {
|
|
48
|
+
if (token.length > MAX_TOKEN_LENGTH) return refused("id_token too_long");
|
|
49
|
+
const parts = token.split(".");
|
|
50
|
+
if (parts.length !== 3 || !parts.every((part) => SEGMENT.test(part))) return refused("id_token malformed");
|
|
51
|
+
const [encodedHeader = "", encodedPayload = "", encodedSignature = ""] = parts;
|
|
52
|
+
const header = headerSchema.safeParse(parseJson(encodedHeader));
|
|
53
|
+
if (!header.success) return refused("id_token malformed");
|
|
54
|
+
const algorithm = header.data.alg;
|
|
55
|
+
if (!Object.hasOwn(ALGORITHMS, algorithm)) return refused("id_token algorithm");
|
|
56
|
+
const payload = parseJson(encodedPayload);
|
|
57
|
+
if (payload === undefined) return refused("id_token malformed");
|
|
58
|
+
return passed({
|
|
59
|
+
algorithm: algorithm as IdTokenAlgorithm,
|
|
60
|
+
keyType: ALGORITHMS[algorithm as IdTokenAlgorithm],
|
|
61
|
+
kid: header.data.kid,
|
|
62
|
+
signingInput: `${encodedHeader}.${encodedPayload}`,
|
|
63
|
+
signature: Buffer.from(encodedSignature, "base64url"),
|
|
64
|
+
payload,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function parseJson(segment: string): unknown {
|
|
69
|
+
try {
|
|
70
|
+
return JSON.parse(Buffer.from(segment, "base64url").toString("utf8")) as unknown;
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Whether `key` signed the token. An ES256 signature is the JWS form (r || s), not DER. */
|
|
77
|
+
export function isSignedBy(token: DecodedIdToken, key: KeyObject): boolean {
|
|
78
|
+
const data = Buffer.from(token.signingInput, "ascii");
|
|
79
|
+
try {
|
|
80
|
+
if (token.algorithm === "ES256") {
|
|
81
|
+
return key.asymmetricKeyDetails?.namedCurve === "prime256v1" && verify("sha256", data, { key, dsaEncoding: "ieee-p1363" }, token.signature);
|
|
82
|
+
}
|
|
83
|
+
return verify("sha256", data, key, token.signature);
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface ExpectedClaims {
|
|
90
|
+
readonly issuer: string;
|
|
91
|
+
readonly clientId: string;
|
|
92
|
+
readonly nonce: string;
|
|
93
|
+
readonly now: Date;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What a valid token says about the person. */
|
|
97
|
+
export interface IdentityClaims {
|
|
98
|
+
readonly subject: string;
|
|
99
|
+
readonly email: string | null;
|
|
100
|
+
readonly isEmailVerified: boolean;
|
|
101
|
+
readonly hostedDomain: string | null;
|
|
102
|
+
/** `name`, else `given_name`, normalized; null when the token carries neither. */
|
|
103
|
+
readonly displayName: string | null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The identity, or the reason (for the log) the claims do not fit this sign-in. */
|
|
107
|
+
export function checkIdTokenClaims(payload: unknown, expected: ExpectedClaims): Checked<IdentityClaims> {
|
|
108
|
+
const parsed = claimsSchema.safeParse(payload);
|
|
109
|
+
if (!parsed.success) return refused("id_token claims");
|
|
110
|
+
const claims = parsed.data;
|
|
111
|
+
const nowSeconds = expected.now.getTime() / 1000;
|
|
112
|
+
if (claims.iss.replace(/\/+$/, "") !== expected.issuer) return refused("id_token issuer");
|
|
113
|
+
const audiences = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
|
|
114
|
+
if (!audiences.includes(expected.clientId)) return refused("id_token audience");
|
|
115
|
+
if ((audiences.length > 1 || claims.azp !== undefined) && claims.azp !== expected.clientId) return refused("id_token azp");
|
|
116
|
+
if (claims.exp <= nowSeconds - SKEW_SECONDS) return refused("id_token expired");
|
|
117
|
+
if (claims.iat > nowSeconds + SKEW_SECONDS) return refused("id_token issued_in_future");
|
|
118
|
+
if (claims.nonce === undefined || !isSameText(claims.nonce, expected.nonce)) return refused("id_token nonce");
|
|
119
|
+
return passed({
|
|
120
|
+
subject: claims.sub,
|
|
121
|
+
email: claims.email === undefined ? null : claims.email.trim().toLowerCase(),
|
|
122
|
+
isEmailVerified: claims.email_verified === true,
|
|
123
|
+
hostedDomain: claims.hd === undefined ? null : claims.hd.trim().toLowerCase(),
|
|
124
|
+
displayName: toDisplayName(claims.name) ?? toDisplayName(claims.given_name),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A profile claim as a display name: NFC, control and format characters dropped, whitespace collapsed, trimmed, at
|
|
130
|
+
* most `MAX_DISPLAY_NAME_LENGTH` characters. Null for anything but a string with visible text.
|
|
131
|
+
*/
|
|
132
|
+
export function toDisplayName(value: unknown): string | null {
|
|
133
|
+
if (typeof value !== "string") return null;
|
|
134
|
+
const cleaned = value.normalize("NFC").replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/gu, " ").trim();
|
|
135
|
+
const name = [...cleaned].slice(0, MAX_DISPLAY_NAME_LENGTH).join("").trimEnd();
|
|
136
|
+
return name === "" ? null : name;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isSameText(a: string, b: string): boolean {
|
|
140
|
+
const left = Buffer.from(a, "utf8");
|
|
141
|
+
const right = Buffer.from(b, "utf8");
|
|
142
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
143
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// OpenID Connect sign-in (`auth({ oidc })`): the flow, its context and the allowlist check.
|
|
2
|
+
export { findOidcProvider, getOidcCallbackPath, getOidcProviders, getOidcRedirectUri, type OidcContext } from "./context.js";
|
|
3
|
+
export {
|
|
4
|
+
completeOidcSignIn,
|
|
5
|
+
getAllowedEmail,
|
|
6
|
+
startOidcSignIn,
|
|
7
|
+
type CompleteOidcSignInInput,
|
|
8
|
+
type CompleteOidcSignInResult,
|
|
9
|
+
type OidcCallbackParams,
|
|
10
|
+
type StartedOidcSignIn,
|
|
11
|
+
type StartOidcSignInInput,
|
|
12
|
+
type StartOidcSignInResult,
|
|
13
|
+
} from "./flow.js";
|
|
14
|
+
export type { IdentityClaims } from "./id-token.js";
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// The authorization code exchange at the provider's token endpoint (RFC 6749 §4.1.3, with the PKCE verifier of
|
|
2
|
+
// RFC 7636): a form POST through core's `requestJson`, which follows no redirect, so the client secret never reaches
|
|
3
|
+
// another host. Only the ID token is read; the access token is not kept.
|
|
4
|
+
import { requestJson } from "@softure-ai/core";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import type { OidcProvider } from "../../options.js";
|
|
7
|
+
import { getAuthOptions } from "../options.js";
|
|
8
|
+
import { passed, refused, type Checked, type OidcClient, type OidcContext } from "./context.js";
|
|
9
|
+
|
|
10
|
+
const tokenBodySchema = z.object({ id_token: z.string().min(1).max(16_384) });
|
|
11
|
+
// Only an RFC 6749 error code shape is read (it goes to the log); any other body is just a failed call.
|
|
12
|
+
const errorBodySchema = z.object({ error: z.string().regex(/^[a-z_]{1,64}$/) });
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
export interface TokenExchangeInput {
|
|
16
|
+
readonly provider: OidcProvider;
|
|
17
|
+
readonly client: OidcClient;
|
|
18
|
+
readonly tokenEndpoint: string;
|
|
19
|
+
readonly code: string;
|
|
20
|
+
readonly codeVerifier: string;
|
|
21
|
+
readonly redirectUri: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The ID token for `code`, or the reason (for the log): the OAuth error code or core's failure code. */
|
|
25
|
+
export async function exchangeCode(ctx: OidcContext, input: TokenExchangeInput): Promise<Checked<string>> {
|
|
26
|
+
const form = new URLSearchParams({
|
|
27
|
+
grant_type: "authorization_code",
|
|
28
|
+
code: input.code,
|
|
29
|
+
redirect_uri: input.redirectUri,
|
|
30
|
+
code_verifier: input.codeVerifier,
|
|
31
|
+
});
|
|
32
|
+
const headers = new Headers();
|
|
33
|
+
if (input.provider.clientAuth === "basic" && input.client.clientSecret !== null) {
|
|
34
|
+
// RFC 6749 §2.3.1: both parts form-encoded before the Basic encoding.
|
|
35
|
+
const user = encodeURIComponent(input.client.clientId);
|
|
36
|
+
const password = encodeURIComponent(input.client.clientSecret);
|
|
37
|
+
headers.set("authorization", `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`);
|
|
38
|
+
} else {
|
|
39
|
+
form.set("client_id", input.client.clientId);
|
|
40
|
+
if (input.client.clientSecret !== null) form.set("client_secret", input.client.clientSecret);
|
|
41
|
+
}
|
|
42
|
+
const options = getAuthOptions(ctx.config).oidc;
|
|
43
|
+
const answer = await requestJson({
|
|
44
|
+
url: input.tokenEndpoint,
|
|
45
|
+
method: "POST",
|
|
46
|
+
form,
|
|
47
|
+
headers,
|
|
48
|
+
schema: tokenBodySchema,
|
|
49
|
+
errorSchema: errorBodySchema,
|
|
50
|
+
fetch: options.fetch,
|
|
51
|
+
timeoutMs: options.httpTimeoutMs,
|
|
52
|
+
clock: ctx.clock,
|
|
53
|
+
});
|
|
54
|
+
if (answer.ok) {
|
|
55
|
+
// A write answered with no body is `ok(undefined)`; a token endpoint must answer one.
|
|
56
|
+
return answer.value === undefined ? refused("token empty_answer") : passed(answer.value.id_token);
|
|
57
|
+
}
|
|
58
|
+
return refused(`token ${answer.errorBody?.error ?? answer.error}`);
|
|
59
|
+
}
|
|
@@ -9,7 +9,7 @@ import { consumeRateLimit } from "@softure-ai/security/server";
|
|
|
9
9
|
import { and, eq, gt, lte } from "drizzle-orm";
|
|
10
10
|
import type { AuthUser } from "../contract.js";
|
|
11
11
|
import type { PasswordResetSender } from "../password-reset-sender.js";
|
|
12
|
-
import { passwordResets, sessions, users } from "../schema.js";
|
|
12
|
+
import { AUTH_USER_COLUMNS, passwordResets, sessions, users } from "../schema.js";
|
|
13
13
|
import { getAuthOptions, getAuthRoutes } from "./options.js";
|
|
14
14
|
import { hashPassword } from "./password.js";
|
|
15
15
|
import { assertAuthBuckets, BUCKETS, emailSubjectKey } from "./rate-limits.js";
|
|
@@ -22,9 +22,10 @@ const MINUTE_MS = 60 * 1000;
|
|
|
22
22
|
/** The query parameter of the reset link that carries the token. */
|
|
23
23
|
export const RESET_TOKEN_PARAM = "token";
|
|
24
24
|
|
|
25
|
-
/** Whether
|
|
25
|
+
/** Whether password reset is offered at all: passwords are on and the app passed a sender. */
|
|
26
26
|
export function isPasswordResetEnabled(config: SoftureConfig): boolean {
|
|
27
|
-
|
|
27
|
+
const options = getAuthOptions(config);
|
|
28
|
+
return options.password.enabled && options.passwordReset.send !== undefined;
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
export interface PasswordResetRequestInput {
|
|
@@ -67,7 +68,7 @@ export async function deliverPasswordReset(ctx: AuthContext, email: string): Pro
|
|
|
67
68
|
if (send === undefined) {
|
|
68
69
|
throw new Error("@softure-ai/auth: deliverPasswordReset needs auth({ passwordReset: { send } })");
|
|
69
70
|
}
|
|
70
|
-
const [user] = await ctx.db.select(
|
|
71
|
+
const [user] = await ctx.db.select(AUTH_USER_COLUMNS).from(users).where(eq(users.email, email)).limit(1);
|
|
71
72
|
if (user === undefined) return "no_account";
|
|
72
73
|
if (enqueue !== undefined) {
|
|
73
74
|
await enqueue(ctx, user.id);
|
|
@@ -87,13 +88,12 @@ export async function sendPasswordReset(ctx: AuthContext, userId: string): Promi
|
|
|
87
88
|
if (send === undefined) {
|
|
88
89
|
throw new Error("@softure-ai/auth: sendPasswordReset needs auth({ passwordReset: { send } })");
|
|
89
90
|
}
|
|
90
|
-
const [user] = await ctx.db.select(
|
|
91
|
+
const [user] = await ctx.db.select(AUTH_USER_COLUMNS).from(users).where(eq(users.id, userId)).limit(1);
|
|
91
92
|
if (user === undefined) return "no_account";
|
|
92
93
|
await issueAndSend(ctx, user, send);
|
|
93
94
|
return "sent";
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
const USER_COLUMNS = { id: users.id, email: users.email, createdAt: users.createdAt };
|
|
97
97
|
|
|
98
98
|
async function issueAndSend(ctx: AuthContext, user: AuthUser, send: PasswordResetSender): Promise<void> {
|
|
99
99
|
const { token, expiresAt } = await issuePasswordReset(ctx, user.id);
|
|
@@ -123,7 +123,7 @@ export function getPasswordResetLink(config: SoftureConfig, token: string): stri
|
|
|
123
123
|
export async function findPasswordResetUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
|
|
124
124
|
if (!isSessionTokenShape(token)) return null;
|
|
125
125
|
const [row] = await ctx.db
|
|
126
|
-
.select(
|
|
126
|
+
.select(AUTH_USER_COLUMNS)
|
|
127
127
|
.from(passwordResets)
|
|
128
128
|
.innerJoin(users, eq(users.id, passwordResets.userId))
|
|
129
129
|
.where(and(eq(passwordResets.tokenHash, hashSessionToken(token)), gt(passwordResets.expiresAt, ctx.clock.now())))
|
package/src/server/privacy.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
// The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account, its roles, its
|
|
2
|
-
// sessions
|
|
1
|
+
// The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account (with its display name), its roles, its
|
|
2
|
+
// sessions, a pending reset link and its OpenID Connect identities. Secrets never leave: no password hash and no token hash.
|
|
3
3
|
import { ok, type ModuleContext, type Ok, type PrivacyContributor } from "@softure-ai/core";
|
|
4
4
|
import type { Queryable } from "@softure-ai/db";
|
|
5
5
|
import { asc, eq } from "drizzle-orm";
|
|
6
|
-
import { passwordResets, sessions, userRoles, users } from "../schema.js";
|
|
6
|
+
import { identities, passwordResets, sessions, userRoles, users } from "../schema.js";
|
|
7
7
|
|
|
8
8
|
/** What auth holds about one user, as it appears in their export. */
|
|
9
9
|
export interface AuthUserData {
|
|
@@ -13,16 +13,26 @@ export interface AuthUserData {
|
|
|
13
13
|
readonly email: string;
|
|
14
14
|
readonly createdAt: Date;
|
|
15
15
|
readonly passwordChangedAt: Date;
|
|
16
|
+
/** The name the OpenID Connect provider sent; null when none did. */
|
|
17
|
+
readonly displayName: string | null;
|
|
16
18
|
} | null;
|
|
17
19
|
/** Stored roles; a role held through `adminEmails` is configuration, not stored data. */
|
|
18
20
|
readonly roles: readonly { readonly role: string; readonly grantedAt: Date }[];
|
|
19
21
|
readonly sessions: readonly { readonly createdAt: Date; readonly expiresAt: Date }[];
|
|
20
22
|
readonly passwordReset: { readonly createdAt: Date; readonly expiresAt: Date } | null;
|
|
23
|
+
/** The provider identities that sign in to the account. */
|
|
24
|
+
readonly identities: readonly {
|
|
25
|
+
readonly provider: string;
|
|
26
|
+
readonly subject: string;
|
|
27
|
+
readonly email: string;
|
|
28
|
+
readonly createdAt: Date;
|
|
29
|
+
readonly lastLoginAt: Date;
|
|
30
|
+
}[];
|
|
21
31
|
}
|
|
22
32
|
|
|
23
33
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
34
|
|
|
25
|
-
const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null };
|
|
35
|
+
const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null, identities: [] };
|
|
26
36
|
|
|
27
37
|
/** The user's auth data. An id that is not a UUID cannot be an account, so it has none. */
|
|
28
38
|
export async function exportAuthUserData(context: ModuleContext, userId: string): Promise<Ok<AuthUserData>> {
|
|
@@ -30,7 +40,7 @@ export async function exportAuthUserData(context: ModuleContext, userId: string)
|
|
|
30
40
|
// Core types `db` as unknown; privacy passes the @softure-ai/db handle or its transaction.
|
|
31
41
|
const db = context.db as Queryable;
|
|
32
42
|
const [account] = await db
|
|
33
|
-
.select({ id: users.id, email: users.email, createdAt: users.createdAt, passwordChangedAt: users.passwordChangedAt })
|
|
43
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt, passwordChangedAt: users.passwordChangedAt, displayName: users.displayName })
|
|
34
44
|
.from(users)
|
|
35
45
|
.where(eq(users.id, userId));
|
|
36
46
|
const roles = await db
|
|
@@ -47,7 +57,18 @@ export async function exportAuthUserData(context: ModuleContext, userId: string)
|
|
|
47
57
|
.select({ createdAt: passwordResets.createdAt, expiresAt: passwordResets.expiresAt })
|
|
48
58
|
.from(passwordResets)
|
|
49
59
|
.where(eq(passwordResets.userId, userId));
|
|
50
|
-
|
|
60
|
+
const userIdentities = await db
|
|
61
|
+
.select({
|
|
62
|
+
provider: identities.provider,
|
|
63
|
+
subject: identities.subject,
|
|
64
|
+
email: identities.email,
|
|
65
|
+
createdAt: identities.createdAt,
|
|
66
|
+
lastLoginAt: identities.lastLoginAt,
|
|
67
|
+
})
|
|
68
|
+
.from(identities)
|
|
69
|
+
.where(eq(identities.userId, userId))
|
|
70
|
+
.orderBy(asc(identities.provider));
|
|
71
|
+
return ok({ account: account ?? null, roles, sessions: userSessions, passwordReset: passwordReset ?? null, identities: userIdentities });
|
|
51
72
|
}
|
|
52
73
|
|
|
53
74
|
/**
|
|
@@ -60,6 +81,7 @@ export async function deleteAuthUserData(context: ModuleContext, userId: string)
|
|
|
60
81
|
await db.delete(sessions).where(eq(sessions.userId, userId));
|
|
61
82
|
await db.delete(passwordResets).where(eq(passwordResets.userId, userId));
|
|
62
83
|
await db.delete(userRoles).where(eq(userRoles.userId, userId));
|
|
84
|
+
await db.delete(identities).where(eq(identities.userId, userId));
|
|
63
85
|
await db.delete(users).where(eq(users.id, userId));
|
|
64
86
|
return ok();
|
|
65
87
|
}
|
|
@@ -12,6 +12,8 @@ export const BUCKETS = {
|
|
|
12
12
|
passwordReset: "password-reset",
|
|
13
13
|
passwordResetAccount: "password-reset-account",
|
|
14
14
|
passwordResetConfirm: "password-reset-confirm",
|
|
15
|
+
oidcStart: "oidc-start",
|
|
16
|
+
oidcCallback: "oidc-callback",
|
|
15
17
|
} as const;
|
|
16
18
|
|
|
17
19
|
/** The subject key of an account's email for `login-account` and `password-reset-account`. */
|
|
@@ -27,11 +29,15 @@ export function userSubjectKey(userId: string): string {
|
|
|
27
29
|
/** The buckets only password reset counts in; not needed while it is off. */
|
|
28
30
|
const RESET_BUCKETS: ReadonlySet<string> = new Set([BUCKETS.passwordReset, BUCKETS.passwordResetAccount, BUCKETS.passwordResetConfirm]);
|
|
29
31
|
|
|
32
|
+
/** The buckets only OpenID Connect sign-in counts in; not needed without providers. */
|
|
33
|
+
const OIDC_BUCKETS: ReadonlySet<string> = new Set([BUCKETS.oidcStart, BUCKETS.oidcCallback]);
|
|
34
|
+
|
|
30
35
|
const checkedConfigs = new WeakSet<SoftureConfig>();
|
|
31
36
|
|
|
32
37
|
/**
|
|
33
38
|
* Throws, naming every missing bucket, when the app's `security({ buckets })` lacks one auth
|
|
34
|
-
* counts in: the reset buckets only when password reset is on (`passwordReset.send`)
|
|
39
|
+
* counts in: the reset buckets only when password reset is on (`passwordReset.send`), the OpenID Connect ones only
|
|
40
|
+
* with a provider. Checked once
|
|
35
41
|
* per config, before the first attempt is counted, so a setup mistake is one clear error instead of
|
|
36
42
|
* a generic failure on every login.
|
|
37
43
|
*/
|
|
@@ -39,8 +45,10 @@ export function assertAuthBuckets(config: SoftureConfig): void {
|
|
|
39
45
|
if (checkedConfigs.has(config)) return;
|
|
40
46
|
const options = getModule(config, "security")?.options as { buckets?: Readonly<Record<string, unknown>> } | undefined;
|
|
41
47
|
const configured = options?.buckets ?? {};
|
|
42
|
-
const
|
|
43
|
-
const
|
|
48
|
+
const authOptions = getAuthOptions(config);
|
|
49
|
+
const isResetOn = authOptions.passwordReset.send !== undefined;
|
|
50
|
+
const isOidcOn = authOptions.oidc.providers.length > 0;
|
|
51
|
+
const required = Object.values(BUCKETS).filter((name) => (isResetOn || !RESET_BUCKETS.has(name)) && (isOidcOn || !OIDC_BUCKETS.has(name)));
|
|
44
52
|
const missing = required.filter((name) => !Object.hasOwn(configured, name));
|
|
45
53
|
if (missing.length > 0) {
|
|
46
54
|
throw new Error(
|
package/src/server/register.ts
CHANGED
|
@@ -68,10 +68,10 @@ export async function registerUser(ctx: AuthContext, input: RegisterInput): Prom
|
|
|
68
68
|
.onConflictDoNothing({ target: users.email })
|
|
69
69
|
.returning();
|
|
70
70
|
if (row === undefined) return err("auth.email_taken");
|
|
71
|
-
const user = { id: row.id, email: row.email, createdAt: row.createdAt };
|
|
71
|
+
const user = { id: row.id, email: row.email, createdAt: row.createdAt, displayName: row.displayName };
|
|
72
72
|
|
|
73
73
|
const fields = pickRegistrationFields(options.registrationFields, input.fields);
|
|
74
|
-
await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields }, txCtx);
|
|
74
|
+
await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields, oidcProvider: null }, txCtx);
|
|
75
75
|
const session = await createSession(txCtx, user.id);
|
|
76
76
|
return ok({ user, session });
|
|
77
77
|
});
|
package/src/server/sessions.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { ModuleContext } from "@softure-ai/core";
|
|
|
3
3
|
import type { Queryable } from "@softure-ai/db";
|
|
4
4
|
import { and, eq, gt, lte, ne } from "drizzle-orm";
|
|
5
5
|
import type { AuthUser, NewSession } from "../contract.js";
|
|
6
|
-
import { sessions, users } from "../schema.js";
|
|
6
|
+
import { AUTH_USER_COLUMNS, sessions, users } from "../schema.js";
|
|
7
7
|
import { getAuthOptions, getLegacyTokenPattern } from "./options.js";
|
|
8
8
|
import { createSessionToken, hashSessionToken, isSessionTokenShape } from "./session-token.js";
|
|
9
9
|
|
|
@@ -24,7 +24,7 @@ export async function createSession(ctx: AuthContext, userId: string): Promise<N
|
|
|
24
24
|
export async function findSessionUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
|
|
25
25
|
if (!isSessionTokenShape(token, getLegacyTokenPattern(ctx.config))) return null;
|
|
26
26
|
const [row] = await ctx.db
|
|
27
|
-
.select(
|
|
27
|
+
.select(AUTH_USER_COLUMNS)
|
|
28
28
|
.from(sessions)
|
|
29
29
|
.innerJoin(users, eq(users.id, sessions.userId))
|
|
30
30
|
.where(and(eq(sessions.tokenHash, hashSessionToken(token)), gt(sessions.expiresAt, ctx.clock.now())))
|
package/src/server/switches.ts
CHANGED
|
@@ -14,9 +14,10 @@ const OFF = new Set(["false", "0"]);
|
|
|
14
14
|
* Whether registration is closed. The app's switch provider answers first (env override, stored
|
|
15
15
|
* value, default and fail mode as it defines them). Without one, the env override wins over the
|
|
16
16
|
* declared default; a value it cannot read closes registration (fail closed) and is logged once, by
|
|
17
|
-
* name, never by value.
|
|
17
|
+
* name, never by value. With `password.enabled: false` the register form is gone, so it is always closed.
|
|
18
18
|
*/
|
|
19
19
|
export async function isRegistrationClosed(ctx: ModuleContext, env: Readonly<Record<string, string | undefined>> = process.env): Promise<boolean> {
|
|
20
|
+
if (!getAuthOptions(ctx.config).password.enabled) return true;
|
|
20
21
|
const reading = await readSwitch(ctx, REGISTRATION_CLOSED_SWITCH);
|
|
21
22
|
if (reading.kind === "value") return reading.isEnabled;
|
|
22
23
|
const override = env[REGISTRATION_CLOSED_ENV]?.trim().toLowerCase();
|
package/src/testing/account.ts
CHANGED
|
@@ -71,11 +71,11 @@ export async function createTestAccount(target: Queryable | AuthContext, input:
|
|
|
71
71
|
if (row === undefined) throw new Error(`createTestAccount: an account with the email "${email.value}" already exists`);
|
|
72
72
|
const roles = input.roles ?? [];
|
|
73
73
|
if (roles.length > 0) await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
|
|
74
|
-
const user = { id: row.id, email: row.email, createdAt: row.createdAt };
|
|
74
|
+
const user = { id: row.id, email: row.email, createdAt: row.createdAt, displayName: row.displayName };
|
|
75
75
|
if (input.runHooks === true && ctx !== null) {
|
|
76
76
|
const options = getAuthOptions(ctx.config);
|
|
77
77
|
const consent = options.requireConsent ? { acceptedAt: now } : null;
|
|
78
|
-
await options.onRegistered?.({ user, consent, fields: input.fields ?? {} }, { ...ctx, db: tx });
|
|
78
|
+
await options.onRegistered?.({ user, consent, fields: input.fields ?? {}, oidcProvider: null }, { ...ctx, db: tx });
|
|
79
79
|
}
|
|
80
80
|
return user;
|
|
81
81
|
});
|
package/src/testing/index.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
1
|
// Test helpers of @softure-ai/auth: accounts created directly in the database, for tests that need
|
|
2
|
-
// a user but are not about registration
|
|
2
|
+
// a user but are not about registration, and a fake OpenID Connect provider for tests of the sign-in.
|
|
3
|
+
// Server-only; never imported by the module's runtime code.
|
|
3
4
|
export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
|
|
5
|
+
export {
|
|
6
|
+
createFakeOidcProvider,
|
|
7
|
+
type FakeOidcFailure,
|
|
8
|
+
type FakeOidcProvider,
|
|
9
|
+
type FakeOidcProviderOptions,
|
|
10
|
+
type FakeOidcUser,
|
|
11
|
+
type FakeSignInOptions,
|
|
12
|
+
} from "./oidc-provider.js";
|