@stacksjs/auth 0.75.573 → 0.75.575
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/dist/display-name.d.ts +60 -0
- package/dist/display-name.js +1 -0
- package/dist/email-verification.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/register.js +1 -1
- package/package.json +14 -14
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A name as it is compared and stored: compatibility forms folded (full-width
|
|
3
|
+
* letters and dots become their plain selves, so `bit.ly` is judged as
|
|
4
|
+
* `bit.ly`), runs of whitespace collapsed to one space, ends trimmed.
|
|
5
|
+
*/
|
|
6
|
+
export declare function normalizeDisplayName(name: unknown): string;
|
|
7
|
+
/**
|
|
8
|
+
* Why `name` may not be stored as a display name, or `null` when it may.
|
|
9
|
+
*
|
|
10
|
+
* The order is the order of how alarming the finding is, so an audit that
|
|
11
|
+
* prints the reason prints the most telling one.
|
|
12
|
+
*/
|
|
13
|
+
export declare function displayNameProblem(name: unknown): DisplayNameProblem | null;
|
|
14
|
+
/** The sentence a person reads when their name was refused. */
|
|
15
|
+
export declare function displayNameMessage(problem: DisplayNameProblem): string;
|
|
16
|
+
/**
|
|
17
|
+
* The first name a mail may greet someone by, or `undefined` for "no name".
|
|
18
|
+
*
|
|
19
|
+
* Every mail that says "Hi ..." reads the name through this, whatever wrote
|
|
20
|
+
* the column. A name that would not pass registration today yields no name at
|
|
21
|
+
* all rather than a cleaned-up one: a row holding an advert is not improved
|
|
22
|
+
* by printing the first word of it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function greetingName(name: unknown): string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* What a display name may be, and what of it an email may print.
|
|
27
|
+
*
|
|
28
|
+
* A name is the one free-text field an anonymous visitor fills at sign-up,
|
|
29
|
+
* and the framework then writes it into mail it sends from the application's
|
|
30
|
+
* own domain. Registration never proved the address belonged to the person
|
|
31
|
+
* registering it, so a name of "70.000 TL bonus bit.ly/..." registered against
|
|
32
|
+
* somebody else's address became an advert delivered to a stranger, greeted
|
|
33
|
+
* by name, with the application as its sender (2026-11-13: three such
|
|
34
|
+
* accounts on each of two production services).
|
|
35
|
+
*
|
|
36
|
+
* Two rules, kept apart on purpose:
|
|
37
|
+
*
|
|
38
|
+
* - {@link displayNameProblem} decides what registration STORES. A name is
|
|
39
|
+
* letters, marks, digits, spaces and a little punctuation, at most
|
|
40
|
+
* {@link DISPLAY_NAME_MAX_LENGTH} characters, and never a web address.
|
|
41
|
+
* - {@link greetingName} decides what a mail PRINTS, and trusts nothing: it
|
|
42
|
+
* re-applies the rule to whatever is in the column, because rows written
|
|
43
|
+
* before this existed, by a social provider, or by a later profile edit
|
|
44
|
+
* never went through registration. It answers with a first name or nothing.
|
|
45
|
+
*
|
|
46
|
+
* No dependencies: `buddy user:audit` and the mail actions import this
|
|
47
|
+
* without booting the rest of auth.
|
|
48
|
+
*/
|
|
49
|
+
/**
|
|
50
|
+
* The longest name registration stores.
|
|
51
|
+
*
|
|
52
|
+
* Eighty characters holds every real full name with room to spare (the
|
|
53
|
+
* longest in common use run to about sixty) and is too short to carry a
|
|
54
|
+
* sentence of advertising. The `users.name` column keeps its own, larger
|
|
55
|
+
* ceiling; this is the limit on what a stranger may put there.
|
|
56
|
+
*/
|
|
57
|
+
export declare const DISPLAY_NAME_MAX_LENGTH: 80;
|
|
58
|
+
/** The shortest name registration stores, as `RegisterAction` always had it. */
|
|
59
|
+
export declare const DISPLAY_NAME_MIN_LENGTH: 2;
|
|
60
|
+
export type DisplayNameProblem = 'empty' | 'too_short' | 'too_long' | 'control' | 'markup' | 'link' | 'characters';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DISPLAY_NAME_MAX_LENGTH=80;export const DISPLAY_NAME_MIN_LENGTH=2;const GREETING_MAX_LENGTH=30;const JOINERS=/[\u200C\u200D]/g;const CONTROL=/[\p{Cc}\p{Cf}\u2028\u2029]/u;const MARKUP=/[<>]/;const LINK=/:\/\/|www\.|[/\\@]|[\p{L}\p{N}-]{2,}\.[\p{L}\p{N}]{2,}/iu;const ALLOWED=/^[\p{L}\p{M}\p{N} .,'\u2019()\-]+$/u;export function normalizeDisplayName(name){if(typeof name!=="string")return"";return name.normalize("NFKC").replace(/[^\S\n\r]+/g," ").trim()}export function displayNameProblem(name){if(typeof name!=="string")return"empty";const normalized=normalizeDisplayName(name);if(normalized==="")return"empty";const visible=normalized.replace(JOINERS,"");if(CONTROL.test(visible))return"control";if(MARKUP.test(visible))return"markup";if(LINK.test(visible))return"link";if(!ALLOWED.test(visible))return"characters";const length=[...normalized].length;if(length>DISPLAY_NAME_MAX_LENGTH)return"too_long";if(length<DISPLAY_NAME_MIN_LENGTH)return"too_short";return null}export function displayNameMessage(problem){switch(problem){case"link":return"Name cannot contain a link or web address. If your name has a dot in it, add a space after the dot.";case"markup":case"control":case"characters":return"Name can only contain letters, numbers, spaces, and the punctuation . , ' - ( )";case"too_long":return`Name must be at most ${DISPLAY_NAME_MAX_LENGTH} characters.`;default:return`Name must be between ${DISPLAY_NAME_MIN_LENGTH} and ${DISPLAY_NAME_MAX_LENGTH} characters.`}}export function greetingName(name){if(displayNameProblem(name)!==null)return;const first=normalizeDisplayName(name).split(" ")[0].replace(/[.,()]+$/,"");if([...first].length>GREETING_MAX_LENGTH||!/\p{L}/u.test(first))return;return first}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHmac,randomBytes,timingSafeEqual}from"node:crypto";import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{mail,template}from"@stacksjs/email";import{log}from"@stacksjs/logging";import{normalizeAuthEmail}from"./credential-user";import{authLinkBase}from"./link-url";function getVerificationKey(){const appKey=config.app.key;if(typeof appKey!=="string"||appKey.length===0){throw new Error("[auth] config.app.key is not set - email-verification HMAC requires a real APP_KEY. "+"Run `./buddy key:generate` to provision one, or set the APP_KEY env var before booting the app.")}return appKey}function generateVerificationToken(userId,email){const nonce=randomBytes(32).toString("hex");const payload=`${userId}:${normalizeAuthEmail(email)}:${nonce}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");return{token:nonce,hash}}function verifyToken(userId,email,token,storedHash){const payload=`${userId}:${normalizeAuthEmail(email)}:${token}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");const a=Buffer.from(hash);const b=Buffer.from(storedHash);if(a.length!==b.length)return false;return timingSafeEqual(a,b)}function getExpiryMinutes(){const authConfig=config.auth??{};const emailVerification=authConfig.emailVerification;if(emailVerification!=null&&typeof emailVerification==="object"){const ev=emailVerification;if(typeof ev.expire==="number"){return ev.expire}}return 60}function getVerificationUrl(userId,token){const base=authLinkBase();const tpl=config.auth.emailVerification?.url??"/verify-email/{id}/{token}";const filled=tpl.replace("{id}",String(userId)).replace("{token}",token);return/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`}export function isEmailVerified(user){return user.email_verified_at!=null}export async function sendVerificationEmail(user){await deliverAfterCommit(await prepareVerificationEmail(user))}async function prepareVerificationEmail(user){const expiryMinutes=getExpiryMinutes();const createdAt=new Date;const expiresAt=new Date(createdAt.getTime()+expiryMinutes*60*1000);const prepared=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||typeof owner.email!=="string"||!owner.email)throw new Error("[auth] Email verification owner no longer exists or has no email.");const{token,hash}=generateVerificationToken(user.id,owner.email);await db.deleteFrom("email_verifications").where("user_id","=",user.id).execute();await db.insertInto("email_verifications").values({user_id:user.id,token:hash,expires_at:sqlDateTime(expiresAt),created_at:sqlDateTime(createdAt)}).executeTakeFirst();const stored=await db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["token"]).execute();if(stored.length!==1||stored[0]?.token!==hash)throw new Error("[auth] Email verification could not replace the token.");return{currentUser:{id:Number(owner.id),email:owner.email,name:typeof owner.name==="string"?owner.name:user.name},token}});return()=>deliverVerificationEmail(prepared.currentUser,prepared.token,expiryMinutes)}async function deliverAfterCommit(deliver){if(!enqueueAfterCommit(deliver))await deliver()}async function deliverVerificationEmail(user,token,expiryMinutes){const verificationUrl=getVerificationUrl(user.id,token);const appName=config.app.name||"Stacks";let html;let text;try{const rendered=await template("email-verification",{subject:`Verify Your ${appName} Email Address`,variables:{verificationUrl,expiryMinutes,userName:user.name
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHmac,randomBytes,timingSafeEqual}from"node:crypto";import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{mail,template}from"@stacksjs/email";import{log}from"@stacksjs/logging";import{normalizeAuthEmail}from"./credential-user";import{greetingName}from"./display-name";import{authLinkBase}from"./link-url";function getVerificationKey(){const appKey=config.app.key;if(typeof appKey!=="string"||appKey.length===0){throw new Error("[auth] config.app.key is not set - email-verification HMAC requires a real APP_KEY. "+"Run `./buddy key:generate` to provision one, or set the APP_KEY env var before booting the app.")}return appKey}function generateVerificationToken(userId,email){const nonce=randomBytes(32).toString("hex");const payload=`${userId}:${normalizeAuthEmail(email)}:${nonce}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");return{token:nonce,hash}}function verifyToken(userId,email,token,storedHash){const payload=`${userId}:${normalizeAuthEmail(email)}:${token}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");const a=Buffer.from(hash);const b=Buffer.from(storedHash);if(a.length!==b.length)return false;return timingSafeEqual(a,b)}function getExpiryMinutes(){const authConfig=config.auth??{};const emailVerification=authConfig.emailVerification;if(emailVerification!=null&&typeof emailVerification==="object"){const ev=emailVerification;if(typeof ev.expire==="number"){return ev.expire}}return 60}function getVerificationUrl(userId,token){const base=authLinkBase();const tpl=config.auth.emailVerification?.url??"/verify-email/{id}/{token}";const filled=tpl.replace("{id}",String(userId)).replace("{token}",token);return/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`}export function isEmailVerified(user){return user.email_verified_at!=null}export async function sendVerificationEmail(user){await deliverAfterCommit(await prepareVerificationEmail(user))}async function prepareVerificationEmail(user){const expiryMinutes=getExpiryMinutes();const createdAt=new Date;const expiresAt=new Date(createdAt.getTime()+expiryMinutes*60*1000);const prepared=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||typeof owner.email!=="string"||!owner.email)throw new Error("[auth] Email verification owner no longer exists or has no email.");const{token,hash}=generateVerificationToken(user.id,owner.email);await db.deleteFrom("email_verifications").where("user_id","=",user.id).execute();await db.insertInto("email_verifications").values({user_id:user.id,token:hash,expires_at:sqlDateTime(expiresAt),created_at:sqlDateTime(createdAt)}).executeTakeFirst();const stored=await db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["token"]).execute();if(stored.length!==1||stored[0]?.token!==hash)throw new Error("[auth] Email verification could not replace the token.");return{currentUser:{id:Number(owner.id),email:owner.email,name:typeof owner.name==="string"?owner.name:user.name},token}});return()=>deliverVerificationEmail(prepared.currentUser,prepared.token,expiryMinutes)}async function deliverAfterCommit(deliver){if(!enqueueAfterCommit(deliver))await deliver()}async function deliverVerificationEmail(user,token,expiryMinutes){const verificationUrl=getVerificationUrl(user.id,token);const appName=config.app.name||"Stacks";let html;let text;try{const rendered=await template("email-verification",{subject:`Verify Your ${appName} Email Address`,variables:{verificationUrl,expiryMinutes,userName:greetingName(user.name)}});html=rendered.html;text=rendered.text;if(!html&&!text)throw new Error("email-verification template missing or rendered empty")}catch(templateError){const errorMessage=templateError instanceof Error?templateError.message:String(templateError);log.warn(`[email] Email verification template failed, using plain text fallback: ${errorMessage}`);html=undefined;text=`Please verify your email address by visiting: ${verificationUrl}
|
|
2
2
|
|
|
3
3
|
This link expires in ${expiryMinutes} minutes.`}await mail.sendOrFail({to:user.email,subject:`Verify Your ${appName} Email Address`,text,html})}export async function verifyEmail(userId,token){return db.transaction(async()=>{const record=await db.primary.selectFrom("email_verifications").where("user_id","=",userId).select(["id","token","expires_at"]).executeTakeFirst();if(!record)return{success:false,message:"No verification request found. Please request a new verification email."};const observed=db.deleteFrom("email_verifications").where("user_id","=",userId).where("id","=",record.id).where("token","=",record.token);const claim=record.expires_at==null?observed.whereNull("expires_at"):observed.where("expires_at","=",record.expires_at);const expiresAt=parseSqlDateTime(record.expires_at)??new Date(Number.NaN);if(Number.isNaN(expiresAt.getTime())||Date.now()>=expiresAt.getTime()){await claim.execute();return{success:false,message:"Verification link has expired. Please request a new one."}}let owner=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")owner=owner.lockForUpdate();const user=await owner.executeTakeFirst();if(!user||typeof user.email!=="string"||!user.email)return{success:false,message:"Invalid verification link."};if(!verifyToken(userId,user.email,token,record.token))return{success:false,message:"Invalid verification link."};if(mutationCount(await claim.execute())!==1)return{success:false,message:"Invalid verification link."};if(Date.now()>=expiresAt.getTime())return{success:false,message:"Verification link has expired. Please request a new one."};const updated=await db.updateTable("users").set({email_verified_at:sqlDateTime()}).where("id","=",userId).execute();if(mutationCount(updated)!==1&&user.email_verified_at==null)throw new Error("[auth] Email verification could not update the user.");return{success:true,message:"Email verified successfully."}})}export async function setEmailVerified(userId,verified){await db.updateTable("users").set({email_verified_at:verified?sqlDateTime():null}).where("id","=",userId).execute()}export async function resendVerificationEmail(user){if(isEmailVerified(user)){return{success:false,message:"Email is already verified."}}const outcome=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)return{result:{success:false,message:"User not found."}};if(isEmailVerified(owner))return{result:{success:false,message:"Email is already verified."}};let existingQuery=db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["created_at"]);if(getDatabaseDialect()!=="sqlite")existingQuery=existingQuery.lockForUpdate();const existing=await existingQuery.executeTakeFirst();if(existing){const createdAt=parseSqlDateTime(existing.created_at);const secondsSince=createdAt?(Date.now()-createdAt.getTime())/1000:Number.NaN;if(Number.isNaN(secondsSince)){return{result:{success:false,message:"Please wait a moment before requesting another verification email."}}}if(secondsSince<60){return{result:{success:false,message:`Please wait ${Math.ceil(60-secondsSince)} seconds before requesting another verification email.`}}}}const deliver=await prepareVerificationEmail(user);return{result:{success:true,message:"Verification email sent."},deliver}},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(outcome.deliver)await deliverAfterCommit(outcome.deliver);return outcome.result}export const EmailVerification={isVerified:isEmailVerified,send:sendVerificationEmail,verify:verifyEmail,resend:resendVerificationEmail};
|
package/dist/index.d.ts
CHANGED
|
@@ -36,6 +36,7 @@ export * from './passkeys';
|
|
|
36
36
|
export * from './password/reset';
|
|
37
37
|
export * from './password/reset-token';
|
|
38
38
|
export * from './register';
|
|
39
|
+
export * from './display-name';
|
|
39
40
|
export * from './user';
|
|
40
41
|
// Token management (Laravel Passport-style)
|
|
41
42
|
export * from './tokens';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./authentication";export*from"./impersonation";export{requestImpersonation}from"./impersonation-auth";export*from"./impersonation-store";export*from"./authenticator";export*from"./client";export*from"./credential-user";export*from"./middleware";export*from"./oauth-authorization";export*from"./oauth-authorization-endpoint";export*from"./oauth-authorization-requests";export*from"./oauth-authorization-response";export*from"./oauth-authorization-codes";export*from"./oauth-browser-session";export*from"./oauth-client-registration";export*from"./oauth-consent";export*from"./oauth-delegated-access";export*from"./oauth-grants";export*from"./oauth-introspection";export*from"./oauth-metadata";export*from"./oauth-provider";export*from"./oauth-pruning";export*from"./oauth-pkce";export*from"./oauth-revocation";export*from"./oauth-token-exchange";export*from"./oauth-token-endpoint";export*from"./oauth-token-request";export*from"./oauth-token-response";export*from"./rate-limiter";export*from"./magic-link";export*from"./passkey";export*from"./passkeys";export*from"./password/reset";export*from"./password/reset-token";export*from"./register";export*from"./user";export*from"./tokens";export*from"./gate";export*from"./policy";export*from"./authorizable";export*from"./permissions";export*from"./rbac";export{createBqbRbacStore}from"./rbac-store-bqb";export{DEFAULT_ROLE_PACKS,seedDefaultRoles}from"./rbac-seed";export{adminEmails,databaseAdminAccounts,nameFromEmail,provisionAdmins}from"./admins";export*from"./email-verification";export*from"./session-auth";export*from"./cookie-auth";export*from"./browser-session";export*from"./browser-session-store";export*from"./request-token";export*from"./page-gate";export*from"./socials";export*from"./session-handoff";export{generateTOTP,verifyTOTP,generateTOTPSecret,totpKeyUri}from"@stacksjs/ts-auth";export*from"./two-factor";export*from"./two-factor-recovery-codes";export*from"./team";export*from"./referrals";export*from"./oauth-dynamic-registration";export*from"./oauth-protected-resource";export*from"./oauth-userinfo";export*from"./oauth-server";
|
|
1
|
+
export*from"./authentication";export*from"./impersonation";export{requestImpersonation}from"./impersonation-auth";export*from"./impersonation-store";export*from"./authenticator";export*from"./client";export*from"./credential-user";export*from"./middleware";export*from"./oauth-authorization";export*from"./oauth-authorization-endpoint";export*from"./oauth-authorization-requests";export*from"./oauth-authorization-response";export*from"./oauth-authorization-codes";export*from"./oauth-browser-session";export*from"./oauth-client-registration";export*from"./oauth-consent";export*from"./oauth-delegated-access";export*from"./oauth-grants";export*from"./oauth-introspection";export*from"./oauth-metadata";export*from"./oauth-provider";export*from"./oauth-pruning";export*from"./oauth-pkce";export*from"./oauth-revocation";export*from"./oauth-token-exchange";export*from"./oauth-token-endpoint";export*from"./oauth-token-request";export*from"./oauth-token-response";export*from"./rate-limiter";export*from"./magic-link";export*from"./passkey";export*from"./passkeys";export*from"./password/reset";export*from"./password/reset-token";export*from"./register";export*from"./display-name";export*from"./user";export*from"./tokens";export*from"./gate";export*from"./policy";export*from"./authorizable";export*from"./permissions";export*from"./rbac";export{createBqbRbacStore}from"./rbac-store-bqb";export{DEFAULT_ROLE_PACKS,seedDefaultRoles}from"./rbac-seed";export{adminEmails,databaseAdminAccounts,nameFromEmail,provisionAdmins}from"./admins";export*from"./email-verification";export*from"./session-auth";export*from"./cookie-auth";export*from"./browser-session";export*from"./browser-session-store";export*from"./request-token";export*from"./page-gate";export*from"./socials";export*from"./session-handoff";export{generateTOTP,verifyTOTP,generateTOTPSecret,totpKeyUri}from"@stacksjs/ts-auth";export*from"./two-factor";export*from"./two-factor-recovery-codes";export*from"./team";export*from"./referrals";export*from"./oauth-dynamic-registration";export*from"./oauth-protected-resource";export*from"./oauth-userinfo";export*from"./oauth-server";
|
package/dist/register.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{HttpError}from"@stacksjs/error-handling";import{User}from"@stacksjs/orm";import{makeHash}from"@stacksjs/security";import{Auth}from"./authentication";import{normalizeAuthEmail}from"./credential-user";import{isUniqueViolation}from"./rbac-store-bqb";import{attributeReferral}from"./referrals";function duplicateEmailError(){if(config.auth?.registration?.preventEnumeration===false)return new HttpError(409,"Email already exists");return new HttpError(422,"Registration could not be completed. Please check your details and try again.")}const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export async function register(credentials,tokenOptions){const{email:rawEmail,password
|
|
1
|
+
import{config}from"@stacksjs/config";import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{HttpError}from"@stacksjs/error-handling";import{User}from"@stacksjs/orm";import{makeHash}from"@stacksjs/security";import{Auth}from"./authentication";import{normalizeAuthEmail}from"./credential-user";import{displayNameMessage,displayNameProblem,normalizeDisplayName}from"./display-name";import{isUniqueViolation}from"./rbac-store-bqb";import{attributeReferral}from"./referrals";function duplicateEmailError(){if(config.auth?.registration?.preventEnumeration===false)return new HttpError(409,"Email already exists");return new HttpError(422,"Registration could not be completed. Please check your details and try again.")}const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export async function register(credentials,tokenOptions){const{email:rawEmail,password}=credentials;const email=typeof rawEmail==="string"?normalizeAuthEmail(rawEmail):rawEmail;if(typeof email!=="string"||email.length>254||!EMAIL_RE.test(email)){throw new HttpError(422,"Email address is invalid")}if(typeof password!=="string"||password.length<8){throw new HttpError(422,"Password must be at least 8 characters")}let name=credentials.name;if(name!==undefined&&name!==null){const problem=displayNameProblem(name);if(problem&&problem!=="too_short")throw new HttpError(422,displayNameMessage(problem));name=normalizeDisplayName(name)}const hashedPassword=await makeHash(password,{algorithm:"bcrypt"});const userId=await db.transaction(async(rawTrx)=>{const trx=rawTrx;const sql=sqlHelpers(getDatabaseDialect());const existing=await trx.unsafe(`SELECT id FROM users WHERE LOWER(email) = ${sql.param(1)} LIMIT 1`,[email]);const existingUser=existing[0];if(existingUser)throw duplicateEmailError();try{await trx.insertInto("users").values({email,password:hashedPassword,name}).execute()}catch(err){if(isUniqueViolation(err))throw duplicateEmailError();throw err}const createdRows=await trx.unsafe(`SELECT id FROM users WHERE email = ${sql.param(1)} LIMIT 1`,[email]);const created=createdRows[0];if(!created)throw new Error("Failed to retrieve created user");if(credentials.referralCode)await attributeReferral(Number(created.id),credentials.referralCode,trx);return Number(created.id)});const user=await User.find(userId);if(!user)throw new Error("Failed to retrieve created user");const{plainTextToken,refreshToken,expiresIn}=await Auth.createTokenForUser(user,{...tokenOptions,name:"user-auth-token"});return{token:plainTextToken,refreshToken,expiresIn}}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/auth",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.575",
|
|
6
6
|
"description": "A more simplistic way to authenticate.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -59,19 +59,19 @@
|
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"@stacksjs/bun-router": "^0.1.24",
|
|
62
|
-
"@stacksjs/cache": "0.75.
|
|
63
|
-
"@stacksjs/config": "0.75.
|
|
64
|
-
"@stacksjs/database": "0.75.
|
|
65
|
-
"@stacksjs/email": "0.75.
|
|
66
|
-
"@stacksjs/env": "0.75.
|
|
67
|
-
"@stacksjs/error-handling": "0.75.
|
|
68
|
-
"@stacksjs/logging": "0.75.
|
|
69
|
-
"@stacksjs/orm": "0.75.
|
|
70
|
-
"@stacksjs/path": "0.75.
|
|
71
|
-
"@stacksjs/router": "0.75.
|
|
72
|
-
"@stacksjs/security": "0.75.
|
|
73
|
-
"@stacksjs/socials": "0.75.
|
|
74
|
-
"@stacksjs/storage": "0.75.
|
|
62
|
+
"@stacksjs/cache": "0.75.575",
|
|
63
|
+
"@stacksjs/config": "0.75.575",
|
|
64
|
+
"@stacksjs/database": "0.75.575",
|
|
65
|
+
"@stacksjs/email": "0.75.575",
|
|
66
|
+
"@stacksjs/env": "0.75.575",
|
|
67
|
+
"@stacksjs/error-handling": "0.75.575",
|
|
68
|
+
"@stacksjs/logging": "0.75.575",
|
|
69
|
+
"@stacksjs/orm": "0.75.575",
|
|
70
|
+
"@stacksjs/path": "0.75.575",
|
|
71
|
+
"@stacksjs/router": "0.75.575",
|
|
72
|
+
"@stacksjs/security": "0.75.575",
|
|
73
|
+
"@stacksjs/socials": "0.75.575",
|
|
74
|
+
"@stacksjs/storage": "0.75.575",
|
|
75
75
|
"@stacksjs/ts-auth": "^0.4.7",
|
|
76
76
|
"ts-qr-codes": "^0.1.8"
|
|
77
77
|
},
|