@stacksjs/auth 0.75.573 → 0.75.579
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/enterprise-oidc.d.ts +19 -0
- package/dist/enterprise-oidc.js +1 -0
- package/dist/enterprise-saml-xml.d.ts +6 -0
- package/dist/enterprise-saml-xml.js +1 -0
- package/dist/enterprise-saml.d.ts +16 -0
- package/dist/enterprise-saml.js +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/register.js +1 -1
- package/package.json +19 -15
|
@@ -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};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Store all three fields in a one-use, browser-bound native OAuth flow. */
|
|
2
|
+
export declare function enterpriseOidcChallenge(): EnterpriseOidcChallenge;
|
|
3
|
+
export declare function enterpriseOidcAuthorization(config: EnterpriseOidcConfig, challenge: EnterpriseOidcChallenge): Promise<string>;
|
|
4
|
+
/**
|
|
5
|
+
* The caller must consume a native browser-bound OAuth flow before this call.
|
|
6
|
+
* Signature validation is mandatory even though HTTPS protects token transport.
|
|
7
|
+
* Returns identity only. Account linking and role assignment remain application policy.
|
|
8
|
+
*/
|
|
9
|
+
export declare function verifyEnterpriseOidcCallback(config: EnterpriseOidcConfig, callbackUrl: string, challenge: EnterpriseOidcChallenge): Promise<EnterpriseOidcIdentity>;
|
|
10
|
+
/** Operator-approved OIDC relying-party configuration. Never derive this from login input. */
|
|
11
|
+
export declare interface EnterpriseOidcConfig {
|
|
12
|
+
issuer: string
|
|
13
|
+
clientId: string
|
|
14
|
+
clientSecret: string
|
|
15
|
+
redirectUri: string
|
|
16
|
+
fetch?: typeof fetch
|
|
17
|
+
}
|
|
18
|
+
export declare interface EnterpriseOidcChallenge { state: string, nonce: string, verifier: string }
|
|
19
|
+
export declare interface EnterpriseOidcIdentity { issuer: string, subject: string, email: string | null, emailVerified: boolean }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as oauth from"oauth4webapi";function https(value){const url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.hash)throw new TypeError("Enterprise OIDC requires HTTPS URLs without credentials or fragments.");return url}function options(config){const transport=config.fetch??fetch;return{[oauth.customFetch]:async(url,init)=>{const response=await transport(url,{...init,redirect:"error",signal:AbortSignal.timeout(1e4)});if(response.status>=300&&response.status<400)throw new TypeError("OIDC endpoint redirects are not allowed.");return response}}}async function provider(config){const issuer=https(config.issuer);https(config.redirectUri);if(!config.clientId||!config.clientSecret)throw new TypeError("OIDC client configuration is missing.");const requestOptions=options(config);const metadata=await oauth.processDiscoveryResponse(issuer,await oauth.discoveryRequest(issuer,{...requestOptions,algorithm:"oidc"}));for(const endpoint of[metadata.authorization_endpoint,metadata.token_endpoint,metadata.jwks_uri]){if(!endpoint||https(endpoint).origin!==issuer.origin)throw new TypeError("OIDC endpoints must use the approved issuer origin.")}const client={client_id:config.clientId,id_token_signed_response_alg:"RS256"};return{metadata,client,requestOptions}}export function enterpriseOidcChallenge(){return{state:oauth.generateRandomState(),nonce:oauth.generateRandomNonce(),verifier:oauth.generateRandomCodeVerifier()}}export async function enterpriseOidcAuthorization(config,challenge){const{metadata}=await provider(config);const url=new URL(metadata.authorization_endpoint);url.search=new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",scope:"openid email",state:challenge.state,nonce:challenge.nonce,code_challenge:await oauth.calculatePKCECodeChallenge(challenge.verifier),code_challenge_method:"S256"}).toString();return url.href}export async function verifyEnterpriseOidcCallback(config,callbackUrl,challenge){const callback=new URL(callbackUrl);const expected=new URL(config.redirectUri);if(callback.origin!==expected.origin||callback.pathname!==expected.pathname)throw new TypeError("OIDC callback does not match the registered redirect URI.");const{metadata,client,requestOptions}=await provider(config);const params=oauth.validateAuthResponse(metadata,client,callback,challenge.state);const response=await oauth.authorizationCodeGrantRequest(metadata,client,oauth.ClientSecretPost(config.clientSecret),params,config.redirectUri,challenge.verifier,requestOptions);const result=await oauth.processAuthorizationCodeResponse(metadata,client,response,{requireIdToken:true,expectedNonce:challenge.nonce});await oauth.validateApplicationLevelSignature(metadata,response,requestOptions);const claims=oauth.getValidatedIdTokenClaims(result);if(!claims?.sub||claims.iss!==config.issuer)throw new TypeError("OIDC identity is missing.");return{issuer:claims.iss,subject:claims.sub,email:typeof claims.email==="string"?claims.email:null,emailVerified:claims.email_verified===true}}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DOMParser } from '@xmldom/xmldom';
|
|
2
|
+
export declare function parseEnterpriseSamlXml(xml: string): unknown;
|
|
3
|
+
/** Verify one root-owned reference using the pinned certificate, never embedded KeyInfo. */
|
|
4
|
+
export declare function verifiedEnterpriseSamlResponse(xml: string, certificate: string): string;
|
|
5
|
+
declare type XmlElement = NonNullable<ReturnType<DOMParser['parseFromString']>['documentElement']>;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DOMParser}from"@xmldom/xmldom";import{SignedXml}from"xml-crypto";const DS="http://www.w3.org/2000/09/xmldsig#";const C14N="http://www.w3.org/2001/10/xml-exc-c14n#";const ENVELOPED="http://www.w3.org/2000/09/xmldsig#enveloped-signature";export function parseEnterpriseSamlXml(xml){if(/<!DOCTYPE|<!ENTITY/i.test(xml))throw new TypeError("SAML entities are not allowed.");return new DOMParser({onError(){throw new TypeError("Malformed SAML XML.")}}).parseFromString(xml,"text/xml")}function children(parent,namespace,name){return Array.from(parent.childNodes).filter((node)=>node.nodeType===1&&node.namespaceURI===namespace&&node.localName===name)}export function verifiedEnterpriseSamlResponse(xml,certificate){const document=parseEnterpriseSamlXml(xml),root=document.documentElement;if(!root)throw new TypeError("SAML response is empty.");const ids=new Set;for(const element of[root,...Array.from(root.getElementsByTagName("*"))]){for(const attribute of Array.from(element.attributes)){if(attribute.localName?.toLowerCase()!=="id")continue;if(!attribute.value||ids.has(attribute.value))throw new TypeError("SAML IDs must be unique.");ids.add(attribute.value)}}const signatures=children(root,DS,"Signature"),id=root.getAttribute("ID");if(!id||signatures.length!==1)throw new TypeError("One signed root Response is required.");const signedInfo=children(signatures[0],DS,"SignedInfo");if(signedInfo.length!==1)throw new TypeError("Invalid SAML SignedInfo.");const references=children(signedInfo[0],DS,"Reference");const canonical=children(signedInfo[0],DS,"CanonicalizationMethod");const method=children(signedInfo[0],DS,"SignatureMethod");if(references.length!==1||references[0].getAttribute("URI")!=="#"+id||canonical.length!==1||canonical[0].getAttribute("Algorithm")!==C14N||method.length!==1||method[0].getAttribute("Algorithm")!=="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")throw new TypeError("SAML root signature must reference exactly its own parent.");const transforms=references[0].getElementsByTagNameNS(DS,"Transform");const digest=children(references[0],DS,"DigestMethod");if(transforms.length!==2||transforms[0].getAttribute("Algorithm")!==ENVELOPED||transforms[1].getAttribute("Algorithm")!==C14N||digest.length!==1||digest[0].getAttribute("Algorithm")!=="http://www.w3.org/2001/04/xmlenc#sha256")throw new TypeError("Unsupported SAML signature transforms or digest.");const verifier=new SignedXml({publicCert:certificate,getCertFromKeyInfo:()=>null});verifier.loadSignature(signatures[0].toString());if(!verifier.checkSignature(xml))throw new TypeError("SAML root signature did not verify.");const verified=verifier.getSignedReferences();if(verified.length!==1)throw new TypeError("One verified SAML reference is required.");const signedRoot=parseEnterpriseSamlXml(verified[0]).documentElement;if(!signedRoot||signedRoot.getAttribute("ID")!==id||signedRoot.localName!==root.localName||signedRoot.namespaceURI!==root.namespaceURI)throw new TypeError("Verified SAML root does not match.");return verified[0]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare function enterpriseSamlRequest(): EnterpriseSamlRequest;
|
|
2
|
+
export declare function enterpriseSamlAuthorization(config: EnterpriseSamlConfig, relayState: string, request: EnterpriseSamlRequest): Promise<string>;
|
|
3
|
+
/** Caller must consume its native browser-bound flow before invoking this. */
|
|
4
|
+
export declare function verifyEnterpriseSamlResponse(config: EnterpriseSamlConfig, encoded: string, request: EnterpriseSamlRequest): Promise<EnterpriseSamlIdentity>;
|
|
5
|
+
export declare interface EnterpriseSamlConfig {
|
|
6
|
+
issuer: string
|
|
7
|
+
entityId: string
|
|
8
|
+
entryPoint: string
|
|
9
|
+
callbackUrl: string
|
|
10
|
+
idpCert: string
|
|
11
|
+
privateKey: string
|
|
12
|
+
publicCert: string
|
|
13
|
+
}
|
|
14
|
+
/** Keep this in a native one-use browser-bound flow, scoped to this provider. */
|
|
15
|
+
export declare interface EnterpriseSamlRequest { requestId: string, createdAt: number }
|
|
16
|
+
export declare interface EnterpriseSamlIdentity { issuer: string, subject: string, email: string | null, emailVerified: boolean }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SAML,ValidateInResponseTo}from"@node-saml/node-saml";import{parseEnterpriseSamlXml,verifiedEnterpriseSamlResponse}from"./enterprise-saml-xml";const SAML_NS="urn:oasis:names:tc:SAML:2.0:assertion";const PROTOCOL_NS="urn:oasis:names:tc:SAML:2.0:protocol";const DS_NS="http://www.w3.org/2000/09/xmldsig#";const PERSISTENT="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";const AGE_MS=300000;function client(config,request){for(const value of[config.entryPoint,config.callbackUrl]){const url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.hash)throw new TypeError("SAML requires approved HTTPS endpoints.")}if(!config.issuer||!config.entityId||!config.idpCert||!config.privateKey||!config.publicCert||!/^_[a-f0-9-]{36}$/i.test(request.requestId)||!Number.isSafeInteger(request.createdAt)||request.createdAt>Date.now()||Date.now()-request.createdAt>=AGE_MS)throw new TypeError("SAML configuration or request is invalid.");let consumed=false;const cache={async saveAsync(key,value){return key===request.requestId?{value,createdAt:request.createdAt}:null},async getAsync(key){return!consumed&&key===request.requestId?new Date(request.createdAt).toISOString():null},async removeAsync(key){if(key!==request.requestId||consumed)return null;consumed=true;return key},async consumeAsync(key){if(key!==request.requestId||consumed)return null;consumed=true;return new Date(request.createdAt).toISOString()}};return new SAML({callbackUrl:config.callbackUrl,issuer:config.entityId,audience:config.entityId,entryPoint:config.entryPoint,idpIssuer:config.issuer,idpCert:config.idpCert,privateKey:config.privateKey,publicCert:config.publicCert,wantAssertionsSigned:true,wantAuthnResponseSigned:true,validateInResponseTo:ValidateInResponseTo.always,acceptedClockSkewMs:0,maxAssertionAgeMs:AGE_MS,requestIdExpirationPeriodMs:AGE_MS,signatureAlgorithm:"sha256",digestAlgorithm:"sha256",identifierFormat:PERSISTENT,generateUniqueId:()=>request.requestId,cacheProvider:cache})}export function enterpriseSamlRequest(){return{requestId:`_${crypto.randomUUID()}`,createdAt:Date.now()}}export async function enterpriseSamlAuthorization(config,relayState,request){return await client(config,request).getAuthorizeUrlAsync(relayState,undefined)}export async function verifyEnterpriseSamlResponse(config,encoded,request){if(!encoded||encoded.length>250000||!/^[A-Za-z0-9+/=\r\n]+$/.test(encoded))throw new TypeError("Invalid SAML response encoding.");const xml=Buffer.from(encoded,"base64").toString("utf8");if(Buffer.byteLength(xml)>128000||/<!DOCTYPE|<!ENTITY/i.test(xml))throw new TypeError("SAML entities and oversized XML are not allowed.");const{profile,loggedOut}=await client(config,request).validatePostResponseAsync({SAMLResponse:encoded});if(!profile||loggedOut||profile.issuer!==config.issuer||profile.nameIDFormat!==PERSISTENT||!profile.nameID)throw new TypeError("SAML identity is missing or not persistent.");const received=parseEnterpriseSamlXml(xml);const verified=verifiedEnterpriseSamlResponse(xml,config.idpCert);const document=parseEnterpriseSamlXml(verified),root=document.documentElement;if(!received.documentElement)throw new TypeError("SAML root is missing.");if(root.namespaceURI!==PROTOCOL_NS||root.localName!=="Response"||root.getAttribute("Version")!=="2.0"||root.getAttribute("Destination")!==config.callbackUrl||root.getAttribute("InResponseTo")!==request.requestId)throw new TypeError("SAML response recipient or request does not match.");const assertions=Array.from(root.childNodes).filter((node)=>node.nodeType===1&&node.localName==="Assertion");if(assertions.length!==1||assertions[0].namespaceURI!==SAML_NS||assertions[0].getAttribute("Version")!=="2.0")throw new TypeError("One SAML assertion is required.");const assertion=assertions[0];const audience=assertion.getElementsByTagNameNS(SAML_NS,"Audience");const confirmations=assertion.getElementsByTagNameNS(SAML_NS,"SubjectConfirmation");const data=assertion.getElementsByTagNameNS(SAML_NS,"SubjectConfirmationData");const conditions=assertion.getElementsByTagNameNS(SAML_NS,"Conditions");const status=root.getElementsByTagNameNS(PROTOCOL_NS,"StatusCode");if(audience.length!==1||audience[0].textContent!==config.entityId||confirmations.length!==1||confirmations[0].getAttribute("Method")!=="urn:oasis:names:tc:SAML:2.0:cm:bearer"||data.length!==1||data[0].getAttribute("Recipient")!==config.callbackUrl||data[0].getAttribute("InResponseTo")!==request.requestId||conditions.length!==1||!conditions[0].getAttribute("NotOnOrAfter")||!data[0].getAttribute("NotOnOrAfter")||assertion.getElementsByTagNameNS(SAML_NS,"AuthnStatement").length!==1||status.length!==1||status[0].getAttribute("Value")!=="urn:oasis:names:tc:SAML:2.0:status:Success")throw new TypeError("SAML bearer confirmation, conditions, status or audience is invalid.");const methods=received.documentElement.getElementsByTagNameNS(DS_NS,"SignatureMethod"),digests=received.documentElement.getElementsByTagNameNS(DS_NS,"DigestMethod");if(methods.length!==2||Array.from(methods).some((node)=>node.getAttribute("Algorithm")!=="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")||Array.from(digests).some((node)=>node.getAttribute("Algorithm")!=="http://www.w3.org/2001/04/xmlenc#sha256"))throw new TypeError("SAML requires RSA-SHA256 signatures and SHA256 digests.");return{issuer:profile.issuer,subject:profile.nameID,email:typeof profile.email==="string"?profile.email:null,emailVerified:true}}
|
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.579",
|
|
6
6
|
"description": "A more simplistic way to authenticate.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -59,21 +59,25 @@
|
|
|
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.579",
|
|
63
|
+
"@stacksjs/config": "0.75.579",
|
|
64
|
+
"@stacksjs/database": "0.75.579",
|
|
65
|
+
"@stacksjs/email": "0.75.579",
|
|
66
|
+
"@stacksjs/env": "0.75.579",
|
|
67
|
+
"@stacksjs/error-handling": "0.75.579",
|
|
68
|
+
"@stacksjs/logging": "0.75.579",
|
|
69
|
+
"@stacksjs/orm": "0.75.579",
|
|
70
|
+
"@stacksjs/path": "0.75.579",
|
|
71
|
+
"@stacksjs/router": "0.75.579",
|
|
72
|
+
"@stacksjs/security": "0.75.579",
|
|
73
|
+
"@stacksjs/socials": "0.75.579",
|
|
74
|
+
"@stacksjs/storage": "0.75.579",
|
|
75
75
|
"@stacksjs/ts-auth": "^0.4.7",
|
|
76
|
-
"ts-qr-codes": "^0.1.8"
|
|
76
|
+
"ts-qr-codes": "^0.1.8",
|
|
77
|
+
"oauth4webapi": "^3.8.8",
|
|
78
|
+
"@node-saml/node-saml": "^5.2.0",
|
|
79
|
+
"@xmldom/xmldom": "^0.9.12",
|
|
80
|
+
"xml-crypto": "^6.4.0"
|
|
77
81
|
},
|
|
78
82
|
"devDependencies": {
|
|
79
83
|
"better-dx": "^0.2.39"
|