@stacksjs/security 0.70.45 → 0.70.54
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/LICENSE.md +21 -0
- package/dist/index.js +1 -1
- package/dist/src/crypt.d.ts +10 -0
- package/dist/src/hash.d.ts +13 -2
- package/package.json +5 -5
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Open Web Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var k=import.meta.require;import{Buffer as q}from"buffer";import{config as E}from"@stacksjs/config";async function C(w,U,G=256){let $=new TextEncoder,x=await crypto.subtle.importKey("raw",$.encode(w),{name:"PBKDF2"},!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:U,iterations:1e5,hash:"SHA-256"},x,{name:"AES-GCM",length:G},!1,["encrypt","decrypt"])}async function m(w,U,G){let $=G?.algorithm||"AES-GCM",x=G?.keyLength||256,F=G?.iv||crypto.getRandomValues(new Uint8Array(12)),J=crypto.getRandomValues(new Uint8Array(16)),Q=await C(U,J,x),N=new TextEncoder,D=await crypto.subtle.encrypt({name:$,iv:F},Q,N.encode(w)),O=new Uint8Array(J.length+F.length+D.byteLength);return O.set(J,0),O.set(F,J.length),O.set(new Uint8Array(D),J.length+F.length),{encrypted:Buffer.from(O).toString("base64"),iv:Buffer.from(F).toString("base64"),algorithm:$}}async function K(w,U,G="AES-GCM"){let $=Buffer.from(w,"base64"),x=$.slice(0,16),F=$.slice(16,28),J=$.slice(28),Q=await C(U,x),N=await crypto.subtle.decrypt({name:G,iv:F},Q,J);return new TextDecoder().decode(N)}function b(w){return Buffer.from(w,"utf-8").toString("base64")}function H(w){return Buffer.from(w,"base64").toString("utf-8")}function S(w,U){let G=U?.algorithm||"sha256",$=U?.encoding||"hex",x=new Bun.CryptoHasher(G);return x.update(w),x.digest($)}function W(w,U="hex"){return S(w,{algorithm:"md5",encoding:U})}async function M(w,U){let G=U?.algorithm||"bcrypt";if(G==="bcrypt")return await Bun.password.hash(w,{algorithm:"bcrypt",cost:U?.cost||10});return await Bun.password.hash(w,{algorithm:G,memoryCost:U?.memoryCost||65536,timeCost:U?.timeCost||3})}async function z(w,U){return await Bun.password.verify(w,U)}function n(w=32){let U=crypto.getRandomValues(new Uint8Array(w));return`base64:${Buffer.from(U).toString("base64")}`}function _(w){return w.startsWith("base64:")?w.slice(7):w}var T=1,u=600000,v=32,R=16,j=12,l=64,X=new Map;function t(w,U,G){return`${G}:${q.from(U).toString("base64")}:${w}`}async function I(w,U,G){let $=t(w,U,G),x=X.get($);if(x)return x.hits++,X.delete($),X.set($,x),x.key;let F=await crypto.subtle.importKey("raw",new TextEncoder().encode(w),{name:"PBKDF2"},!1,["deriveKey"]),J=await crypto.subtle.deriveKey({name:"PBKDF2",salt:U,iterations:G,hash:"SHA-256"},F,{name:"AES-GCM",length:v*8},!1,["encrypt","decrypt"]);if(X.set($,{key:J,hits:1}),X.size>l){let Q=X.keys().next().value;if(Q!==void 0)X.delete(Q)}return J}async function g(w,U){let G=crypto.getRandomValues(new Uint8Array(R)),$=crypto.getRandomValues(new Uint8Array(j)),x=await I(U,G,u),F=await crypto.subtle.encrypt({name:"AES-GCM",iv:$},x,new TextEncoder().encode(w)),J=new Uint8Array(F),Q=new Uint8Array(1+R+j+J.byteLength);return Q[0]=T,Q.set(G,1),Q.set($,1+R),Q.set(J,1+R+j),q.from(Q).toString("base64")}async function d(w,U){let G=q.from(w,"base64");if(G.length<1+R+j+16)return null;if(G[0]!==T)return null;let $=new Uint8Array(G.subarray(1,1+R)),x=new Uint8Array(G.subarray(1+R,1+R+j)),F=new Uint8Array(G.subarray(1+R+j)),J=await I(U,$,u);try{let Q=await crypto.subtle.decrypt({name:"AES-GCM",iv:x},J,F);return new TextDecoder().decode(Q)}catch{return null}}async function F2(w,U){if(!w&&w!=="")throw Error("encrypt() requires a string message");let G=U||E.app.key;if(!G)throw Error("APP_KEY is not defined");return await g(w,_(G))}async function J2(w,U){if(!w)throw Error("decrypt() requires a non-empty encrypted string");let G=U||E.app.key;if(!G)throw Error("APP_KEY is not defined");let $=_(G),x=await d(w,$);if(x!==null)return x;try{return await K(w,$)}catch(F){if($!==G)try{return await K(w,G)}catch{}throw F}}function Q2(){X.clear()}import{timingSafeEqual as P}from"crypto";var V=null;function L(){if(V)return V;try{let{hashing:w}=k("@stacksjs/config");return V=w||{},V}catch{return console.warn("[Security] Failed to load hashing config, using defaults"),V={driver:"bcrypt",bcrypt:{rounds:12},argon2:{memory:65536,time:2}},V}}function B(w){if(!w||typeof w!=="string")return"unknown";if(w.startsWith("$2a$")||w.startsWith("$2b$")||w.startsWith("$2y$"))return"bcrypt";if(w.startsWith("$argon2id$"))return"argon2id";if(w.startsWith("$argon2i$"))return"argon2i";if(w.startsWith("$argon2d$"))return"argon2d";return"unknown"}function p(w){let U=B(w),G={};if(U==="bcrypt"){let $=w.match(/^\$2[aby]\$(\d{2})\$/);if($&&$[1]!==void 0)G.rounds=Number.parseInt($[1],10)}else if(U==="argon2id"||U==="argon2i"||U==="argon2d"){let $=w.match(/v=(\d+)/),x=w.match(/m=(\d+)/),F=w.match(/t=(\d+)/),J=w.match(/p=(\d+)/);if($&&$[1]!==void 0)G.version=Number.parseInt($[1],10);if(x&&x[1]!==void 0)G.memory=Number.parseInt(x[1],10);if(F&&F[1]!==void 0)G.rounds=Number.parseInt(F[1],10);if(J&&J[1]!==void 0)G.parallelism=Number.parseInt(J[1],10)}return{algorithm:U,options:G}}function X2(w,U){let G=p(w),$=L(),x=U?.algorithm||$.driver||"bcrypt",F=(N)=>{if(N==="argon2")return"argon2id";return N},J=F(G.algorithm),Q=F(x);if(J!==Q)return!0;if(J==="bcrypt"){let N=U?.rounds||$.bcrypt?.rounds||10;if(G.options.rounds!==N)return!0}if(J.startsWith("argon2")){let N=U?.memory||$.argon2?.memory||65536,D=U?.time||$.argon2?.time||2;if(G.options.memory!==N||G.options.rounds!==D)return!0}return!1}async function D2(w,U){let G=L(),$=U?.algorithm||G.driver||"bcrypt";if($==="bcrypt")return await r(w,U?.rounds);if($==="argon2"||$==="argon2id"||$==="argon2i"||$==="argon2d")return await o(w,{type:$==="argon2"?"argon2id":$,memory:U?.memory,time:U?.time});throw Error(`Unsupported hashing algorithm: ${$}`)}async function O2(w,U){if(!w||!U)return!1;if(B(U)==="unknown")try{return await z(w,U)}catch{return!1}return await z(w,U)}async function r(w,U){let G=L(),$=U||G.bcrypt?.rounds||12;return await M(w,{algorithm:"bcrypt",cost:$})}async function o(w,U){let G=L(),$=U?.type||"argon2id",x=U?.memory||G.argon2?.memory||65536,F=U?.time||G.argon2?.time||2;return await M(w,{algorithm:$,memoryCost:x,timeCost:F})}async function j2(w,U){let G=B(U);if(G!=="argon2"&&G!=="argon2i"&&G!=="argon2id"&&G!=="argon2d")return!1;return await z(w,U)}async function V2(w,U){if(B(U)!=="bcrypt")return!1;return await z(w,U)}function z2(w,U){let G=H(U),$=Buffer.from(G),x=Buffer.from(w);if($.length!==x.length)return!1;return P($,x)}function L2(w){return W(w)}function B2(w,U){let G=Buffer.from(w),$=Buffer.from(U);if(G.length!==$.length)return P(G,G),!1;return P(G,$)}function q2(){return n(32)}import{createHmac as i,timingSafeEqual as c}from"crypto";class Z extends Error{reason;constructor(w,U="mismatch"){super(w);this.name="InvalidWebhookSignature",this.reason=U}}function f(w){if(!/^[0-9a-f]*$/i.test(w)||w.length%2!==0)throw new Z("Signature is not valid hex","malformed");return Buffer.from(w,"hex")}function A(w,U){if(w.length!==U.length)return c(w,w),!1;return c(w,U)}function y(w,U,G){return i(G,w).update(U).digest()}function h(w){let U=w.split(","),G=Number.NaN,$=[];for(let x of U){let F=x.indexOf("=");if(F===-1)continue;let J=x.slice(0,F).trim(),Q=x.slice(F+1).trim();if(J==="t")G=Number.parseInt(Q,10);else if(J==="v1")$.push(Q)}if(!Number.isFinite(G)||$.length===0)throw new Z("Stripe-Signature header is malformed","malformed");return{timestamp:G,signatures:$}}function s(w,U,G,$={}){if(!w)throw new Z("Stripe webhook secret is empty","missing");if(!U)throw new Z("Stripe-Signature header is missing","missing");let{timestamp:x,signatures:F}=h(U),J=$.toleranceSeconds??300;if(Math.floor(($.now??Date.now())/1000)-x>J)throw new Z("Stripe webhook timestamp is outside tolerance window","expired");let N=typeof G==="string"?G:G.toString("utf8"),D=y(w,`${x}.${N}`,"sha256");for(let O of F){let Y;try{Y=f(O)}catch{continue}if(A(D,Y))return!0}throw new Z("Stripe webhook signature did not match","mismatch")}function e(w,U,G){if(!w)throw new Z("GitHub webhook secret is empty","missing");if(!U)throw new Z("X-Hub-Signature-256 header is missing","missing");let $="sha256=";if(!U.startsWith($))throw new Z("X-Hub-Signature-256 has wrong algorithm prefix","malformed");let x=f(U.slice($.length)),F=y(w,G,"sha256");if(!A(F,x))throw new Z("GitHub webhook signature did not match","mismatch");return!0}function a(w,U,G,$="sha256"){if(!w)throw new Z("HMAC secret is empty","missing");if(!G)throw new Z("Signature header is missing","missing");let x=G.indexOf("="),F=x!==-1&&/^[a-z0-9]+$/i.test(G.slice(0,x))?G.slice(x+1):G,J=f(F),Q=y(w,U,$);if(!A(Q,J))throw new Z("HMAC signature did not match","mismatch");return!0}function A2(w,U,G,$,x={}){switch(w){case"stripe":return s(U,G,$,x);case"github":return e(U,G,$);case"generic":return a(U,$,G,x.algorithm??"sha256");default:throw new Z(`Unknown webhook provider: ${String(w)}`,"malformed")}}export{A2 as verifyWebhook,s as verifyStripe,a as verifyHmac,O2 as verifyHash,e as verifyGithub,B2 as timingSafeEqualString,X2 as needsRehash,L2 as md5Encode,D2 as makeHash,D2 as make,m as legacyEncrypt,p as info,X2 as hashNeedsRehash,D2 as hashMake,p as hashInfo,B as hashDetectAlgorithm,O2 as hashCheck,q2 as generateAppKey,F2 as encrypt,B as detectAlgorithm,J2 as decrypt,O2 as check,V2 as bcryptVerify,r as bcryptEncode,z2 as base64Verify,b as base64Encode,j2 as argon2Verify,o as argon2Encode,Q2 as _resetCryptCacheForTests,Z as InvalidWebhookSignature};
|
package/dist/src/crypt.d.ts
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
import { encrypt as cryptoEncrypt } from 'ts-security-crypto';
|
|
1
2
|
declare function encrypt(message: string, customPassphrase?: string): Promise<string>;
|
|
2
3
|
declare function decrypt(encrypted: string, customPassphrase?: string): Promise<string>;
|
|
4
|
+
/**
|
|
5
|
+
* For tests + observability: reset the per-process derived-key cache.
|
|
6
|
+
* Production code never needs to call this — the cache is bounded
|
|
7
|
+
* (`DERIVED_KEY_CACHE_MAX = 64`) and entries evict in FIFO order.
|
|
8
|
+
*/
|
|
9
|
+
export declare function _resetCryptCacheForTests(): void;
|
|
10
|
+
// Re-export pre-existing helpers from ts-security-crypto so callers
|
|
11
|
+
// that imported them from `@stacksjs/security` keep working.
|
|
3
12
|
export { decrypt, encrypt };
|
|
13
|
+
export { cryptoEncrypt as legacyEncrypt };
|
package/dist/src/hash.d.ts
CHANGED
|
@@ -44,12 +44,23 @@ export declare function argon2Encode(password: string, options?: {
|
|
|
44
44
|
time?: number
|
|
45
45
|
}): Promise<string>;
|
|
46
46
|
/**
|
|
47
|
-
* Verify a password against an Argon2 hash
|
|
47
|
+
* Verify a password against an Argon2 hash.
|
|
48
|
+
*
|
|
49
|
+
* Refuses to verify hashes that aren't actually Argon2 — `Bun.password.verify`
|
|
50
|
+
* auto-detects the algorithm from the hash prefix, which means a stray
|
|
51
|
+
* call `argon2Verify(password, bcryptHash)` would return `true` if the
|
|
52
|
+
* password matched. The algorithm guard restores the function-name
|
|
53
|
+
* contract (stacksjs/stacks#1861 H-8).
|
|
54
|
+
*
|
|
48
55
|
* @deprecated Use check() instead which auto-detects the algorithm
|
|
49
56
|
*/
|
|
50
57
|
export declare function argon2Verify(password: string, hash: string): Promise<boolean>;
|
|
51
58
|
/**
|
|
52
|
-
* Verify a password against a bcrypt hash
|
|
59
|
+
* Verify a password against a bcrypt hash.
|
|
60
|
+
*
|
|
61
|
+
* Refuses to verify hashes that aren't actually bcrypt — see the note
|
|
62
|
+
* on {@link argon2Verify} (stacksjs/stacks#1861 H-8).
|
|
63
|
+
*
|
|
53
64
|
* @deprecated Use check() instead which auto-detects the algorithm
|
|
54
65
|
*/
|
|
55
66
|
export declare function bcryptVerify(password: string, hash: string): Promise<boolean>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/security",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.70.
|
|
4
|
+
"version": "0.70.54",
|
|
5
5
|
"description": "The Stacks framework security.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"ts-security-crypto": "0.0.2"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@stacksjs/config": "
|
|
53
|
+
"@stacksjs/config": "0.70.54",
|
|
54
54
|
"better-dx": "^0.2.12",
|
|
55
|
-
"@stacksjs/env": "
|
|
56
|
-
"@stacksjs/types": "
|
|
57
|
-
"@stacksjs/validation": "
|
|
55
|
+
"@stacksjs/env": "0.70.54",
|
|
56
|
+
"@stacksjs/types": "0.70.54",
|
|
57
|
+
"@stacksjs/validation": "0.70.54"
|
|
58
58
|
}
|
|
59
59
|
}
|