@cedarjs/auth-dbauth-api 7.1.0 → 7.1.1-next.468

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.
@@ -1,6 +1,7 @@
1
- import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/types';
1
+ import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server';
2
2
  import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda';
3
3
  import type { CorsConfig, CorsContext, PartialRequest } from '@cedarjs/api';
4
+ import type { DbAuthCookieConfig } from './session.js';
4
5
  interface SignupFlowOptions<TUserAttributes = Record<string, unknown>> {
5
6
  /**
6
7
  * Allow users to sign up. Defaults to true.
@@ -96,6 +97,33 @@ interface ResetPasswordFlowOptions<TUser = UserType> {
96
97
  flowNotEnabled?: string;
97
98
  };
98
99
  }
100
+ interface ChangePasswordFlowOptions<TUser = UserType> {
101
+ /**
102
+ * Allow logged in users to change their password by providing their current
103
+ * one. Defaults to true.
104
+ * Needs to be explicitly set to false to disable the flow
105
+ */
106
+ enabled?: boolean;
107
+ /**
108
+ * Invoked after the new password has been saved. This is where you can
109
+ * notify the user that their password was changed. Returning anything
110
+ * truthy keeps the user logged in. Returning anything falsy logs them out.
111
+ */
112
+ handler: (user: TUser) => boolean | Promise<boolean>;
113
+ /**
114
+ * If `false` (the default) the new password MUST be different from the
115
+ * current one
116
+ */
117
+ allowReusedPassword?: boolean;
118
+ errors?: {
119
+ currentPasswordRequired?: string;
120
+ newPasswordRequired?: string;
121
+ incorrectCurrentPassword?: string;
122
+ passwordNotSet?: string;
123
+ reusedPassword?: string;
124
+ flowNotEnabled?: string;
125
+ };
126
+ }
99
127
  interface WebAuthnFlowOptions {
100
128
  enabled: boolean;
101
129
  expires: number;
@@ -168,35 +196,15 @@ export interface DbAuthHandlerOptions<TUser = UserType, TUserAttributes = Record
168
196
  challenge?: string;
169
197
  };
170
198
  /**
171
- * Object containing cookie config options
199
+ * Object containing change password options
172
200
  */
173
- cookie?: {
174
- /** @deprecated set this option in `cookie.attributes` */
175
- Path?: string;
176
- /** @deprecated set this option in `cookie.attributes` */
177
- HttpOnly?: boolean;
178
- /** @deprecated set this option in `cookie.attributes` */
179
- Secure?: boolean;
180
- /** @deprecated set this option in `cookie.attributes` */
181
- SameSite?: string;
182
- /** @deprecated set this option in `cookie.attributes` */
183
- Domain?: string;
184
- attributes?: {
185
- Path?: string;
186
- HttpOnly?: boolean;
187
- Secure?: boolean;
188
- SameSite?: string;
189
- Domain?: string;
190
- };
191
- /**
192
- * The name of the cookie that dbAuth sets
193
- *
194
- * %port% will be replaced with the port the api server is running on.
195
- * If you have multiple RW apps running on the same host, you'll need to
196
- * make sure they all use unique cookie names
197
- */
198
- name?: string;
201
+ changePassword: ChangePasswordFlowOptions<TUser> | {
202
+ enabled: false;
199
203
  };
204
+ /**
205
+ * Object containing cookie config options
206
+ */
207
+ cookie?: DbAuthCookieConfig;
200
208
  /**
201
209
  * Object containing forgot password options
202
210
  */
@@ -249,11 +257,13 @@ export interface SignupHandlerOptions<TUserAttributes> {
249
257
  salt: string;
250
258
  userAttributes?: TUserAttributes;
251
259
  }
252
- export type AuthMethodNames = 'forgotPassword' | 'getToken' | 'login' | 'logout' | 'resetPassword' | 'signup' | 'webAuthnAuthenticate' | 'webAuthnAuthOptions' | 'webAuthnRegOptions' | 'webAuthnRegister' | 'validateResetToken';
260
+ export type AuthMethodNames = 'changePassword' | 'forgotPassword' | 'getToken' | 'login' | 'logout' | 'resetPassword' | 'signup' | 'webAuthnAuthenticate' | 'webAuthnAuthOptions' | 'webAuthnRegOptions' | 'webAuthnRegister' | 'validateResetToken';
253
261
  type Params = AuthenticationResponseJSON & RegistrationResponseJSON & {
254
262
  username?: string;
255
263
  password?: string;
256
264
  resetToken?: string;
265
+ currentPassword?: string;
266
+ newPassword?: string;
257
267
  method: AuthMethodNames;
258
268
  [key: string]: any;
259
269
  } & {
@@ -290,6 +300,7 @@ export declare class DbAuthHandler<TUser extends UserType, TUserAttributes = Rec
290
300
  get normalizedRequest(): PartialRequest<Params>;
291
301
  static get METHODS(): AuthMethodNames[];
292
302
  static get VERBS(): {
303
+ changePassword: string;
293
304
  forgotPassword: string;
294
305
  getToken: string;
295
306
  login: string;
@@ -325,6 +336,7 @@ export declare class DbAuthHandler<TUser extends UserType, TUserAttributes = Rec
325
336
  }>;
326
337
  _requestHost(): string | null;
327
338
  _requestProtocol(): string | null;
339
+ changePassword(): Promise<AuthMethodOutput>;
328
340
  forgotPassword(): Promise<AuthMethodOutput>;
329
341
  getToken(): Promise<AuthMethodOutput>;
330
342
  login(): Promise<AuthMethodOutput>;
@@ -339,25 +351,24 @@ export declare class DbAuthHandler<TUser extends UserType, TUserAttributes = Rec
339
351
  _validateOptions(): void;
340
352
  _saveChallenge(userId: string | number, value: string | null): Promise<void>;
341
353
  _webAuthnCookie(id: string, expires: string): string;
342
- _sanitizeUser(user: Record<string, unknown>): any;
354
+ _sanitizeUser(user: Record<string, unknown>): Record<string, unknown>;
343
355
  _decodeEvent(): void;
344
356
  _cookieAttributes({ expires, options, }: {
345
357
  expires?: 'now' | string;
346
358
  options?: DbAuthHandlerOptions['cookie'];
347
- }): (string | null)[];
359
+ }): string[];
348
360
  _createAuthProviderCookieString(): string;
349
361
  _createSessionCookieString<TIdType = any>(data: DbAuthSession<TIdType>, csrfToken: string): string;
350
362
  _findUserByToken(token: string): Promise<any>;
351
363
  _clearResetToken(user: Record<string, unknown>): Promise<void>;
352
364
  _verifyUser(username: string | undefined, password: string | undefined): Promise<any>;
353
365
  _verifyPassword(user: Record<string, unknown>, password: string): Promise<Record<string, unknown>>;
366
+ _passwordMatches(user: Record<string, unknown>, password: string): boolean;
354
367
  _getCurrentUser(): Promise<any>;
355
368
  _createUser(): Promise<any>;
356
369
  _getAuthMethod(): Promise<AuthMethodNames>;
357
370
  _validateField(name: string, value: string | undefined): value is string;
358
- _loginResponse(user: Record<string, any>, statusCode?: number): [{
359
- id: string;
360
- }, Headers, {
371
+ _loginResponse(user: Record<string, any>, statusCode?: number): [Record<string, any>, Headers, {
361
372
  statusCode: number;
362
373
  }];
363
374
  _logoutResponse(response?: Record<string, unknown>): AuthMethodOutput;
@@ -1 +1 @@
1
- {"version":3,"file":"DbAuthHandler.d.ts","sourceRoot":"","sources":["../src/DbAuthHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,0BAA0B,EAC1B,wBAAwB,EACzB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,YAAY,CAAA;AAIhF,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AA8B3E,UAAU,iBAAiB,CAAC,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACnE;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;;OAOG;IACH,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,eAAe,CAAC,KAAK,GAAG,CAAA;IAE7E;;;OAGG;IACH,kBAAkB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAA;IAElD;;OAEG;IACH,MAAM,CAAC,EAAE;QACP,YAAY,CAAC,EAAE,MAAM,CAAA;QACrB,aAAa,CAAC,EAAE,MAAM,CAAA;QACtB,cAAc,CAAC,EAAE,MAAM,CAAA;KACxB,CAAA;IAED;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,UAAU,yBAAyB,CAAC,KAAK,GAAG,QAAQ;IAClD;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,KAAK,GAAG,CAAA;IAC5C,MAAM,CAAC,EAAE;QACP,gBAAgB,CAAC,EAAE,MAAM,CAAA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4BAA4B,CAC1B,QAAQ,EAAE,MAAM,EAChB,uBAAuB,EAAE,MAAM,GAAG,SAAS;;;;;;;;CAgB9C"}
@@ -13,9 +13,18 @@ import {
13
13
  resolveRequestHost,
14
14
  resolveRequestProtocol
15
15
  } from "./originValidation.js";
16
+ import {
17
+ buildCookieAttributes,
18
+ createAuthProviderCookieString,
19
+ createCsrfToken,
20
+ createExpiresAtDate,
21
+ createLoginResponse,
22
+ createSessionCookieString,
23
+ DEFAULT_ALLOWED_USER_FIELDS,
24
+ sanitizeUser
25
+ } from "./session.js";
16
26
  import {
17
27
  decryptSession,
18
- encryptSession,
19
28
  extractCookie,
20
29
  extractHashingOptions,
21
30
  generateCookieName,
@@ -27,7 +36,6 @@ import {
27
36
  legacyHashPassword,
28
37
  webAuthnSession
29
38
  } from "./shared.js";
30
- const DEFAULT_ALLOWED_USER_FIELDS = ["id", "email"];
31
39
  class DbAuthHandler {
32
40
  event;
33
41
  _normalizedRequest;
@@ -57,6 +65,7 @@ class DbAuthHandler {
57
65
  // class constant: list of auth methods that are supported
58
66
  static get METHODS() {
59
67
  return [
68
+ "changePassword",
60
69
  "forgotPassword",
61
70
  "getToken",
62
71
  "login",
@@ -73,6 +82,7 @@ class DbAuthHandler {
73
82
  // class constant: maps the auth functions to their required HTTP verb for access
74
83
  static get VERBS() {
75
84
  return {
85
+ changePassword: "POST",
76
86
  forgotPassword: "POST",
77
87
  getToken: "GET",
78
88
  login: "POST",
@@ -92,7 +102,7 @@ class DbAuthHandler {
92
102
  }
93
103
  // generate a new token (standard UUID)
94
104
  static get CSRF_TOKEN() {
95
- return uuidv4();
105
+ return createCsrfToken();
96
106
  }
97
107
  static get AVAILABLE_WEBAUTHN_TRANSPORTS() {
98
108
  return ["usb", "ble", "nfc", "internal"];
@@ -135,11 +145,9 @@ class DbAuthHandler {
135
145
  this.dbCredentialAccessor = this.options.credentialModelAccessor ? this.db[this.options.credentialModelAccessor] : null;
136
146
  this.hasInvalidSession = false;
137
147
  this.allowedUserFields = this.options.allowedUserFields || DEFAULT_ALLOWED_USER_FIELDS;
138
- const sessionExpiresAt = /* @__PURE__ */ new Date();
139
- sessionExpiresAt.setSeconds(
140
- sessionExpiresAt.getSeconds() + this.options.login.expires
148
+ this.sessionExpiresDate = createExpiresAtDate(
149
+ this.options.login.expires
141
150
  );
142
- this.sessionExpiresDate = sessionExpiresAt.toUTCString();
143
151
  const webAuthnExpiresAt = /* @__PURE__ */ new Date();
144
152
  webAuthnExpiresAt.setSeconds(
145
153
  webAuthnExpiresAt.getSeconds() + (this.options?.webAuthn?.expires || 0)
@@ -244,6 +252,83 @@ class DbAuthHandler {
244
252
  isFetchApiRequest(this.event) ? this.event.url : void 0
245
253
  );
246
254
  }
255
+ async changePassword() {
256
+ const options = this.options.changePassword;
257
+ if (!options || options.enabled === false) {
258
+ throw new DbAuthError.FlowNotEnabledError(
259
+ options?.errors?.flowNotEnabled || `Change password flow is not enabled`
260
+ );
261
+ }
262
+ const sessionUserId = this.session?.[this.options.authFields.id];
263
+ if (!sessionUserId) {
264
+ throw new DbAuthError.NotLoggedInError();
265
+ }
266
+ const { currentPassword, newPassword } = this.normalizedRequest.jsonBody || {};
267
+ if (currentPassword == null || String(currentPassword).trim() === "") {
268
+ throw new DbAuthError.PasswordRequiredError(
269
+ options.errors?.currentPasswordRequired || "Current password is required"
270
+ );
271
+ }
272
+ if (newPassword == null || String(newPassword).trim() === "") {
273
+ throw new DbAuthError.PasswordRequiredError(
274
+ options.errors?.newPasswordRequired || "New password is required"
275
+ );
276
+ }
277
+ ;
278
+ this.options.signup.passwordValidation?.(
279
+ newPassword
280
+ );
281
+ let user;
282
+ try {
283
+ user = await this.dbAccessor.findUnique({
284
+ where: { [this.options.authFields.id]: sessionUserId }
285
+ });
286
+ } catch {
287
+ throw new DbAuthError.GenericError();
288
+ }
289
+ if (!user) {
290
+ throw new DbAuthError.UserNotFoundError();
291
+ }
292
+ if (!user[this.options.authFields.hashedPassword]) {
293
+ throw new DbAuthError.PasswordNotSetError(options.errors?.passwordNotSet);
294
+ }
295
+ try {
296
+ await this._verifyPassword(user, currentPassword);
297
+ } catch (e) {
298
+ if (e instanceof DbAuthError.IncorrectPasswordError) {
299
+ throw new DbAuthError.IncorrectPasswordError(
300
+ user[this.options.authFields.username],
301
+ options.errors?.incorrectCurrentPassword || "Current password is incorrect"
302
+ );
303
+ }
304
+ throw e;
305
+ }
306
+ if (!options.allowReusedPassword && this._passwordMatches(user, newPassword)) {
307
+ throw new DbAuthError.ReusedPasswordError(options.errors?.reusedPassword);
308
+ }
309
+ const [hashedPassword, salt] = hashPassword(newPassword);
310
+ try {
311
+ user = await this.dbAccessor.update({
312
+ where: {
313
+ [this.options.authFields.id]: user[this.options.authFields.id]
314
+ },
315
+ data: {
316
+ [this.options.authFields.hashedPassword]: hashedPassword,
317
+ [this.options.authFields.salt]: salt,
318
+ [this.options.authFields.resetToken]: null,
319
+ [this.options.authFields.resetTokenExpiresAt]: null
320
+ }
321
+ });
322
+ } catch {
323
+ throw new DbAuthError.GenericError();
324
+ }
325
+ const response = await options.handler(this._sanitizeUser(user));
326
+ if (response) {
327
+ return this._loginResponse(user);
328
+ } else {
329
+ return this._logoutResponse({});
330
+ }
331
+ }
247
332
  async forgotPassword() {
248
333
  const { enabled = true } = this.options.forgotPassword;
249
334
  if (!enabled) {
@@ -442,9 +527,9 @@ class DbAuthHandler {
442
527
  expectedChallenge: user[this.options.authFields.challenge],
443
528
  expectedOrigin: webAuthnOptions.origin,
444
529
  expectedRPID: webAuthnOptions.domain,
445
- authenticator: {
446
- credentialID: credential[webAuthnOptions.credentialFields.id],
447
- credentialPublicKey: credential[webAuthnOptions.credentialFields.publicKey],
530
+ credential: {
531
+ id: credential[webAuthnOptions.credentialFields.id],
532
+ publicKey: credential[webAuthnOptions.credentialFields.publicKey],
448
533
  counter: credential[webAuthnOptions.credentialFields.counter],
449
534
  transports: credential[webAuthnOptions.credentialFields.transports] ? JSON.parse(
450
535
  credential[webAuthnOptions.credentialFields.transports]
@@ -586,7 +671,11 @@ class DbAuthHandler {
586
671
  if (!verified || !registrationInfo) {
587
672
  throw new DbAuthError.WebAuthnError("Registration failed");
588
673
  }
589
- const { credentialPublicKey, credentialID, counter } = registrationInfo;
674
+ const {
675
+ id: credentialID,
676
+ publicKey: credentialPublicKey,
677
+ counter
678
+ } = registrationInfo.credential;
590
679
  const existingDevice = await this.dbCredentialAccessor.findFirst({
591
680
  where: {
592
681
  [this.options.webAuthn.credentialFields.id]: credentialID,
@@ -634,6 +723,9 @@ class DbAuthHandler {
634
723
  if (this.options?.resetPassword?.enabled !== false && !this.options?.resetPassword?.handler) {
635
724
  throw new DbAuthError.NoResetPasswordHandlerError();
636
725
  }
726
+ if (this.options?.changePassword && this.options.changePassword.enabled !== false && !this.options.changePassword.handler) {
727
+ throw new DbAuthError.NoChangePasswordHandlerError();
728
+ }
637
729
  if (this.options?.credentialModelAccessor && !this.options?.webAuthn || this.options?.webAuthn && !this.options?.credentialModelAccessor) {
638
730
  throw new DbAuthError.NoWebAuthnConfigError();
639
731
  }
@@ -665,13 +757,7 @@ class DbAuthHandler {
665
757
  // removes any fields not explicitly allowed to be sent to the client before
666
758
  // sending a response over the wire
667
759
  _sanitizeUser(user) {
668
- const sanitized = JSON.parse(JSON.stringify(user));
669
- Object.keys(sanitized).forEach((key) => {
670
- if (!this.allowedUserFields.includes(key)) {
671
- delete sanitized[key];
672
- }
673
- });
674
- return sanitized;
760
+ return sanitizeUser(user, this.allowedUserFields);
675
761
  }
676
762
  // Converts LambdaEvent or FetchRequest to
677
763
  _decodeEvent() {
@@ -684,41 +770,27 @@ class DbAuthHandler {
684
770
  expires = "now",
685
771
  options = {}
686
772
  }) {
687
- const userCookieAttributes = this.options.cookie?.attributes ? { ...this.options.cookie?.attributes } : { ...this.options.cookie };
688
- if (!this.options.cookie?.attributes) {
689
- delete userCookieAttributes.name;
690
- }
691
- const cookieOptions = { ...userCookieAttributes, ...options };
692
- const meta = Object.keys(cookieOptions).map((key) => {
693
- const optionValue = cookieOptions[key];
694
- if (optionValue === true) {
695
- return key;
696
- } else if (optionValue === false) {
697
- return null;
698
- } else {
699
- return `${key}=${optionValue}`;
700
- }
701
- }).filter((v) => v);
702
- const expiresAt = expires === "now" ? DbAuthHandler.PAST_EXPIRES_DATE : expires;
703
- meta.push(`Expires=${expiresAt}`);
704
- return meta;
773
+ return buildCookieAttributes({
774
+ cookieConfig: this.options.cookie,
775
+ expires,
776
+ overrideAttributes: options
777
+ });
705
778
  }
706
779
  _createAuthProviderCookieString() {
707
- return [
708
- `auth-provider=dbAuth`,
709
- ...this._cookieAttributes({ expires: this.sessionExpiresDate })
710
- ].join(";");
780
+ return createAuthProviderCookieString({
781
+ cookieConfig: this.options.cookie,
782
+ expiresAt: this.sessionExpiresDate
783
+ });
711
784
  }
712
785
  // returns the set-cookie header to be returned in the request (effectively
713
786
  // creates the session)
714
787
  _createSessionCookieString(data, csrfToken) {
715
- const session = JSON.stringify(data) + ";" + csrfToken;
716
- const encrypted = encryptSession(session);
717
- const sessionCookieString = [
718
- `${generateCookieName(this.options.cookie?.name)}=${encrypted}`,
719
- ...this._cookieAttributes({ expires: this.sessionExpiresDate })
720
- ].join(";");
721
- return sessionCookieString;
788
+ return createSessionCookieString({
789
+ data,
790
+ csrfToken,
791
+ cookieConfig: this.options.cookie,
792
+ expiresAt: this.sessionExpiresDate
793
+ });
722
794
  }
723
795
  async _findUserByToken(token) {
724
796
  const tokenExpires = /* @__PURE__ */ new Date();
@@ -823,6 +895,16 @@ class DbAuthHandler {
823
895
  this.options.login?.errors?.incorrectPassword
824
896
  );
825
897
  }
898
+ // compares a plain text password with the user's stored hash, using the
899
+ // same algorithm and options the stored hash was created with. Unlike
900
+ // `_verifyPassword` this has no side effects and does not throw
901
+ _passwordMatches(user, password) {
902
+ const storedHash = user[this.options.authFields.hashedPassword];
903
+ const salt = user[this.options.authFields.salt];
904
+ const options = extractHashingOptions(storedHash);
905
+ const [hashedPassword] = Object.keys(options).length ? hashPassword(password, { salt, options }) : legacyHashPassword(password, salt);
906
+ return hashedPassword === storedHash;
907
+ }
826
908
  // gets the user from the database and returns only its ID
827
909
  async _getCurrentUser() {
828
910
  if (!this.session?.[this.options.authFields.id]) {
@@ -901,16 +983,12 @@ class DbAuthHandler {
901
983
  }
902
984
  }
903
985
  _loginResponse(user, statusCode = 200) {
904
- const sessionData = this._sanitizeUser(user);
905
- const csrfToken = DbAuthHandler.CSRF_TOKEN;
906
- const headers = new Headers();
907
- headers.append("csrf-token", csrfToken);
908
- headers.append("set-cookie", this._createAuthProviderCookieString());
909
- headers.append(
910
- "set-cookie",
911
- this._createSessionCookieString(sessionData, csrfToken)
912
- );
913
- return [sessionData, headers, { statusCode }];
986
+ return createLoginResponse(user, {
987
+ cookie: this.options.cookie,
988
+ allowedUserFields: this.allowedUserFields,
989
+ expiresAt: this.sessionExpiresDate,
990
+ statusCode
991
+ });
914
992
  }
915
993
  _logoutResponse(response) {
916
994
  return [response ? JSON.stringify(response) : "", this._deleteSessionHeader];
package/dist/errors.d.ts CHANGED
@@ -16,6 +16,9 @@ export declare class NoForgotPasswordHandlerError extends Error {
16
16
  export declare class NoResetPasswordHandlerError extends Error {
17
17
  constructor();
18
18
  }
19
+ export declare class NoChangePasswordHandlerError extends Error {
20
+ constructor();
21
+ }
19
22
  export declare class NoWebAuthnConfigError extends Error {
20
23
  constructor();
21
24
  }
@@ -79,6 +82,9 @@ export declare class ResetTokenRequiredError extends Error {
79
82
  export declare class ReusedPasswordError extends Error {
80
83
  constructor(message?: string);
81
84
  }
85
+ export declare class PasswordNotSetError extends Error {
86
+ constructor(message?: string);
87
+ }
82
88
  export declare class PasswordValidationError extends Error {
83
89
  constructor(message?: string);
84
90
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,oBAAqB,SAAQ,KAAK;;CAO9C;AAED,qBAAa,wBAAyB,SAAQ,KAAK;;CAKlD;AAED,qB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I5C;AAED,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,SAA2B;CAI/C;AAED,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,SAAmB;CAIvC;AAED,qBAAa,sBAAuB,SAAQ,aAAa;gBAErD,OAAO,SAAyD;CAKnE"}
package/dist/errors.js CHANGED
@@ -36,6 +36,12 @@ class NoResetPasswordHandlerError extends Error {
36
36
  this.name = "NoResetPasswordHandlerError";
37
37
  }
38
38
  }
39
+ class NoChangePasswordHandlerError extends Error {
40
+ constructor() {
41
+ super("dbAuth requires a change password handler in order to notify user");
42
+ this.name = "NoChangePasswordHandlerError";
43
+ }
44
+ }
39
45
  class NoWebAuthnConfigError extends Error {
40
46
  constructor() {
41
47
  super(
@@ -172,6 +178,12 @@ class ReusedPasswordError extends Error {
172
178
  this.name = "ReusedPasswordError";
173
179
  }
174
180
  }
181
+ class PasswordNotSetError extends Error {
182
+ constructor(message = 'This account does not have a password. Use "Forgot password" to set one') {
183
+ super(message);
184
+ this.name = "PasswordNotSetError";
185
+ }
186
+ }
175
187
  class PasswordValidationError extends Error {
176
188
  constructor(message = "Password is invalid") {
177
189
  super(message);
@@ -203,6 +215,7 @@ export {
203
215
  GenericError,
204
216
  IncorrectPasswordError,
205
217
  MissingWebAuthnConfigError,
218
+ NoChangePasswordHandlerError,
206
219
  NoForgotPasswordHandlerError,
207
220
  NoLoginHandlerError,
208
221
  NoResetPasswordHandlerError,
@@ -213,6 +226,7 @@ export {
213
226
  NoWebAuthnConfigError,
214
227
  NoWebAuthnSessionError,
215
228
  NotLoggedInError,
229
+ PasswordNotSetError,
216
230
  PasswordRequiredError,
217
231
  PasswordValidationError,
218
232
  ResetTokenExpiredError,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './DbAuthHandler.js';
2
2
  export { PasswordValidationError } from './errors.js';
3
+ export * from './session.js';
3
4
  export * from './shared.js';
4
5
  export { authDecoder, createAuthDecoder } from './decoder.js';
5
6
  export * from './originValidation.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AACrD,cAAc,aAAa,CAAA;AAC3B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAC7D,cAAc,uBAAuB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AACrD,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAC7D,cAAc,uBAAuB,CAAA"}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./DbAuthHandler.js";
2
2
  import { PasswordValidationError } from "./errors.js";
3
+ export * from "./session.js";
3
4
  export * from "./shared.js";
4
5
  import { authDecoder, createAuthDecoder } from "./decoder.js";
5
6
  export * from "./originValidation.js";
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Cookie attributes that can be set on a dbAuth cookie, either as
3
+ * `cookie.attributes` or (deprecated) directly on `cookie`.
4
+ */
5
+ export interface DbAuthCookieAttributes {
6
+ Path?: string;
7
+ HttpOnly?: boolean;
8
+ Secure?: boolean;
9
+ SameSite?: string;
10
+ Domain?: string;
11
+ }
12
+ /**
13
+ * Configuration for the cookies dbAuth sets: the session cookie's name, and
14
+ * the attributes applied to every cookie dbAuth writes (the session cookie
15
+ * and the `auth-provider` cookie).
16
+ */
17
+ export interface DbAuthCookieConfig extends DbAuthCookieAttributes {
18
+ attributes?: DbAuthCookieAttributes;
19
+ /**
20
+ * The name of the cookie that dbAuth sets
21
+ *
22
+ * %port% will be replaced with the port the api server is running on.
23
+ * If you have multiple RW apps running on the same host, you'll need to
24
+ * make sure they all use unique cookie names
25
+ */
26
+ name?: string;
27
+ }
28
+ /**
29
+ * Returns a UTC date string `expiresInSeconds` seconds in the future. Used as
30
+ * the `Expires` cookie attribute for a session that should stay valid for
31
+ * that long from now.
32
+ */
33
+ export declare function createExpiresAtDate(expiresInSeconds: number): string;
34
+ /**
35
+ * Generates a new CSRF token (a standard UUID) to pair with a session.
36
+ */
37
+ export declare function createCsrfToken(): string;
38
+ /**
39
+ * Removes any fields not explicitly allowed to be sent to the client before
40
+ * sending a user record over the wire.
41
+ */
42
+ export declare function sanitizeUser(user: Record<string, unknown>, allowedUserFields: string[]): Record<string, unknown>;
43
+ /**
44
+ * Builds the Set-Cookie attribute strings (`Path`, `HttpOnly`, `SameSite`,
45
+ * `Secure`, `Domain`, `Expires`) for a dbAuth cookie.
46
+ *
47
+ * Pass `expires: 'now'` (the default) to get the attributes needed to expire
48
+ * the cookie, or a UTC date string (e.g. from `createExpiresAtDate`) to set a
49
+ * future expiration.
50
+ */
51
+ export declare function buildCookieAttributes({ cookieConfig, expires, overrideAttributes, }: {
52
+ cookieConfig?: DbAuthCookieConfig;
53
+ expires?: 'now' | string;
54
+ overrideAttributes?: DbAuthCookieAttributes;
55
+ }): string[];
56
+ /**
57
+ * Builds the Set-Cookie header string for the `auth-provider` cookie dbAuth
58
+ * sets alongside the session cookie.
59
+ */
60
+ export declare function createAuthProviderCookieString({ cookieConfig, expiresAt, }: {
61
+ cookieConfig?: DbAuthCookieConfig;
62
+ expiresAt: string;
63
+ }): string;
64
+ /**
65
+ * Builds the Set-Cookie header string for the dbAuth session cookie: the
66
+ * `data;csrfToken` payload, encrypted, under the configured cookie name and
67
+ * attributes.
68
+ */
69
+ export declare function createSessionCookieString<TIdType = unknown>({ data, csrfToken, cookieConfig, expiresAt, }: {
70
+ data: Record<string, TIdType>;
71
+ csrfToken: string;
72
+ cookieConfig?: DbAuthCookieConfig;
73
+ expiresAt: string;
74
+ }): string;
75
+ /** Fields returned from the user record when none are explicitly allowed */
76
+ export declare const DEFAULT_ALLOWED_USER_FIELDS: string[];
77
+ export interface CreateLoginResponseOptions {
78
+ /**
79
+ * Object containing cookie config options: the cookie name (with %port%
80
+ * support) and the attributes applied to it (`Path`, `HttpOnly`,
81
+ * `SameSite`, `Secure`, `Domain`).
82
+ */
83
+ cookie?: DbAuthCookieConfig;
84
+ /**
85
+ * The fields that are allowed to be returned from the user record.
86
+ * Defaults to `id` and `email`.
87
+ */
88
+ allowedUserFields?: string[];
89
+ /**
90
+ * The `Expires` cookie attribute value for the session and `auth-provider`
91
+ * cookies: a UTC date string in the future. Build one with
92
+ * `createExpiresAtDate(expiresInSeconds)`.
93
+ */
94
+ expiresAt: string;
95
+ /**
96
+ * The HTTP status code to return in the response tuple. Defaults to 200.
97
+ */
98
+ statusCode?: number;
99
+ }
100
+ /**
101
+ * Mints a dbAuth session for the given user: a CSRF token, a session cookie
102
+ * (the sanitized user data paired with the CSRF token, encrypted), and the
103
+ * `auth-provider` cookie, in the same `[body, headers, { statusCode }]` shape
104
+ * every dbAuth auth method returns.
105
+ *
106
+ * Callable without a `DbAuthHandler` instance, so any code that has already
107
+ * verified a user's identity — a WebAuthn assertion, an OAuth callback, a
108
+ * magic link — can issue a session the same way the built-in login flow
109
+ * does.
110
+ */
111
+ export declare function createLoginResponse(user: Record<string, unknown>, options: CreateLoginResponseOptions): [Record<string, unknown>, Headers, {
112
+ statusCode: number;
113
+ }];
114
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE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MAAM,2BAA2B,UAAkB,CAAA;AAE1D,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,MAAM,CAAC,EAAE,kBAAkB,CAAA;IAC3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5B;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,EAAE,0BAA0B,GAClC,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CA+B5D"}
@@ -0,0 +1,103 @@
1
+ import { v4 as uuidv4 } from "uuid";
2
+ import { encryptSession, generateCookieName } from "./shared.js";
3
+ const PAST_EXPIRES_DATE = (/* @__PURE__ */ new Date(
4
+ "1970-01-01T00:00:00.000+00:00"
5
+ )).toUTCString();
6
+ function createExpiresAtDate(expiresInSeconds) {
7
+ const expiresAt = /* @__PURE__ */ new Date();
8
+ expiresAt.setSeconds(expiresAt.getSeconds() + expiresInSeconds);
9
+ return expiresAt.toUTCString();
10
+ }
11
+ function createCsrfToken() {
12
+ return uuidv4();
13
+ }
14
+ function sanitizeUser(user, allowedUserFields) {
15
+ const sanitized = JSON.parse(JSON.stringify(user));
16
+ Object.keys(sanitized).forEach((key) => {
17
+ if (!allowedUserFields.includes(key)) {
18
+ delete sanitized[key];
19
+ }
20
+ });
21
+ return sanitized;
22
+ }
23
+ function buildCookieAttributes({
24
+ cookieConfig,
25
+ expires = "now",
26
+ overrideAttributes = {}
27
+ }) {
28
+ const userCookieAttributes = cookieConfig?.attributes ? { ...cookieConfig.attributes } : { ...cookieConfig };
29
+ if (!cookieConfig?.attributes) {
30
+ delete userCookieAttributes.name;
31
+ }
32
+ const cookieOptions = { ...userCookieAttributes, ...overrideAttributes };
33
+ const meta = Object.keys(cookieOptions).map((key) => {
34
+ const optionValue = cookieOptions[key];
35
+ if (optionValue === true) {
36
+ return key;
37
+ } else if (optionValue === false) {
38
+ return null;
39
+ } else {
40
+ return `${key}=${optionValue}`;
41
+ }
42
+ }).filter((v) => v !== null);
43
+ const expiresAt = expires === "now" ? PAST_EXPIRES_DATE : expires;
44
+ meta.push(`Expires=${expiresAt}`);
45
+ return meta;
46
+ }
47
+ function createAuthProviderCookieString({
48
+ cookieConfig,
49
+ expiresAt
50
+ }) {
51
+ return [
52
+ `auth-provider=dbAuth`,
53
+ ...buildCookieAttributes({ cookieConfig, expires: expiresAt })
54
+ ].join(";");
55
+ }
56
+ function createSessionCookieString({
57
+ data,
58
+ csrfToken,
59
+ cookieConfig,
60
+ expiresAt
61
+ }) {
62
+ const session = JSON.stringify(data) + ";" + csrfToken;
63
+ const encrypted = encryptSession(session);
64
+ return [
65
+ `${generateCookieName(cookieConfig?.name)}=${encrypted}`,
66
+ ...buildCookieAttributes({ cookieConfig, expires: expiresAt })
67
+ ].join(";");
68
+ }
69
+ const DEFAULT_ALLOWED_USER_FIELDS = ["id", "email"];
70
+ function createLoginResponse(user, options) {
71
+ const allowedUserFields = options.allowedUserFields ?? DEFAULT_ALLOWED_USER_FIELDS;
72
+ const sessionData = sanitizeUser(user, allowedUserFields);
73
+ const csrfToken = createCsrfToken();
74
+ const headers = new Headers();
75
+ headers.append("csrf-token", csrfToken);
76
+ headers.append(
77
+ "set-cookie",
78
+ createAuthProviderCookieString({
79
+ cookieConfig: options.cookie,
80
+ expiresAt: options.expiresAt
81
+ })
82
+ );
83
+ headers.append(
84
+ "set-cookie",
85
+ createSessionCookieString({
86
+ data: sessionData,
87
+ csrfToken,
88
+ cookieConfig: options.cookie,
89
+ expiresAt: options.expiresAt
90
+ })
91
+ );
92
+ return [sessionData, headers, { statusCode: options.statusCode ?? 200 }];
93
+ }
94
+ export {
95
+ DEFAULT_ALLOWED_USER_FIELDS,
96
+ buildCookieAttributes,
97
+ createAuthProviderCookieString,
98
+ createCsrfToken,
99
+ createExpiresAtDate,
100
+ createLoginResponse,
101
+ createSessionCookieString,
102
+ sanitizeUser
103
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedarjs/auth-dbauth-api",
3
- "version": "7.1.0",
3
+ "version": "7.1.1-next.468",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/cedarjs/cedar.git",
@@ -57,22 +57,29 @@
57
57
  "test:watch": "vitest watch"
58
58
  },
59
59
  "dependencies": {
60
- "@cedarjs/project-config": "7.1.0",
60
+ "@cedarjs/project-config": "7.1.1-next.468",
61
61
  "md5": "2.3.0",
62
62
  "uuid": "11.1.1"
63
63
  },
64
64
  "devDependencies": {
65
- "@cedarjs/api": "7.1.0",
66
- "@cedarjs/framework-tools": "7.1.0",
67
- "@simplewebauthn/server": "10.0.1",
68
- "@simplewebauthn/types": "10.0.0",
69
- "@types/aws-lambda": "8.10.163",
65
+ "@cedarjs/api": "7.1.1-next.468",
66
+ "@cedarjs/framework-tools": "7.1.1-next.468",
67
+ "@simplewebauthn/server": "13.3.3",
68
+ "@types/aws-lambda": "8.10.164",
70
69
  "@types/md5": "2.3.6",
71
- "concurrently": "9.2.4",
72
- "publint": "0.3.24",
70
+ "concurrently": "9.2.5",
71
+ "publint": "0.3.25",
73
72
  "typescript": "5.9.3",
74
73
  "vitest": "4.1.11"
75
74
  },
75
+ "peerDependencies": {
76
+ "@simplewebauthn/server": "^13.0.0"
77
+ },
78
+ "peerDependenciesMeta": {
79
+ "@simplewebauthn/server": {
80
+ "optional": true
81
+ }
82
+ },
76
83
  "engines": {
77
84
  "node": ">=24"
78
85
  },