@@ -3,11 +3,12 @@ import * as bufutil from "../commons/bufutil.js";
33import { csprng , hkdfalgkeysz , hkdfraw , sha512 } from "../commons/crypto.js" ;
44import * as envutil from "../commons/envutil.js" ;
55import * as util from "../commons/util.js" ;
6+ import * as system from "../system.js" ;
67import { log } from "./log.js" ;
78
89export const keysize = 64 ; // bytes
9-
10- let sessionSecret = csprng ( keysize ) ; // start with random secret
10+ export const serverid = "888811119999" ;
11+ let sessionSecret = null ; // lazily initialized
1112const pskctx = bufutil . fromStr ( "presharedkeyforclient" ) ;
1213// hex: 790bb45383670663ce9a39480be2de5426179506c8a6b2be922af055896438dd06dd320e68cd81348a32d679c026f73be64fdbbc46c43bfbc0f98160ffae2452
1314export const fixedID64 = new Uint8Array ( [
@@ -24,6 +25,10 @@ const pskfixedsalt = new Uint8Array([
2425 215 , 155 , 17 , 183 , 198 , 68 , 34 , 44 , 171 , 8 , 145 , 166 , 227 , 206 ,
2526] ) ;
2627
28+ ( ( _main ) => {
29+ system . when ( "prepare" ) . then ( prep ) ;
30+ } ) ( ) ;
31+
2732export class PskCred {
2833 /** @type {Uint8Array } client id */
2934 id ;
@@ -65,7 +70,19 @@ export class PskCred {
6570 }
6671}
6772
68- export const staticPskCred = new PskCred ( fixedID64 , csprng ( 64 ) ) ;
73+ // lazily init with "prep()" is due to limitations imposed on Workers.
74+ // ✘ core:user:serverless-dns: Uncaught Error: Disallowed operation called within global scope.
75+ // Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values
76+ // are not allowed within global scope. To fix this error, perform this operation within a handler.
77+ // https://developers.cloudflare.com/workers/runtime-apis/handlers/
78+ function prep ( ) {
79+ log . i ( "psk: prepared" ) ;
80+ staticPskCred = new PskCred ( fixedID64 , csprng ( keysize ) ) ;
81+ sessionSecret = csprng ( keysize ) ;
82+ }
83+
84+ /** @type {PskCred? } */
85+ export let staticPskCred = null ; // lazily initialized
6986export const recentPskCreds = new LfuCache ( "psk" , 1000 ) ;
7087
7188/**
@@ -91,6 +108,11 @@ export async function generateTlsPsk(clientid) {
91108 // www.rfc-editor.org/rfc/rfc9257.html#section-8
92109 // www.rfc-editor.org/rfc/rfc9258.html#section-4
93110 const k256 = await pskSessionKey ( ) ;
111+ if ( bufutil . emptyBuf ( k256 ) ) {
112+ log . e ( "psk: no session key set yet" ) ;
113+ return null ;
114+ }
115+
94116 // www.rfc-editor.org/rfc/rfc9257.html#section-4.2
95117 const clientpsk = await hkdfraw ( k256 , clientid ) ;
96118
@@ -124,8 +146,8 @@ export async function newSession(seed, newctxstr) {
124146 */
125147async function pskSessionKey ( ) {
126148 const nokey = null ;
127- if ( bufutil . emptyBuf ( pskctx ) ) {
128- log . e ( "key: ctx missing " ) ;
149+ if ( bufutil . emptyBuf ( pskctx ) || bufutil . emptyBuf ( sessionSecret ) ) {
150+ log . e ( "key: ctx or secret not set " ) ;
129151 return nokey ;
130152 }
131153
0 commit comments