@stacksjs/auth 0.75.575 → 0.75.580

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.
@@ -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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/auth",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.575",
5
+ "version": "0.75.580",
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.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",
62
+ "@stacksjs/cache": "0.75.580",
63
+ "@stacksjs/config": "0.75.580",
64
+ "@stacksjs/database": "0.75.580",
65
+ "@stacksjs/email": "0.75.580",
66
+ "@stacksjs/env": "0.75.580",
67
+ "@stacksjs/error-handling": "0.75.580",
68
+ "@stacksjs/logging": "0.75.580",
69
+ "@stacksjs/orm": "0.75.580",
70
+ "@stacksjs/path": "0.75.580",
71
+ "@stacksjs/router": "0.75.580",
72
+ "@stacksjs/security": "0.75.580",
73
+ "@stacksjs/socials": "0.75.580",
74
+ "@stacksjs/storage": "0.75.580",
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"