@stefanobalocco/honosignedrequests 1.0.0 → 1.1.1

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 CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2025, Stefano Balocco <stefano.balocco@gmail.com>
1
+ Copyright (c) 2025-2026, Stefano Balocco <stefano.balocco@gmail.com>
2
2
  All rights reserved.
3
3
  Redistribution and use in source and binary forms, with or without
4
4
  modification, are permitted provided that the following conditions are met:
@@ -0,0 +1,38 @@
1
+ type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE';
2
+ type SessionConfig = {
3
+ sessionId: number;
4
+ token: string;
5
+ sequenceNumber: number;
6
+ };
7
+ type SignedRequest<T = Record<string, any>> = {
8
+ sessionId: number;
9
+ timestamp: number;
10
+ signature: string;
11
+ } & T;
12
+ type SignedRequestOptions = {
13
+ baseUrl?: string;
14
+ headers?: Record<string, string>;
15
+ method?: Methods;
16
+ };
17
+ declare class SignedRequester {
18
+ private static readonly _primitives;
19
+ private readonly _baseUrl;
20
+ private readonly _onError?;
21
+ private _sessionId;
22
+ private _token;
23
+ private _sequenceNumber;
24
+ private _semaphore;
25
+ private _semaphoreQueue;
26
+ private _semaphoreAcquire;
27
+ private _semaphoreRelease;
28
+ private _incrementSequenceNumber;
29
+ private _loadFromStorage;
30
+ constructor(baseUrl?: string, onError?: (error: unknown) => void);
31
+ setSession(config: SessionConfig): void;
32
+ getSession(): boolean;
33
+ clearSession(): void;
34
+ signedRequest(path: string, parameters: Record<string, any>, options?: SignedRequestOptions): Promise<Response>;
35
+ signedRequestJson<T = any>(path: string, parameters: Record<string, any>, options?: SignedRequestOptions): Promise<T>;
36
+ }
37
+ export type { SessionConfig, SignedRequest, SignedRequestOptions };
38
+ export { SignedRequester };
@@ -0,0 +1,218 @@
1
+ function _base64url_encode(value, onError) {
2
+ let returnValue = '';
3
+ if (0 < value?.length) {
4
+ try {
5
+ const base64String = Array.from(value, (byte) => String.fromCharCode(byte)).join('');
6
+ returnValue = btoa(base64String)
7
+ .replace(/\+/g, '-')
8
+ .replace(/\//g, '_')
9
+ .replace(/=+$/, '');
10
+ }
11
+ catch (error) {
12
+ onError?.(error);
13
+ }
14
+ }
15
+ return returnValue;
16
+ }
17
+ function _base64url_decode(value, onError) {
18
+ let returnValue;
19
+ if (0 < value?.length && /^[A-Za-z0-9_-]*$/.test(value)) {
20
+ const padding = value.length % 4;
21
+ const paddedValue = 0 === padding ? value : value.padEnd(value.length + (4 - padding), '=');
22
+ const base64 = paddedValue.replace(/-/g, '+').replace(/_/g, '/');
23
+ try {
24
+ const binaryString = atob(base64);
25
+ returnValue = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
26
+ }
27
+ catch (error) {
28
+ onError?.(error);
29
+ }
30
+ }
31
+ return returnValue;
32
+ }
33
+ class SignedRequester {
34
+ _semaphoreAcquire(wait = true) {
35
+ let returnValue = Promise.resolve(false);
36
+ if (!this._semaphore) {
37
+ this._semaphore = true;
38
+ returnValue = Promise.resolve(true);
39
+ }
40
+ else if (wait) {
41
+ returnValue = new Promise((resolve) => {
42
+ this._semaphoreQueue.push(resolve);
43
+ });
44
+ }
45
+ return returnValue;
46
+ }
47
+ _semaphoreRelease() {
48
+ if (this._semaphore) {
49
+ if (0 < this._semaphoreQueue.length) {
50
+ const nextWaiting = this._semaphoreQueue.shift();
51
+ if (nextWaiting) {
52
+ nextWaiting(true);
53
+ }
54
+ }
55
+ else {
56
+ this._semaphore = false;
57
+ }
58
+ }
59
+ }
60
+ _incrementSequenceNumber() {
61
+ if (undefined !== this._sequenceNumber) {
62
+ this._sequenceNumber++;
63
+ localStorage.setItem('sequenceNumber', this._sequenceNumber.toString());
64
+ }
65
+ }
66
+ _loadFromStorage() {
67
+ let returnValue = false;
68
+ const sessionIdStr = localStorage.getItem('sessionId');
69
+ const tokenStr = localStorage.getItem('token');
70
+ const sequenceNumberStr = localStorage.getItem('sequenceNumber');
71
+ if (sessionIdStr && tokenStr && sequenceNumberStr) {
72
+ const sessionId = parseInt(sessionIdStr);
73
+ const sequenceNumber = parseInt(sequenceNumberStr);
74
+ const token = _base64url_decode(tokenStr, this._onError);
75
+ if (!isNaN(sessionId) && !isNaN(sequenceNumber) && token) {
76
+ this._sessionId = sessionId;
77
+ this._token = token;
78
+ this._sequenceNumber = sequenceNumber;
79
+ returnValue = true;
80
+ }
81
+ }
82
+ return returnValue;
83
+ }
84
+ constructor(baseUrl, onError) {
85
+ this._semaphore = false;
86
+ this._semaphoreQueue = [];
87
+ this._baseUrl = baseUrl;
88
+ this._onError = onError;
89
+ }
90
+ setSession(config) {
91
+ const token = _base64url_decode(config.token, this._onError);
92
+ if (token) {
93
+ this._sessionId = config.sessionId;
94
+ this._token = token;
95
+ this._sequenceNumber = config.sequenceNumber;
96
+ localStorage.setItem('sessionId', config.sessionId.toString());
97
+ localStorage.setItem('token', config.token);
98
+ localStorage.setItem('sequenceNumber', config.sequenceNumber.toString());
99
+ }
100
+ else {
101
+ throw new Error('Invalid token format');
102
+ }
103
+ }
104
+ getSession() {
105
+ let returnValue;
106
+ if (undefined !== this._sessionId &&
107
+ undefined !== this._token &&
108
+ undefined !== this._sequenceNumber) {
109
+ returnValue = true;
110
+ }
111
+ else {
112
+ returnValue = this._loadFromStorage();
113
+ }
114
+ return returnValue;
115
+ }
116
+ clearSession() {
117
+ localStorage.removeItem('sessionId');
118
+ localStorage.removeItem('token');
119
+ localStorage.removeItem('sequenceNumber');
120
+ this._sessionId = undefined;
121
+ this._token = undefined;
122
+ this._sequenceNumber = undefined;
123
+ }
124
+ async signedRequest(path, parameters, options = {}) {
125
+ let returnValue;
126
+ let error;
127
+ await this._semaphoreAcquire();
128
+ try {
129
+ if (undefined !== this._sessionId &&
130
+ undefined !== this._token &&
131
+ undefined !== this._sequenceNumber) {
132
+ const timestamp = Date.now();
133
+ const parametersArray = Object.entries(parameters);
134
+ const parametersOrdered = [
135
+ ['sessionId', this._sessionId],
136
+ ['sequenceNumber', this._sequenceNumber],
137
+ ['timestamp', timestamp],
138
+ ...parametersArray.sort((a, b) => a[0].localeCompare(b[0]))
139
+ ];
140
+ const dataToSign = parametersOrdered
141
+ .map(([name, value]) => {
142
+ const serializedValue = SignedRequester._primitives.has(typeof value) || null === value
143
+ ? String(value)
144
+ : JSON.stringify(value);
145
+ return `${name}=${serializedValue}`;
146
+ })
147
+ .join(';');
148
+ const cryptoKey = await crypto.subtle.importKey('raw', this._token, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
149
+ const encoder = new TextEncoder();
150
+ const signatureBuffer = await crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(dataToSign));
151
+ const signature = _base64url_encode(new Uint8Array(signatureBuffer), this._onError);
152
+ const signedPayload = {
153
+ sessionId: this._sessionId,
154
+ timestamp: timestamp,
155
+ signature: signature
156
+ };
157
+ Object.assign(signedPayload, Object.fromEntries(parametersArray));
158
+ const url = options.baseUrl
159
+ ? `${options.baseUrl}${path}`
160
+ : (this._baseUrl ? `${this._baseUrl}${path}` : path);
161
+ const method = options.method || 'POST';
162
+ returnValue = await fetch(url, {
163
+ method: method,
164
+ headers: {
165
+ 'Content-Type': 'application/json',
166
+ ...options.headers
167
+ },
168
+ body: JSON.stringify(signedPayload)
169
+ });
170
+ if (returnValue.ok) {
171
+ this._incrementSequenceNumber();
172
+ }
173
+ else if (401 === returnValue.status) {
174
+ this.clearSession();
175
+ }
176
+ }
177
+ else {
178
+ error = new Error('Session not configured');
179
+ }
180
+ }
181
+ catch (e) {
182
+ error = e instanceof Error ? e : new Error(String(e));
183
+ }
184
+ finally {
185
+ this._semaphoreRelease();
186
+ }
187
+ if (error) {
188
+ throw error;
189
+ }
190
+ return returnValue;
191
+ }
192
+ async signedRequestJson(path, parameters, options = {}) {
193
+ let returnValue;
194
+ let error;
195
+ try {
196
+ const response = await this.signedRequest(path, parameters, options);
197
+ if (response.ok) {
198
+ returnValue = (await response.json());
199
+ }
200
+ else {
201
+ error = new Error(`Request failed with status ${response.status}`);
202
+ }
203
+ }
204
+ catch (e) {
205
+ error = e instanceof Error ? e : new Error(String(e));
206
+ }
207
+ if (error) {
208
+ throw error;
209
+ }
210
+ return returnValue;
211
+ }
212
+ }
213
+ SignedRequester._primitives = new Set([
214
+ 'undefined',
215
+ 'string',
216
+ 'number'
217
+ ]);
218
+ export { SignedRequester };
@@ -0,0 +1 @@
1
+ function t(t,e){let s;if(0<t?.length&&/^[A-Za-z0-9_-]*$/.test(t)){const i=t.length%4,o=(0===i?t:t.padEnd(t.length+(4-i),"=")).replace(/-/g,"+").replace(/_/g,"/");try{const t=atob(o);s=Uint8Array.from(t,t=>t.charCodeAt(0))}catch(t){e?.(t)}}return s}class e{t(t=!0){let e=Promise.resolve(!1);return this.i?t&&(e=new Promise(t=>{this.o.push(t)})):(this.i=!0,e=Promise.resolve(!0)),e}h(){if(this.i)if(0<this.o.length){const t=this.o.shift();t&&t(!0)}else this.i=!1}l(){void 0!==this.u&&(this.u++,localStorage.setItem("sequenceNumber",this.u.toString()))}S(){let e=!1;const s=localStorage.getItem("sessionId"),i=localStorage.getItem("token"),o=localStorage.getItem("sequenceNumber");if(s&&i&&o){const r=parseInt(s),n=parseInt(o),a=t(i,this.m);isNaN(r)||isNaN(n)||!a||(this.p=r,this.N=a,this.u=n,e=!0)}return e}constructor(t,e){this.i=!1,this.o=[],this.v=t,this.m=e}setSession(e){const s=t(e.token,this.m);if(!s)throw new Error("Invalid token format");this.p=e.sessionId,this.N=s,this.u=e.sequenceNumber,localStorage.setItem("sessionId",e.sessionId.toString()),localStorage.setItem("token",e.token),localStorage.setItem("sequenceNumber",e.sequenceNumber.toString())}getSession(){let t;return t=void 0!==this.p&&void 0!==this.N&&void 0!==this.u||this.S(),t}clearSession(){localStorage.removeItem("sessionId"),localStorage.removeItem("token"),localStorage.removeItem("sequenceNumber"),this.p=void 0,this.N=void 0,this.u=void 0}async signedRequest(t,s,i={}){let o,r;await this.t();try{if(void 0!==this.p&&void 0!==this.N&&void 0!==this.u){const r=Date.now(),n=Object.entries(s),a=[["sessionId",this.p],["sequenceNumber",this.u],["timestamp",r],...n.sort((t,e)=>t[0].localeCompare(e[0]))].map(([t,s])=>`${t}=${e.q.has(typeof s)||null===s?String(s):JSON.stringify(s)}`).join(";"),h=await crypto.subtle.importKey("raw",this.N,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=new TextEncoder,l=await crypto.subtle.sign("HMAC",h,c.encode(a)),u=function(t,e){let s="";if(0<t?.length)try{const e=Array.from(t,t=>String.fromCharCode(t)).join("");s=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){e?.(t)}return s}(new Uint8Array(l),this.m),d={sessionId:this.p,timestamp:r,signature:u};Object.assign(d,Object.fromEntries(n));const g=i.baseUrl?`${i.baseUrl}${t}`:this.v?`${this.v}${t}`:t,S=i.method||"POST";o=await fetch(g,{method:S,headers:{"Content-Type":"application/json",...i.headers},body:JSON.stringify(d)}),o.ok?this.l():401===o.status&&this.clearSession()}else r=new Error("Session not configured")}catch(t){r=t instanceof Error?t:new Error(String(t))}finally{this.h()}if(r)throw r;return o}async signedRequestJson(t,e,s={}){let i,o;try{const r=await this.signedRequest(t,e,s);r.ok?i=await r.json():o=new Error(`Request failed with status ${r.status}`)}catch(t){o=t instanceof Error?t:new Error(String(t))}if(o)throw o;return i}}e.q=new Set(["undefined","string","number"]);export{e as SignedRequester};
@@ -1,5 +1,5 @@
1
- import { Undefinedable } from './Common';
2
- import { Session } from './Session';
1
+ import { Undefinedable } from './Common.js';
2
+ import { Session } from './Session.js';
3
3
  export declare abstract class SessionsStorage {
4
4
  abstract create(validityToken: number, tokenLength: number, userId: number): Promise<Session>;
5
5
  abstract getBySessionId(sessionId: number): Promise<Undefinedable<Session>>;
@@ -1,6 +1,6 @@
1
- import { Undefinedable } from './Common';
2
- import { Session } from './Session';
3
- import { SessionsStorage } from './SessionsStorage';
1
+ import { Undefinedable } from './Common.js';
2
+ import { Session } from './Session.js';
3
+ import { SessionsStorage } from './SessionsStorage.js';
4
4
  type SessionStorageLocalConfig = {
5
5
  maxSessions: number;
6
6
  maxSessionsPerUser: number;
@@ -1,4 +1,4 @@
1
- import { randomBytes, randomInt } from './Common';
1
+ import { randomBytes, randomInt } from './Common.js';
2
2
  export class SessionsStorageLocal {
3
3
  _maxSessions;
4
4
  _maxSessionsPerUser;
@@ -1,11 +1,12 @@
1
1
  import { MiddlewareHandler } from 'hono';
2
- import { Undefinedable } from './Common';
3
- import { Session } from './Session';
4
- import { SessionsStorage } from './SessionsStorage';
2
+ import { Undefinedable } from './Common.js';
3
+ import { Session } from './Session.js';
4
+ import { SessionsStorage } from './SessionsStorage.js';
5
5
  type SignedRequestsManagerConfig = {
6
6
  validitySignature: number;
7
7
  validityToken: number;
8
8
  tokenLength: number;
9
+ onError?: (error: unknown) => void;
9
10
  };
10
11
  export declare class SignedRequestsManager {
11
12
  private static readonly _primitives;
@@ -13,6 +14,7 @@ export declare class SignedRequestsManager {
13
14
  private readonly _validitySignature;
14
15
  private readonly _validityToken;
15
16
  private readonly _tokenLength;
17
+ private readonly _onError?;
16
18
  constructor(storage?: SessionsStorage, options?: Partial<SignedRequestsManagerConfig>);
17
19
  createSession(userId: number): Promise<Session>;
18
20
  validate(sessionId: number, timestamp: number, parameters: [string, any][], signature: Uint8Array<ArrayBuffer>): Promise<Undefinedable<Session>>;
@@ -1,15 +1,17 @@
1
- import { constantTimeEqual, fromBase64Url, hmacSha256 } from './Common';
2
- import { SessionsStorageLocal } from './SessionsStorageLocal';
1
+ import { constantTimeEqual, fromBase64Url, hmacSha256 } from './Common.js';
2
+ import { SessionsStorageLocal } from './SessionsStorageLocal.js';
3
3
  export class SignedRequestsManager {
4
4
  static _primitives = new Set(['string', 'number', 'boolean']);
5
5
  _storage;
6
6
  _validitySignature;
7
7
  _validityToken;
8
8
  _tokenLength;
9
+ _onError;
9
10
  constructor(storage, options) {
10
11
  this._validitySignature = options?.validitySignature ?? 5000;
11
12
  this._validityToken = options?.validityToken ?? 60 * 60000;
12
13
  this._tokenLength = options?.tokenLength ?? 32;
14
+ this._onError = options?.onError;
13
15
  if (!storage) {
14
16
  storage = new SessionsStorageLocal();
15
17
  }
@@ -81,7 +83,7 @@ export class SignedRequestsManager {
81
83
  }
82
84
  }
83
85
  catch (error) {
84
- console.error('Session validation error:', error);
86
+ this._onError?.(error);
85
87
  }
86
88
  if (session) {
87
89
  context.set('session', session);
package/package.json CHANGED
@@ -1,7 +1,18 @@
1
1
  {
2
2
  "name": "@stefanobalocco/honosignedrequests",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "An hono middleware to manage signed requests, including a client implementation.",
5
+ "author": "Stefano Balocco <stefano.balocco@gmail.com>",
6
+ "license": "BSD-3-Clause",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/StefanoBalocco/HonoSignedRequests.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/StefanoBalocco/HonoSignedRequests/issues"
13
+ },
14
+ "homepage": "https://github.com/StefanoBalocco/HonoSignedRequests",
15
+ "type": "module",
5
16
  "main": "dist/index.js",
6
17
  "types": "dist/index.d.ts",
7
18
  "exports": {
@@ -15,15 +26,21 @@
15
26
  }
16
27
  },
17
28
  "devDependencies": {
29
+ "@hono/node-server": "^1.13.7",
30
+ "@types/node": "^22.10.5",
31
+ "ava": "^6.4.1",
32
+ "c8": "^10.1.3",
18
33
  "hono": "^4.10.6",
19
34
  "terser": "^5.44.1",
20
- "typescript": "^5.5.3"
35
+ "typescript": "^5.5.3",
36
+ "undici": "^7.4.0"
21
37
  },
22
38
  "peerDependencies": {
23
39
  "hono": "^4.0.0"
24
40
  },
25
41
  "files": [
26
- "dist"
42
+ "dist",
43
+ "client/dist"
27
44
  ],
28
45
  "keywords": [
29
46
  "hono",
@@ -33,10 +50,11 @@
33
50
  "session",
34
51
  "authentication"
35
52
  ],
36
- "license": "BSD-3-Clause",
37
53
  "scripts": {
38
- "build": "npm run build:server && npm run build:client",
54
+ "build": "npm run build:server && npm run build:client && npm run build:tests",
39
55
  "build:server": "tsc",
40
- "build:client": "tsc -p client/tsconfig.json && terser client/dist/SignedRequester.js -o client/dist/SignedRequester.min.js --toplevel -m -c --mangle-props regex=/^_/"
56
+ "build:client": "tsc -p client/tsconfig.json && terser client/dist/SignedRequester.js -o client/dist/SignedRequester.min.js --toplevel -m -c --mangle-props regex=/^_/",
57
+ "build:tests": "tsc -p tests/tsconfig.json",
58
+ "run:tests": "npx ava tests/dist/*.test.js --verbose"
41
59
  }
42
60
  }