@stacksjs/config 0.75.612 → 0.75.613

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Whether a field's value may be sent back to the form.
3
+ *
4
+ * Never a password, a token or a card's details, however the field is spelled
5
+ * (`current_password`, `apiKey`, `_token`): a refused form must not put a
6
+ * secret into a cookie, and a password field is drawn empty anyway. A field
7
+ * that only sounds like one (`tokens_per_minute`) is left out too: a value
8
+ * typed again costs less than a secret sent back.
9
+ */
10
+ export declare function flashableField(name: string): boolean;
11
+ /**
12
+ * What of a posted form can go back to it: text, numbers, yes or no, and
13
+ * lists of those. A file is not sent back (the browser will not refill a file
14
+ * input), nor is anything that is not a plain value.
15
+ */
16
+ export declare function flashableInput(input: Record<string, unknown>): Record<string, string | string[]>;
17
+ /**
18
+ * Seal a refusal for the cookie, or null when there is no application key to
19
+ * sign it with.
20
+ *
21
+ * The messages always fit. What was typed is dropped, longest value first,
22
+ * until the whole thing does: a form that comes back without one long answer
23
+ * still says what was wrong, and a cookie the browser throws away says
24
+ * nothing. Past that the messages themselves are cut to one a field, then to
25
+ * as many fields as fit.
26
+ */
27
+ export declare function sealFormFlash(flash: FormFlash, key: string | undefined | null): string | null;
28
+ /**
29
+ * Read a sealed refusal back, for the page at `path`.
30
+ *
31
+ * Null for anything that is not exactly what this application sealed for
32
+ * this page and still in date: no cookie, no key, a signature that does not
33
+ * match, another page's, one past its time, or a body that is not the shape
34
+ * it should be. A page then draws as if nothing had been refused.
35
+ */
36
+ export declare function openFormFlash(value: string | undefined | null, key: string | undefined | null, path: string, now?: number): FormFlash | null;
37
+ /** The `Set-Cookie` that carries a sealed refusal or notice to the page. */
38
+ export declare function formFlashCookie(value: string, secure: boolean): string;
39
+ /** The `Set-Cookie` that removes it, once a page has shown it. */
40
+ export declare function expiredFormFlashCookie(secure: boolean): string;
41
+ /**
42
+ * Remove the cookie with the response of the page that showed it.
43
+ *
44
+ * For the page the cookie names, asked for with a GET and answered with HTML.
45
+ * Anything else leaves it alone: a script or an image fetched on the way has
46
+ * shown it to no one, and nor has another page, whose request may land
47
+ * between the refusal and the redirect that follows it. Returns the response
48
+ * to send, the same one when there was nothing to do.
49
+ */
50
+ export declare function clearShownFormFlash(request: Request, response: Response, key: string | undefined | null): Response;
51
+ export declare const FORM_FLASH_COOKIE: 'stacks_form_flash';
52
+ /** How long it is good for. The redirect that reads it follows at once. */
53
+ export declare const FORM_FLASH_SECONDS: 120;
54
+ /**
55
+ * The most the sealed value may weigh. A browser keeps about 4096 bytes for a
56
+ * cookie with its name and attributes.
57
+ */
58
+ export declare const FORM_FLASH_MAX_BYTES: 3600;
59
+ /** The longest notice carried. A sentence, not a document. */
60
+ export declare const FORM_FLASH_NOTICE_LENGTH: 500;
61
+ export declare interface FormFlash {
62
+ path: string
63
+ errors: Record<string, string[]>
64
+ old: Record<string, string | string[]>
65
+ notice?: string
66
+ formError?: string
67
+ expires: number
68
+ }
@@ -0,0 +1 @@
1
+ import{createHmac,timingSafeEqual}from"node:crypto";export const FORM_FLASH_COOKIE="stacks_form_flash";export const FORM_FLASH_SECONDS=120;export const FORM_FLASH_MAX_BYTES=3600;export const FORM_FLASH_NOTICE_LENGTH=500;const SECRET_WORDS=new Set(["password","passwords","passphrase","secret","secrets","token","tokens","cvv","cvc","otp","pin","ssn","credential","credentials","signature"]);const SECRET_PHRASES=["api key","private key","card number","security code","access key"];export function flashableField(name){const words=name.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[^a-z\d]+/gi," ").trim().toLowerCase();if(!words)return false;if(words.split(" ").some((word)=>SECRET_WORDS.has(word)))return false;return!SECRET_PHRASES.some((phrase)=>words.includes(phrase))}export function flashableInput(input){const kept={};const plain=(value)=>typeof value==="string"?value:typeof value==="number"||typeof value==="boolean"?String(value):null;for(const[name,value]of Object.entries(input)){if(!flashableField(name))continue;if(Array.isArray(value)){const values=value.map(plain);if(values.every((entry)=>entry!==null))kept[name]=values;continue}const one=plain(value);if(one!==null)kept[name]=one}return kept}function encode(text){return Buffer.from(text,"utf8").toString("base64url")}function signature(body,key){return createHmac("sha256",key).update(`stacks-form-flash:${body}`).digest("base64url")}function weight(value){return typeof value==="string"?value.length:value.reduce((total,entry)=>total+entry.length+3,0)}export function sealFormFlash(flash,key){if(!key)return null;const errors=Object.fromEntries(Object.entries(flash.errors).map(([field,messages])=>[field,[...messages]]));const old={...flash.old};const notice=flash.notice?flash.notice.slice(0,FORM_FLASH_NOTICE_LENGTH):undefined;const formError=flash.formError?flash.formError.slice(0,FORM_FLASH_NOTICE_LENGTH):undefined;const sealed=()=>{const body=encode(JSON.stringify({path:flash.path,errors,old,notice,formError,expires:flash.expires}));return`${body}.${signature(body,key)}`};let value=sealed();while(value.length>FORM_FLASH_MAX_BYTES&&Object.keys(old).length>0){const longest=Object.keys(old).reduce((a,b)=>weight(old[b])>weight(old[a])?b:a);delete old[longest];value=sealed()}if(value.length>FORM_FLASH_MAX_BYTES){for(const field of Object.keys(errors))errors[field]=errors[field].slice(0,1).map((message)=>message.slice(0,200));value=sealed()}while(value.length>FORM_FLASH_MAX_BYTES&&Object.keys(errors).length>1){delete errors[Object.keys(errors).pop()];value=sealed()}return value}function stringList(value){return Array.isArray(value)&&value.every((entry)=>typeof entry==="string")}function samePage(a,b){const trim=(path)=>(path.length>1?path.replace(/\/+$/,""):path)||"/";return trim(a)===trim(b)}export function openFormFlash(value,key,path,now=Date.now()){if(!value||!key)return null;const mark=value.lastIndexOf(".");if(mark<=0)return null;const body=value.slice(0,mark);const given=Buffer.from(value.slice(mark+1),"utf8");const expected=Buffer.from(signature(body,key),"utf8");if(given.length!==expected.length||!timingSafeEqual(given,expected))return null;let parsed;try{parsed=JSON.parse(Buffer.from(body,"base64url").toString("utf8"))}catch{return null}if(!parsed||typeof parsed!=="object")return null;const flash=parsed;if(typeof flash.path!=="string"||typeof flash.expires!=="number"||!flash.errors||typeof flash.errors!=="object"||!flash.old||typeof flash.old!=="object")return null;if(flash.expires<=now||!samePage(flash.path,path))return null;if(!Object.values(flash.errors).every(stringList))return null;if(!Object.values(flash.old).every((entry)=>typeof entry==="string"||stringList(entry)))return null;if(flash.notice!==undefined&&typeof flash.notice!=="string"||flash.formError!==undefined&&typeof flash.formError!=="string")return null;const opened={path:flash.path,errors:flash.errors,old:flash.old,expires:flash.expires};if(flash.notice)opened.notice=flash.notice;if(flash.formError)opened.formError=flash.formError;return opened}export function formFlashCookie(value,secure){return`${FORM_FLASH_COOKIE}=${value}; Path=/; Max-Age=${FORM_FLASH_SECONDS}; HttpOnly; SameSite=Lax${secure?"; Secure":""}`}export function expiredFormFlashCookie(secure){return`${FORM_FLASH_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${secure?"; Secure":""}`}export function clearShownFormFlash(request,response,key){const method=request.method.toUpperCase();if(method!=="GET"&&method!=="HEAD")return response;const cookie=request.headers.get("cookie")??"";const at=cookie.indexOf(`${FORM_FLASH_COOKIE}=`);if(at===-1)return response;if(!(response.headers.get("content-type")??"").includes("text/html"))return response;const rest=cookie.slice(at+FORM_FLASH_COOKIE.length+1);const end=rest.indexOf(";");let path;try{path=new URL(request.url).pathname}catch{return response}if(!openFormFlash((end===-1?rest:rest.slice(0,end)).trim(),key,path))return response;const secure=request.headers.get("x-forwarded-proto")==="https"||request.url.startsWith("https:");const expired=expiredFormFlashCookie(secure);try{response.headers.append("set-cookie",expired);return response}catch{const headers=new Headers(response.headers);headers.append("set-cookie",expired);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}
package/dist/index.d.ts CHANGED
@@ -27,4 +27,5 @@ export {
27
27
  type SiteSnapshot,
28
28
  type StacksRequestContext,
29
29
  } from './request-context';
30
+ export { clearShownFormFlash, expiredFormFlashCookie, flashableField, flashableInput, FORM_FLASH_COOKIE, FORM_FLASH_MAX_BYTES, FORM_FLASH_SECONDS, formFlashCookie, openFormFlash, sealFormFlash, type FormFlash } from './form-flash';
30
31
  export * from './capabilities';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export*from"./config";export{FRAMEWORK_DEFAULTS}from"./defaults";export{validateConfig,reportConfigIssues}from"./validators";export{feature,enableFeature,disableFeature,resetFeature,listFeatures}from"./features";export{packageComponentRoots,packageJobRoots,packageMigrationRoots,packageModelRoots,packageViewRoots}from"./discovered-resources";export{DEFAULT_VIEW_ROUTE_BUNDLES,DEFAULT_VIEW_TEMPLATES,DEFAULT_VIEWS_ALWAYS,resolveViewPatterns,withheldDefaultViews}from"./views";export{createRequestContext,enterRequestScope,installRequestContext,installRequestScope,parseCookieHeader,scopedRequestSnapshot,scopeStxServeContext,useRequestEvent}from"./request-context";export*from"./capabilities";
1
+ export*from"./config";export{FRAMEWORK_DEFAULTS}from"./defaults";export{validateConfig,reportConfigIssues}from"./validators";export{feature,enableFeature,disableFeature,resetFeature,listFeatures}from"./features";export{packageComponentRoots,packageJobRoots,packageMigrationRoots,packageModelRoots,packageViewRoots}from"./discovered-resources";export{DEFAULT_VIEW_ROUTE_BUNDLES,DEFAULT_VIEW_TEMPLATES,DEFAULT_VIEWS_ALWAYS,resolveViewPatterns,withheldDefaultViews}from"./views";export{createRequestContext,enterRequestScope,installRequestContext,installRequestScope,parseCookieHeader,scopedRequestSnapshot,scopeStxServeContext,useRequestEvent}from"./request-context";export{clearShownFormFlash,expiredFormFlashCookie,flashableField,flashableInput,FORM_FLASH_COOKIE,FORM_FLASH_MAX_BYTES,FORM_FLASH_SECONDS,formFlashCookie,openFormFlash,sealFormFlash}from"./form-flash";export*from"./capabilities";
@@ -12,7 +12,7 @@ export declare function parseCookieHeader(header: string | null | undefined): Re
12
12
  * replaced between requests — capturing it would pin the first request's
13
13
  * cookies onto every later one.
14
14
  */
15
- export declare function createRequestContext(read: () => RequestContextSnapshot | undefined): StacksRequestContext;
15
+ export declare function createRequestContext(read: () => RequestContextSnapshot | undefined, flashKey?: () => string | undefined): StacksRequestContext;
16
16
  /**
17
17
  * Install the context as the `requestContext` global and return it.
18
18
  *
@@ -155,4 +155,11 @@ export declare interface StacksRequestContext {
155
155
  ip: () => string
156
156
  host: () => string
157
157
  site: () => SiteSnapshot | null
158
+ errors: () => Record<string, string[]>
159
+ error: (field: string) => string
160
+ hasErrors: () => boolean
161
+ formError: () => string
162
+ old: (field: string, fallback?: string) => string
163
+ oldValues: (field: string) => string[]
164
+ notice: () => string
158
165
  }
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";export function parseCookieHeader(header){const out={};if(!header)return out;for(const part of header.split(";")){const trimmed=part.trim();const eq=trimmed.indexOf("=");if(eq===-1)continue;const key=trimmed.slice(0,eq).trim();if(!key)continue;const value=trimmed.slice(eq+1).trim();try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}export function createRequestContext(read){const snapshot=()=>read()??{};const searchOf=()=>{const direct=snapshot().search;if(direct)return direct;const url=snapshot().url??"";const mark=url.indexOf("?");return mark===-1?"":url.slice(mark)};return{cookie:(name)=>snapshot().cookies?.[name]??null,cookies:()=>snapshot().cookies??{},url:()=>snapshot().url??"",path:()=>{const direct=snapshot().path;if(direct)return direct;const url=snapshot().url??"";if(!url)return"";try{return new URL(url).pathname}catch{const mark=url.indexOf("?");return mark===-1?url:url.slice(0,mark)}},search:searchOf,query:()=>{const out={};const search=searchOf();if(!search)return out;new URLSearchParams(search.startsWith("?")?search.slice(1):search).forEach((value,key)=>{out[key]=value});return out},params:()=>snapshot().params??{},locale:()=>snapshot().locale??"en",ip:()=>snapshot().ip??"",host:()=>snapshot().host??"",site:()=>snapshot().site??null}}export function installRequestContext(read){const context=createRequestContext(read);globalThis.requestContext=context;return context}const SCOPE_STORAGE_KEY=Symbol.for("stacks.config.requestScope");const scopeStorage=globalThis[SCOPE_STORAGE_KEY]??=new AsyncLocalStorage;export function enterRequestScope(request){const url=new URL(request.url);const own={cookies:parseCookieHeader(request.headers.get("cookie")),url:request.url,path:url.pathname,search:url.search,host:request.headers.get("host")??url.host,site:null};scopeStorage.enterWith({own});return own}export function scopedRequestSnapshot(){const scope=scopeStorage.getStore();if(!scope)return;const{own,published}=scope;if(!published)return own.siteHost?{...own,host:own.siteHost}:own;const merged={...own,...published,site:own.site??published.site??null};return own.siteHost?{...merged,host:own.siteHost}:merged}const STX_SERVE_CONTEXT="__stxServeContext";export function scopeStxServeContext(){const existing=Object.getOwnPropertyDescriptor(globalThis,STX_SERVE_CONTEXT);if(existing?.get)return;let unscoped=existing?.value;Object.defineProperty(globalThis,STX_SERVE_CONTEXT,{configurable:true,enumerable:false,get:()=>{const scope=scopeStorage.getStore();return scope?scope.published:unscoped},set:(value)=>{const scope=scopeStorage.getStore();if(scope)scope.published=value;else unscoped=value}})}export function installRequestScope(){scopeStxServeContext();return installRequestContext(scopedRequestSnapshot)}export function useRequestEvent(){const context=globalThis.requestContext??createRequestContext(()=>{return});return{url:context.url(),path:context.path(),search:context.search(),query:context.query(),cookies:context.cookies(),params:context.params(),locale:context.locale(),ip:context.ip(),host:context.host(),site:context.site()}}
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{config}from"./config";import{FORM_FLASH_COOKIE,openFormFlash}from"./form-flash";export function parseCookieHeader(header){const out={};if(!header)return out;for(const part of header.split(";")){const trimmed=part.trim();const eq=trimmed.indexOf("=");if(eq===-1)continue;const key=trimmed.slice(0,eq).trim();if(!key)continue;const value=trimmed.slice(eq+1).trim();try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}export function createRequestContext(read,flashKey=()=>config.app?.key){const snapshot=()=>read()??{};const searchOf=()=>{const direct=snapshot().search;if(direct)return direct;const url=snapshot().url??"";const mark=url.indexOf("?");return mark===-1?"":url.slice(mark)};const pathOf=()=>{const direct=snapshot().path;if(direct)return direct;const url=snapshot().url??"";if(!url)return"";try{return new URL(url).pathname}catch{const mark=url.indexOf("?");return mark===-1?url:url.slice(0,mark)}};const flash=()=>{const sealed=snapshot().cookies?.[FORM_FLASH_COOKIE];return sealed?openFormFlash(sealed,flashKey(),pathOf()):null};return{cookie:(name)=>snapshot().cookies?.[name]??null,cookies:()=>snapshot().cookies??{},url:()=>snapshot().url??"",path:pathOf,search:searchOf,query:()=>{const out={};const search=searchOf();if(!search)return out;new URLSearchParams(search.startsWith("?")?search.slice(1):search).forEach((value,key)=>{out[key]=value});return out},params:()=>snapshot().params??{},locale:()=>snapshot().locale??"en",ip:()=>snapshot().ip??"",host:()=>snapshot().host??"",site:()=>snapshot().site??null,errors:()=>flash()?.errors??{},error:(field)=>flash()?.errors[field]?.[0]??"",hasErrors:()=>Boolean(flash()?.formError)||Object.keys(flash()?.errors??{}).length>0,formError:()=>flash()?.formError??"",old:(field,fallback="")=>{const value=flash()?.old[field];if(value===undefined)return fallback;return typeof value==="string"?value:value[0]??fallback},oldValues:(field)=>{const value=flash()?.old[field];return value===undefined?[]:typeof value==="string"?[value]:value},notice:()=>flash()?.notice??""}}export function installRequestContext(read){const context=createRequestContext(read);globalThis.requestContext=context;return context}const SCOPE_STORAGE_KEY=Symbol.for("stacks.config.requestScope");const scopeStorage=globalThis[SCOPE_STORAGE_KEY]??=new AsyncLocalStorage;export function enterRequestScope(request){const url=new URL(request.url);const own={cookies:parseCookieHeader(request.headers.get("cookie")),url:request.url,path:url.pathname,search:url.search,host:request.headers.get("host")??url.host,site:null};scopeStorage.enterWith({own});return own}export function scopedRequestSnapshot(){const scope=scopeStorage.getStore();if(!scope)return;const{own,published}=scope;if(!published)return own.siteHost?{...own,host:own.siteHost}:own;const merged={...own,...published,site:own.site??published.site??null};return own.siteHost?{...merged,host:own.siteHost}:merged}const STX_SERVE_CONTEXT="__stxServeContext";export function scopeStxServeContext(){const existing=Object.getOwnPropertyDescriptor(globalThis,STX_SERVE_CONTEXT);if(existing?.get)return;let unscoped=existing?.value;Object.defineProperty(globalThis,STX_SERVE_CONTEXT,{configurable:true,enumerable:false,get:()=>{const scope=scopeStorage.getStore();return scope?scope.published:unscoped},set:(value)=>{const scope=scopeStorage.getStore();if(scope)scope.published=value;else unscoped=value}})}export function installRequestScope(){scopeStxServeContext();return installRequestContext(scopedRequestSnapshot)}export function useRequestEvent(){const context=globalThis.requestContext??createRequestContext(()=>{return});return{url:context.url(),path:context.path(),search:context.search(),query:context.query(),cookies:context.cookies(),params:context.params(),locale:context.locale(),ip:context.ip(),host:context.host(),site:context.site()}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/config",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.612",
5
+ "version": "0.75.613",
6
6
  "description": "The Stacks config helper methods.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -55,16 +55,16 @@
55
55
  "prepublishOnly": "bun run build"
56
56
  },
57
57
  "dependencies": {
58
- "@stacksjs/events": "0.75.612",
59
- "@stacksjs/features": "0.75.612",
60
- "@stacksjs/path": "0.75.612",
61
- "@stacksjs/tunnel": "0.75.612",
58
+ "@stacksjs/events": "0.75.613",
59
+ "@stacksjs/features": "0.75.613",
60
+ "@stacksjs/path": "0.75.613",
61
+ "@stacksjs/tunnel": "0.75.613",
62
62
  "ts-pantry": "^0.11.198"
63
63
  },
64
64
  "devDependencies": {
65
- "@stacksjs/alias": "0.75.612",
66
- "@stacksjs/env": "0.75.612",
67
- "@stacksjs/types": "0.75.612",
65
+ "@stacksjs/alias": "0.75.613",
66
+ "@stacksjs/env": "0.75.613",
67
+ "@stacksjs/types": "0.75.613",
68
68
  "better-dx": "^0.2.39"
69
69
  }
70
70
  }