@stacksjs/auth 0.75.515 → 0.75.519
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/admins.js +1 -1
- package/dist/authentication.js +2 -2
- package/dist/authenticator.js +1 -1
- package/dist/authorizable.js +1 -1
- package/dist/browser-session-store.js +1 -1
- package/dist/browser-session.js +1 -1
- package/dist/client.js +1 -1
- package/dist/cookie.js +1 -1
- package/dist/credential-user.js +1 -1
- package/dist/email-verification.js +2 -2
- package/dist/gate.js +1 -1
- package/dist/impersonation-auth.js +1 -1
- package/dist/impersonation-store.js +4 -4
- package/dist/impersonation.js +1 -1
- package/dist/link-url.js +1 -1
- package/dist/magic-link-revocation.js +1 -1
- package/dist/magic-link.js +2 -2
- package/dist/middleware.js +1 -1
- package/dist/oauth-authorization-codes.js +5 -5
- package/dist/oauth-authorization-endpoint.js +1 -1
- package/dist/oauth-authorization-requests.js +7 -7
- package/dist/oauth-authorization-response.js +1 -1
- package/dist/oauth-authorization.js +1 -1
- package/dist/oauth-browser-session.js +1 -1
- package/dist/oauth-client-policy.js +1 -1
- package/dist/oauth-client-registration.js +14 -14
- package/dist/oauth-consent.js +2 -2
- package/dist/oauth-delegated-access.js +1 -1
- package/dist/oauth-dynamic-registration.js +1 -1
- package/dist/oauth-grants.js +10 -10
- package/dist/oauth-introspection.js +3 -3
- package/dist/oauth-metadata.js +1 -1
- package/dist/oauth-pkce.js +1 -1
- package/dist/oauth-protected-resource.js +1 -1
- package/dist/oauth-provider.js +1 -1
- package/dist/oauth-pruning.js +2 -2
- package/dist/oauth-revocation.js +2 -2
- package/dist/oauth-server.js +1 -1
- package/dist/oauth-token-endpoint.js +1 -1
- package/dist/oauth-token-exchange.js +14 -14
- package/dist/oauth-token-request.js +1 -1
- package/dist/oauth-userinfo.js +1 -1
- package/dist/page-gate.js +1 -1
- package/dist/passkey.js +1 -1
- package/dist/passkeys.js +1 -1
- package/dist/password/credentials.js +2 -2
- package/dist/password/reset-store.js +1 -1
- package/dist/password/reset-token.js +1 -1
- package/dist/password/reset.js +2 -2
- package/dist/password-rehash.js +1 -1
- package/dist/permissions.js +1 -1
- package/dist/policy.js +1 -1
- package/dist/rate-limiter.js +2 -2
- package/dist/rbac-seed.js +1 -1
- package/dist/rbac-store-bqb.js +1 -1
- package/dist/rbac.js +1 -1
- package/dist/referrals.js +1 -1
- package/dist/register.js +1 -1
- package/dist/session-auth.js +1 -1
- package/dist/session-credential.js +1 -1
- package/dist/session-handoff.js +1 -1
- package/dist/socials.js +1 -1
- package/dist/team.js +1 -1
- package/dist/token-revocation.js +7 -7
- package/dist/token.js +1 -1
- package/dist/tokens.js +31 -31
- package/dist/two-factor-recovery-codes.js +1 -1
- package/dist/two-factor.js +1 -1
- package/dist/user.js +1 -1
- package/package.json +14 -14
package/dist/oauth-provider.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{oauthAuthorizationServerMetadataPath}from"./oauth-metadata";const DEFAULT_LIFETIMES={authorizationRequest:
|
|
1
|
+
import{oauthAuthorizationServerMetadataPath}from"./oauth-metadata";const DEFAULT_LIFETIMES={authorizationRequest:10*60*1000,authorizationCode:10*60*1000,accessToken:60*60*1000,refreshToken:30*24*60*60*1000};const DEFAULT_ENDPOINTS={authorization:"oauth/authorize",token:"oauth/token",revocation:"oauth/revoke",introspection:"oauth/introspect"};const RESERVED_AUTH_GET_PATHS=new Set(["/generate-registration-options","/generate-authentication-options"]);const RESERVED_AUTH_POST_PATHS=new Set(["/login","/register","/verify-registration","/verify-authentication","/generate-two-factor-secret","/enable-two-factor","/disable-two-factor","/verify-two-factor-login"]);function canonicalIssuer(value){if(!value)throw new Error("OAuth provider is enabled but `auth.oauthProvider.issuer` is not configured.");let issuer;try{issuer=new URL(value)}catch{throw new Error("`auth.oauthProvider.issuer` must be an absolute URL.")}if(issuer.username||issuer.password)throw new Error("`auth.oauthProvider.issuer` must not contain credentials.");if(issuer.search||issuer.hash)throw new Error("`auth.oauthProvider.issuer` must not contain a query or fragment.");const loopback=issuer.hostname==="localhost"||issuer.hostname==="127.0.0.1"||issuer.hostname==="[::1]";if(issuer.protocol!=="https:"&&!(issuer.protocol==="http:"&&loopback))throw new Error("`auth.oauthProvider.issuer` must use HTTPS outside loopback development.");issuer.pathname=issuer.pathname.replace(/\/+$/,"")||"/";return issuer}function endpoint(issuer,configured,fallback){const resolved=new URL(configured??fallback,`${issuer.toString().replace(/\/+$/,"")}/`);if(resolved.origin!==issuer.origin)throw new Error("OAuth provider endpoints must share the configured issuer origin.");if(resolved.username||resolved.password||resolved.search||resolved.hash)throw new Error("OAuth provider endpoints must not contain credentials, a query, or a fragment.");return resolved.toString().replace(/\/$/,"")}function assertEndpointRouteAvailable(name,value,methods){const pathname=new URL(value).pathname;const reservedNamespace=pathname==="/auth"||pathname.startsWith("/auth/");const reservedMethod=methods.some((method)=>method==="GET"?RESERVED_AUTH_GET_PATHS.has(pathname):RESERVED_AUTH_POST_PATHS.has(pathname));if(reservedNamespace||reservedMethod)throw new Error(`auth.oauthProvider ${name} endpoint must not shadow a reserved auth route: ${pathname}`)}function positiveLifetime(name,value){if(!Number.isSafeInteger(value)||value<=0)throw new Error(`auth.oauthProvider.lifetimes.${name} must be a positive safe integer of milliseconds.`);if(!Number.isFinite(new Date(Date.now()+value).getTime()))throw new Error(`auth.oauthProvider.lifetimes.${name} is outside the supported date range.`);return value}const POLICY_TOKEN=/^[\x21\x23-\x5B\x5D-\x7E]+$/;function resolvedResources(configured){const resources={};const audiences=new Set;for(const[key,resource]of Object.entries(configured??{})){if(!POLICY_TOKEN.test(key))throw new Error(`auth.oauthProvider resource key is not a valid policy token: ${key}`);let audience;try{audience=new URL(resource.audience)}catch{throw new Error(`auth.oauthProvider resource audience must be an absolute URI: ${key}`)}if(audience.username||audience.password||audience.hash)throw new Error(`auth.oauthProvider resource audience must not contain credentials or a fragment: ${key}`);if(audiences.has(resource.audience))throw new Error(`auth.oauthProvider resources must each have a unique audience: ${resource.audience}`);audiences.add(resource.audience);resources[key]={audience:resource.audience,...resource.description===undefined?{}:{description:resource.description}}}return resources}function resolvedScopes(configured,resources){const scopes={};for(const[key,scope]of Object.entries(configured??{})){if(!POLICY_TOKEN.test(key))throw new Error(`auth.oauthProvider scope is not a valid OAuth scope token: ${key}`);if(!scope.description?.trim())throw new Error(`auth.oauthProvider scope description must not be empty: ${key}`);const scopeResources=[...scope.resources??[]];if(new Set(scopeResources).size!==scopeResources.length)throw new Error(`auth.oauthProvider scope contains a duplicate resource: ${key}`);for(const resource of scopeResources){if(!resources[resource])throw new Error(`auth.oauthProvider scope references an unknown resource: ${key} -> ${resource}`)}scopes[key]={description:scope.description,...scope.resources===undefined?{}:{resources:scopeResources}}}return scopes}function resolvedClientTypes(configured){const clientTypes=[...configured??["confidential","public"]];if(!clientTypes.length||new Set(clientTypes).size!==clientTypes.length||clientTypes.some((type)=>type!=="confidential"&&type!=="public"))throw new Error("auth.oauthProvider.clientTypes must contain unique supported client types.");return clientTypes}function resolvedConsent(options){const rememberFor=options?.rememberFor??0;if(!Number.isSafeInteger(rememberFor)||rememberFor<0)throw new Error("auth.oauthProvider.consent.rememberFor must be a non-negative safe integer of milliseconds.");const view=options?.view??"auth/oauth/consent";if(!view||view.length>255||view.startsWith("/")||view.includes("..")||/[\u0000-\u001F\u007F]/.test(view))throw new Error("auth.oauthProvider.consent.view must be a safe relative view name.");const resolveWorkspace=options?.resolveWorkspace;if(resolveWorkspace!==undefined&&typeof resolveWorkspace!=="function")throw new Error("auth.oauthProvider.consent.resolveWorkspace must be a function.");return{rememberFor,view,...resolveWorkspace?{resolveWorkspace}:{}}}export async function resolveOAuthConsentWorkspace(provider,context){const resolved=await provider.consent.resolveWorkspace?.(context)??null;if(resolved===null)return null;if(typeof resolved.id!=="string"||!resolved.id||resolved.id.length>255||/[\u0000-\u001F\u007F]/.test(resolved.id))throw new Error("OAuth consent workspace id must contain 1 to 255 characters without controls.");if(typeof resolved.label!=="string"||!resolved.label.trim()||resolved.label.length>255||/[\u0000-\u001F\u007F]/.test(resolved.label))throw new Error("OAuth consent workspace label must contain 1 to 255 characters without controls.");return{id:resolved.id,label:resolved.label.trim()}}export function resolveOAuthProviderConfig(options){if(options?.enabled!==true)return null;const issuer=canonicalIssuer(options.issuer);const subjectEligibility=options.subjectEligibility;if(subjectEligibility!==undefined&&typeof subjectEligibility!=="function")throw new Error("auth.oauthProvider.subjectEligibility must be a function.");const resources=resolvedResources(options.resources);const scopes=resolvedScopes(options.scopes,resources);const lifetimes={authorizationRequest:positiveLifetime("authorizationRequest",options.lifetimes?.authorizationRequest??DEFAULT_LIFETIMES.authorizationRequest),authorizationCode:positiveLifetime("authorizationCode",options.lifetimes?.authorizationCode??DEFAULT_LIFETIMES.authorizationCode),accessToken:positiveLifetime("accessToken",options.lifetimes?.accessToken??DEFAULT_LIFETIMES.accessToken),refreshToken:positiveLifetime("refreshToken",options.lifetimes?.refreshToken??DEFAULT_LIFETIMES.refreshToken)};const endpoints={authorization:endpoint(issuer,options.endpoints?.authorization,DEFAULT_ENDPOINTS.authorization),token:endpoint(issuer,options.endpoints?.token,DEFAULT_ENDPOINTS.token),revocation:endpoint(issuer,options.endpoints?.revocation,DEFAULT_ENDPOINTS.revocation),introspection:endpoint(issuer,options.endpoints?.introspection,DEFAULT_ENDPOINTS.introspection)};if(new Set(Object.values(endpoints)).size!==Object.keys(endpoints).length)throw new Error("auth.oauthProvider endpoints must each use a unique URL.");assertEndpointRouteAvailable("authorization",endpoints.authorization,["GET","POST"]);assertEndpointRouteAvailable("token",endpoints.token,["POST"]);assertEndpointRouteAvailable("revocation",endpoints.revocation,["POST"]);assertEndpointRouteAvailable("introspection",endpoints.introspection,["POST"]);if(new URL(endpoints.authorization).pathname===oauthAuthorizationServerMetadataPath(issuer.toString()))throw new Error("auth.oauthProvider authorization endpoint must not shadow the metadata route.");let dynamicRegistration;if(options.dynamicRegistration){const origins=[...options.dynamicRegistration.allowedRedirectOrigins];if(!origins.length||origins.some((origin)=>new URL(origin).origin!==origin||!origin.startsWith("https://")))throw new Error("OAuth dynamic registration requires exact HTTPS redirect origins.");const registration=endpoint(issuer,options.dynamicRegistration.endpoint,"oauth/register");if(Object.values(endpoints).includes(registration)||new URL(registration).pathname===oauthAuthorizationServerMetadataPath(issuer.toString()))throw new Error("OAuth registration endpoint must use a unique URL.");assertEndpointRouteAvailable("registration",registration,["POST"]);if(!resolvedClientTypes(options.clientTypes).includes("public"))throw new Error("OAuth dynamic registration requires public clients.");dynamicRegistration={endpoint:registration,allowedRedirectOrigins:origins}}const grantTypes=options.clientCredentials?["authorization_code","refresh_token","client_credentials"]:["authorization_code","refresh_token"];return{enabled:true,issuer:issuer.toString().replace(/\/$/,""),endpoints,...dynamicRegistration?{dynamicRegistration}:{},responseTypes:["code"],grantTypes,clientCredentials:options.clientCredentials===true,introspection:options.introspection===true,...subjectEligibility?{subjectEligibility}:{},codeChallengeMethods:["S256"],clientTypes:resolvedClientTypes(options.clientTypes),scopes,resources,lifetimes,consent:resolvedConsent(options.consent)}}
|
package/dist/oauth-pruning.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{db,getDatabaseDialect,markContextWrote,mutationCount,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";export async function pruneOAuthAuthorizationArtifacts(options={}){const now=options.now??new Date
|
|
1
|
+
import{db,getDatabaseDialect,markContextWrote,mutationCount,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";export async function pruneOAuthAuthorizationArtifacts(options={}){const now=options.now??new Date;const consumedRetentionMs=options.consumedRetentionMs??7*24*60*60*1000;if(!Number.isFinite(now.getTime()))throw new TypeError("OAuth authorization prune time must be a valid date.");if(!Number.isSafeInteger(consumedRetentionMs)||consumedRetentionMs<0)throw new TypeError("OAuth authorization consumed retention must be a non-negative safe integer of milliseconds.");const sql=sqlHelpers(getDatabaseDialect());const nowSql=sqlDateTime(now);const consumedBeforeDate=new Date(now.getTime()-consumedRetentionMs);if(!Number.isFinite(consumedBeforeDate.getTime()))throw new TypeError("OAuth authorization consumed retention is outside the supported date range.");const consumedBefore=sqlDateTime(consumedBeforeDate);const result=await db.transaction(async(rawTrx)=>{const trx=rawTrx;const requests=await trx.unsafe(`
|
|
2
2
|
DELETE FROM oauth_authorization_requests
|
|
3
3
|
WHERE expires_at <= ${sql.param(1)}
|
|
4
4
|
OR (consumed_at IS NOT NULL AND consumed_at <= ${sql.param(2)})
|
|
5
|
-
`,[nowSql,consumedBefore])
|
|
5
|
+
`,[nowSql,consumedBefore]);const codes=await trx.unsafe(`
|
|
6
6
|
DELETE FROM oauth_auth_codes
|
|
7
7
|
WHERE expires_at <= ${sql.param(1)}
|
|
8
8
|
OR (consumed_at IS NOT NULL AND consumed_at <= ${sql.param(2)})
|
package/dist/oauth-revocation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{withAuthenticatedOAuthTokenClient}from"./oauth-client-registration";import{OAuthTokenRequestError,parseOAuthRevocationRequest}from"./oauth-token-request";import{oauthTokenErrorResponse}from"./oauth-token-response";import{revokeTokenPair}from"./token-revocation";const REVOCATION_HEADERS={"Cache-Control":"no-store",Pragma:"no-cache"};async function delegatedAccessTokenId(request,kind){if(!/^[a-f0-9]{80}$/.test(request.token))return null;const sql=sqlHelpers(getDatabaseDialect())
|
|
1
|
+
import{createHash}from"node:crypto";import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{withAuthenticatedOAuthTokenClient}from"./oauth-client-registration";import{OAuthTokenRequestError,parseOAuthRevocationRequest}from"./oauth-token-request";import{oauthTokenErrorResponse}from"./oauth-token-response";import{revokeTokenPair}from"./token-revocation";const REVOCATION_HEADERS={"Cache-Control":"no-store",Pragma:"no-cache"};async function delegatedAccessTokenId(request,kind){if(!/^[a-f0-9]{80}$/.test(request.token))return null;const sql=sqlHelpers(getDatabaseDialect());const hash=createHash("sha256").update(request.token).digest("hex");const lock=sql.isSqlite?"":" FOR UPDATE";const rows=kind==="access_token"?await db.unsafe(`
|
|
2
2
|
SELECT id FROM oauth_access_tokens
|
|
3
3
|
WHERE token = ${sql.param(1)} AND oauth_client_id = ${sql.param(2)}
|
|
4
4
|
AND oauth_grant_id IS NOT NULL
|
|
@@ -10,4 +10,4 @@ import{createHash}from"node:crypto";import{db,getDatabaseDialect,sqlHelpers}from
|
|
|
10
10
|
WHERE r.token = ${sql.param(1)} AND a.oauth_client_id = ${sql.param(2)}
|
|
11
11
|
AND a.oauth_grant_id IS NOT NULL
|
|
12
12
|
LIMIT 1${lock}
|
|
13
|
-
`,[hash,request.clientId])
|
|
13
|
+
`,[hash,request.clientId]);const id=Number(rows[0]?.id);return Number.isSafeInteger(id)&&id>0?id:null}async function revokeOAuthClientToken(request){const order=request.tokenTypeHint==="refresh_token"?["refresh_token","access_token"]:["access_token","refresh_token"];for(const kind of order){const id=await delegatedAccessTokenId(request,kind);if(id==null)continue;await revokeTokenPair({id});return}}export async function handleOAuthRevocationRequest(input){const basic=/^Basic\s/i.test(input.authorization??"");const responseOptions={clientAuthenticatedWithBasic:basic,basicRealm:"oauth-revoke"};const mediaType=input.contentType?.split(";",1)[0]?.trim().toLowerCase();if(mediaType!=="application/x-www-form-urlencoded")return oauthTokenErrorResponse("invalid_request",responseOptions);try{const request=parseOAuthRevocationRequest(input.body,input.authorization);const authenticated=await withAuthenticatedOAuthTokenClient(String(request.clientId),request.clientSecret,async()=>{await revokeOAuthClientToken(request);return true});if(!authenticated)return oauthTokenErrorResponse("invalid_client",responseOptions);return new Response(null,{status:200,headers:REVOCATION_HEADERS})}catch(error){if(error instanceof OAuthTokenRequestError)return oauthTokenErrorResponse(error.error,responseOptions);throw error}}
|
package/dist/oauth-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJsonBody,readTextBody,RequestBodyError}from"@stacksjs/router/body";import{OAuthAuthorizationRequestError}from"./oauth-authorization";import{beginOAuthAuthorizationRequest,handleOAuthAuthorizationConsentRequest}from"./oauth-authorization-endpoint";import{bindOAuthAuthorizationRequestWorkspace}from"./oauth-authorization-requests";import{oauthAuthorizationRequestErrorResponse}from"./oauth-authorization-response";import{oauthAuthorizationBrowserSession}from"./oauth-browser-session";import{loadOAuthAuthorizationConsentView}from"./oauth-consent";import{handleDynamicOAuthRegistration}from"./oauth-dynamic-registration";import{disconnectOAuthGrant,listOAuthConnections}from"./oauth-grants";import{oauthAuthorizationServerMetadata}from"./oauth-metadata";import{handleOAuthRevocationRequest}from"./oauth-revocation";import{handleOAuthTokenRequest}from"./oauth-token-endpoint";function json(body,status=200){return Response.json(body,{status,headers:{"Cache-Control":"no-store",Pragma:"no-cache","Referrer-Policy":"no-referrer"}})}const invalid=()=>json({error:"invalid_request"},400);export function createOAuthAuthorizationServer(options){if(!/^\/(?!\/)[^?#\\]*$/.test(options.consentPage)||/[\u0000-\u0020]/.test(options.consentPage))throw TypeError("OAuth consentPage must be a local absolute path.");const provider=()=>typeof options.provider==="function"?options.provider():options.provider
|
|
1
|
+
import{readJsonBody,readTextBody,RequestBodyError}from"@stacksjs/router/body";import{OAuthAuthorizationRequestError}from"./oauth-authorization";import{beginOAuthAuthorizationRequest,handleOAuthAuthorizationConsentRequest}from"./oauth-authorization-endpoint";import{bindOAuthAuthorizationRequestWorkspace}from"./oauth-authorization-requests";import{oauthAuthorizationRequestErrorResponse}from"./oauth-authorization-response";import{oauthAuthorizationBrowserSession}from"./oauth-browser-session";import{loadOAuthAuthorizationConsentView}from"./oauth-consent";import{handleDynamicOAuthRegistration}from"./oauth-dynamic-registration";import{disconnectOAuthGrant,listOAuthConnections}from"./oauth-grants";import{oauthAuthorizationServerMetadata}from"./oauth-metadata";import{handleOAuthRevocationRequest}from"./oauth-revocation";import{handleOAuthTokenRequest}from"./oauth-token-endpoint";function json(body,status=200){return Response.json(body,{status,headers:{"Cache-Control":"no-store",Pragma:"no-cache","Referrer-Policy":"no-referrer"}})}const invalid=()=>json({error:"invalid_request"},400);export function createOAuthAuthorizationServer(options){if(!/^\/(?!\/)[^?#\\]*$/.test(options.consentPage)||/[\u0000-\u0020]/.test(options.consentPage))throw new TypeError("OAuth consentPage must be a local absolute path.");const provider=()=>typeof options.provider==="function"?options.provider():options.provider;const identity=async(request)=>{const subject=await options.authenticate(request);if(subject instanceof Response)return subject;if(!subject||!/^[A-Za-z0-9_.:-]{1,255}$/.test(subject.type)||!Number.isSafeInteger(subject.id)||subject.id<=0||!subject.label.trim())return json({error:"authentication_required"},401);return subject};const method=(request,expected)=>request.method!==expected?new Response(null,{status:405,headers:{Allow:expected,"Cache-Control":"no-store"}}):null;const wire=async(request,handler)=>{const denied=method(request,"POST");if(denied)return denied;try{return await handler(await readTextBody(request,16384))}catch(error){if(error instanceof RequestBodyError)return json({error:"invalid_request"},error.status);throw error}};return{metadata:()=>json(oauthAuthorizationServerMetadata(provider())),async register(request){const denied=method(request,"POST");if(denied)return denied;try{return await handleDynamicOAuthRegistration(provider(),await readJsonBody(request,16384))}catch(error){if(error instanceof RequestBodyError)return json({error:"invalid_client_metadata"},error.status);throw error}},async begin(request){const denied=method(request,"GET");if(denied)return denied;const resolved=provider();const browser=oauthAuthorizationBrowserSession(request,resolved);try{const result=await beginOAuthAuthorizationRequest({provider:resolved,query:new URL(request.url).searchParams,browserSessionId:browser.id});return new Response(null,{status:302,headers:{Location:`${options.consentPage}?request_id=${encodeURIComponent(result.requestId)}`,"Set-Cookie":browser.cookie,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}catch(error){if(!(error instanceof OAuthAuthorizationRequestError))throw error;return oauthAuthorizationRequestErrorResponse(error,resolved.issuer)??invalid()}},async consent(request){if(!["GET","POST"].includes(request.method))return method(request,"GET, POST");const subject=await identity(request);if(subject instanceof Response)return subject;const resolved=provider();if(request.method==="POST")return handleOAuthAuthorizationConsentRequest({provider:resolved,request,subjectType:subject.type,subjectId:subject.id,workspaceId:subject.workspaceId,resolveWorkspaceId:subject.resolveWorkspaceId});const params=new URL(request.url).searchParams;if(params.getAll("request_id").length!==1||[...params.keys()].some((key)=>key!=="request_id"))return invalid();if(resolved.consent.resolveWorkspace&&!await bindOAuthAuthorizationRequestWorkspace(params.get("request_id"),oauthAuthorizationBrowserSession(request,resolved).id,subject.workspaceId??null))return invalid();const consent=await loadOAuthAuthorizationConsentView({provider:resolved,requestId:params.get("request_id"),browserSessionId:oauthAuthorizationBrowserSession(request,resolved).id});if(!consent)return invalid();return json({consent,user:{id:subject.id,name:subject.label}})},token:(request)=>wire(request,(body)=>{const resolved=provider();return handleOAuthTokenRequest(resolved,{body,contentType:request.headers.get("content-type"),authorization:request.headers.get("authorization")},{isSubjectEligible:resolved.subjectEligibility??(()=>false)})}),revoke:(request)=>wire(request,(body)=>handleOAuthRevocationRequest({body,contentType:request.headers.get("content-type"),authorization:request.headers.get("authorization")})),async connections(request){const denied=method(request,"GET");if(denied)return denied;const subject=await identity(request);if(subject instanceof Response)return subject;const connections=(await listOAuthConnections(subject.type,subject.id)).filter((connection)=>!options.connectionAudience||connection.audiences.includes(options.connectionAudience));return json({connections})},async disconnect(request,grantId){const denied=method(request,"DELETE");if(denied)return denied;const subject=await identity(request);if(subject instanceof Response)return subject;const connections=await listOAuthConnections(subject.type,subject.id);if(!connections.some((connection)=>connection.grantId===grantId&&(!options.connectionAudience||connection.audiences.includes(options.connectionAudience))))return json({disconnected:false});return json({disconnected:await disconnectOAuthGrant(subject.type,subject.id,grantId)})}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exchangeOAuthClientCredentials,exchangeOAuthAuthorizationCode,refreshOAuthDelegatedToken}from"./oauth-token-exchange";import{OAuthTokenRequestError,parseOAuthTokenRequest}from"./oauth-token-request";import{oauthTokenErrorResponse,oauthTokenExchangeResponse}from"./oauth-token-response";export async function handleOAuthTokenRequest(provider,input,dependencies){const
|
|
1
|
+
import{exchangeOAuthClientCredentials,exchangeOAuthAuthorizationCode,refreshOAuthDelegatedToken}from"./oauth-token-exchange";import{OAuthTokenRequestError,parseOAuthTokenRequest}from"./oauth-token-request";import{oauthTokenErrorResponse,oauthTokenExchangeResponse}from"./oauth-token-response";export async function handleOAuthTokenRequest(provider,input,dependencies){const basic=/^Basic\s/i.test(input.authorization??"");const responseOptions={clientAuthenticatedWithBasic:basic};const mediaType=input.contentType?.split(";",1)[0]?.trim().toLowerCase();if(mediaType!=="application/x-www-form-urlencoded")return oauthTokenErrorResponse("invalid_request",responseOptions);try{const request=parseOAuthTokenRequest(input.body,input.authorization);if(request.grantType==="authorization_code"){const result=await exchangeOAuthAuthorizationCode({code:request.code,audiences:request.audiences,clientId:request.clientId,clientSecret:request.clientSecret,redirectUri:request.redirectUri,codeVerifier:request.codeVerifier,accessTokenLifetimeMs:provider.lifetimes.accessToken,refreshTokenLifetimeMs:provider.lifetimes.refreshToken,isSubjectEligible:dependencies.isSubjectEligible});return oauthTokenExchangeResponse(result,responseOptions)}if(request.grantType==="client_credentials"){const result=await exchangeOAuthClientCredentials({provider,audiences:request.audiences,clientId:request.clientId,clientSecret:request.clientSecret,scopes:request.scopes,accessTokenLifetimeMs:provider.lifetimes.accessToken});return oauthTokenExchangeResponse(result,responseOptions)}const result=await refreshOAuthDelegatedToken({refreshToken:request.refreshToken,audiences:request.audiences,clientId:request.clientId,clientSecret:request.clientSecret,scopes:request.scopes,accessTokenLifetimeMs:provider.lifetimes.accessToken,refreshTokenLifetimeMs:provider.lifetimes.refreshToken,isSubjectEligible:dependencies.isSubjectEligible});return oauthTokenExchangeResponse(result,responseOptions)}catch(error){if(error instanceof OAuthTokenRequestError)return oauthTokenErrorResponse(error.error,responseOptions);throw error}}
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import{createHash,randomBytes}from"node:crypto";import{db,getDatabaseDialect,markContextWrote,mutationCount,parseSqlDateTime,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{withAuthorizationCode}from"./oauth-authorization-codes";import{withAuthenticatedOAuthTokenClient}from"./oauth-client-registration";import{createOAuthGrant,disconnectOAuthGrant}from"./oauth-grants";import{verifyS256CodeChallenge}from"./oauth-pkce";class InactiveOAuthClientError extends Error{}const invalidGrant={ok
|
|
1
|
+
import{createHash,randomBytes}from"node:crypto";import{db,getDatabaseDialect,markContextWrote,mutationCount,parseSqlDateTime,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{withAuthorizationCode}from"./oauth-authorization-codes";import{withAuthenticatedOAuthTokenClient}from"./oauth-client-registration";import{createOAuthGrant,disconnectOAuthGrant}from"./oauth-grants";import{verifyS256CodeChallenge}from"./oauth-pkce";class InactiveOAuthClientError extends Error{}const invalidGrant={ok:false,reason:"invalid_grant"};const invalidClient={ok:false,reason:"invalid_client"};const unauthorizedClient={ok:false,reason:"unauthorized_client"};const invalidScope={ok:false,reason:"invalid_scope"};const inactiveSubject=Symbol("inactive-oauth-subject");function tokenHash(value){return createHash("sha256").update(value,"ascii").digest("hex")}async function containAuthorizationCodeReplay(input){if(!/^[A-Za-z0-9_-]{43}$/.test(input.code))return;const sql=sqlHelpers(getDatabaseDialect());const rows=await db.unsafe(`
|
|
2
2
|
SELECT grant_id, client_id, subject_type, subject_id, redirect_uri,
|
|
3
3
|
code_challenge, code_challenge_method, consumed_at
|
|
4
4
|
FROM oauth_auth_codes
|
|
5
5
|
WHERE code_hash = ${sql.param(1)}
|
|
6
6
|
LIMIT 1
|
|
7
|
-
`,[tokenHash(input.code)])
|
|
7
|
+
`,[tokenHash(input.code)]);const code=rows[0];const subjectId=Number(code?.subject_id);if(!code?.consumed_at||!code.grant_id||!/^[a-f0-9]{32}$/.test(code.grant_id)||String(code.client_id)!==String(input.clientId)||!Number.isSafeInteger(subjectId)||subjectId<=0||code.redirect_uri!==input.redirectUri||code.code_challenge_method!=="S256"||!await verifyS256CodeChallenge(input.codeVerifier,code.code_challenge))return;await disconnectOAuthGrant(code.subject_type,subjectId,code.grant_id)}function validLifetime(lifetimeMs){if(!Number.isSafeInteger(lifetimeMs)||lifetimeMs<=0)throw new TypeError("OAuth token lifetime must be a positive safe integer.");return lifetimeMs}function deadline(issuedAt,lifetimeMs,mysql){const value=new Date(issuedAt.getTime()+lifetimeMs);if(!Number.isFinite(value.getTime()))throw new TypeError("OAuth token lifetime is outside the supported date range.");if(mysql)value.setUTCMilliseconds(0);return value}function storedValues(value){if(value==null)return null;try{const parsed=JSON.parse(value);return Array.isArray(parsed)&&parsed.every((item)=>typeof item==="string")?parsed:null}catch{return null}}function activeFlag(value){return value===false||value===0}async function mintDelegatedTokenPair(grant,options){const sql=sqlHelpers(getDatabaseDialect());const accessToken=randomBytes(40).toString("hex");const refreshToken=options.issueRefreshToken?randomBytes(40).toString("hex"):undefined;const refreshFamilyId=refreshToken?options.refreshFamilyId??randomBytes(16).toString("hex"):undefined;if(refreshFamilyId&&!/^[a-f0-9]{32}$/.test(refreshFamilyId))throw new TypeError("OAuth refresh token family identifier is invalid.");const accessHash=tokenHash(accessToken);const refreshHash=refreshToken?tokenHash(refreshToken):undefined;const createdAt=new Date;if(sql.isMysql)createdAt.setUTCMilliseconds(0);const accessExpiresAt=deadline(createdAt,options.accessLifetimeMs,sql.isMysql);const refreshExpiresAt=options.issueRefreshToken?deadline(createdAt,options.refreshLifetimeMs,sql.isMysql):undefined;const revoked=sql.isPostgres?false:0;const accessValues=sql.params(grant.subjectType,grant.subjectId,grant.subjectId,grant.clientId,accessHash,`oauth:${grant.grantId}`,JSON.stringify(grant.scopes),grant.grantId,JSON.stringify(grant.resources),JSON.stringify(grant.audiences),grant.workspaceId,revoked,sqlDateTime(accessExpiresAt),sqlDateTime(createdAt),sqlDateTime(createdAt));await db.unsafe(`
|
|
8
8
|
INSERT INTO oauth_access_tokens (
|
|
9
9
|
tokenable_type, tokenable_id, user_id, oauth_client_id, token, name, scopes,
|
|
10
10
|
oauth_grant_id, resources, audiences, workspace_id, revoked, expires_at, created_at, updated_at
|
|
11
11
|
) VALUES (${accessValues.sql})
|
|
12
|
-
`,accessValues.values);const
|
|
12
|
+
`,accessValues.values);const accessRows=await db.unsafe(`
|
|
13
13
|
SELECT id, tokenable_type, tokenable_id, oauth_client_id, token, scopes, oauth_grant_id,
|
|
14
14
|
resources, audiences, workspace_id, revoked, expires_at
|
|
15
15
|
FROM oauth_access_tokens WHERE token = ${sql.param(1)} LIMIT 1
|
|
16
|
-
`,[accessHash])
|
|
16
|
+
`,[accessHash]);const storedAccess=accessRows[0];if(!storedAccess||storedAccess.tokenable_type!==grant.subjectType||String(storedAccess.tokenable_id)!==String(grant.subjectId)||String(storedAccess.oauth_client_id)!==String(grant.clientId)||storedAccess.oauth_grant_id!==grant.grantId||JSON.stringify(storedValues(storedAccess.scopes))!==JSON.stringify(grant.scopes)||JSON.stringify(storedValues(storedAccess.resources))!==JSON.stringify(grant.resources)||JSON.stringify(storedValues(storedAccess.audiences))!==JSON.stringify(grant.audiences)||storedAccess.workspace_id!==grant.workspaceId||!activeFlag(storedAccess.revoked)||parseSqlDateTime(storedAccess.expires_at)?.getTime()!==accessExpiresAt.getTime())throw new Error("Failed to persist the delegated access token.");if(refreshToken&&refreshHash&&refreshExpiresAt){const refreshValues=sql.params(Number(storedAccess.id),refreshHash,refreshFamilyId,options.refreshParentId??null,revoked,sqlDateTime(refreshExpiresAt),sqlDateTime(createdAt));await db.unsafe(`
|
|
17
17
|
INSERT INTO oauth_refresh_tokens (access_token_id, token, family_id, parent_id, revoked, expires_at, created_at)
|
|
18
18
|
VALUES (${refreshValues.sql})
|
|
19
|
-
`,refreshValues.values);const
|
|
19
|
+
`,refreshValues.values);const refreshRows=await db.unsafe(`
|
|
20
20
|
SELECT id, access_token_id, token, family_id, parent_id, revoked, expires_at
|
|
21
21
|
FROM oauth_refresh_tokens WHERE token = ${sql.param(1)} LIMIT 1
|
|
22
|
-
`,[refreshHash])
|
|
22
|
+
`,[refreshHash]);const storedRefresh=refreshRows[0];if(!storedRefresh||String(storedRefresh.access_token_id)!==String(storedAccess.id)||storedRefresh.family_id!==refreshFamilyId||String(storedRefresh.parent_id??"")!==String(options.refreshParentId??"")||!activeFlag(storedRefresh.revoked)||parseSqlDateTime(storedRefresh.expires_at)?.getTime()!==refreshExpiresAt.getTime())throw new Error("Failed to persist the delegated refresh token.")}return{accessToken,...refreshToken?{refreshToken}:{},tokenType:"Bearer",expiresIn:Math.max(0,Math.floor((accessExpiresAt.getTime()-createdAt.getTime())/1000)),grantId:grant.grantId,clientId:grant.clientId,subjectType:grant.subjectType,subjectId:grant.subjectId,scopes:grant.scopes,resources:grant.resources,audiences:grant.audiences,workspaceId:grant.workspaceId}}function grantFromRefreshRows(refresh,stored){const clientId=Number(refresh.oauth_client_id);const subjectId=Number(refresh.tokenable_id);const scopes=storedValues(refresh.scopes);const resources=storedValues(refresh.resources);const audiences=storedValues(refresh.audiences);const grantScopes=storedValues(stored?.grant_scopes??null);const grantResources=storedValues(stored?.grant_resources??null);const grantAudiences=storedValues(stored?.grant_audiences??null);if(!stored||stored.grant_revoked_at!=null||!refresh.oauth_grant_id||!/^[a-f0-9]{32}$/.test(refresh.oauth_grant_id)||!Number.isSafeInteger(clientId)||clientId<=0||!Number.isSafeInteger(subjectId)||subjectId<=0||!scopes?.length||new Set(scopes).size!==scopes.length||!resources||!audiences||!grantScopes||!grantResources||!grantAudiences||String(stored.grant_client_id)!==String(clientId)||stored.grant_subject_type!==refresh.tokenable_type||String(stored.grant_subject_id)!==String(subjectId)||!scopes.every((scope)=>grantScopes.includes(scope))||JSON.stringify(grantResources)!==JSON.stringify(resources)||JSON.stringify(grantAudiences)!==JSON.stringify(audiences)||stored.grant_workspace_id!==refresh.workspace_id)return null;return{grantId:refresh.oauth_grant_id,clientId,subjectType:refresh.tokenable_type,subjectId,scopes,resources,audiences,workspaceId:refresh.workspace_id}}async function revokeDelegatedRefreshFamily(refresh){const sql=sqlHelpers(getDatabaseDialect());const revoked=sql.isPostgres?true:1;if(refresh.family_id&&/^[a-f0-9]{32}$/.test(refresh.family_id)){await db.unsafe(`
|
|
23
23
|
UPDATE oauth_access_tokens
|
|
24
24
|
SET revoked = ${sql.param(1)}
|
|
25
25
|
WHERE id IN (
|
|
@@ -29,21 +29,21 @@ import{createHash,randomBytes}from"node:crypto";import{db,getDatabaseDialect,mar
|
|
|
29
29
|
UPDATE oauth_refresh_tokens
|
|
30
30
|
SET revoked = ${sql.param(1)}
|
|
31
31
|
WHERE family_id = ${sql.param(2)}
|
|
32
|
-
`,[revoked,refresh.family_id]);return}await db.unsafe(`UPDATE oauth_access_tokens SET revoked = ${sql.param(1)} WHERE id = ${sql.param(2)}`,[revoked,refresh.access_token_id]);await db.unsafe(`UPDATE oauth_refresh_tokens SET revoked = ${sql.param(1)} WHERE id = ${sql.param(2)}`,[revoked,refresh.id])}export async function exchangeAuthorizationCode(input){const sql=sqlHelpers(getDatabaseDialect())
|
|
32
|
+
`,[revoked,refresh.family_id]);return}await db.unsafe(`UPDATE oauth_access_tokens SET revoked = ${sql.param(1)} WHERE id = ${sql.param(2)}`,[revoked,refresh.access_token_id]);await db.unsafe(`UPDATE oauth_refresh_tokens SET revoked = ${sql.param(1)} WHERE id = ${sql.param(2)}`,[revoked,refresh.id])}export async function exchangeAuthorizationCode(input){const sql=sqlHelpers(getDatabaseDialect());const accessLifetimeMs=validLifetime(input.accessTokenLifetimeMs);const issueRefreshToken=input.issueRefreshToken!==false;const refreshLifetimeMs=issueRefreshToken?validLifetime(input.refreshTokenLifetimeMs):0;try{const result=await withAuthorizationCode(input.code,input,async(grant)=>{const clientLock=sql.isPostgres?" FOR SHARE":sql.isMysql?" LOCK IN SHARE MODE":"";const clients=await db.unsafe(`
|
|
33
33
|
SELECT id FROM oauth_clients
|
|
34
34
|
WHERE id = ${sql.param(1)} AND revoked = ${sql.boolFalse}
|
|
35
35
|
LIMIT 1${clientLock}
|
|
36
|
-
`,[grant.clientId])
|
|
36
|
+
`,[grant.clientId]);if(clients.length!==1)throw new InactiveOAuthClientError;if(input.isSubjectEligible&&!await input.isSubjectEligible({type:grant.subjectType,id:grant.subjectId,clientId:grant.clientId,grantId:grant.grantId,workspaceId:grant.workspaceId})){if(!await disconnectOAuthGrant(grant.subjectType,grant.subjectId,grant.grantId))throw new Error("Inactive OAuth subject authorization state could not be revoked.");return inactiveSubject}return mintDelegatedTokenPair(grant,{accessLifetimeMs,refreshLifetimeMs,issueRefreshToken})});if(!result.ok)return result;return result.value===inactiveSubject?invalidGrant:{ok:true,value:result.value}}catch(error){if(error instanceof InactiveOAuthClientError)return invalidGrant;throw error}}export async function exchangeOAuthAuthorizationCode(input){const{clientSecret,...exchange}=input;const result=await withAuthenticatedOAuthTokenClient(String(input.clientId),clientSecret,async(client)=>{const exchanged=await exchangeAuthorizationCode({...exchange,issueRefreshToken:client.grantTypes.includes("refresh_token")});if(!exchanged.ok)await containAuthorizationCodeReplay(exchange);return exchanged});return result??invalidClient}export async function exchangeOAuthClientCredentials(input){const accessLifetimeMs=validLifetime(input.accessTokenLifetimeMs);const authenticated=await withAuthenticatedOAuthTokenClient(String(input.clientId),input.clientSecret,async(client)=>{if(!input.provider.clientCredentials||client.type!=="confidential"||!client.grantTypes.includes("client_credentials"))return{result:unauthorizedClient,wrote:false};const scopes=input.scopes?[...input.scopes]:[...client.scopes];if(!scopes.length||new Set(scopes).size!==scopes.length||!scopes.every((scope)=>client.scopes.includes(scope)&&input.provider.scopes[scope]))return{result:invalidScope,wrote:false};const resources=[...new Set(scopes.flatMap((scope)=>input.provider.scopes[scope]?.resources??[]))];if(!resources.every((resource)=>client.resources.includes(resource)&&input.provider.resources[resource]))return{result:invalidScope,wrote:false};const machineClientId=Number(client.id);if(input.audiences&&(!input.audiences.length||new Set(input.audiences).size!==input.audiences.length||input.audiences.length!==resources.length||input.audiences.some((audience)=>!resources.some((resource)=>input.provider.resources[resource]?.audience===audience))))return{result:invalidScope,wrote:false};const grant=await createOAuthGrant({clientId:machineClientId,subjectType:"oauth_clients",subjectId:machineClientId,scopes,resources,audiences:resources.map((resource)=>input.provider.resources[resource].audience)});const pair=await mintDelegatedTokenPair({grantId:grant.id,clientId:grant.clientId,subjectType:grant.subjectType,subjectId:grant.subjectId,scopes:grant.scopes,resources:grant.resources,audiences:grant.audiences,workspaceId:grant.workspaceId},{accessLifetimeMs,refreshLifetimeMs:0,issueRefreshToken:false});return{result:{ok:true,value:pair},wrote:true}});if(!authenticated)return invalidClient;if(authenticated.wrote)markContextWrote();return authenticated.result}export async function refreshOAuthDelegatedToken(input){const accessLifetimeMs=validLifetime(input.accessTokenLifetimeMs);const refreshLifetimeMs=validLifetime(input.refreshTokenLifetimeMs);const authenticated=await withAuthenticatedOAuthTokenClient(String(input.clientId),input.clientSecret,async(client)=>{if(!client.grantTypes.includes("refresh_token"))return{result:unauthorizedClient,wrote:false};if(!/^[a-f0-9]{80}$/.test(input.refreshToken))return{result:invalidGrant,wrote:false};const sql=sqlHelpers(getDatabaseDialect());const hash=tokenHash(input.refreshToken);const lock=sql.isSqlite?"":" FOR UPDATE";const lookup=await db.unsafe(`
|
|
37
37
|
SELECT r.id, r.family_id, a.oauth_client_id
|
|
38
38
|
FROM oauth_refresh_tokens r
|
|
39
39
|
JOIN oauth_access_tokens a ON a.id = r.access_token_id
|
|
40
40
|
WHERE r.token = ${sql.param(1)}
|
|
41
41
|
LIMIT 1
|
|
42
|
-
`,[hash])
|
|
42
|
+
`,[hash]);const candidate=lookup[0];if(!candidate||String(candidate.oauth_client_id)!==String(input.clientId))return{result:invalidGrant,wrote:false};if(candidate.family_id&&/^[a-f0-9]{32}$/.test(candidate.family_id)){await db.unsafe(`
|
|
43
43
|
SELECT id FROM oauth_refresh_tokens
|
|
44
44
|
WHERE family_id = ${sql.param(1)}
|
|
45
45
|
ORDER BY id${lock}
|
|
46
|
-
`,[candidate.family_id])
|
|
46
|
+
`,[candidate.family_id])}const rows=await db.unsafe(`
|
|
47
47
|
SELECT r.id, r.access_token_id, r.token, r.family_id, r.parent_id, r.revoked,
|
|
48
48
|
r.expires_at, r.created_at, a.tokenable_type, a.tokenable_id,
|
|
49
49
|
a.oauth_client_id, a.oauth_grant_id, a.scopes, a.resources, a.audiences,
|
|
@@ -52,7 +52,7 @@ import{createHash,randomBytes}from"node:crypto";import{db,getDatabaseDialect,mar
|
|
|
52
52
|
JOIN oauth_access_tokens a ON a.id = r.access_token_id
|
|
53
53
|
WHERE r.id = ${sql.param(1)} AND r.token = ${sql.param(2)}
|
|
54
54
|
LIMIT 1${lock}
|
|
55
|
-
`,[candidate.id,hash])
|
|
55
|
+
`,[candidate.id,hash]);const refresh=rows[0];if(!refresh||String(refresh.oauth_client_id)!==String(input.clientId))return{result:invalidGrant,wrote:false};const familyIsValid=Boolean(refresh.family_id&&/^[a-f0-9]{32}$/.test(refresh.family_id));if(!activeFlag(refresh.revoked)||!activeFlag(refresh.access_revoked)||!familyIsValid){await revokeDelegatedRefreshFamily(refresh);return{result:invalidGrant,wrote:true}}if((parseSqlDateTime(refresh.expires_at)?.getTime()??0)<=Date.now())return{result:invalidGrant,wrote:false};const grantLock=sql.isSqlite?"":" FOR UPDATE";const grants=await db.unsafe(`
|
|
56
56
|
SELECT id, client_id AS grant_client_id, subject_type AS grant_subject_type,
|
|
57
57
|
subject_id AS grant_subject_id, scopes AS grant_scopes,
|
|
58
58
|
resources AS grant_resources, audiences AS grant_audiences,
|
|
@@ -60,12 +60,12 @@ import{createHash,randomBytes}from"node:crypto";import{db,getDatabaseDialect,mar
|
|
|
60
60
|
FROM oauth_grants
|
|
61
61
|
WHERE id = ${sql.param(1)}
|
|
62
62
|
LIMIT 1${grantLock}
|
|
63
|
-
`,[refresh.oauth_grant_id])
|
|
63
|
+
`,[refresh.oauth_grant_id]);const grant=grantFromRefreshRows(refresh,grants[0]);if(!grant){await revokeDelegatedRefreshFamily(refresh);return{result:invalidGrant,wrote:true}}if(input.isSubjectEligible&&!await input.isSubjectEligible({type:grant.subjectType,id:grant.subjectId,clientId:grant.clientId,grantId:grant.grantId,workspaceId:grant.workspaceId})){if(!await disconnectOAuthGrant(grant.subjectType,grant.subjectId,grant.grantId))throw new Error("Inactive OAuth subject authorization state could not be revoked.");return{result:invalidGrant,wrote:true}}if(input.audiences&&(!input.audiences.length||new Set(input.audiences).size!==input.audiences.length||input.audiences.length!==grant.audiences.length||input.audiences.some((audience)=>!grant.audiences.includes(audience))))return{result:invalidGrant,wrote:false};const scopes=input.scopes?[...input.scopes]:grant.scopes;if(!scopes.length||new Set(scopes).size!==scopes.length||!scopes.every((scope)=>grant.scopes.includes(scope)&&client.scopes.includes(scope)))return{result:invalidScope,wrote:false};const revoked=sql.isPostgres?true:1;const refreshClaim=await db.unsafe(`
|
|
64
64
|
UPDATE oauth_refresh_tokens
|
|
65
65
|
SET revoked = ${sql.param(1)}
|
|
66
66
|
WHERE id = ${sql.param(2)} AND revoked = ${sql.param(3)}
|
|
67
|
-
`,[revoked,refresh.id,sql.isPostgres
|
|
67
|
+
`,[revoked,refresh.id,sql.isPostgres?false:0]);const accessClaim=await db.unsafe(`
|
|
68
68
|
UPDATE oauth_access_tokens
|
|
69
69
|
SET revoked = ${sql.param(1)}
|
|
70
70
|
WHERE id = ${sql.param(2)} AND revoked = ${sql.param(3)}
|
|
71
|
-
`,[revoked,refresh.access_token_id,sql.isPostgres
|
|
71
|
+
`,[revoked,refresh.access_token_id,sql.isPostgres?false:0]);if(mutationCount(refreshClaim)!==1||mutationCount(accessClaim)!==1){await revokeDelegatedRefreshFamily(refresh);return{result:invalidGrant,wrote:true}}const pair=await mintDelegatedTokenPair({...grant,scopes},{accessLifetimeMs,refreshLifetimeMs,issueRefreshToken:true,refreshFamilyId:refresh.family_id,refreshParentId:Number(refresh.id)});return{result:{ok:true,value:pair},wrote:true}});if(!authenticated)return invalidClient;if(authenticated.wrote)markContextWrote();return authenticated.result}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";export class OAuthTokenRequestError extends Error{error;constructor(error,message){super(message);this.error=error;this.name="OAuthTokenRequestError"}}function reject(error,message){throw new OAuthTokenRequestError(error,message)}function single(params,name,required
|
|
1
|
+
import{Buffer}from"node:buffer";export class OAuthTokenRequestError extends Error{error;constructor(error,message){super(message);this.error=error;this.name="OAuthTokenRequestError"}}function reject(error,message){throw new OAuthTokenRequestError(error,message)}function single(params,name,required=false){const values=params.getAll(name);if(values.length>1)reject("invalid_request",`OAuth token parameter must not be repeated: ${name}`);const value=values[0];if(required&&!value)reject("invalid_request",`OAuth token parameter is required: ${name}`);if(value?.includes("�"))reject("invalid_request",`OAuth token parameter is not valid UTF-8: ${name}`);return value}function clientIdentifier(value){if(!/^[0-9]{1,20}$/.test(value))reject("invalid_client","OAuth client identifier is invalid.");const id=Number(value);if(!Number.isSafeInteger(id)||id<=0)reject("invalid_client","OAuth client identifier is invalid.");return id}function decodeCredential(value){try{return decodeURIComponent(value.replace(/\+/g," "))}catch{return reject("invalid_client","OAuth client credentials are malformed.")}}function basicCredentials(header){const match=/^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header);if(!match)reject("invalid_client","OAuth client authentication must use a valid Basic header.");const encoded=match[1];let bytes;try{bytes=Buffer.from(encoded,"base64")}catch{return reject("invalid_client","OAuth client credentials are malformed.")}if(bytes.toString("base64").replace(/=+$/,"")!==encoded.replace(/=+$/,""))reject("invalid_client","OAuth client credentials are malformed.");let decoded;try{decoded=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{return reject("invalid_client","OAuth client credentials are not valid UTF-8.")}const separator=decoded.indexOf(":");if(separator<1)reject("invalid_client","OAuth client credentials are malformed.");const clientId=clientIdentifier(decodeCredential(decoded.slice(0,separator)));const clientSecret=decodeCredential(decoded.slice(separator+1));if(!clientSecret||clientSecret.length>4096)reject("invalid_client","OAuth client secret is invalid.");return{clientId,clientSecret}}function clientCredentials(params,authorization){const bodyClientId=single(params,"client_id");const bodyClientSecret=single(params,"client_secret");if(authorization){if(bodyClientId!==undefined||bodyClientSecret!==undefined)reject("invalid_request","OAuth client authentication methods must not be combined.");return basicCredentials(authorization)}if(bodyClientSecret!==undefined)reject("invalid_request","OAuth client secrets must use Basic authentication.");return{clientId:clientIdentifier(bodyClientId??"")}}function tokenValue(params,name){const value=single(params,name,true);if(value.length>4096||/\s/.test(value))reject("invalid_request",`OAuth token parameter is invalid: ${name}`);return value}function requestedScopes(params){const value=single(params,"scope");if(value===undefined)return;const scopes=value.split(" ");if(scopes.some((scope)=>!/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope))||new Set(scopes).size!==scopes.length)reject("invalid_request","OAuth scope must contain unique scope tokens.");return scopes}export function parseOAuthTokenRequest(body,authorization){if(body.length>16384)reject("invalid_request","OAuth token request is too large.");const params=new URLSearchParams(body);for(const name of["grant_type","client_id","client_secret","code","redirect_uri","code_verifier","refresh_token","scope"])single(params,name);const credentials=clientCredentials(params,authorization);const audiences=params.getAll("resource");if(audiences.length>10||new Set(audiences).size!==audiences.length||audiences.some((value)=>{try{const url=new URL(value);return!!(url.username||url.password||url.hash)}catch{return true}}))reject("invalid_request","OAuth resource must contain unique absolute URIs without credentials or fragments.");if(audiences.length)credentials.audiences=audiences;const grantType=single(params,"grant_type",true);if(grantType==="authorization_code"){const codeVerifier=single(params,"code_verifier",true);if(!/^[A-Za-z0-9\-._~]{43,128}$/.test(codeVerifier))reject("invalid_request","OAuth PKCE verifier is invalid.");const redirectUri=single(params,"redirect_uri",true);if(redirectUri.length>2048)reject("invalid_request","OAuth redirect URI is too large.");return{grantType,...credentials,code:tokenValue(params,"code"),redirectUri,codeVerifier}}if(grantType==="refresh_token"){const scopes=requestedScopes(params);return{grantType,...credentials,refreshToken:tokenValue(params,"refresh_token"),...scopes?{scopes}:{}}}if(grantType==="client_credentials"){if(!authorization||!credentials.clientSecret)reject("invalid_client","The client_credentials grant requires Basic client authentication.");const scopes=requestedScopes(params);return{grantType,...credentials,...scopes?{scopes}:{}}}return reject("unsupported_grant_type","OAuth grant type is not supported.")}export function parseOAuthRevocationRequest(body,authorization){if(body.length>16384)reject("invalid_request","OAuth revocation request is too large.");const params=new URLSearchParams(body);for(const name of["client_id","client_secret","token","token_type_hint"])single(params,name);const credentials=clientCredentials(params,authorization);const token=tokenValue(params,"token");const tokenTypeHint=single(params,"token_type_hint");if(tokenTypeHint!==undefined&&tokenTypeHint!=="access_token"&&tokenTypeHint!=="refresh_token")reject("unsupported_token_type","OAuth revocation token type is not supported.");return{...credentials,token,...tokenTypeHint?{tokenTypeHint}:{}}}export function parseOAuthIntrospectionRequest(body,authorization){if(body.length>16384)reject("invalid_request","OAuth introspection request is too large.");const params=new URLSearchParams(body);for(const name of["client_id","client_secret","token","token_type_hint"])single(params,name);if(!authorization)reject("invalid_client","OAuth introspection requires Basic client authentication.");const credentials=clientCredentials(params,authorization);const token=tokenValue(params,"token");const tokenTypeHint=single(params,"token_type_hint");if(tokenTypeHint!==undefined&&tokenTypeHint!=="access_token"&&tokenTypeHint!=="refresh_token")reject("unsupported_token_type","OAuth introspection token type is not supported.");return{...credentials,token,...tokenTypeHint?{tokenTypeHint}:{}}}
|
package/dist/oauth-userinfo.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac}from"node:crypto";import{authorizeOAuthDelegatedToken,oauthBearerAuthorizationErrorResponse}from"./oauth-delegated-access";export function pairwiseOAuthSubject(secret,clientId,subject){if(secret.length<32)throw TypeError("A pairwise subject secret must be at least 32 characters.");if(clientId===""||clientId==null||!subject.type||!Number.isSafeInteger(subject.id))throw TypeError("A pairwise subject needs a client, a subject type and a numeric subject id.");return createHmac("sha256",secret).update(`${clientId}\x00${subject.type}\x00${subject.id}`).digest("base64url")}function bearerOf(request){const header=request.headers.get("authorization")||""
|
|
1
|
+
import{createHmac}from"node:crypto";import{authorizeOAuthDelegatedToken,oauthBearerAuthorizationErrorResponse}from"./oauth-delegated-access";export function pairwiseOAuthSubject(secret,clientId,subject){if(secret.length<32)throw new TypeError("A pairwise subject secret must be at least 32 characters.");if(clientId===""||clientId==null||!subject.type||!Number.isSafeInteger(subject.id))throw new TypeError("A pairwise subject needs a client, a subject type and a numeric subject id.");return createHmac("sha256",secret).update(`${clientId}\x00${subject.type}\x00${subject.id}`).digest("base64url")}function bearerOf(request){const header=request.headers.get("authorization")||"";const match=/^Bearer ([\x21-\x7E]{1,4096})$/.exec(header);return match?match[1]:null}export async function oauthUserInfoResponse(request,options){const bearer=bearerOf(request);if(!bearer)return oauthBearerAuthorizationErrorResponse({ok:false,reason:"invalid_token"});const{pairwiseSecret,claims,authorize=authorizeOAuthDelegatedToken,...requirement}=options;let subject=null;const result=await authorize(bearer,{...requirement,isSubjectEligible:async(candidate)=>{subject=candidate;return requirement.isSubjectEligible(candidate)}});if(!result.ok)return oauthBearerAuthorizationErrorResponse(result);const resolved=subject;if(!resolved)return oauthBearerAuthorizationErrorResponse({ok:false,reason:"invalid_token"});const sub=pairwiseOAuthSubject(pairwiseSecret,resolved.clientId,resolved);const released=await claims({sub,subject:resolved,clientId:resolved.clientId,scopes:[...result.token.scopes]});if(!released)return oauthBearerAuthorizationErrorResponse({ok:false,reason:"invalid_token"});return new Response(JSON.stringify({...released,sub}),{headers:{"Cache-Control":"no-store",Pragma:"no-cache","Content-Type":"application/json; charset=utf-8"}})}
|
package/dist/page-gate.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Auth}from"./authentication";import{authCookieName}from"./cookie-auth";export function stxPageAuthMiddleware(options={}){const redirectTo=options.redirectTo??"/login"
|
|
1
|
+
import{Auth}from"./authentication";import{authCookieName}from"./cookie-auth";export function stxPageAuthMiddleware(options={}){const redirectTo=options.redirectTo??"/login";const home=options.home??"/";const validate=options.validate??((token)=>Auth.getUserFromToken(token));async function signedInUser(ctx){const token=ctx.cookies[authCookieName({name:options.cookieName})];if(!token)return;try{return await validate(token)}catch{return}}const auth=Object.assign(async(_req,ctx)=>{if(await signedInUser(ctx))return null;return ctx.redirect(redirectTo)},{priority:1});const guest=Object.assign(async(_req,ctx)=>{if(await signedInUser(ctx))return Response.redirect(home,302);return null},{priority:1});return{auth,guest}}
|
package/dist/passkey.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{User}from"@stacksjs/orm";export{generateRegistrationOptions,generateAuthenticationOptions,verifyRegistrationResponse,verifyAuthenticationResponse,startRegistration,startAuthentication,browserSupportsWebAuthn,browserSupportsWebAuthnAutofill,platformAuthenticatorIsAvailable}from"@stacksjs/ts-auth";export function passkeyDescriptors(passkeys){return passkeys.map((passkey)=>({id:passkey.id,type:"public-key",transports:parseTransports(passkey.transports)}))}function parseTransports(stored){if(!stored)return;try{const parsed=JSON.parse(stored);return Array.isArray(parsed)&&parsed.length?parsed.filter((value)=>["ble","internal","nfc","usb","hybrid"].includes(value)):
|
|
1
|
+
import{Buffer}from"node:buffer";import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{User}from"@stacksjs/orm";export{generateRegistrationOptions,generateAuthenticationOptions,verifyRegistrationResponse,verifyAuthenticationResponse,startRegistration,startAuthentication,browserSupportsWebAuthn,browserSupportsWebAuthnAutofill,platformAuthenticatorIsAvailable}from"@stacksjs/ts-auth";export function passkeyDescriptors(passkeys){return passkeys.map((passkey)=>({id:passkey.id,type:"public-key",transports:parseTransports(passkey.transports)}))}function parseTransports(stored){if(!stored)return;try{const parsed=JSON.parse(stored);return Array.isArray(parsed)&&parsed.length?parsed.filter((value)=>["ble","internal","nfc","usb","hybrid"].includes(value)):undefined}catch{return}}export async function getUserPasskeys(userId){const rows=await db.primary.selectFrom("passkeys").selectAll().where("user_id","=",userId).execute();return rows}export async function getUserPasskey(userId,passkeyId){const row=await db.primary.selectFrom("passkeys").selectAll().where("id","=",passkeyId).where("user_id","=",userId).executeTakeFirst();return row}export async function updatePasskeyCounter(userId,passkeyId,newCounter,verifiedCredential){if(!Number.isSafeInteger(newCounter)||newCounter<0)return false;const passkey=verifiedCredential??await getUserPasskey(userId,passkeyId);if(!passkey)return false;const stored=Number(passkey.counter??0);if(newCounter<=stored&&!(newCounter===0&&stored===0)){return false}if(newCounter===0){return db.transaction(async()=>{let query=db.primary.selectFrom("passkeys").selectAll().where("id","=",passkeyId).where("user_id","=",userId).where("counter","=",0).where("cred_public_key","=",passkey.cred_public_key);if(getDatabaseDialect()!=="sqlite")query=query.lockForUpdate();const current=await query.executeTakeFirst();if(!current)return false;await db.updateTable("passkeys").set({last_used_at:sqlDateTime()}).where("id","=",passkeyId).where("user_id","=",userId).execute();return true})}const claimed=await db.updateTable("passkeys").set({counter:newCounter,last_used_at:sqlDateTime()}).where("id","=",passkeyId).where("user_id","=",userId).where("counter","=",stored).where("cred_public_key","=",passkey.cred_public_key).execute();return mutationCount(claimed)===1}export async function setCurrentRegistrationOptions(user,verified){if(!verified.verified)throw new Error("[auth/passkey] Registration is not verified");const credentialId=verified.registrationInfo?.credential.id;const credentialPublicKey=verified.registrationInfo?.credential.publicKey;if(!credentialId){throw new Error("[auth/passkey] WebAuthn registration response is missing credential.id")}if(!credentialPublicKey){throw new Error("[auth/passkey] WebAuthn registration response is missing credential.publicKey")}const passkeyData={id:credentialId,cred_public_key:JSON.stringify(Array.from(new Uint8Array(credentialPublicKey))),user_id:user.id,webauthn_user_id:user.email||"",counter:verified.registrationInfo?.credential.counter||0,credential_type:verified.registrationInfo?.credentialType||"",device_type:verified.registrationInfo?.credentialDeviceType||"",backup_eligible:false,backup_status:verified.registrationInfo?.credentialBackedUp||false,transports:JSON.stringify(["internal"]),last_used_at:sqlDateTime()};await db.insertInto("passkeys").values(passkeyData).executeTakeFirstOrThrow()}const DEFAULT_CHALLENGE_TTL_SECONDS=5*60;export async function storeWebAuthnChallenge(userId,challenge,purpose,ttlSeconds=DEFAULT_CHALLENGE_TTL_SECONDS){const expiresAt=sqlDateTime(new Date(Date.now()+ttlSeconds*1000));const encodedChallenge=typeof challenge==="string"?challenge:Buffer.from(challenge).toString("base64url");await db.transaction(async()=>{await db.deleteFrom("webauthn_challenges").where("user_id","=",userId).where("purpose","=",purpose).execute();await db.insertInto("webauthn_challenges").values({user_id:userId,challenge:encodedChallenge,purpose,expires_at:expiresAt}).execute();const stored=await db.primary.selectFrom("webauthn_challenges").where("user_id","=",userId).where("purpose","=",purpose).select("challenge").execute();if(stored.length!==1||stored[0]?.challenge!==encodedChallenge)throw new Error("[auth] WebAuthn challenge could not be stored.")})}export async function consumeWebAuthnChallenge(userId,purpose){const row=await db.primary.selectFrom("webauthn_challenges").where("user_id","=",userId).where("purpose","=",purpose).select(["challenge","expires_at"]).executeTakeFirst();if(!row)return null;const claimed=await db.deleteFrom("webauthn_challenges").where("user_id","=",userId).where("purpose","=",purpose).where("challenge","=",row.challenge).where("expires_at","=",row.expires_at).execute();if(mutationCount(claimed)!==1)return null;const expiresAt=parseSqlDateTime(row.expires_at)?.getTime()??0;if(Date.now()>=expiresAt)return null;return Buffer.from(String(row.challenge),"base64url")}
|
package/dist/passkeys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomBytes}from"node:crypto";import{Buffer}from"node:buffer";import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{generateRegistrationOptions,generateAuthenticationOptions,verifyRegistrationResponse,verifyAuthenticationResponse,registrationOptionsToJSON,authenticationOptionsToJSON,registrationCredentialFromJSON,authenticationCredentialFromJSON}from"@stacksjs/ts-auth";import{getUserPasskeys,passkeyDescriptors,updatePasskeyCounter}from"./passkey";export class PasskeyError extends Error{}const TTL=
|
|
1
|
+
import{createHash,randomBytes}from"node:crypto";import{Buffer}from"node:buffer";import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{generateRegistrationOptions,generateAuthenticationOptions,verifyRegistrationResponse,verifyAuthenticationResponse,registrationOptionsToJSON,authenticationOptionsToJSON,registrationCredentialFromJSON,authenticationCredentialFromJSON}from"@stacksjs/ts-auth";import{getUserPasskeys,passkeyDescriptors,updatePasskeyCounter}from"./passkey";export class PasskeyError extends Error{}const TTL=5*60*1000;const digest=(token)=>createHash("sha256").update(token).digest("hex");function relyingParty(party){const url=new URL(party.origin);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url.hostname)))throw new Error("Passkeys require HTTPS or localhost");return{origin:url.origin,rpID:url.hostname}}async function issue(purpose,challenge,userId,origin){const token=randomBytes(32).toString("base64url");await db.deleteFrom("passkey_ceremonies").where("expires_at","<",sqlDateTime()).execute();await db.insertInto("passkey_ceremonies").values({id:digest(token),user_id:userId,purpose,challenge:Buffer.from(challenge).toString("base64url"),origin,expires_at:sqlDateTime(new Date(Date.now()+TTL))}).execute();return token}async function consume(token,purpose,origin,userId){if(typeof token!=="string"||!/^[A-Za-z0-9_-]{43}$/.test(token))throw new PasskeyError("Passkey request expired. Please try again.");const row=await db.primary.selectFrom("passkey_ceremonies").selectAll().where("id","=",digest(token)).where("purpose","=",purpose).where("origin","=",origin).executeTakeFirst();if(!row||userId!==undefined&&Number(row.user_id)!==userId)throw new PasskeyError("Passkey request expired. Please try again.");const claimed=await db.deleteFrom("passkey_ceremonies").where("id","=",row.id).execute();if(mutationCount(claimed)!==1||(parseSqlDateTime(row.expires_at)?.getTime()??0)<=Date.now())throw new PasskeyError("Passkey request expired. Please try again.");return row}export async function beginPasskeyRegistration(user,party){const{origin,rpID}=relyingParty(party);const existing=await getUserPasskeys(user.id);const handle=createHash("sha256").update(`stacks:passkey:${rpID}:${user.id}`).digest("base64url");const options=generateRegistrationOptions({rpID,rpName:party.name,userID:handle,userName:user.email||String(user.id),userDisplayName:user.name,attestationType:"none",excludeCredentials:passkeyDescriptors(existing),authenticatorSelection:{residentKey:"required",requireResidentKey:true,userVerification:"required"}});return{ceremony:await issue("registration",options.challenge,user.id,origin),options:registrationOptionsToJSON(options)}}export async function finishPasskeyRegistration(userId,token,credential,party){const{origin,rpID}=relyingParty(party);const ceremony=await consume(token,"registration",origin,userId);let verified;try{verified=await verifyRegistrationResponse(registrationCredentialFromJSON(credential),Buffer.from(ceremony.challenge,"base64url"),origin,rpID,{requireUserVerification:true})}catch{throw new PasskeyError("Passkey could not be verified.")}const info=verified.registrationInfo;if(!verified.verified||!info||info.credential.id.length>255)throw new PasskeyError("Passkey could not be verified.");const transports=Array.isArray(credential.response.transports)?credential.response.transports.filter((value)=>["internal","hybrid","usb","nfc","ble"].includes(value)):[];await db.insertInto("passkeys").values({id:info.credential.id,user_id:userId,cred_public_key:Buffer.from(info.credential.publicKey).toString("base64url"),webauthn_user_id:createHash("sha256").update(`stacks:passkey:${rpID}:${userId}`).digest("base64url"),counter:info.credential.counter,credential_type:info.credentialType,device_type:info.credentialDeviceType,backup_eligible:info.credentialDeviceType==="multiDevice",backup_status:info.credentialBackedUp,transports:JSON.stringify(transports||[]),created_at:sqlDateTime(),last_used_at:null}).execute()}export async function beginPasskeyAuthentication(party){const{origin,rpID}=relyingParty(party);const options=generateAuthenticationOptions({rpID,userVerification:"required"});return{ceremony:await issue("authentication",options.challenge,null,origin),options:authenticationOptionsToJSON(options)}}export async function finishPasskeyAuthentication(token,credential,party){const{origin,rpID}=relyingParty(party);const ceremony=await consume(token,"authentication",origin);try{const decoded=authenticationCredentialFromJSON(credential);const passkey=await db.primary.selectFrom("passkeys").selectAll().where("id","=",decoded.id).executeTakeFirst();if(!passkey)throw new PasskeyError("Passkey could not be verified.");if(decoded.response.userHandle&&Buffer.from(decoded.response.userHandle).toString()!==passkey.webauthn_user_id)throw new PasskeyError("Passkey could not be verified.");const stored=String(passkey.cred_public_key);const key=stored.startsWith("{")||stored.startsWith("[")?Uint8Array.from(Object.values(JSON.parse(stored))).buffer:new Uint8Array(Buffer.from(stored,"base64url")).buffer;const verified=await verifyAuthenticationResponse(decoded,Buffer.from(ceremony.challenge,"base64url"),origin,rpID,key,Number(passkey.counter),{requireUserVerification:true});const counter=verified.authenticationInfo?.newCounter;if(!verified.verified||counter===undefined||!await updatePasskeyCounter(Number(passkey.user_id),decoded.id,counter,{counter:Number(passkey.counter),cred_public_key:String(passkey.cred_public_key)}))throw new PasskeyError("Passkey could not be verified.");return Number(passkey.user_id)}catch{throw new PasskeyError("Passkey could not be verified.")}}export async function listPasskeys(userId){return(await getUserPasskeys(userId)).map((key)=>({id:key.id,device:key.device_type,created_at:key.created_at,last_used_at:key.last_used_at}))}export async function removePasskey(userId,credentialId,hasAlternativeSignIn){return db.transaction(async()=>{let query=db.primary.selectFrom("users").selectAll().where("id","=",userId);if(getDatabaseDialect()!=="sqlite")query=query.lockForUpdate();const user=await query.executeTakeFirst();if(!user)return false;const keys=await getUserPasskeys(userId);if(!keys.some((key)=>key.id===credentialId))return false;const alternative=hasAlternativeSignIn?await hasAlternativeSignIn(user):typeof user.password==="string"&&user.password.length>0;if(keys.length===1&&!alternative)throw new PasskeyError("Add a password or another passkey before removing your last passkey.");return mutationCount(await db.deleteFrom("passkeys").where("user_id","=",userId).where("id","=",credentialId).execute())===1})}
|
|
@@ -2,7 +2,7 @@ import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDia
|
|
|
2
2
|
SELECT DATA_TYPE AS kind, DATETIME_PRECISION AS stamp_precision
|
|
3
3
|
FROM information_schema.COLUMNS
|
|
4
4
|
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'password_changed_at'
|
|
5
|
-
`).execute()
|
|
5
|
+
`).execute();const column=columns[0];if(columns.length!==1||!column||!["datetime","timestamp"].includes(String(column.kind))||!/^[0-6]$/.test(String(column.stamp_precision)))throw new Error("[auth] Cannot verify password_changed_at temporal precision.");const precision=Number(column.stamp_precision);const rows=await db.primary.unsafe(`
|
|
6
6
|
SELECT (password_changed_at = CAST(? AS DATETIME(${precision}))) AS stamp_matches
|
|
7
7
|
FROM users WHERE id = ?
|
|
8
|
-
`,[stamp,userId]).execute();return rows.length===1&&(rows[0]?.stamp_matches
|
|
8
|
+
`,[stamp,userId]).execute();return rows.length===1&&(rows[0]?.stamp_matches===true||rows[0]?.stamp_matches===1)}async function revokePendingPasswordResets(email){if(typeof email!=="string"||!email)return;try{await db.transaction(async()=>{await deletePasswordResetCredentials(email)})}catch(error){const message=error&&typeof error==="object"&&"message"in error&&typeof error.message==="string"?error.message:String(error);if(/^(?:no such table: (?:main\.)?password_resets|relation "password_resets" does not exist|Table '(?:[^'.]+\.)?password_resets' doesn't exist)$/i.test(message))return;throw error}}export async function revokeAccountCredentials(userId,options={}){if(!Number.isSafeInteger(userId)||userId<=0)throw new TypeError("[auth] revokeAccountCredentials needs a positive integer user id.");if(options.exceptTokenId!==undefined&&(!Number.isSafeInteger(options.exceptTokenId)||options.exceptTokenId<=0))throw new TypeError("[auth] exceptTokenId must be a positive integer.");if(options.tx!==undefined&&!isInTransaction())throw new TypeError("[auth] revokeAccountCredentials was given a tx but is not running inside that transaction.");return db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)throw new Error("[auth] revokeAccountCredentials: the user does not exist.");let passwordChangedAt=null;const stampValue=sqlDateTime(new Date);if(Object.hasOwn(owner,"password_changed_at")){const stamped=await db.updateTable("users").set({password_changed_at:stampValue}).where("id","=",userId).execute();const changed=mutationCount(stamped);if(changed!==1&&!(changed===0&&getDatabaseDialect()==="mysql"&&await mysqlPasswordStampMatches(userId,stampValue)))throw new Error("[auth] revokeAccountCredentials could not stamp password_changed_at.");passwordChangedAt=parseSqlDateTime(stampValue)}else{log.warn("[auth] password_changed_at column missing - run `buddy migrate`; credentials are revoked without the credential-version stamp")}await revokePendingPasswordResets(owner.email);await revokeTwoFactorChallenges(userId);await revokeMagicLinks(userId);await revokeOAuthSubjectAuthorizationState("users",userId);await revokeTokenPairs(userId,DEFAULT_TOKENABLE_TYPE,options.exceptTokenId);await sessionDestroyAll(userId,options.exceptSessionId!==undefined?{exceptId:options.exceptSessionId}:{});let keptTokenId=null;if(options.exceptTokenId!==undefined&&passwordChangedAt){const rebound=await db.updateTable("oauth_access_tokens").set({created_at:stampValue}).where("id","=",options.exceptTokenId).where("tokenable_id","=",userId).execute();if(mutationCount(rebound)===1){await db.updateTable("oauth_refresh_tokens").set({created_at:stampValue}).where("access_token_id","=",options.exceptTokenId).execute();keptTokenId=options.exceptTokenId}}else if(options.exceptTokenId!==undefined){keptTokenId=options.exceptTokenId}return{passwordChangedAt,keptTokenId}})}export async function changePassword(userId,currentPassword,newPassword,options={}){if(typeof newPassword!=="string"||newPassword.length===0)return{success:false,reason:"invalid-new-password"};const user=await db.primary.selectFrom("users").where("id","=",userId).selectAll().executeTakeFirst();if(!user)return{success:false,reason:"user-not-found"};const storedHash=typeof user.password==="string"?user.password:"";if(typeof currentPassword!=="string"||!storedHash||!await verifyHash(currentPassword,storedHash))return{success:false,reason:"invalid-current-password"};const hashed=await makeHash(newPassword,{algorithm:"bcrypt"});const swept=await withVerifiedPassword(userId,storedHash,async()=>{const updated=await db.updateTable("users").set({password:hashed,...Object.hasOwn(user,"updated_at")?{updated_at:sqlDateTime()}:{}}).where("id","=",userId).execute();if(mutationCount(updated)!==1)throw new Error("[auth] changePassword could not update the password.");return revokeAccountCredentials(userId,{...options.keepTokenId!==undefined&&{exceptTokenId:options.keepTokenId},...options.keepSessionId!==undefined&&{exceptSessionId:options.keepSessionId}})});if(!swept)return{success:false,reason:"invalid-current-password"};const notify=options.notify??true;if(notify!==false&&user.email){const recipient={id:Number(user.id),email:String(user.email),...user.name?{name:String(user.name)}:{}};const send=async()=>{try{if(typeof notify==="function")await notify(recipient);else await sendPasswordChangedNotification(recipient.email)}catch(error){log.error(`[auth] password-changed notification failed: ${error instanceof Error?error.message:String(error)}`)}};if(!enqueueAfterCommit(send))send()}return{success:true,keptTokenId:swept.keptTokenId}}export async function sendPasswordChangedNotification(userEmail){const appName=config.app.name||"Stacks";const supportEmail=config.app.supportEmail||config.email?.from?.address||"";const changedAt=new Date().toLocaleString("en-US",{dateStyle:"full",timeStyle:"short"});try{const{html,text}=await template("password-changed",{subject:`Your ${appName} password has been changed`,variables:{changedAt,supportEmail}});if(!html&&!text){await mail.sendOrFail({to:userEmail,subject:`Your ${appName} password has been changed`,text:`Your ${appName} password was changed on ${changedAt}.${supportEmail?` If this wasn't you, contact ${supportEmail}.`:""}`});return}await mail.sendOrFail({to:userEmail,subject:`Your ${appName} password has been changed`,text,html})}catch(error){console.error("[PasswordReset] Failed to send password changed notification:",error)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{normalizeAuthEmail}from"../credential-user";function ownerAddress(email){return{where:`LOWER(email) = ${
|
|
1
|
+
import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";import{normalizeAuthEmail}from"../credential-user";function ownerAddress(email){const sql=sqlHelpers(getDatabaseDialect());return{where:`LOWER(email) = ${sql.param(1)}`,parameters:[normalizeAuthEmail(email)]}}export async function pendingPasswordResetCredentials(email){const owner=ownerAddress(email);return await db.primary.unsafe(`SELECT email, created_at FROM password_resets WHERE ${owner.where}`,owner.parameters)}export async function deletePasswordResetCredentials(email){const owner=ownerAddress(email);await db.unsafe(`DELETE FROM password_resets WHERE ${owner.where}`,owner.parameters);const remaining=await db.primary.unsafe(`SELECT email FROM password_resets WHERE ${owner.where} LIMIT 1`,owner.parameters);if(remaining.length)throw new Error("Password reset credentials could not be removed")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomBytes}from"node:crypto";import{config}from"@stacksjs/config";import{db,lockRow,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{findAuthUserRowByEmail,normalizeAuthEmail}from"../credential-user";import{deletePasswordResetCredentials,pendingPasswordResetCredentials}from"./reset-store";export function passwordResetTokenDigest(token){return createHash("sha256").update(token).digest("hex")}export function mintPasswordResetToken(){const token=randomBytes(32).toString("hex");return{token,digest:passwordResetTokenDigest(token)}}export async function issuePasswordResetToken(address,options={}){const email=normalizeAuthEmail(address)
|
|
1
|
+
import{createHash,randomBytes}from"node:crypto";import{config}from"@stacksjs/config";import{db,lockRow,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{findAuthUserRowByEmail,normalizeAuthEmail}from"../credential-user";import{deletePasswordResetCredentials,pendingPasswordResetCredentials}from"./reset-store";export function passwordResetTokenDigest(token){return createHash("sha256").update(token).digest("hex")}export function mintPasswordResetToken(){const token=randomBytes(32).toString("hex");return{token,digest:passwordResetTokenDigest(token)}}export async function issuePasswordResetToken(address,options={}){const email=normalizeAuthEmail(address);const throttleMs=options.throttleMs??Number(config.auth.passwordReset?.throttle??60)*1000;if(!Number.isFinite(throttleMs)||throttleMs<0)throw new RangeError("Reset throttle must be nonnegative");if(options.expiresAt!==undefined&&(!(options.expiresAt instanceof Date)||!(options.expiresAt.getTime()>Date.now())))throw new RangeError("Reset expiry must be a future date");const observed=await findAuthUserRowByEmail(email);if(!observed)return{issued:false};return db.transaction(async(tx)=>{const user=await lockRow(tx,"users",{id:Number(observed.id)});if(!user||normalizeAuthEmail(String(user.email))!==email||options.eligible&&options.eligible(user)!==true)return{issued:false};const now=Date.now();const pending=await pendingPasswordResetCredentials(email);const createdAt=pending.reduce((latest,credential)=>Math.max(latest,parseSqlDateTime(credential.created_at)?.getTime()??Number.NEGATIVE_INFINITY),Number.NEGATIVE_INFINITY);if(throttleMs>0&&now<createdAt+throttleMs)return{issued:false};if(options.expiresAt!==undefined&&!(options.expiresAt.getTime()>now))throw new RangeError("Reset expiry must be a future date");const token=`${Number(observed.id)}.${mintPasswordResetToken().token}`;await deletePasswordResetCredentials(email);const saved=await db.insertInto("password_resets").values({email,token:passwordResetTokenDigest(token),created_at:sqlDateTime(new Date(now)),expires_at:options.expiresAt?sqlDateTime(options.expiresAt):null}).execute();if(mutationCount(saved)!==1)throw new Error("Password reset token could not be issued");return{issued:true,token,userId:Number(observed.id),email}})}export async function consumePasswordResetToken(token,apply,options={}){if(!token||token.length>1024)return{consumed:false};const digest=passwordResetTokenDigest(token);const observed=await db.primary.selectFrom("password_resets").select(["email"]).where("token","=",digest).executeTakeFirst();if(!observed)return{consumed:false};const email=String(observed.email);const owner=await findAuthUserRowByEmail(email);if(!owner)return{consumed:false};const boundAccount=/^([1-9]\d*)\.[a-f0-9]{64}$/.exec(token)?.[1];if(boundAccount&&boundAccount!==String(owner.id))return{consumed:false};const ttlMs=options.ttlMs??Number(config.auth.passwordReset?.expire??60)*60000;if(!Number.isFinite(ttlMs)||ttlMs<=0)throw new RangeError("Reset lifetime must be positive");return db.transaction(async(tx)=>{const user=await lockRow(tx,"users",{id:Number(owner.id)});if(!user||normalizeAuthEmail(String(user.email))!==normalizeAuthEmail(email))return{consumed:false};const reset=await lockRow(tx,"password_resets",{email});if(!reset||reset.token!==digest)return{consumed:false};const deadline=reset.expires_at==null?(parseSqlDateTime(reset.created_at)?.getTime()??0)+ttlMs:parseSqlDateTime(reset.expires_at)?.getTime()??0;if(!(deadline>Date.now())){await db.deleteFrom("password_resets").where("email","=",email).where("token","=",digest).execute();return{consumed:false}}const deleted=await db.deleteFrom("password_resets").where("email","=",email).where("token","=",digest).execute();if(mutationCount(deleted)!==1)throw new Error("Password reset token could not be consumed");const value=await apply({userId:Number(owner.id),email,hasExplicitExpiry:reset.expires_at!=null});return{consumed:true,value}})}
|
package/dist/password/reset.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import{config,feature,overridesReady}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{mountedDefaultRouteBundles}from"@stacksjs/router";import{makeHash,verifyHash}from"@stacksjs/security";import{authLinkBase}from"../link-url";import{findAuthUserRowByEmail,normalizeAuthEmail}from"../credential-user";import{revokeAccountCredentials,sendPasswordChangedNotification}from"./credentials";export{changePassword,revokeAccountCredentials,sendPasswordChangedNotification}from"./credentials";function getTokenExpireMinutes(){return config.auth.passwordReset?.expire??60}function getResetThrottleMilliseconds(){const seconds=config.auth.passwordReset?.throttle??60;if(seconds===0)return 0;const milliseconds=seconds*1000;return Number.isFinite(milliseconds)&&milliseconds>0?milliseconds:60000}function resetRequestIsThrottled(createdAt,throttleMs){if(throttleMs===0)return
|
|
1
|
+
import{randomBytes}from"node:crypto";import{config,feature,overridesReady}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{mountedDefaultRouteBundles}from"@stacksjs/router";import{makeHash,verifyHash}from"@stacksjs/security";import{authLinkBase}from"../link-url";import{findAuthUserRowByEmail,normalizeAuthEmail}from"../credential-user";import{revokeAccountCredentials,sendPasswordChangedNotification}from"./credentials";export{changePassword,revokeAccountCredentials,sendPasswordChangedNotification}from"./credentials";function getTokenExpireMinutes(){return config.auth.passwordReset?.expire??60}function getResetThrottleMilliseconds(){const seconds=config.auth.passwordReset?.throttle??60;if(seconds===0)return 0;const milliseconds=seconds*1000;return Number.isFinite(milliseconds)&&milliseconds>0?milliseconds:60000}function resetRequestIsThrottled(createdAt,throttleMs){if(throttleMs===0)return false;const created=parseSqlDateTime(createdAt);return created!=null&&created.getTime()+throttleMs>Date.now()}function isWithinExpiry(row){const explicit=row.expires_at;if(explicit!=null)return(parseSqlDateTime(explicit)?.getTime()??0)>Date.now();const created=parseSqlDateTime(row.created_at);const expireMinutes=getTokenExpireMinutes();return created!=null&&Number.isFinite(expireMinutes)&&expireMinutes>0&&created.getTime()+expireMinutes*60000>Date.now()}export function passwordResets(value){const email=normalizeAuthEmail(value);function generateResetToken(){return randomBytes(32).toString("hex")}async function createResetToken(userId,expiresAtOverride){const throttleMs=getResetThrottleMilliseconds();const observed=await db.primary.selectFrom("password_resets").where("email","=",email).select("created_at").orderBy("created_at","desc").executeTakeFirst();if(resetRequestIsThrottled(observed?.created_at,throttleMs))return;const token=generateResetToken();const hashedToken=await makeHash(token,{algorithm:"bcrypt"});const expireMinutes=getTokenExpireMinutes();const issued=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).select(["id","email"]);if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||normalizeAuthEmail(String(owner.email??""))!==email)return false;const current=await db.primary.selectFrom("password_resets").where("email","=",email).select("created_at").orderBy("created_at","desc").executeTakeFirst();if(resetRequestIsThrottled(current?.created_at,throttleMs))return false;const createdAt=new Date;const expiresAt=sqlDateTime(expiresAtOverride??new Date(createdAt.getTime()+expireMinutes*60000));await db.deleteFrom("password_resets").where("email","=",email).execute();await db.insertInto("password_resets").values({email,token:hashedToken,expires_at:expiresAt,created_at:sqlDateTime(createdAt)}).executeTakeFirst();const stored=await db.primary.selectFrom("password_resets").where("email","=",email).select(["token"]).execute();if(stored.length!==1||stored[0]?.token!==hashedToken)throw new Error("Password reset could not replace its token");return true},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(!issued)return;return{token,expiresAt:expiresAtOverride??new Date(Date.now()+expireMinutes*60000)}}async function sendEmail(options={}){const purpose=options.purpose==="setup"?"setup":"reset";if(options.expiresAt!==undefined&&(!(options.expiresAt instanceof Date)||!Number.isFinite(options.expiresAt.getTime())||options.expiresAt.getTime()<=Date.now()))throw new TypeError("[PasswordReset] expiresAt must be a future Date.");const user=await findAuthUserRowByEmail(email);if(!user)return;const userId=Number(user.id);if(!Number.isSafeInteger(userId)||userId<=0)return;const issued=await createResetToken(userId,options.expiresAt);if(!issued)return;const delivery={purpose,userId,email,token:issued.token,url:await resetUrlFor(issued.token),expiresAt:issued.expiresAt};const deliver=options.deliver?async()=>{await options.deliver(delivery)}:()=>deliverResetEmail(delivery);if(!enqueueAfterCommit(deliver))await deliver()}async function resetUrlFor(token){const base=authLinkBase();const tpl=config.auth.passwordReset?.url??"/password/reset/{token}?email={email}";if(!config.auth.passwordReset?.url)await warnIfDefaultResetPageMissing();const filled=tpl.replace("{token}",token).replace("{email}",encodeURIComponent(email));return/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`}async function deliverResetEmail(delivery){const resetUrl=delivery.url;const expireMinutes=Math.max(1,Math.round((delivery.expiresAt.getTime()-Date.now())/60000));const appName=config.app.name||"Stacks";const setup=delivery.purpose==="setup";const subject=setup?`Set Your ${appName} Password`:`Reset Your ${appName} Password`;let html;let text;try{const rendered=await template("password-reset",{subject,variables:{resetUrl,expireMinutes,purpose:delivery.purpose}});html=rendered.html;text=rendered.text;if(!html&&!text)throw new Error("password-reset template missing or rendered empty")}catch(templateError){const msg=templateError instanceof Error?templateError.message:String(templateError);console.warn(`[PasswordReset] template render failed, sending plain-text fallback: ${msg}`);html=undefined;text=setup?`Choose your password by visiting: ${resetUrl}
|
|
2
2
|
|
|
3
3
|
This link expires in ${expireMinutes} minutes.`:`Reset your password by visiting: ${resetUrl}
|
|
4
4
|
|
|
5
|
-
This link expires in ${expireMinutes} minutes. If you didn't request this, you can safely ignore this email.`}await mail.sendOrFail({to:delivery.email,subject,text,html})}async function verifyToken(token){const result=await db.primary.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]).executeTakeFirst();if(!result)return
|
|
5
|
+
This link expires in ${expireMinutes} minutes. If you didn't request this, you can safely ignore this email.`}await mail.sendOrFail({to:delivery.email,subject,text,html})}async function verifyToken(token){const result=await db.primary.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]).executeTakeFirst();if(!result)return false;if(!isWithinExpiry(result)){await db.deleteFrom("password_resets").where("email","=",email).where("token","=",result.token).execute();return false}const hashedToken=result.token;return await verifyHash(token,hashedToken)}async function resetPassword(token,newPassword){const owner=await findAuthUserRowByEmail(email);if(!owner)return{success:false,message:"Invalid or expired reset token"};const ownerId=Number(owner.id);if(!Number.isSafeInteger(ownerId)||ownerId<=0)return{success:false,message:"Invalid or expired reset token"};const result=await db.transaction(async(rawTrx)=>{const trx=rawTrx;let userQuery=trx.selectFrom("users").where("id","=",ownerId).selectAll();if(getDatabaseDialect()!=="sqlite")userQuery=userQuery.lockForUpdate();const user=await userQuery.executeTakeFirst();if(!user||normalizeAuthEmail(String(user.email??""))!==email)return{success:false,message:"Invalid or expired reset token"};let resetQuery=trx.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]);if(getDatabaseDialect()!=="sqlite")resetQuery=resetQuery.lockForUpdate();const resetRecord=await resetQuery.executeTakeFirst();if(!resetRecord){return{success:false,message:"Invalid or expired reset token"}}if(!isWithinExpiry(resetRecord)){await trx.deleteFrom("password_resets").where("email","=",email).execute();return{success:false,message:"This password reset link has expired. Please request a new one."}}const hashedToken=resetRecord.token;const isValid=await verifyHash(token,hashedToken);if(!isValid){return{success:false,message:"Invalid or expired reset token"}}const hashedPassword=await makeHash(newPassword,{algorithm:"bcrypt"});if(!isWithinExpiry(resetRecord))return{success:false,message:"Invalid or expired reset token"};const updated=await trx.updateTable("users").set({password:hashedPassword}).where("id","=",user.id).execute();if(mutationCount(updated)!==1)throw new Error("Password reset could not update its owner");const consumed=await trx.deleteFrom("password_resets").where("email","=",email).where("token","=",hashedToken).execute();if(mutationCount(consumed)!==1)throw new Error("Password reset token could not be consumed");await revokeAccountCredentials(Number(user.id));return{success:true}});if(result.success){const notify=()=>sendPasswordChangedNotification(email).catch((err)=>{console.error("[PasswordReset] Failed to send notification:",err)});if(!enqueueAfterCommit(notify))notify();return{success:true}}return result}return{sendEmail,verifyToken,resetPassword}}let warnedDefaultResetPage=false;async function warnIfDefaultResetPageMissing(){if(warnedDefaultResetPage)return;warnedDefaultResetPage=true;try{await overridesReady;if(mountedDefaultRouteBundles(feature).has("auth"))return}catch{return}log.warn("[PasswordReset] Reset links point at the default /password/reset/{token} page, which needs the auth route bundle, and it is not mounted (it mounts with the dashboard, or with STACKS_DEFAULT_ROUTES=auth). Set config.auth.passwordReset.url to your own reset page, or mount the bundle.")}
|
package/dist/password-rehash.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{db,enqueueAfterCommit}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";import{makeHash,needsRehash}from"@stacksjs/security";const pendingRehashes=new Set;function warnAboutRehash(userId,cause){const reason=cause instanceof Error?cause.message:String(cause);try{log.warn(`[auth] Password rehash failed for user#${userId}: ${reason}`)}catch{}}async function rehashPassword(userId,plaintext,verifiedHash){const replacement=await makeHash(plaintext);await db.updateTable("users").set({password:replacement}).where("id","=",userId).where("password","=",verifiedHash).execute()}function queuePasswordRehash(userId,plaintext,verifiedHash){let task;task=new Promise((resolve)=>setTimeout(resolve,0)).then(()=>rehashPassword(userId,plaintext,verifiedHash)).catch((cause)=>warnAboutRehash(userId,cause)).finally(()=>pendingRehashes.delete(task));pendingRehashes.add(task)}export function schedulePasswordRehash(userId,plaintext,verifiedHash){try{if(config.hashing?.rehashOnLogin
|
|
1
|
+
import{config}from"@stacksjs/config";import{db,enqueueAfterCommit}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";import{makeHash,needsRehash}from"@stacksjs/security";const pendingRehashes=new Set;function warnAboutRehash(userId,cause){const reason=cause instanceof Error?cause.message:String(cause);try{log.warn(`[auth] Password rehash failed for user#${userId}: ${reason}`)}catch{}}async function rehashPassword(userId,plaintext,verifiedHash){const replacement=await makeHash(plaintext);await db.updateTable("users").set({password:replacement}).where("id","=",userId).where("password","=",verifiedHash).execute()}function queuePasswordRehash(userId,plaintext,verifiedHash){let task;task=new Promise((resolve)=>setTimeout(resolve,0)).then(()=>rehashPassword(userId,plaintext,verifiedHash)).catch((cause)=>warnAboutRehash(userId,cause)).finally(()=>pendingRehashes.delete(task));pendingRehashes.add(task)}export function schedulePasswordRehash(userId,plaintext,verifiedHash){try{if(config.hashing?.rehashOnLogin===false||!needsRehash(verifiedHash))return;const schedule=()=>queuePasswordRehash(userId,plaintext,verifiedHash);if(!enqueueAfterCommit(schedule))schedule()}catch(cause){warnAboutRehash(userId,cause)}}export async function flushPasswordRehashes(){while(pendingRehashes.size>0)await Promise.allSettled([...pendingRehashes])}
|
package/dist/permissions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function defineRolePermissions(grants){const frozenGrants=Object.fromEntries(Object.entries(grants).map(([role,permissions])=>[role,Object.freeze([...permissions])]))
|
|
1
|
+
export function defineRolePermissions(grants){const frozenGrants=Object.fromEntries(Object.entries(grants).map(([role,permissions])=>[role,Object.freeze([...permissions])]));const forRole=(role)=>role?frozenGrants[role]??[]:[];const roleCan=(role,permission)=>forRole(role).includes(permission);const can=(subject,permission)=>roleCan(subject?.role,permission);const canAny=(subject,permissions)=>permissions.some((permission)=>can(subject,permission));const canAll=(subject,permissions)=>permissions.every((permission)=>can(subject,permission));return Object.freeze({roleCan,can,canAny,canAll,forRole})}
|
package/dist/policy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthorizationResponse}from"./gate";export class BasePolicy{allow(message){return AuthorizationResponse.allow(message)}deny(message,code){return AuthorizationResponse.deny(message,code)}denyIf(condition,message){if(condition)return this.deny(message)
|
|
1
|
+
import{AuthorizationResponse}from"./gate";export class BasePolicy{allow(message){return AuthorizationResponse.allow(message)}deny(message,code){return AuthorizationResponse.deny(message,code)}denyIf(condition,message){if(condition){return this.deny(message)}return true}denyUnless(condition,message){if(!condition){return this.deny(message)}return true}allowIf(condition,message){if(condition){return this.allow(message)}return false}}import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";import{existsSync}from"node:fs";import{policy as registerPolicy}from"./gate";let policyRegistry=null;async function loadPolicyRegistry(){if(policyRegistry)return policyRegistry;policyRegistry=(async()=>{const dir=p.storagePath("framework/auto-imports");const registryPath=`${dir}/policies.ts`;if(!existsSync(registryPath))return null;const module=await import(registryPath);if(!module.policies)throw new Error(`Invalid policies registry: ${registryPath}`);return Object.fromEntries(Object.entries(module.policies).map(([name,file])=>[name,p.resolveModulePath(file,dir)]))})();return policyRegistry}function policyDirectories(){return[p.appPath("Policies"),p.defaultsPath("app/Policies")]}async function findPolicyFile(name){const registry=await loadPolicyRegistry();if(registry)return registry[name]??null;const{fs}=await import("@stacksjs/storage");for(const dir of policyDirectories()){const candidate=`${dir}/${name}.ts`;if(fs.existsSync(candidate))return candidate}return null}export function resetPolicyRegistry(){policyRegistry=null}export async function discoverPolicies(){const{fs}=await import("@stacksjs/storage");const explicit=new Set;const authorization=await loadGatesModule();const mappings=authorization?.policies??{};for(const[modelName,config]of Object.entries(mappings)){const policyFile=typeof config==="string"?config:config.policy;const policyPath=await findPolicyFile(policyFile);if(!policyPath){log.warn(`[auth] app/Gates.ts maps ${modelName} to ${policyFile}, and no such policy exists`);continue}try{const policyModule=await import(policyPath);const PolicyClass=policyModule.default||policyModule[policyFile];if(!PolicyClass){log.warn(`[auth] ${policyPath} has no default export, so ${modelName} has no policy`);continue}registerPolicy(modelName,PolicyClass);explicit.add(modelName);log.debug(`Registered policy: ${policyFile} for ${modelName}`)}catch(error){log.error(`Failed to load policy ${policyFile}:`,error)}}const registry=await loadPolicyRegistry();let discovered;if(registry){discovered=Object.entries(registry).filter(([name])=>name.endsWith("Policy")).map(([policyName,policyPath])=>({policyName,policyPath}))}else{const policiesDir=p.appPath("Policies");if(!fs.existsSync(policiesDir)){log.debug("No Policies directory found");return}discovered=fs.readdirSync(policiesDir).filter((file)=>file.endsWith("Policy.ts")).map((file)=>({policyName:file.replace(".ts",""),policyPath:`${policiesDir}/${file}`}))}for(const{policyName,policyPath}of discovered){const modelName=policyName.replace(/Policy$/,"");if(explicit.has(modelName))continue;try{const policyModule=await import(policyPath);const PolicyClass=policyModule.default||policyModule[policyName];if(PolicyClass){registerPolicy(modelName,PolicyClass);log.debug(`Auto-discovered policy: ${policyName} for ${modelName}`)}}catch(error){log.error(`Failed to load policy ${policyName}:`,error)}}}async function loadGatesModule(){const{fs}=await import("@stacksjs/storage");const gatesPath=p.appPath("Gates.ts");if(!fs.existsSync(gatesPath))return null;const module=await import(gatesPath);return{gates:module.default?.gates??module.gates,policies:module.default?.policies??module.policies,before:module.default?.before??module.before,after:module.default?.after??module.after}}export async function registerGates(){const{define,before,after}=await import("./gate");const authorization=await loadGatesModule();if(!authorization){log.debug("No Gates.ts found");return}for(const[ability,callback]of Object.entries(authorization.gates??{})){if(typeof callback==="function"){define(ability,callback);log.debug(`Registered gate: ${ability}`)}}for(const callback of authorization.before??[]){if(typeof callback==="function")before(callback)}for(const callback of authorization.after??[]){if(typeof callback==="function")after(callback)}log.debug("Gates registered successfully")}export async function initializeAuthorization(){try{await registerGates()}catch(error){log.error("[auth] app/Gates.ts failed to load - no gates are registered and every Gate check will deny:",error)}try{await discoverPolicies()}catch(error){log.error("[auth] policy discovery failed - model authorization will deny:",error)}}export{AuthorizationResponse};
|