@softure-ai/auth 0.2.6 → 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.
Files changed (65) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +18 -8
  3. package/dist/contract.d.ts +6 -0
  4. package/dist/contract.d.ts.map +1 -1
  5. package/dist/contract.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/messages/index.d.ts +20 -2
  8. package/dist/messages/index.d.ts.map +1 -1
  9. package/dist/messages/index.js +13 -3
  10. package/dist/messages/index.js.map +1 -1
  11. package/dist/schema.d.ts +88 -0
  12. package/dist/schema.d.ts.map +1 -1
  13. package/dist/schema.js +5 -1
  14. package/dist/schema.js.map +1 -1
  15. package/dist/server/login.js +1 -1
  16. package/dist/server/login.js.map +1 -1
  17. package/dist/server/oidc/accounts.d.ts +2 -0
  18. package/dist/server/oidc/accounts.d.ts.map +1 -1
  19. package/dist/server/oidc/accounts.js +18 -10
  20. package/dist/server/oidc/accounts.js.map +1 -1
  21. package/dist/server/oidc/flow.js +2 -2
  22. package/dist/server/oidc/flow.js.map +1 -1
  23. package/dist/server/oidc/id-token.d.ts +9 -0
  24. package/dist/server/oidc/id-token.d.ts.map +1 -1
  25. package/dist/server/oidc/id-token.js +17 -0
  26. package/dist/server/oidc/id-token.js.map +1 -1
  27. package/dist/server/password-reset.d.ts.map +1 -1
  28. package/dist/server/password-reset.js +4 -5
  29. package/dist/server/password-reset.js.map +1 -1
  30. package/dist/server/privacy.d.ts +2 -0
  31. package/dist/server/privacy.d.ts.map +1 -1
  32. package/dist/server/privacy.js +2 -2
  33. package/dist/server/privacy.js.map +1 -1
  34. package/dist/server/register.js +1 -1
  35. package/dist/server/register.js.map +1 -1
  36. package/dist/server/sessions.js +2 -2
  37. package/dist/server/sessions.js.map +1 -1
  38. package/dist/testing/account.js +1 -1
  39. package/dist/testing/account.js.map +1 -1
  40. package/dist/testing/oidc-provider.d.ts +4 -0
  41. package/dist/testing/oidc-provider.d.ts.map +1 -1
  42. package/dist/testing/oidc-provider.js +4 -0
  43. package/dist/testing/oidc-provider.js.map +1 -1
  44. package/dist/ui/oidc-sign-in.d.ts +1 -1
  45. package/dist/ui/oidc-sign-in.d.ts.map +1 -1
  46. package/dist/ui/oidc-sign-in.js +3 -1
  47. package/dist/ui/oidc-sign-in.js.map +1 -1
  48. package/migrations/0006_add_users_display_name.sql +8 -0
  49. package/module.json +1 -1
  50. package/package.json +1 -1
  51. package/src/contract.ts +6 -0
  52. package/src/index.ts +1 -1
  53. package/src/messages/index.ts +29 -4
  54. package/src/schema.ts +6 -1
  55. package/src/server/login.ts +1 -1
  56. package/src/server/oidc/accounts.ts +20 -10
  57. package/src/server/oidc/flow.ts +2 -2
  58. package/src/server/oidc/id-token.ts +19 -0
  59. package/src/server/password-reset.ts +4 -5
  60. package/src/server/privacy.ts +4 -2
  61. package/src/server/register.ts +1 -1
  62. package/src/server/sessions.ts +2 -2
  63. package/src/testing/account.ts +1 -1
  64. package/src/testing/oidc-provider.ts +6 -0
  65. package/src/ui/oidc-sign-in.tsx +4 -3
@@ -1,13 +1,13 @@
1
1
  // The account an OpenID Connect identity signs in to. The provider's subject finds it (`auth.identities`), so an
2
2
  // email change at the provider keeps it; a first sign-in links the account with the same verified email, or creates
3
3
  // one with an unusable password when the provider may create accounts. One transaction, so two first sign-ins at
4
- // once end with one account and one identity.
4
+ // once end with one account and one identity. Every sign-in that carries a display name stores it on the account.
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { err, ok, type Err, type Ok } from "@softure-ai/core";
7
7
  import { and, eq } from "drizzle-orm";
8
8
  import type { AuthUser } from "../../contract.js";
9
9
  import type { OidcProvider } from "../../options.js";
10
- import { identities, users } from "../../schema.js";
10
+ import { AUTH_USER_COLUMNS, identities, users } from "../../schema.js";
11
11
  import { getAuthOptions } from "../options.js";
12
12
  import { hashPassword } from "../password.js";
13
13
  import type { AuthContext } from "../sessions.js";
@@ -16,6 +16,8 @@ export interface OidcIdentity {
16
16
  readonly subject: string;
17
17
  /** Verified, trimmed and lowercased. */
18
18
  readonly email: string;
19
+ /** Normalized (`toDisplayName`); null when the token carries none, which keeps the stored one. */
20
+ readonly displayName: string | null;
19
21
  }
20
22
 
21
23
  export type OidcAccountResult = Ok<AuthUser> | Err<"auth.oidc_no_account">;
@@ -28,7 +30,7 @@ export async function resolveOidcAccount(ctx: AuthContext, provider: OidcProvide
28
30
  const txCtx: AuthContext = { ...ctx, db: tx };
29
31
  const findLinked = async (): Promise<AuthUser | undefined> => {
30
32
  const [row] = await tx
31
- .select({ id: users.id, email: users.email, createdAt: users.createdAt })
33
+ .select(AUTH_USER_COLUMNS)
32
34
  .from(identities)
33
35
  .innerJoin(users, eq(users.id, identities.userId))
34
36
  .where(and(eq(identities.provider, provider.id), eq(identities.subject, identity.subject)))
@@ -42,11 +44,11 @@ export async function resolveOidcAccount(ctx: AuthContext, provider: OidcProvide
42
44
  .update(identities)
43
45
  .set({ email: identity.email, lastLoginAt: now })
44
46
  .where(and(eq(identities.provider, provider.id), eq(identities.subject, identity.subject)));
45
- return ok(linked);
47
+ return ok(await storeDisplayName(tx, linked, identity.displayName));
46
48
  }
47
49
 
48
50
  let [user] = await tx
49
- .select({ id: users.id, email: users.email, createdAt: users.createdAt })
51
+ .select(AUTH_USER_COLUMNS)
50
52
  .from(users)
51
53
  .where(eq(users.email, identity.email))
52
54
  .limit(1);
@@ -57,14 +59,14 @@ export async function resolveOidcAccount(ctx: AuthContext, provider: OidcProvide
57
59
  const unusablePassword = await hashPassword(randomBytes(32).toString("base64url"), options.password.scrypt);
58
60
  const [created] = await tx
59
61
  .insert(users)
60
- .values({ email: identity.email, passwordHash: unusablePassword, createdAt: now, passwordChangedAt: now })
62
+ .values({ email: identity.email, passwordHash: unusablePassword, createdAt: now, passwordChangedAt: now, displayName: identity.displayName })
61
63
  .onConflictDoNothing({ target: users.email })
62
- .returning({ id: users.id, email: users.email, createdAt: users.createdAt });
64
+ .returning(AUTH_USER_COLUMNS);
63
65
  isCreated = created !== undefined;
64
66
  // Taken meanwhile by another sign-in or a registration: that account is the one to link.
65
67
  [user] =
66
68
  created === undefined
67
- ? await tx.select({ id: users.id, email: users.email, createdAt: users.createdAt }).from(users).where(eq(users.email, identity.email)).limit(1)
69
+ ? await tx.select(AUTH_USER_COLUMNS).from(users).where(eq(users.email, identity.email)).limit(1)
68
70
  : [created];
69
71
  if (user === undefined) return err("auth.oidc_no_account");
70
72
  }
@@ -76,7 +78,15 @@ export async function resolveOidcAccount(ctx: AuthContext, provider: OidcProvide
76
78
  // The pair may have been linked meanwhile; an account that already has another subject of this provider is refused.
77
79
  const nowLinked = await findLinked();
78
80
  if (nowLinked?.id !== user.id) return err("auth.oidc_no_account");
79
- if (isCreated) await options.onRegistered?.({ user, consent: null, fields: {}, oidcProvider: provider.id }, txCtx);
80
- return ok(user);
81
+ const signedIn = await storeDisplayName(tx, user, identity.displayName);
82
+ if (isCreated) await options.onRegistered?.({ user: signedIn, consent: null, fields: {}, oidcProvider: provider.id }, txCtx);
83
+ return ok(signedIn);
81
84
  });
82
85
  }
86
+
87
+ /** The account with the provider's display name stored; unchanged when the token carries none or the same one. */
88
+ async function storeDisplayName(db: AuthContext["db"], user: AuthUser, displayName: string | null): Promise<AuthUser> {
89
+ if (displayName === null || displayName === user.displayName) return user;
90
+ await db.update(users).set({ displayName }).where(eq(users.id, user.id));
91
+ return { ...user, displayName };
92
+ }
@@ -25,7 +25,7 @@ import { exchangeCode } from "./token-request.js";
25
25
  const RANDOM_BYTES = 32;
26
26
  const MAX_STATE_LENGTH = 512;
27
27
  const MAX_CODE_LENGTH = 4096;
28
- const REQUIRED_SCOPES = ["openid", "email"];
28
+ const REQUIRED_SCOPES = ["openid", "email", "profile"];
29
29
 
30
30
  export interface StartOidcSignInInput {
31
31
  readonly provider: string;
@@ -150,7 +150,7 @@ export async function completeOidcSignIn(ctx: OidcContext, input: CompleteOidcSi
150
150
 
151
151
  const email = getAllowedEmail(provider, claims.value);
152
152
  if (email === null) return err("auth.oidc_not_allowed");
153
- const account = await resolveOidcAccount(ctx, provider, { subject: claims.value.subject, email });
153
+ const account = await resolveOidcAccount(ctx, provider, { subject: claims.value.subject, email, displayName: claims.value.displayName });
154
154
  if (!account.ok) return account;
155
155
 
156
156
  await deleteExpiredSessions(ctx, account.value.id);
@@ -8,6 +8,8 @@ import { passed, refused, type Checked } from "./context.js";
8
8
  /** Clock skew tolerated between this server and the provider. */
9
9
  const SKEW_SECONDS = 60;
10
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;
11
13
  const SEGMENT = /^[A-Za-z0-9_-]+$/;
12
14
 
13
15
  const ALGORITHMS = { RS256: "RSA", ES256: "EC" } as const;
@@ -27,6 +29,9 @@ const claimsSchema = z.object({
27
29
  // Most providers send a boolean; some send the string.
28
30
  email_verified: z.union([z.boolean(), z.enum(["true", "false"]).transform((value) => value === "true")]).optional(),
29
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(),
30
35
  });
31
36
 
32
37
  export interface DecodedIdToken {
@@ -94,6 +99,8 @@ export interface IdentityClaims {
94
99
  readonly email: string | null;
95
100
  readonly isEmailVerified: boolean;
96
101
  readonly hostedDomain: string | null;
102
+ /** `name`, else `given_name`, normalized; null when the token carries neither. */
103
+ readonly displayName: string | null;
97
104
  }
98
105
 
99
106
  /** The identity, or the reason (for the log) the claims do not fit this sign-in. */
@@ -114,9 +121,21 @@ export function checkIdTokenClaims(payload: unknown, expected: ExpectedClaims):
114
121
  email: claims.email === undefined ? null : claims.email.trim().toLowerCase(),
115
122
  isEmailVerified: claims.email_verified === true,
116
123
  hostedDomain: claims.hd === undefined ? null : claims.hd.trim().toLowerCase(),
124
+ displayName: toDisplayName(claims.name) ?? toDisplayName(claims.given_name),
117
125
  });
118
126
  }
119
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
+
120
139
  function isSameText(a: string, b: string): boolean {
121
140
  const left = Buffer.from(a, "utf8");
122
141
  const right = Buffer.from(b, "utf8");
@@ -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";
@@ -68,7 +68,7 @@ export async function deliverPasswordReset(ctx: AuthContext, email: string): Pro
68
68
  if (send === undefined) {
69
69
  throw new Error("@softure-ai/auth: deliverPasswordReset needs auth({ passwordReset: { send } })");
70
70
  }
71
- const [user] = await ctx.db.select(USER_COLUMNS).from(users).where(eq(users.email, email)).limit(1);
71
+ const [user] = await ctx.db.select(AUTH_USER_COLUMNS).from(users).where(eq(users.email, email)).limit(1);
72
72
  if (user === undefined) return "no_account";
73
73
  if (enqueue !== undefined) {
74
74
  await enqueue(ctx, user.id);
@@ -88,13 +88,12 @@ export async function sendPasswordReset(ctx: AuthContext, userId: string): Promi
88
88
  if (send === undefined) {
89
89
  throw new Error("@softure-ai/auth: sendPasswordReset needs auth({ passwordReset: { send } })");
90
90
  }
91
- const [user] = await ctx.db.select(USER_COLUMNS).from(users).where(eq(users.id, userId)).limit(1);
91
+ const [user] = await ctx.db.select(AUTH_USER_COLUMNS).from(users).where(eq(users.id, userId)).limit(1);
92
92
  if (user === undefined) return "no_account";
93
93
  await issueAndSend(ctx, user, send);
94
94
  return "sent";
95
95
  }
96
96
 
97
- const USER_COLUMNS = { id: users.id, email: users.email, createdAt: users.createdAt };
98
97
 
99
98
  async function issueAndSend(ctx: AuthContext, user: AuthUser, send: PasswordResetSender): Promise<void> {
100
99
  const { token, expiresAt } = await issuePasswordReset(ctx, user.id);
@@ -124,7 +123,7 @@ export function getPasswordResetLink(config: SoftureConfig, token: string): stri
124
123
  export async function findPasswordResetUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
125
124
  if (!isSessionTokenShape(token)) return null;
126
125
  const [row] = await ctx.db
127
- .select({ id: users.id, email: users.email, createdAt: users.createdAt })
126
+ .select(AUTH_USER_COLUMNS)
128
127
  .from(passwordResets)
129
128
  .innerJoin(users, eq(users.id, passwordResets.userId))
130
129
  .where(and(eq(passwordResets.tokenHash, hashSessionToken(token)), gt(passwordResets.expiresAt, ctx.clock.now())))
@@ -1,4 +1,4 @@
1
- // The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account, its roles, its
1
+ // The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account (with its display name), its roles, its
2
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";
@@ -13,6 +13,8 @@ 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 }[];
@@ -38,7 +40,7 @@ export async function exportAuthUserData(context: ModuleContext, userId: string)
38
40
  // Core types `db` as unknown; privacy passes the @softure-ai/db handle or its transaction.
39
41
  const db = context.db as Queryable;
40
42
  const [account] = await db
41
- .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 })
42
44
  .from(users)
43
45
  .where(eq(users.id, userId));
44
46
  const roles = await db
@@ -68,7 +68,7 @@ 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
74
  await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields, oidcProvider: null }, txCtx);
@@ -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({ id: users.id, email: users.email, createdAt: users.createdAt })
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())))
@@ -71,7 +71,7 @@ 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;
@@ -34,6 +34,10 @@ export interface FakeOidcUser {
34
34
  readonly emailVerified?: boolean;
35
35
  /** Google's Workspace domain claim. */
36
36
  readonly hostedDomain?: string;
37
+ /** The `name` claim (sent with the `profile` scope). */
38
+ readonly name?: string;
39
+ /** The `given_name` claim. */
40
+ readonly givenName?: string;
37
41
  }
38
42
 
39
43
  export interface FakeSignInOptions {
@@ -131,6 +135,8 @@ export function createFakeOidcProvider(options: FakeOidcProviderOptions = {}): F
131
135
  };
132
136
  if (pending.nonce !== null) claims.nonce = pending.nonce;
133
137
  if (pending.user.hostedDomain !== undefined) claims.hd = pending.user.hostedDomain;
138
+ if (pending.user.name !== undefined) claims.name = pending.user.name;
139
+ if (pending.user.givenName !== undefined) claims.given_name = pending.user.givenName;
134
140
  for (const [name, value] of Object.entries(pending.options.claims ?? {})) {
135
141
  if (value === undefined) delete claims[name];
136
142
  else claims[name] = value;
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { formatMessage } from "@softure-ai/core";
4
4
  import { Button, type ButtonVariant, type ClassNames, createSlotClassGetter, FormError } from "@softure-ai/ui";
5
- import type { AuthMessages } from "../messages/index.js";
5
+ import { type AuthMessages, getOidcMessages } from "../messages/index.js";
6
6
 
7
7
  // The OpenID Connect buttons: one small form per provider, posting `provider` and `next` to the start action
8
8
  // (`oidcSignInAction` of `@softure-ai/auth/next`), so it works without JavaScript. Copy comes from messages.
@@ -42,6 +42,7 @@ const DEFAULT_CLASSES: Readonly<Record<OidcSignInSlot, string>> = {
42
42
  export function OidcSignIn(props: OidcSignInProps) {
43
43
  const { action, providers, messages, next, error, hasDivider = false, classNames, unstyled, submitVariant = "secondary" } = props;
44
44
  const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
45
+ const copy = getOidcMessages(messages);
45
46
  return (
46
47
  <div className={slot("root")}>
47
48
  <FormError message={error} unstyled={unstyled} />
@@ -50,11 +51,11 @@ export function OidcSignIn(props: OidcSignInProps) {
50
51
  <input type="hidden" name="provider" value={provider.id} />
51
52
  {next === undefined ? null : <input type="hidden" name="next" value={next} />}
52
53
  <Button type="submit" variant={submitVariant} fullWidth classNames={{ root: slot("submit") }} unstyled={unstyled}>
53
- {formatMessage(messages.oidc.signInWith, { provider: provider.name })}
54
+ {formatMessage(copy.signInWith, { provider: provider.name })}
54
55
  </Button>
55
56
  </form>
56
57
  ))}
57
- {hasDivider ? <p className={slot("divider")}>{messages.oidc.divider}</p> : null}
58
+ {hasDivider ? <p className={slot("divider")}>{copy.divider}</p> : null}
58
59
  </div>
59
60
  );
60
61
  }