@oino-ts/hashid 0.0.11
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/README.md +222 -0
- package/dist/cjs/OINOHashid.js +103 -0
- package/dist/cjs/index.js +5 -0
- package/dist/esm/OINOHashid.js +99 -0
- package/dist/esm/index.js +1 -0
- package/dist/types/OINOHashid.d.ts +40 -0
- package/dist/types/index.d.ts +1 -0
- package/package.json +32 -0
- package/src/OINOHashid.test.ts +48 -0
- package/src/OINOHashid.ts +113 -0
- package/src/index.ts +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# OINO TS
|
|
2
|
+
OINO Is Not an ORM but it's trying to solve a similar problem for API development. Instead of mirroring your DB schema in code that needs manual updates, OINO will get the data schema from DBMS using SQL in real time. Every time your app starts, it has an updated data model which enables automatic (de)serialize SQL results to JSON/CSV and back. OINO works on the level below routing where you pass the method, URL ID, body and request parameters to the API-object. OINO will parse and validate the data against the data model and generate proper SQL for your DB. Because OINO knows how data is serialized (e.g. JSON), what column it belongs to (e.g. floating point number) and what the target database is, it knows how to parse, format and escape the value as valid SQL.
|
|
3
|
+
|
|
4
|
+
```
|
|
5
|
+
const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
|
|
6
|
+
return new Response(result.modelset.writeString(OINOContentType.json))
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# GETTING STARTED
|
|
11
|
+
|
|
12
|
+
### Setup
|
|
13
|
+
Install the `@oino-ts/core` npm package and necessary database packages and import them in your code.
|
|
14
|
+
```
|
|
15
|
+
bun install @oino-ts/core
|
|
16
|
+
bun install @oino-ts/bunsqlite
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
import { OINODb, OINOApi, OINOFactory } from "@oino-ts/core";
|
|
21
|
+
import { OINODbBunSqlite } from "@oino-ts/bunsqlite"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### Register database and logger
|
|
25
|
+
Register your database implementation and logger (see [`OINOConsoleLog`](https://pragmatta.github.io/oino-ts/classes/core_src.OINOConsoleLog.html) how to implement your own)
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
OINOLog.setLogger(new OINOConsoleLog())
|
|
29
|
+
OINOFactory.registerDb("OINODbBunSqlite", OINODbBunSqlite)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Create a database
|
|
33
|
+
Creating a database connection [`OINODb`](https://pragmatta.github.io/oino-ts/classes/core_src_OINODb.OINODb.html) is done by passing [`OINODbParams`](https://pragmatta.github.io/oino-ts/types/core_src.OINODbParams.html) to the factory method. For [`OINODbBunSqlite`](https://pragmatta.github.io/oino-ts/classes/bunsqlite_OINODbBunSqlite.OINODbBunSqlite.html) that means a file url for the database file, for others network host, port, credentials etc.
|
|
34
|
+
```
|
|
35
|
+
const db:OINODb = await OINOFactory.createDb( { type: "OINODbBunSqlite", url: "file://../localDb/northwind.sqlite" } )
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Create an API
|
|
39
|
+
From a database you can create an [`OINOApi`](https://pragmatta.github.io/oino-ts/classes/core_src_OINOApi.OINOApi.html) by passing [`OINOApiParams`](https://pragmatta.github.io/oino-ts/types/core_src.OINOApiParams.html) with table name and preferences to the factory method.
|
|
40
|
+
```
|
|
41
|
+
const api_employees:OINOApi = await OINOFactory.createApi(db, { tableName: "Employees", excludeFields:["BirthDate"] })
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Pass HTTP requests to API
|
|
45
|
+
When you receive a HTTP request, just pass the method, URL ID, body and params to the correct API, which will parse and validate input and return results.
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Write results back to HTTP Response
|
|
52
|
+
The results for a GET request will contain [`OINOModelSet`](https://pragmatta.github.io/oino-ts/classes/core_src_OINOModelSet.OINOModelSet.html) data that can be written out as JSON or CSV as needed. For other requests result is just success or error with messages.
|
|
53
|
+
```
|
|
54
|
+
return new Response(result.modelset.writeString(OINOContentType.json))
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# FEATURES
|
|
59
|
+
|
|
60
|
+
## RESTfull
|
|
61
|
+
OINO maps HTTP methods GET/POST/PUT/DELETE to SQL operations SELECT/INSERT/UPDATE/DELETE. The GET/POST requests can be made without URL ID to get all rows or insert new ones and others target a single row using URL ID.
|
|
62
|
+
|
|
63
|
+
### HTTP GET
|
|
64
|
+
```
|
|
65
|
+
Request and response:
|
|
66
|
+
> curl.exe -X GET http://localhost:3001/orderdetails/11077:77
|
|
67
|
+
[
|
|
68
|
+
{"_OINOID_":"11077:77","OrderID":11077,"ProductID":77,"UnitPrice":13,"Quantity":2,"Discount":0}
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
SQL:
|
|
72
|
+
SELECT "OrderID","ProductID","UnitPrice","Quantity","Discount" FROM [OrderDetails] WHERE ("OrderID"=11077 AND "ProductID"=77);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### HTTP POST
|
|
76
|
+
```
|
|
77
|
+
Request and response:
|
|
78
|
+
> curl.exe -X POST http://localhost:3001/orderdetails -H "Content-Type: application/json" --data '[{\"OrderID\":11077,\"ProductID\":99,\"UnitPrice\":19,\"Quantity\":1,\"Discount\":0}]'
|
|
79
|
+
{"success":true,"statusCode":200,"statusMessage":"OK","messages":[]}
|
|
80
|
+
|
|
81
|
+
SQL:
|
|
82
|
+
INSERT INTO [OrderDetails] ("OrderID","ProductID","UnitPrice","Quantity","Discount") VALUES (11077,99,19,1,0);
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### HTTP PUT
|
|
86
|
+
```
|
|
87
|
+
Request and response:
|
|
88
|
+
> curl.exe -X PUT http://localhost:3001/orderdetails/11077:99 -H "Content-Type: application/json" --data '[{\"UnitPrice\":20}]'
|
|
89
|
+
{"success":true,"statusCode":200,"statusMessage":"OK","messages":[]}
|
|
90
|
+
|
|
91
|
+
SQL:
|
|
92
|
+
UPDATE [OrderDetails] SET "UnitPrice"=20 WHERE ("OrderID"=11077 AND "ProductID"=99);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### HTTP DELETE
|
|
96
|
+
```
|
|
97
|
+
Request and response:
|
|
98
|
+
> curl.exe -X DELETE http://localhost:3001/orderdetails/11077:99
|
|
99
|
+
{"success":true,"statusCode":200,"statusMessage":"OK","messages":[]}
|
|
100
|
+
|
|
101
|
+
SQL:
|
|
102
|
+
DELETE FROM [OrderDetails] WHERE ("OrderID"=11077 AND "ProductID"=99);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Universal Serialization
|
|
106
|
+
OINO handles serialization of data to JSON/CSV/etc. and back based on the data model. It knows what columns exist, what is their data type and how to convert each to JSON/CSV and back. This allows also partial data to be sent, i.e. you can send only columns that need updating or even send extra columns and have them ignored.
|
|
107
|
+
|
|
108
|
+
### Features
|
|
109
|
+
- Files can be sent to BLOB fields using BASE64 encoding.
|
|
110
|
+
- Datetimes are (optionally) normalized to ISO 8601 format.
|
|
111
|
+
- Extended JSON-encoding
|
|
112
|
+
- Unquoted literal `undefined` can be used to represent non-existent values (leaving property out works too but preserving structure might be easier e.g. when translating data).
|
|
113
|
+
- CSV
|
|
114
|
+
- Comma-separated, doublequotes.
|
|
115
|
+
- Unquoted literal `null` represents null values.
|
|
116
|
+
- Unquoted empty string represents undefined values.
|
|
117
|
+
- Form data
|
|
118
|
+
- Multipart-mixed and binary files not supported.
|
|
119
|
+
- Non-existent value line (i.e. nothing after the empty line) treated as a null value.
|
|
120
|
+
- Url-encoded
|
|
121
|
+
- No null values, missing properties treated as undefined.
|
|
122
|
+
- Multiple lines could be used to post multiple rows.
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
## Database Abstraction
|
|
126
|
+
OINO functions as a database abstraction, providing a consistent interface for working with different databases. It abstracts out different conventions in connecting, making queries and formatting data.
|
|
127
|
+
|
|
128
|
+
Currently supported databases:
|
|
129
|
+
- Bun Sqlite through Bun native implementation
|
|
130
|
+
- Postgresql through [pg](https://www.npmjs.com/package/pg)-package
|
|
131
|
+
- Mariadb / Mysql-support through [mariadb](https://www.npmjs.com/package/mariadb)-package
|
|
132
|
+
|
|
133
|
+
## Complex Keys
|
|
134
|
+
To support tables with multipart primary keys OINO generates a composite key `_OINOID_` that is included in the result and can be used as the REST ID. For example in the example above table `OrderDetails` has two primary keys `OrderID` and `ProductID` making the `_OINOID_` of form `11077:99`.
|
|
135
|
+
|
|
136
|
+
## Power Of SQL
|
|
137
|
+
Since OINO controls the SQL, WHERE-conditions can be defined with [`OINOSqlFilter`](https://pragmatta.github.io/oino-ts/classes/core_src.OINOSqlFilter.html) and order with [`OINOSqlOrder`](https://pragmatta.github.io/oino-ts/classes/core_src.OINOSqlOrder.html) that are passed as HTTP request parameters. No more API development where you make unique API endpoints for each filter that fetch all data with original API and filter in backend code. Every API can be filtered when and as needed without unnessecary data tranfer and utilizing SQL indexing when available.
|
|
138
|
+
|
|
139
|
+
## Swagger Support
|
|
140
|
+
Swagger is great as long as the definitions are updated and with OINO you can automatically get a Swagger definition including a data model schema.
|
|
141
|
+
```
|
|
142
|
+
if (url.pathname == "/swagger.json") {
|
|
143
|
+
return new Response(JSON.stringify(OINOSwagger.getApiDefinition(api_array)))
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+

|
|
147
|
+
|
|
148
|
+
## Node support
|
|
149
|
+
OINO is developped Typescript first but compiles to standard CommonJS and the NPM packages should work on either ESM / CommonJS. Checkout sample apps `readmeApp` (ESM) and `nodeApp` (CommonJS).
|
|
150
|
+
|
|
151
|
+
## HTMX support
|
|
152
|
+
OINO is [htmx.org](https://htmx.org) friendly, allowing easy translation of [`OINODataRow`](https://pragmatta.github.io/oino-ts/types/core_src.OINODataRow.html) to HTML output using templates (cf. the [htmx sample app](https://github.com/pragmatta/oino-ts/tree/main/samples/htmxApp)).
|
|
153
|
+
|
|
154
|
+
### Hashids
|
|
155
|
+
Autoinc numeric id's are very pragmatic and fit well with OINO (e.g. using a form without primary key fields to insert new rows with database assigned ids). However it's not always sensible to share information about the sequence. Hashids solve this by masking the original values by encrypting the ids using AES-128 and some randomness. Length of the hashid can be chosen from 12-32 characters where longer ids provide more security. However this should not be considereded a cryptographic solution for keeping ids secret but rather making it infeasible to iterate all ids.
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# STATUS
|
|
159
|
+
OINO is currently a hobby project which should and should considered in alpha status. That also means compatibility breaking changes can be made without prior notice when architectual issues are discovered.
|
|
160
|
+
|
|
161
|
+
## Beta
|
|
162
|
+
For a beta status following milestones are planned:
|
|
163
|
+
|
|
164
|
+
### Realistic app
|
|
165
|
+
There needs to be a realistic app built on top of OINO to get a better grasp of the edge cases.
|
|
166
|
+
|
|
167
|
+
### Security review
|
|
168
|
+
Handling of SQL-injection attacks needs a thorough review, what are the relevant attack vectors are for OINO and what protections are still needed.
|
|
169
|
+
|
|
170
|
+
## Roadmap
|
|
171
|
+
Things that need to happen in some order before beta-status are at least following:
|
|
172
|
+
|
|
173
|
+
### Support for views
|
|
174
|
+
Simple cases of views would work already in some databases but edge cases might get complicated. For example
|
|
175
|
+
- How to handle a view which does not have a complete private key?
|
|
176
|
+
- What edge cases exist in updating views?
|
|
177
|
+
|
|
178
|
+
### Batch updates
|
|
179
|
+
Supporting batch updates similar to batch inserts is slightly bending the RESTfull principles but would still be a useful optional feature.
|
|
180
|
+
|
|
181
|
+
### Aggregation and limits
|
|
182
|
+
Similar to filtering and ordering, aggregation and limits can be implemented as HTTP request parameters telling what column is aggregated or used for ordering or how many results to return.
|
|
183
|
+
|
|
184
|
+
### Streaming
|
|
185
|
+
One core idea is to be efficient in not making unnecessary copies of the data and minimizing garbage collection debt. This can be taken further by implementing streaming, allowing large dataset to be written to HTTP response as SQL result rows are received.
|
|
186
|
+
|
|
187
|
+
### SQL generation callbacks
|
|
188
|
+
It would be useful to allow developer to validate / override SQL generation to cover cases OINO does not support or even workaround issues.
|
|
189
|
+
|
|
190
|
+
### Transactions
|
|
191
|
+
Even though the basic case for OINO is executing SQL operations on individual rows, having an option to use SQL transactions could make sense at least for batch operations.
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# HELP
|
|
195
|
+
|
|
196
|
+
## Bug reports
|
|
197
|
+
Fixing bugs is a priority and getting good quality bug reports helps. It's recommended to use the sample Northwind database included with project to replicate issues or make an SQL script export of the relevant table.
|
|
198
|
+
|
|
199
|
+
## Feedback
|
|
200
|
+
Understanding and prioritizing the use cases for OINO is also important and feedback about how you'd use OINO is interesting. Feel free to raise issues and feature requests in Github, but understand that short term most of the effort goes towards reaching the beta stage.
|
|
201
|
+
|
|
202
|
+
## Typescript / Javascript architecture
|
|
203
|
+
Typescript building with different targets and module-systemts and a ton of configuration is a complex domain and something I have little experience un so help in fixing problems and how thing ought to be done is appreciated.
|
|
204
|
+
|
|
205
|
+
# LINKS
|
|
206
|
+
- [Github repository](https://github.com/pragmatta/oino-ts)
|
|
207
|
+
- [NPM repository](https://www.npmjs.com/org/oino-ts)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ACKNOWLEDGEMENTS
|
|
211
|
+
|
|
212
|
+
## Libraries
|
|
213
|
+
OINO uses the following open source libraries and npm packages and I would like to thank everyone for their contributions:
|
|
214
|
+
- Postgresql support by [node-postgres package](https://www.npmjs.com/package/pg)
|
|
215
|
+
- Mariadb / Mysql-support by [mariadb package](https://www.npmjs.com/package/mariadb)
|
|
216
|
+
|
|
217
|
+
## Bun
|
|
218
|
+
OINO has been developed using the Bun runtime, not because of the speed improvements but for the first class Typescript support and integrated developper experience. Kudos on the bun team for making Typescript work more exiting again.
|
|
219
|
+
|
|
220
|
+
## SQL Scripts
|
|
221
|
+
The SQL scripts for creating the sample Northwind database are based on [Google Code archive](https://code.google.com/archive/p/northwindextended/downloads) and have been further customized to ensure they would have identical data (in the scope of the automated testing).
|
|
222
|
+
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.OINOHashid = void 0;
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const base_x_1 = require("base-x");
|
|
11
|
+
const HASHID_MIN_LENGTH = 12;
|
|
12
|
+
const HASHID_MAX_LENGTH = 40;
|
|
13
|
+
const HASHID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
14
|
+
const hashidEncoder = (0, base_x_1.default)(HASHID_ALPHABET);
|
|
15
|
+
/**
|
|
16
|
+
* Hashid implementation for OINO API:s for the purpose of making it infeasible to scan
|
|
17
|
+
* through numeric autoinc keys. It's not a solution to keeping the id secret in insecure
|
|
18
|
+
* channels, just making it hard enough to not iterate through the entire key space. Half
|
|
19
|
+
* of the the hashid length is nonce and half cryptotext, i.e. 16 char hashid 8 chars of
|
|
20
|
+
* base64 encoded nonce ~ 6 bytes or 48 bits of entropy.
|
|
21
|
+
*
|
|
22
|
+
*/
|
|
23
|
+
class OINOHashid {
|
|
24
|
+
_key;
|
|
25
|
+
_iv;
|
|
26
|
+
_domainId;
|
|
27
|
+
_minLength;
|
|
28
|
+
_randomIds;
|
|
29
|
+
/**
|
|
30
|
+
* Hashid constructor
|
|
31
|
+
*
|
|
32
|
+
* @param key AES128 key (32 char hex-string)
|
|
33
|
+
* @param domainId a sufficiently unique domain ID in which row-Id's are unique
|
|
34
|
+
* @param minLength minimum length of nonce and crypto
|
|
35
|
+
* @param randomIds whether hash values should remain static per row or random values
|
|
36
|
+
*
|
|
37
|
+
*/
|
|
38
|
+
constructor(key, domainId, minLength = HASHID_MIN_LENGTH, randomIds = false) {
|
|
39
|
+
this._domainId = domainId;
|
|
40
|
+
if ((minLength < HASHID_MIN_LENGTH) || (minLength > HASHID_MAX_LENGTH)) {
|
|
41
|
+
throw Error("OINOHashid minLength needs to be between " + HASHID_MIN_LENGTH + " and " + HASHID_MAX_LENGTH + "!");
|
|
42
|
+
}
|
|
43
|
+
this._minLength = Math.ceil(minLength / 2);
|
|
44
|
+
if (key.length != 32) {
|
|
45
|
+
throw Error("OINOHashid key needs to be a 32 character hex-string!");
|
|
46
|
+
}
|
|
47
|
+
this._randomIds = randomIds;
|
|
48
|
+
this._key = Buffer.from(key, 'hex');
|
|
49
|
+
this._iv = new Buffer(16);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Encode given id value as a hashid either using random data or given seed value for nonce.
|
|
53
|
+
*
|
|
54
|
+
* @param id numeric value
|
|
55
|
+
* @param cellSeed a sufficiently unique seed for the current cell to keep hashids unique but persistent (e.g. fieldname + primarykey values)
|
|
56
|
+
*
|
|
57
|
+
*/
|
|
58
|
+
encode(id, cellSeed = "") {
|
|
59
|
+
// if seed was given use it for pseudorandom chars, otherwise generate them
|
|
60
|
+
let random_chars = "";
|
|
61
|
+
if (this._randomIds) {
|
|
62
|
+
(0, node_crypto_1.randomFillSync)(this._iv, 0, 16);
|
|
63
|
+
random_chars = hashidEncoder.encode(this._iv); // this._iv.toString('base64url')
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
const hmac_seed = (0, node_crypto_1.createHmac)('sha1', this._key);
|
|
67
|
+
hmac_seed.update(this._domainId + " " + cellSeed);
|
|
68
|
+
random_chars = hashidEncoder.encode(hmac_seed.digest()); // hmac_seed.digest('base64url')
|
|
69
|
+
}
|
|
70
|
+
const hmac = (0, node_crypto_1.createHmac)('sha1', this._key);
|
|
71
|
+
let iv_seed = random_chars.substring(0, this._minLength);
|
|
72
|
+
hmac.update(this._domainId + " " + iv_seed);
|
|
73
|
+
const iv_data = hmac.digest();
|
|
74
|
+
iv_data.copy(this._iv, 0, 0, 16);
|
|
75
|
+
let plaintext = id.toString();
|
|
76
|
+
if (plaintext.length < this._minLength) {
|
|
77
|
+
plaintext += " " + random_chars.substring(random_chars.length - (this._minLength - plaintext.length - 1));
|
|
78
|
+
}
|
|
79
|
+
const cipher = (0, node_crypto_1.createCipheriv)('aes-128-gcm', this._key, this._iv);
|
|
80
|
+
const cryptotext = hashidEncoder.encode(cipher.update(plaintext, 'utf8')) + hashidEncoder.encode(cipher.final());
|
|
81
|
+
return iv_seed + cryptotext;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Decode given hashid.
|
|
85
|
+
*
|
|
86
|
+
* @param hashid value
|
|
87
|
+
*
|
|
88
|
+
*/
|
|
89
|
+
decode(hashid) {
|
|
90
|
+
// reproduce nonce from seed
|
|
91
|
+
const hmac = (0, node_crypto_1.createHmac)('sha1', this._key);
|
|
92
|
+
const iv_seed = hashid.substring(0, this._minLength);
|
|
93
|
+
hmac.update(this._domainId + " " + iv_seed);
|
|
94
|
+
const hash = hmac.digest();
|
|
95
|
+
hash.copy(this._iv, 0, 0, 16);
|
|
96
|
+
const cryptotext = hashid.substring(this._minLength);
|
|
97
|
+
const cryptobytes = new Buffer(hashidEncoder.decode(cryptotext));
|
|
98
|
+
const decipher = (0, node_crypto_1.createDecipheriv)('aes-128-gcm', this._key, this._iv);
|
|
99
|
+
const plaintext = decipher.update(cryptobytes, undefined, 'utf8'); //, cryptotext, 'base64url', 'utf8')
|
|
100
|
+
return plaintext.split(" ")[0];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
exports.OINOHashid = OINOHashid;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OINOHashid = void 0;
|
|
4
|
+
var OINOHashid_js_1 = require("./OINOHashid.js");
|
|
5
|
+
Object.defineProperty(exports, "OINOHashid", { enumerable: true, get: function () { return OINOHashid_js_1.OINOHashid; } });
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
3
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
5
|
+
*/
|
|
6
|
+
import { createCipheriv, createDecipheriv, createHmac, randomFillSync } from 'node:crypto';
|
|
7
|
+
import basex from 'base-x';
|
|
8
|
+
const HASHID_MIN_LENGTH = 12;
|
|
9
|
+
const HASHID_MAX_LENGTH = 40;
|
|
10
|
+
const HASHID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
11
|
+
const hashidEncoder = basex(HASHID_ALPHABET);
|
|
12
|
+
/**
|
|
13
|
+
* Hashid implementation for OINO API:s for the purpose of making it infeasible to scan
|
|
14
|
+
* through numeric autoinc keys. It's not a solution to keeping the id secret in insecure
|
|
15
|
+
* channels, just making it hard enough to not iterate through the entire key space. Half
|
|
16
|
+
* of the the hashid length is nonce and half cryptotext, i.e. 16 char hashid 8 chars of
|
|
17
|
+
* base64 encoded nonce ~ 6 bytes or 48 bits of entropy.
|
|
18
|
+
*
|
|
19
|
+
*/
|
|
20
|
+
export class OINOHashid {
|
|
21
|
+
_key;
|
|
22
|
+
_iv;
|
|
23
|
+
_domainId;
|
|
24
|
+
_minLength;
|
|
25
|
+
_randomIds;
|
|
26
|
+
/**
|
|
27
|
+
* Hashid constructor
|
|
28
|
+
*
|
|
29
|
+
* @param key AES128 key (32 char hex-string)
|
|
30
|
+
* @param domainId a sufficiently unique domain ID in which row-Id's are unique
|
|
31
|
+
* @param minLength minimum length of nonce and crypto
|
|
32
|
+
* @param randomIds whether hash values should remain static per row or random values
|
|
33
|
+
*
|
|
34
|
+
*/
|
|
35
|
+
constructor(key, domainId, minLength = HASHID_MIN_LENGTH, randomIds = false) {
|
|
36
|
+
this._domainId = domainId;
|
|
37
|
+
if ((minLength < HASHID_MIN_LENGTH) || (minLength > HASHID_MAX_LENGTH)) {
|
|
38
|
+
throw Error("OINOHashid minLength needs to be between " + HASHID_MIN_LENGTH + " and " + HASHID_MAX_LENGTH + "!");
|
|
39
|
+
}
|
|
40
|
+
this._minLength = Math.ceil(minLength / 2);
|
|
41
|
+
if (key.length != 32) {
|
|
42
|
+
throw Error("OINOHashid key needs to be a 32 character hex-string!");
|
|
43
|
+
}
|
|
44
|
+
this._randomIds = randomIds;
|
|
45
|
+
this._key = Buffer.from(key, 'hex');
|
|
46
|
+
this._iv = new Buffer(16);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Encode given id value as a hashid either using random data or given seed value for nonce.
|
|
50
|
+
*
|
|
51
|
+
* @param id numeric value
|
|
52
|
+
* @param cellSeed a sufficiently unique seed for the current cell to keep hashids unique but persistent (e.g. fieldname + primarykey values)
|
|
53
|
+
*
|
|
54
|
+
*/
|
|
55
|
+
encode(id, cellSeed = "") {
|
|
56
|
+
// if seed was given use it for pseudorandom chars, otherwise generate them
|
|
57
|
+
let random_chars = "";
|
|
58
|
+
if (this._randomIds) {
|
|
59
|
+
randomFillSync(this._iv, 0, 16);
|
|
60
|
+
random_chars = hashidEncoder.encode(this._iv); // this._iv.toString('base64url')
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
const hmac_seed = createHmac('sha1', this._key);
|
|
64
|
+
hmac_seed.update(this._domainId + " " + cellSeed);
|
|
65
|
+
random_chars = hashidEncoder.encode(hmac_seed.digest()); // hmac_seed.digest('base64url')
|
|
66
|
+
}
|
|
67
|
+
const hmac = createHmac('sha1', this._key);
|
|
68
|
+
let iv_seed = random_chars.substring(0, this._minLength);
|
|
69
|
+
hmac.update(this._domainId + " " + iv_seed);
|
|
70
|
+
const iv_data = hmac.digest();
|
|
71
|
+
iv_data.copy(this._iv, 0, 0, 16);
|
|
72
|
+
let plaintext = id.toString();
|
|
73
|
+
if (plaintext.length < this._minLength) {
|
|
74
|
+
plaintext += " " + random_chars.substring(random_chars.length - (this._minLength - plaintext.length - 1));
|
|
75
|
+
}
|
|
76
|
+
const cipher = createCipheriv('aes-128-gcm', this._key, this._iv);
|
|
77
|
+
const cryptotext = hashidEncoder.encode(cipher.update(plaintext, 'utf8')) + hashidEncoder.encode(cipher.final());
|
|
78
|
+
return iv_seed + cryptotext;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Decode given hashid.
|
|
82
|
+
*
|
|
83
|
+
* @param hashid value
|
|
84
|
+
*
|
|
85
|
+
*/
|
|
86
|
+
decode(hashid) {
|
|
87
|
+
// reproduce nonce from seed
|
|
88
|
+
const hmac = createHmac('sha1', this._key);
|
|
89
|
+
const iv_seed = hashid.substring(0, this._minLength);
|
|
90
|
+
hmac.update(this._domainId + " " + iv_seed);
|
|
91
|
+
const hash = hmac.digest();
|
|
92
|
+
hash.copy(this._iv, 0, 0, 16);
|
|
93
|
+
const cryptotext = hashid.substring(this._minLength);
|
|
94
|
+
const cryptobytes = new Buffer(hashidEncoder.decode(cryptotext));
|
|
95
|
+
const decipher = createDecipheriv('aes-128-gcm', this._key, this._iv);
|
|
96
|
+
const plaintext = decipher.update(cryptobytes, undefined, 'utf8'); //, cryptotext, 'base64url', 'utf8')
|
|
97
|
+
return plaintext.split(" ")[0];
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { OINOHashid } from "./OINOHashid.js";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hashid implementation for OINO API:s for the purpose of making it infeasible to scan
|
|
3
|
+
* through numeric autoinc keys. It's not a solution to keeping the id secret in insecure
|
|
4
|
+
* channels, just making it hard enough to not iterate through the entire key space. Half
|
|
5
|
+
* of the the hashid length is nonce and half cryptotext, i.e. 16 char hashid 8 chars of
|
|
6
|
+
* base64 encoded nonce ~ 6 bytes or 48 bits of entropy.
|
|
7
|
+
*
|
|
8
|
+
*/
|
|
9
|
+
export declare class OINOHashid {
|
|
10
|
+
private _key;
|
|
11
|
+
private _iv;
|
|
12
|
+
private _domainId;
|
|
13
|
+
private _minLength;
|
|
14
|
+
private _randomIds;
|
|
15
|
+
/**
|
|
16
|
+
* Hashid constructor
|
|
17
|
+
*
|
|
18
|
+
* @param key AES128 key (32 char hex-string)
|
|
19
|
+
* @param domainId a sufficiently unique domain ID in which row-Id's are unique
|
|
20
|
+
* @param minLength minimum length of nonce and crypto
|
|
21
|
+
* @param randomIds whether hash values should remain static per row or random values
|
|
22
|
+
*
|
|
23
|
+
*/
|
|
24
|
+
constructor(key: string, domainId: string, minLength?: number, randomIds?: boolean);
|
|
25
|
+
/**
|
|
26
|
+
* Encode given id value as a hashid either using random data or given seed value for nonce.
|
|
27
|
+
*
|
|
28
|
+
* @param id numeric value
|
|
29
|
+
* @param cellSeed a sufficiently unique seed for the current cell to keep hashids unique but persistent (e.g. fieldname + primarykey values)
|
|
30
|
+
*
|
|
31
|
+
*/
|
|
32
|
+
encode(id: string, cellSeed?: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* Decode given hashid.
|
|
35
|
+
*
|
|
36
|
+
* @param hashid value
|
|
37
|
+
*
|
|
38
|
+
*/
|
|
39
|
+
decode(hashid: string): string;
|
|
40
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { OINOHashid } from "./OINOHashid.js";
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oino-ts/hashid",
|
|
3
|
+
"version": "0.0.11",
|
|
4
|
+
"description": "OINO TS package for hashid's.",
|
|
5
|
+
"author": "Matias Kiviniemi (pragmatta)",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/pragmatta/oino-ts.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"hashid",
|
|
13
|
+
"typescript",
|
|
14
|
+
"library"
|
|
15
|
+
],
|
|
16
|
+
"main": "./dist/cjs/index.js",
|
|
17
|
+
"module": "./dist/esm/index.js",
|
|
18
|
+
"types": "./dist/types/index.d.ts",
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@types/node": "^20.12.7",
|
|
21
|
+
"@oino-ts/types": "^0.0.11",
|
|
22
|
+
"base-x": "5.0.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src/*.ts",
|
|
28
|
+
"dist/cjs/*.js",
|
|
29
|
+
"dist/esm/*.js",
|
|
30
|
+
"dist/types/*.d.ts"
|
|
31
|
+
]
|
|
32
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
3
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { expect, test } from "bun:test";
|
|
8
|
+
|
|
9
|
+
import { OINOHashid } from "./OINOHashid";
|
|
10
|
+
import { OINOLog, OINOConsoleLog, OINOLogLevel } from "@oino-ts/log"
|
|
11
|
+
|
|
12
|
+
Math.random()
|
|
13
|
+
|
|
14
|
+
OINOLog.setLogger(new OINOConsoleLog(OINOLogLevel.error))
|
|
15
|
+
|
|
16
|
+
test("OINOHashId persistent", async () => {
|
|
17
|
+
for (let j=12; j<=40; j++) {
|
|
18
|
+
const hashid:OINOHashid = new OINOHashid('c7a87c6a5df870842eb6ef6d7937f0b4', 'OINOHashIdTestApp-persistent', j)
|
|
19
|
+
let i:number = 1
|
|
20
|
+
let id:string = ''
|
|
21
|
+
while (i <= j) {
|
|
22
|
+
id += i % 10
|
|
23
|
+
const hashed_id = hashid.encode(id, '')
|
|
24
|
+
const id2 = hashid.decode(hashed_id)
|
|
25
|
+
// console.log("j: " + j + ", i: " + i + ", id: " + id + ", hashed_id: " + hashed_id + ", id2: " + id2)
|
|
26
|
+
expect(id).toMatch(id2)
|
|
27
|
+
i++
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
test("OINOHashId random", async () => {
|
|
34
|
+
for (let j=12; j<=40; j++) {
|
|
35
|
+
const hashid:OINOHashid = new OINOHashid('c7a87c6a5df870842eb6ef6d7937f0b4', 'OINOHashIdTestApp-random', j, true)
|
|
36
|
+
let i:number = 1
|
|
37
|
+
let id:string = ''
|
|
38
|
+
while (i <= j) {
|
|
39
|
+
id += i % 10
|
|
40
|
+
const hashed_id = hashid.encode(id, '')
|
|
41
|
+
const id2 = hashid.decode(hashed_id)
|
|
42
|
+
// console.log("j: " + j + ", i: " + i + ", id: " + id + ", hashed_id: " + hashed_id + ", id2: " + id2)
|
|
43
|
+
expect(id).toMatch(id2)
|
|
44
|
+
i++
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
})
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
3
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createCipheriv, createDecipheriv, createHmac, randomFillSync } from 'node:crypto';
|
|
8
|
+
import basex from 'base-x'
|
|
9
|
+
|
|
10
|
+
const HASHID_MIN_LENGTH:number = 12
|
|
11
|
+
const HASHID_MAX_LENGTH:number = 40
|
|
12
|
+
const HASHID_ALPHABET:string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
13
|
+
const hashidEncoder = basex(HASHID_ALPHABET)
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Hashid implementation for OINO API:s for the purpose of making it infeasible to scan
|
|
17
|
+
* through numeric autoinc keys. It's not a solution to keeping the id secret in insecure
|
|
18
|
+
* channels, just making it hard enough to not iterate through the entire key space. Half
|
|
19
|
+
* of the the hashid length is nonce and half cryptotext, i.e. 16 char hashid 8 chars of
|
|
20
|
+
* base64 encoded nonce ~ 6 bytes or 48 bits of entropy.
|
|
21
|
+
*
|
|
22
|
+
*/
|
|
23
|
+
export class OINOHashid {
|
|
24
|
+
|
|
25
|
+
private _key:Buffer
|
|
26
|
+
private _iv:Buffer
|
|
27
|
+
private _domainId:string
|
|
28
|
+
private _minLength:number
|
|
29
|
+
private _randomIds
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Hashid constructor
|
|
33
|
+
*
|
|
34
|
+
* @param key AES128 key (32 char hex-string)
|
|
35
|
+
* @param domainId a sufficiently unique domain ID in which row-Id's are unique
|
|
36
|
+
* @param minLength minimum length of nonce and crypto
|
|
37
|
+
* @param randomIds whether hash values should remain static per row or random values
|
|
38
|
+
*
|
|
39
|
+
*/
|
|
40
|
+
constructor (key: string, domainId:string, minLength:number = HASHID_MIN_LENGTH, randomIds:boolean = false) {
|
|
41
|
+
this._domainId = domainId
|
|
42
|
+
if ((minLength < HASHID_MIN_LENGTH) || (minLength > HASHID_MAX_LENGTH)) {
|
|
43
|
+
throw Error("OINOHashid minLength needs to be between " + HASHID_MIN_LENGTH + " and " + HASHID_MAX_LENGTH + "!")
|
|
44
|
+
}
|
|
45
|
+
this._minLength = Math.ceil(minLength/2)
|
|
46
|
+
if (key.length != 32) {
|
|
47
|
+
throw Error("OINOHashid key needs to be a 32 character hex-string!")
|
|
48
|
+
}
|
|
49
|
+
this._randomIds = randomIds
|
|
50
|
+
this._key = Buffer.from(key, 'hex')
|
|
51
|
+
this._iv = new Buffer(16)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Encode given id value as a hashid either using random data or given seed value for nonce.
|
|
56
|
+
*
|
|
57
|
+
* @param id numeric value
|
|
58
|
+
* @param cellSeed a sufficiently unique seed for the current cell to keep hashids unique but persistent (e.g. fieldname + primarykey values)
|
|
59
|
+
*
|
|
60
|
+
*/
|
|
61
|
+
encode(id:string, cellSeed:string = ""):string {
|
|
62
|
+
|
|
63
|
+
// if seed was given use it for pseudorandom chars, otherwise generate them
|
|
64
|
+
let random_chars:string = ""
|
|
65
|
+
if (this._randomIds) {
|
|
66
|
+
randomFillSync(this._iv, 0, 16)
|
|
67
|
+
random_chars = hashidEncoder.encode(this._iv) // this._iv.toString('base64url')
|
|
68
|
+
|
|
69
|
+
} else {
|
|
70
|
+
const hmac_seed = createHmac('sha1', this._key)
|
|
71
|
+
hmac_seed.update(this._domainId + " " + cellSeed)
|
|
72
|
+
random_chars = hashidEncoder.encode(hmac_seed.digest()) // hmac_seed.digest('base64url')
|
|
73
|
+
}
|
|
74
|
+
const hmac = createHmac('sha1', this._key)
|
|
75
|
+
let iv_seed:string = random_chars.substring(0, this._minLength)
|
|
76
|
+
hmac.update(this._domainId + " " + iv_seed)
|
|
77
|
+
const iv_data:Buffer = hmac.digest()
|
|
78
|
+
iv_data.copy(this._iv, 0, 0, 16)
|
|
79
|
+
|
|
80
|
+
let plaintext = id.toString()
|
|
81
|
+
if (plaintext.length < this._minLength) {
|
|
82
|
+
plaintext += " " + random_chars.substring(random_chars.length - (this._minLength - plaintext.length - 1))
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const cipher = createCipheriv('aes-128-gcm', this._key, this._iv)
|
|
86
|
+
const cryptotext = hashidEncoder.encode(cipher.update(plaintext, 'utf8')) + hashidEncoder.encode(cipher.final())
|
|
87
|
+
return iv_seed + cryptotext
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Decode given hashid.
|
|
92
|
+
*
|
|
93
|
+
* @param hashid value
|
|
94
|
+
*
|
|
95
|
+
*/
|
|
96
|
+
decode(hashid:string):string {
|
|
97
|
+
// reproduce nonce from seed
|
|
98
|
+
const hmac = createHmac('sha1', this._key)
|
|
99
|
+
const iv_seed = hashid.substring(0, this._minLength)
|
|
100
|
+
hmac.update(this._domainId + " " + iv_seed)
|
|
101
|
+
const hash:Buffer = hmac.digest()
|
|
102
|
+
hash.copy(this._iv, 0, 0, 16)
|
|
103
|
+
|
|
104
|
+
const cryptotext:string = hashid.substring(this._minLength)
|
|
105
|
+
const cryptobytes:Buffer = new Buffer(hashidEncoder.decode(cryptotext))
|
|
106
|
+
const decipher = createDecipheriv('aes-128-gcm', this._key, this._iv)
|
|
107
|
+
const plaintext = decipher.update(cryptobytes, undefined, 'utf8') //, cryptotext, 'base64url', 'utf8')
|
|
108
|
+
|
|
109
|
+
return plaintext.split(" ")[0]
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { OINOHashid } from "./OINOHashid.js"
|