postgrejs 2.22.9 → 2.23.0

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.
Files changed (216) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/{esm/connection → connection}/bind-param.js +2 -0
  3. package/{esm/connection → connection}/connection.js +4 -2
  4. package/{esm/connection → connection}/cursor.js +8 -3
  5. package/{esm/connection → connection}/intl-connection.js +6 -3
  6. package/{esm/connection → connection}/pool.js +4 -1
  7. package/{esm/connection → connection}/portal.js +3 -1
  8. package/{esm/connection → connection}/prepared-statement.js +6 -3
  9. package/{esm/constants.js → constants.js} +1 -1
  10. package/{esm/data-type-map.js → data-type-map.js} +2 -2
  11. package/package.json +12 -31
  12. package/{esm/protocol → protocol}/backend.js +1 -0
  13. package/{esm/protocol → protocol}/buffer-reader.js +2 -1
  14. package/{esm/protocol → protocol}/database-error.js +16 -0
  15. package/{esm/protocol → protocol}/frontend.js +1 -0
  16. package/{esm/protocol → protocol}/pg-socket.js +9 -3
  17. package/{esm/protocol → protocol}/smart-buffer.js +9 -5
  18. package/{esm/util → util}/bigint-methods.js +1 -0
  19. package/cjs/connection/bind-param.js +0 -10
  20. package/cjs/connection/connection.js +0 -295
  21. package/cjs/connection/cursor.js +0 -91
  22. package/cjs/connection/intl-connection.js +0 -258
  23. package/cjs/connection/pool.js +0 -236
  24. package/cjs/connection/portal.js +0 -157
  25. package/cjs/connection/prepared-statement.js +0 -226
  26. package/cjs/constants.js +0 -249
  27. package/cjs/data-type-map.js +0 -131
  28. package/cjs/data-types/bool-type.js +0 -33
  29. package/cjs/data-types/box-type.js +0 -52
  30. package/cjs/data-types/bytea-type.js +0 -28
  31. package/cjs/data-types/char-type.js +0 -27
  32. package/cjs/data-types/circle-type.js +0 -51
  33. package/cjs/data-types/date-type.js +0 -75
  34. package/cjs/data-types/float4-type.js +0 -25
  35. package/cjs/data-types/float8-type.js +0 -25
  36. package/cjs/data-types/int2-type.js +0 -26
  37. package/cjs/data-types/int2-vector-type.js +0 -42
  38. package/cjs/data-types/int4-type.js +0 -28
  39. package/cjs/data-types/int8-type.js +0 -36
  40. package/cjs/data-types/json-type.js +0 -40
  41. package/cjs/data-types/jsonb-type.js +0 -44
  42. package/cjs/data-types/lseg-type.js +0 -55
  43. package/cjs/data-types/numeric-type.js +0 -125
  44. package/cjs/data-types/oid-type.js +0 -32
  45. package/cjs/data-types/point-type.js +0 -42
  46. package/cjs/data-types/time-type.js +0 -66
  47. package/cjs/data-types/timestamp-type.js +0 -89
  48. package/cjs/data-types/timestamptz-type.js +0 -76
  49. package/cjs/data-types/uuid-type.js +0 -39
  50. package/cjs/data-types/varchar-type.js +0 -27
  51. package/cjs/index.js +0 -28
  52. package/cjs/interfaces/command-result.js +0 -2
  53. package/cjs/interfaces/data-mapping-options.js +0 -2
  54. package/cjs/interfaces/data-type.js +0 -2
  55. package/cjs/interfaces/database-connection-params.js +0 -2
  56. package/cjs/interfaces/field-info.js +0 -2
  57. package/cjs/interfaces/query-options.js +0 -2
  58. package/cjs/interfaces/query-result.js +0 -2
  59. package/cjs/interfaces/script-execute-options.js +0 -2
  60. package/cjs/interfaces/script-result.js +0 -2
  61. package/cjs/interfaces/statement-prepare-options.js +0 -2
  62. package/cjs/package.json +0 -3
  63. package/cjs/protocol/backend.js +0 -262
  64. package/cjs/protocol/buffer-reader.js +0 -78
  65. package/cjs/protocol/database-error.js +0 -17
  66. package/cjs/protocol/frontend.js +0 -255
  67. package/cjs/protocol/pg-socket.js +0 -367
  68. package/cjs/protocol/protocol.js +0 -71
  69. package/cjs/protocol/sasl.js +0 -108
  70. package/cjs/protocol/smart-buffer.js +0 -178
  71. package/cjs/safe-event-emitter.js +0 -17
  72. package/cjs/tsconfig-build-cjs.tsbuildinfo +0 -1
  73. package/cjs/types.js +0 -2
  74. package/cjs/util/array-calculatedim.js +0 -18
  75. package/cjs/util/bigint-methods.js +0 -44
  76. package/cjs/util/config-from-env.js +0 -29
  77. package/cjs/util/connection-config.js +0 -61
  78. package/cjs/util/convert-row-to-object.js +0 -12
  79. package/cjs/util/decode-binaryarray.js +0 -38
  80. package/cjs/util/encode-binaryarray.js +0 -44
  81. package/cjs/util/escape-literal.js +0 -26
  82. package/cjs/util/fast-parseint.js +0 -31
  83. package/cjs/util/get-parsers.js +0 -41
  84. package/cjs/util/parse-array.js +0 -60
  85. package/cjs/util/parse-datetime.js +0 -37
  86. package/cjs/util/parse-row.js +0 -11
  87. package/cjs/util/parse-time.js +0 -30
  88. package/cjs/util/stringify-arrayliteral.js +0 -37
  89. package/cjs/util/stringify-for-sql.js +0 -29
  90. package/cjs/util/wrap-row-description.js +0 -34
  91. package/esm/package.json +0 -3
  92. package/types/index.d.cts +0 -25
  93. /package/{types/connection → connection}/bind-param.d.ts +0 -0
  94. /package/{types/connection → connection}/connection.d.ts +0 -0
  95. /package/{types/connection → connection}/cursor.d.ts +0 -0
  96. /package/{types/connection → connection}/intl-connection.d.ts +0 -0
  97. /package/{types/connection → connection}/pool.d.ts +0 -0
  98. /package/{types/connection → connection}/portal.d.ts +0 -0
  99. /package/{types/connection → connection}/prepared-statement.d.ts +0 -0
  100. /package/{types/constants.d.ts → constants.d.ts} +0 -0
  101. /package/{types/data-type-map.d.ts → data-type-map.d.ts} +0 -0
  102. /package/{types/data-types → data-types}/bool-type.d.ts +0 -0
  103. /package/{esm/data-types → data-types}/bool-type.js +0 -0
  104. /package/{types/data-types → data-types}/box-type.d.ts +0 -0
  105. /package/{esm/data-types → data-types}/box-type.js +0 -0
  106. /package/{types/data-types → data-types}/bytea-type.d.ts +0 -0
  107. /package/{esm/data-types → data-types}/bytea-type.js +0 -0
  108. /package/{types/data-types → data-types}/char-type.d.ts +0 -0
  109. /package/{esm/data-types → data-types}/char-type.js +0 -0
  110. /package/{types/data-types → data-types}/circle-type.d.ts +0 -0
  111. /package/{esm/data-types → data-types}/circle-type.js +0 -0
  112. /package/{types/data-types → data-types}/date-type.d.ts +0 -0
  113. /package/{esm/data-types → data-types}/date-type.js +0 -0
  114. /package/{types/data-types → data-types}/float4-type.d.ts +0 -0
  115. /package/{esm/data-types → data-types}/float4-type.js +0 -0
  116. /package/{types/data-types → data-types}/float8-type.d.ts +0 -0
  117. /package/{esm/data-types → data-types}/float8-type.js +0 -0
  118. /package/{types/data-types → data-types}/int2-type.d.ts +0 -0
  119. /package/{esm/data-types → data-types}/int2-type.js +0 -0
  120. /package/{types/data-types → data-types}/int2-vector-type.d.ts +0 -0
  121. /package/{esm/data-types → data-types}/int2-vector-type.js +0 -0
  122. /package/{types/data-types → data-types}/int4-type.d.ts +0 -0
  123. /package/{esm/data-types → data-types}/int4-type.js +0 -0
  124. /package/{types/data-types → data-types}/int8-type.d.ts +0 -0
  125. /package/{esm/data-types → data-types}/int8-type.js +0 -0
  126. /package/{types/data-types → data-types}/json-type.d.ts +0 -0
  127. /package/{esm/data-types → data-types}/json-type.js +0 -0
  128. /package/{types/data-types → data-types}/jsonb-type.d.ts +0 -0
  129. /package/{esm/data-types → data-types}/jsonb-type.js +0 -0
  130. /package/{types/data-types → data-types}/lseg-type.d.ts +0 -0
  131. /package/{esm/data-types → data-types}/lseg-type.js +0 -0
  132. /package/{types/data-types → data-types}/numeric-type.d.ts +0 -0
  133. /package/{esm/data-types → data-types}/numeric-type.js +0 -0
  134. /package/{types/data-types → data-types}/oid-type.d.ts +0 -0
  135. /package/{esm/data-types → data-types}/oid-type.js +0 -0
  136. /package/{types/data-types → data-types}/point-type.d.ts +0 -0
  137. /package/{esm/data-types → data-types}/point-type.js +0 -0
  138. /package/{types/data-types → data-types}/time-type.d.ts +0 -0
  139. /package/{esm/data-types → data-types}/time-type.js +0 -0
  140. /package/{types/data-types → data-types}/timestamp-type.d.ts +0 -0
  141. /package/{esm/data-types → data-types}/timestamp-type.js +0 -0
  142. /package/{types/data-types → data-types}/timestamptz-type.d.ts +0 -0
  143. /package/{esm/data-types → data-types}/timestamptz-type.js +0 -0
  144. /package/{types/data-types → data-types}/uuid-type.d.ts +0 -0
  145. /package/{esm/data-types → data-types}/uuid-type.js +0 -0
  146. /package/{types/data-types → data-types}/varchar-type.d.ts +0 -0
  147. /package/{esm/data-types → data-types}/varchar-type.js +0 -0
  148. /package/{types/index.d.ts → index.d.ts} +0 -0
  149. /package/{esm/index.js → index.js} +0 -0
  150. /package/{types/interfaces → interfaces}/command-result.d.ts +0 -0
  151. /package/{esm/interfaces → interfaces}/command-result.js +0 -0
  152. /package/{types/interfaces → interfaces}/data-mapping-options.d.ts +0 -0
  153. /package/{esm/interfaces → interfaces}/data-mapping-options.js +0 -0
  154. /package/{types/interfaces → interfaces}/data-type.d.ts +0 -0
  155. /package/{esm/interfaces → interfaces}/data-type.js +0 -0
  156. /package/{types/interfaces → interfaces}/database-connection-params.d.ts +0 -0
  157. /package/{esm/interfaces → interfaces}/database-connection-params.js +0 -0
  158. /package/{types/interfaces → interfaces}/field-info.d.ts +0 -0
  159. /package/{esm/interfaces → interfaces}/field-info.js +0 -0
  160. /package/{types/interfaces → interfaces}/query-options.d.ts +0 -0
  161. /package/{esm/interfaces → interfaces}/query-options.js +0 -0
  162. /package/{types/interfaces → interfaces}/query-result.d.ts +0 -0
  163. /package/{esm/interfaces → interfaces}/query-result.js +0 -0
  164. /package/{types/interfaces → interfaces}/script-execute-options.d.ts +0 -0
  165. /package/{esm/interfaces → interfaces}/script-execute-options.js +0 -0
  166. /package/{types/interfaces → interfaces}/script-result.d.ts +0 -0
  167. /package/{esm/interfaces → interfaces}/script-result.js +0 -0
  168. /package/{types/interfaces → interfaces}/statement-prepare-options.d.ts +0 -0
  169. /package/{esm/interfaces → interfaces}/statement-prepare-options.js +0 -0
  170. /package/{types/protocol → protocol}/backend.d.ts +0 -0
  171. /package/{types/protocol → protocol}/buffer-reader.d.ts +0 -0
  172. /package/{types/protocol → protocol}/database-error.d.ts +0 -0
  173. /package/{types/protocol → protocol}/frontend.d.ts +0 -0
  174. /package/{types/protocol → protocol}/pg-socket.d.ts +0 -0
  175. /package/{types/protocol → protocol}/protocol.d.ts +0 -0
  176. /package/{esm/protocol → protocol}/protocol.js +0 -0
  177. /package/{types/protocol → protocol}/sasl.d.ts +0 -0
  178. /package/{esm/protocol → protocol}/sasl.js +0 -0
  179. /package/{types/protocol → protocol}/smart-buffer.d.ts +0 -0
  180. /package/{types/safe-event-emitter.d.ts → safe-event-emitter.d.ts} +0 -0
  181. /package/{esm/safe-event-emitter.js → safe-event-emitter.js} +0 -0
  182. /package/{types/types.d.ts → types.d.ts} +0 -0
  183. /package/{esm/types.js → types.js} +0 -0
  184. /package/{types/util → util}/array-calculatedim.d.ts +0 -0
  185. /package/{esm/util → util}/array-calculatedim.js +0 -0
  186. /package/{types/util → util}/bigint-methods.d.ts +0 -0
  187. /package/{types/util → util}/config-from-env.d.ts +0 -0
  188. /package/{esm/util → util}/config-from-env.js +0 -0
  189. /package/{types/util → util}/connection-config.d.ts +0 -0
  190. /package/{esm/util → util}/connection-config.js +0 -0
  191. /package/{types/util → util}/convert-row-to-object.d.ts +0 -0
  192. /package/{esm/util → util}/convert-row-to-object.js +0 -0
  193. /package/{types/util → util}/decode-binaryarray.d.ts +0 -0
  194. /package/{esm/util → util}/decode-binaryarray.js +0 -0
  195. /package/{types/util → util}/encode-binaryarray.d.ts +0 -0
  196. /package/{esm/util → util}/encode-binaryarray.js +0 -0
  197. /package/{types/util → util}/escape-literal.d.ts +0 -0
  198. /package/{esm/util → util}/escape-literal.js +0 -0
  199. /package/{types/util → util}/fast-parseint.d.ts +0 -0
  200. /package/{esm/util → util}/fast-parseint.js +0 -0
  201. /package/{types/util → util}/get-parsers.d.ts +0 -0
  202. /package/{esm/util → util}/get-parsers.js +0 -0
  203. /package/{types/util → util}/parse-array.d.ts +0 -0
  204. /package/{esm/util → util}/parse-array.js +0 -0
  205. /package/{types/util → util}/parse-datetime.d.ts +0 -0
  206. /package/{esm/util → util}/parse-datetime.js +0 -0
  207. /package/{types/util → util}/parse-row.d.ts +0 -0
  208. /package/{esm/util → util}/parse-row.js +0 -0
  209. /package/{types/util → util}/parse-time.d.ts +0 -0
  210. /package/{esm/util → util}/parse-time.js +0 -0
  211. /package/{types/util → util}/stringify-arrayliteral.d.ts +0 -0
  212. /package/{esm/util → util}/stringify-arrayliteral.js +0 -0
  213. /package/{types/util → util}/stringify-for-sql.d.ts +0 -0
  214. /package/{esm/util → util}/stringify-for-sql.js +0 -0
  215. /package/{types/util → util}/wrap-row-description.d.ts +0 -0
  216. /package/{esm/util → util}/wrap-row-description.js +0 -0
@@ -1,367 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PgSocket = void 0;
4
- const tslib_1 = require("tslib");
5
- const node_crypto_1 = tslib_1.__importDefault(require("node:crypto"));
6
- const node_net_1 = tslib_1.__importDefault(require("node:net"));
7
- const node_path_1 = tslib_1.__importDefault(require("node:path"));
8
- const node_tls_1 = tslib_1.__importDefault(require("node:tls"));
9
- const putil_promisify_1 = tslib_1.__importDefault(require("putil-promisify"));
10
- const constants_js_1 = require("../constants.js");
11
- const safe_event_emitter_js_1 = require("../safe-event-emitter.js");
12
- const backend_js_1 = require("./backend.js");
13
- const database_error_js_1 = require("./database-error.js");
14
- const frontend_js_1 = require("./frontend.js");
15
- const protocol_js_1 = require("./protocol.js");
16
- const sasl_js_1 = require("./sasl.js");
17
- const DEFAULT_PORT_NUMBER = 5432;
18
- const COMMAND_RESULT_PATTERN = /^([^\d]+)(?: (\d+)(?: (\d+))?)?$/;
19
- class PgSocket extends safe_event_emitter_js_1.SafeEventEmitter {
20
- constructor(options) {
21
- super();
22
- this.options = options;
23
- this._state = constants_js_1.ConnectionState.CLOSED;
24
- this._backend = new backend_js_1.Backend();
25
- this._sessionParameters = {};
26
- this._frontend = new frontend_js_1.Frontend({ buffer: options.buffer });
27
- this.setMaxListeners(99);
28
- }
29
- get state() {
30
- if (!this._socket || this._socket.destroyed)
31
- this._state = constants_js_1.ConnectionState.CLOSED;
32
- return this._state;
33
- }
34
- get processID() {
35
- return this._processID;
36
- }
37
- get secretKey() {
38
- return this._secretKey;
39
- }
40
- get sessionParameters() {
41
- return this._sessionParameters;
42
- }
43
- connect() {
44
- if (this._socket)
45
- return;
46
- this._state = constants_js_1.ConnectionState.CONNECTING;
47
- const options = this.options;
48
- const socket = (this._socket = new node_net_1.default.Socket());
49
- const errorHandler = (err) => {
50
- this._state = constants_js_1.ConnectionState.CLOSED;
51
- this._removeListeners();
52
- this._reset();
53
- socket.destroy();
54
- this._socket = undefined;
55
- this.emit('error', err);
56
- };
57
- const connectHandler = () => {
58
- socket.setTimeout(0);
59
- if (this.options.keepAlive || this.options.keepAlive == null)
60
- socket.setKeepAlive(true);
61
- socket.write(this._frontend.getSSLRequestMessage());
62
- socket.once('data', x => {
63
- this._removeListeners();
64
- if (x.toString() === 'S') {
65
- const tslOptions = { ...options.ssl, socket };
66
- if (options.host && node_net_1.default.isIP(options.host) === 0)
67
- tslOptions.servername = options.host;
68
- const tlsSocket = (this._socket = node_tls_1.default.connect(tslOptions));
69
- tlsSocket.once('error', errorHandler);
70
- tlsSocket.once('secureConnect', () => {
71
- this._removeListeners();
72
- this._handleConnect();
73
- });
74
- return;
75
- }
76
- if (x.toString() === 'N') {
77
- if (options.requireSSL) {
78
- return errorHandler(new Error('Server does not support SSL connections'));
79
- }
80
- this._removeListeners();
81
- this._handleConnect();
82
- return;
83
- }
84
- return errorHandler(new Error('There was an error establishing an SSL connection'));
85
- });
86
- };
87
- socket.setNoDelay(true);
88
- socket.setTimeout(options.connectTimeoutMs || 30000, () => errorHandler(new Error('Connection timed out')));
89
- socket.once('error', errorHandler);
90
- socket.once('connect', connectHandler);
91
- this.emit('connecting');
92
- const port = options.port || DEFAULT_PORT_NUMBER;
93
- if (options.host && options.host.startsWith('/')) {
94
- socket.connect(node_path_1.default.join(options.host, '/.s.PGSQL.' + port));
95
- }
96
- else
97
- socket.connect(options.port || DEFAULT_PORT_NUMBER, options.host || 'localhost');
98
- }
99
- close() {
100
- if (!this._socket || this._socket.destroyed) {
101
- this._state = constants_js_1.ConnectionState.CLOSED;
102
- this._socket = undefined;
103
- this._reset();
104
- return;
105
- }
106
- if (this._state === constants_js_1.ConnectionState.CLOSING)
107
- return;
108
- const socket = this._socket;
109
- this._state = constants_js_1.ConnectionState.CLOSING;
110
- this._removeListeners();
111
- socket.once('close', () => this._handleClose());
112
- socket.destroy();
113
- }
114
- sendParseMessage(args, cb) {
115
- if (this.listenerCount('debug'))
116
- this.emit('debug', { location: 'PgSocket.sendParseMessage', args });
117
- this._send(this._frontend.getParseMessage(args), cb);
118
- }
119
- sendBindMessage(args, cb) {
120
- if (this.listenerCount('debug'))
121
- this.emit('debug', { location: 'PgSocket.sendBindMessage', args });
122
- this._send(this._frontend.getBindMessage(args), cb);
123
- }
124
- sendDescribeMessage(args, cb) {
125
- if (this.listenerCount('debug'))
126
- this.emit('debug', { location: 'PgSocket.sendDescribeMessage', args });
127
- this._send(this._frontend.getDescribeMessage(args), cb);
128
- }
129
- sendExecuteMessage(args, cb) {
130
- if (this.listenerCount('debug'))
131
- this.emit('debug', { location: 'PgSocket.sendDescribeMessage', args });
132
- this._send(this._frontend.getExecuteMessage(args), cb);
133
- }
134
- sendCloseMessage(args, cb) {
135
- if (this.listenerCount('debug'))
136
- this.emit('debug', { location: 'PgSocket.sendCloseMessage', args });
137
- this._send(this._frontend.getCloseMessage(args), cb);
138
- }
139
- sendQueryMessage(sql, cb) {
140
- if (this.listenerCount('debug'))
141
- this.emit('debug', { location: 'PgSocket.sendQueryMessage', sql });
142
- this._send(this._frontend.getQueryMessage(sql), cb);
143
- }
144
- sendFlushMessage(cb) {
145
- if (this.listenerCount('debug'))
146
- this.emit('debug', { location: 'PgSocket.sendFlushMessage' });
147
- this._send(this._frontend.getFlushMessage(), cb);
148
- }
149
- sendTerminateMessage(cb) {
150
- if (this.listenerCount('debug'))
151
- this.emit('debug', { location: 'PgSocket.sendTerminateMessage' });
152
- this._send(this._frontend.getTerminateMessage(), cb);
153
- }
154
- sendSyncMessage() {
155
- if (this.listenerCount('debug'))
156
- this.emit('debug', { location: 'PgSocket.sendSyncMessage' });
157
- this._send(this._frontend.getSyncMessage());
158
- }
159
- capture(callback) {
160
- if (this._state === constants_js_1.ConnectionState.CLOSING ||
161
- this._state === constants_js_1.ConnectionState.CLOSED) {
162
- return Promise.reject(new Error('Connection closed'));
163
- }
164
- if (this._state !== constants_js_1.ConnectionState.READY)
165
- return Promise.reject(new Error('Connection is not ready'));
166
- return new Promise((resolve, reject) => {
167
- const done = (err, result) => {
168
- this.removeListener('close', closeHandler);
169
- this.removeListener('error', errorHandler);
170
- this.removeListener('message', msgHandler);
171
- if (err)
172
- reject(err);
173
- else
174
- resolve(result);
175
- };
176
- const errorHandler = (err) => {
177
- this.removeListener('close', closeHandler);
178
- this.removeListener('message', msgHandler);
179
- reject(err);
180
- };
181
- const closeHandler = () => {
182
- this.removeListener('error', errorHandler);
183
- this.removeListener('message', msgHandler);
184
- reject(new Error('Connection closed'));
185
- };
186
- const msgHandler = (code, msg) => {
187
- const x = callback(code, msg, done);
188
- if (putil_promisify_1.default.isPromise(x))
189
- x.catch(err => done(err));
190
- };
191
- this.once('close', closeHandler);
192
- this.once('error', errorHandler);
193
- this.on('message', msgHandler);
194
- });
195
- }
196
- _removeListeners() {
197
- if (!this._socket)
198
- return;
199
- this._socket.removeAllListeners('error');
200
- this._socket.removeAllListeners('connect');
201
- this._socket.removeAllListeners('data');
202
- this._socket.removeAllListeners('close');
203
- }
204
- _reset() {
205
- this._backend.reset();
206
- this._sessionParameters = {};
207
- this._processID = undefined;
208
- this._secretKey = undefined;
209
- this._saslSession = undefined;
210
- }
211
- _handleConnect() {
212
- const socket = this._socket;
213
- if (!socket)
214
- return;
215
- this._state = constants_js_1.ConnectionState.AUTHORIZING;
216
- this._reset();
217
- socket.on('data', (data) => this._handleData(data));
218
- socket.on('error', (err) => this._handleError(err));
219
- socket.on('close', () => this._handleClose());
220
- this._send(this._frontend.getStartupMessage({
221
- user: this.options.user || 'postgres',
222
- database: this.options.database || '',
223
- application_name: this.options.applicationName || '',
224
- }));
225
- }
226
- _handleClose() {
227
- this._reset();
228
- this._socket = undefined;
229
- this._state = constants_js_1.ConnectionState.CLOSED;
230
- this.emit('close');
231
- }
232
- _handleError(err) {
233
- if (this._state !== constants_js_1.ConnectionState.READY) {
234
- this._socket?.end();
235
- }
236
- this.emit('error', err);
237
- }
238
- _handleData(data) {
239
- this._backend.parse(data, (code, payload) => {
240
- try {
241
- switch (code) {
242
- case protocol_js_1.Protocol.BackendMessageCode.Authentication:
243
- this._handleAuthenticationMessage(payload);
244
- break;
245
- case protocol_js_1.Protocol.BackendMessageCode.ErrorResponse:
246
- this.emit('error', new database_error_js_1.DatabaseError(payload));
247
- break;
248
- case protocol_js_1.Protocol.BackendMessageCode.NoticeResponse:
249
- this.emit('notice', payload);
250
- break;
251
- case protocol_js_1.Protocol.BackendMessageCode.NotificationResponse:
252
- this.emit('notification', payload);
253
- break;
254
- case protocol_js_1.Protocol.BackendMessageCode.ParameterStatus:
255
- this._handleParameterStatus(payload);
256
- break;
257
- case protocol_js_1.Protocol.BackendMessageCode.BackendKeyData:
258
- this._handleBackendKeyData(payload);
259
- break;
260
- case protocol_js_1.Protocol.BackendMessageCode.ReadyForQuery:
261
- if (this._state !== constants_js_1.ConnectionState.READY) {
262
- this._state = constants_js_1.ConnectionState.READY;
263
- this.emit('ready');
264
- }
265
- else
266
- this.emit('message', code, payload);
267
- break;
268
- case protocol_js_1.Protocol.BackendMessageCode.CommandComplete: {
269
- const msg = this._handleCommandComplete(payload);
270
- this.emit('message', code, msg);
271
- break;
272
- }
273
- default:
274
- this.emit('message', code, payload);
275
- }
276
- }
277
- catch (e) {
278
- this._handleError(e);
279
- }
280
- });
281
- }
282
- _resolvePassword(cb) {
283
- (async () => {
284
- const pass = typeof this.options.password === 'function'
285
- ? await this.options.password()
286
- : this.options.password;
287
- cb(pass || '');
288
- })().catch(err => this._handleError(err));
289
- }
290
- _handleAuthenticationMessage(msg) {
291
- if (!msg) {
292
- this.emit('authenticate');
293
- return;
294
- }
295
- switch (msg.kind) {
296
- case protocol_js_1.Protocol.AuthenticationMessageKind.CleartextPassword:
297
- this._resolvePassword(password => {
298
- this._send(this._frontend.getPasswordMessage(password));
299
- });
300
- break;
301
- case protocol_js_1.Protocol.AuthenticationMessageKind.MD5Password:
302
- this._resolvePassword(password => {
303
- const md5 = (x) => node_crypto_1.default.createHash('md5').update(x, 'utf8').digest('hex');
304
- const l = md5(password + this.options.user);
305
- const r = md5(Buffer.concat([Buffer.from(l), msg.salt]));
306
- const pass = 'md5' + r;
307
- this._send(this._frontend.getPasswordMessage(pass));
308
- });
309
- break;
310
- case protocol_js_1.Protocol.AuthenticationMessageKind.SASL: {
311
- if (!msg.mechanisms.includes('SCRAM-SHA-256')) {
312
- throw new Error('SASL: Only mechanism SCRAM-SHA-256 is currently supported');
313
- }
314
- const saslSession = (this._saslSession = sasl_js_1.SASL.createSession(this.options.user || '', 'SCRAM-SHA-256'));
315
- this._send(this._frontend.getSASLMessage(saslSession));
316
- break;
317
- }
318
- case protocol_js_1.Protocol.AuthenticationMessageKind.SASLContinue: {
319
- const saslSession = this._saslSession;
320
- if (!saslSession)
321
- throw new Error('SASL: Session not started yet');
322
- this._resolvePassword(password => {
323
- sasl_js_1.SASL.continueSession(saslSession, password, msg.data);
324
- const buf = this._frontend.getSASLFinalMessage(saslSession);
325
- this._send(buf);
326
- });
327
- break;
328
- }
329
- case protocol_js_1.Protocol.AuthenticationMessageKind.SASLFinal: {
330
- const session = this._saslSession;
331
- if (!session)
332
- throw new Error('SASL: Session not started yet');
333
- sasl_js_1.SASL.finalizeSession(session, msg.data);
334
- this._saslSession = undefined;
335
- break;
336
- }
337
- default:
338
- break;
339
- }
340
- }
341
- _handleParameterStatus(msg) {
342
- this._sessionParameters[msg.name] = msg.value;
343
- }
344
- _handleBackendKeyData(msg) {
345
- this._processID = msg.processID;
346
- this._secretKey = msg.secretKey;
347
- }
348
- _handleCommandComplete(msg) {
349
- const m = msg.command && msg.command.match(COMMAND_RESULT_PATTERN);
350
- const result = {
351
- command: m[1],
352
- };
353
- if (m[3] != null) {
354
- result.oid = parseInt(m[2], 10);
355
- result.rowCount = parseInt(m[3], 10);
356
- }
357
- else if (m[2])
358
- result.rowCount = parseInt(m[2], 10);
359
- return result;
360
- }
361
- _send(data, cb) {
362
- if (this._socket && this._socket.writable) {
363
- this._socket.write(data, cb);
364
- }
365
- }
366
- }
367
- exports.PgSocket = PgSocket;
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Protocol = void 0;
4
- var Protocol;
5
- (function (Protocol) {
6
- Protocol.VERSION_MAJOR = 3;
7
- Protocol.VERSION_MINOR = 0;
8
- // https://www.postgresql.org/docs/9.3/protocol-message-formats.html
9
- let BackendMessageCode;
10
- (function (BackendMessageCode) {
11
- BackendMessageCode[BackendMessageCode["Authentication"] = 82] = "Authentication";
12
- BackendMessageCode[BackendMessageCode["BackendKeyData"] = 75] = "BackendKeyData";
13
- BackendMessageCode[BackendMessageCode["BindComplete"] = 50] = "BindComplete";
14
- BackendMessageCode[BackendMessageCode["CloseComplete"] = 51] = "CloseComplete";
15
- BackendMessageCode[BackendMessageCode["CommandComplete"] = 67] = "CommandComplete";
16
- BackendMessageCode[BackendMessageCode["CopyData"] = 100] = "CopyData";
17
- BackendMessageCode[BackendMessageCode["CopyDone"] = 99] = "CopyDone";
18
- BackendMessageCode[BackendMessageCode["CopyInResponse"] = 103] = "CopyInResponse";
19
- BackendMessageCode[BackendMessageCode["CopyOutResponse"] = 72] = "CopyOutResponse";
20
- BackendMessageCode[BackendMessageCode["CopyBothResponse"] = 87] = "CopyBothResponse";
21
- BackendMessageCode[BackendMessageCode["DataRow"] = 68] = "DataRow";
22
- BackendMessageCode[BackendMessageCode["EmptyQueryResponse"] = 73] = "EmptyQueryResponse";
23
- BackendMessageCode[BackendMessageCode["ErrorResponse"] = 69] = "ErrorResponse";
24
- BackendMessageCode[BackendMessageCode["FunctionCallResponse"] = 86] = "FunctionCallResponse";
25
- BackendMessageCode[BackendMessageCode["NegotiateProtocolVersion"] = 118] = "NegotiateProtocolVersion";
26
- BackendMessageCode[BackendMessageCode["NoData"] = 110] = "NoData";
27
- BackendMessageCode[BackendMessageCode["NoticeResponse"] = 78] = "NoticeResponse";
28
- BackendMessageCode[BackendMessageCode["NotificationResponse"] = 65] = "NotificationResponse";
29
- BackendMessageCode[BackendMessageCode["ParameterDescription"] = 116] = "ParameterDescription";
30
- BackendMessageCode[BackendMessageCode["ParameterStatus"] = 83] = "ParameterStatus";
31
- BackendMessageCode[BackendMessageCode["ParseComplete"] = 49] = "ParseComplete";
32
- BackendMessageCode[BackendMessageCode["PortalSuspended"] = 115] = "PortalSuspended";
33
- BackendMessageCode[BackendMessageCode["ReadyForQuery"] = 90] = "ReadyForQuery";
34
- BackendMessageCode[BackendMessageCode["RowDescription"] = 84] = "RowDescription";
35
- })(BackendMessageCode = Protocol.BackendMessageCode || (Protocol.BackendMessageCode = {}));
36
- let FrontendMessageCode;
37
- (function (FrontendMessageCode) {
38
- FrontendMessageCode[FrontendMessageCode["Bind"] = 66] = "Bind";
39
- FrontendMessageCode[FrontendMessageCode["Close"] = 67] = "Close";
40
- FrontendMessageCode[FrontendMessageCode["CopyData"] = 100] = "CopyData";
41
- FrontendMessageCode[FrontendMessageCode["CopyDone"] = 99] = "CopyDone";
42
- FrontendMessageCode[FrontendMessageCode["CopyFail"] = 102] = "CopyFail";
43
- FrontendMessageCode[FrontendMessageCode["Describe"] = 68] = "Describe";
44
- FrontendMessageCode[FrontendMessageCode["Execute"] = 69] = "Execute";
45
- FrontendMessageCode[FrontendMessageCode["Flush"] = 72] = "Flush";
46
- FrontendMessageCode[FrontendMessageCode["FunctionCall"] = 70] = "FunctionCall";
47
- FrontendMessageCode[FrontendMessageCode["Parse"] = 80] = "Parse";
48
- FrontendMessageCode[FrontendMessageCode["PasswordMessage"] = 112] = "PasswordMessage";
49
- FrontendMessageCode[FrontendMessageCode["Query"] = 81] = "Query";
50
- FrontendMessageCode[FrontendMessageCode["Sync"] = 83] = "Sync";
51
- FrontendMessageCode[FrontendMessageCode["Terminate"] = 88] = "Terminate";
52
- })(FrontendMessageCode = Protocol.FrontendMessageCode || (Protocol.FrontendMessageCode = {}));
53
- let AuthenticationMessageKind;
54
- (function (AuthenticationMessageKind) {
55
- AuthenticationMessageKind["KerberosV5"] = "KerberosV5";
56
- AuthenticationMessageKind["CleartextPassword"] = "CleartextPassword";
57
- AuthenticationMessageKind["MD5Password"] = "MD5Password";
58
- AuthenticationMessageKind["SCMCredential"] = "SCMCredential";
59
- AuthenticationMessageKind["GSS"] = "GSS";
60
- AuthenticationMessageKind["SSPI"] = "SSPI";
61
- AuthenticationMessageKind["GSSContinue"] = "GSSContinue";
62
- AuthenticationMessageKind["SASL"] = "SASL";
63
- AuthenticationMessageKind["SASLContinue"] = "SASLContinue";
64
- AuthenticationMessageKind["SASLFinal"] = "SASLFinal";
65
- })(AuthenticationMessageKind = Protocol.AuthenticationMessageKind || (Protocol.AuthenticationMessageKind = {}));
66
- let DataFormat;
67
- (function (DataFormat) {
68
- DataFormat[DataFormat["text"] = 0] = "text";
69
- DataFormat[DataFormat["binary"] = 1] = "binary";
70
- })(DataFormat = Protocol.DataFormat || (Protocol.DataFormat = {}));
71
- })(Protocol || (exports.Protocol = Protocol = {}));
@@ -1,108 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SASL = void 0;
4
- const tslib_1 = require("tslib");
5
- const crypto_1 = tslib_1.__importDefault(require("crypto"));
6
- var SASL;
7
- (function (SASL) {
8
- const CLIENT_KEY = 'Client Key';
9
- const SERVER_KEY = 'Server Key';
10
- const GS2_HEADER = 'n,,';
11
- function createSession(username, mechanism) {
12
- const nonce = crypto_1.default.randomBytes(18).toString('base64');
13
- const clientFirstMessage = `${GS2_HEADER}${firstMessageBare(username, nonce)}`;
14
- return {
15
- username,
16
- mechanism,
17
- nonce,
18
- clientFirstMessage,
19
- };
20
- }
21
- SASL.createSession = createSession;
22
- function continueSession(session, password, data) {
23
- const s = data.toString();
24
- const items = s.split(',');
25
- let nonce = '';
26
- let salt = '';
27
- let iteration = 0;
28
- for (const i of items) {
29
- switch (i[0]) {
30
- case 'r':
31
- nonce = i.substring(2);
32
- break;
33
- case 's':
34
- salt = i.substring(2);
35
- break;
36
- case 'i':
37
- iteration = parseInt(i.substring(2), 10);
38
- break;
39
- default:
40
- break;
41
- }
42
- }
43
- if (!nonce)
44
- throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing');
45
- if (!salt)
46
- throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing');
47
- if (!iteration)
48
- throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing');
49
- if (!nonce.startsWith(session.nonce))
50
- throw new Error('SASL: Server nonce does not start with client nonce');
51
- const serverFirstMessage = `r=${nonce},s=${salt},i=${iteration}`;
52
- const clientFinalMessageWithoutProof = `c=${encode64(GS2_HEADER)},r=${nonce}`;
53
- const authMessage = `${firstMessageBare(session.username, session.nonce)},${serverFirstMessage},${clientFinalMessageWithoutProof}`;
54
- const saltPass = hi(password, salt, iteration);
55
- const clientKey = hmac(saltPass, CLIENT_KEY);
56
- const storedKey = hash(clientKey);
57
- const clientSignature = hmac(storedKey, authMessage);
58
- const clientProofBytes = xor(clientKey, clientSignature);
59
- const clientProof = clientProofBytes.toString('base64');
60
- const serverKey = hmac(saltPass, SERVER_KEY);
61
- const serverSignatureBytes = hmac(serverKey, authMessage);
62
- session.serverSignature = serverSignatureBytes.toString('base64');
63
- session.clientFinalMessage =
64
- clientFinalMessageWithoutProof + ',p=' + clientProof;
65
- }
66
- SASL.continueSession = continueSession;
67
- function finalizeSession(session, data) {
68
- let serverSignature = '';
69
- const arr = data.split(',');
70
- for (const s of arr) {
71
- if (s[0] === 'v')
72
- serverSignature = s.substr(2);
73
- }
74
- if (serverSignature !== session.serverSignature)
75
- throw new Error('SASL: Server signature does not match');
76
- }
77
- SASL.finalizeSession = finalizeSession;
78
- const firstMessageBare = function (username, nonce) {
79
- return `n=${username},r=${nonce}`;
80
- };
81
- /**
82
- * Hi() is, essentially, PBKDF2 [RFC2898] with HMAC() as the
83
- * pseudorandom function (PRF) and with dkLen == output length of
84
- * HMAC() == output length of H()
85
- */
86
- const hi = function (text, salt, iterations) {
87
- return crypto_1.default.pbkdf2Sync(text, Buffer.from(salt, 'base64'), iterations, 32, 'sha256');
88
- };
89
- const encode64 = (str) => Buffer.from(str).toString('base64');
90
- const hmac = function (key, msg) {
91
- return crypto_1.default.createHmac('sha256', key).update(msg).digest();
92
- };
93
- const hash = function (data) {
94
- return crypto_1.default.createHash('sha256').update(data).digest();
95
- };
96
- const xor = function (a, b) {
97
- a = Buffer.isBuffer(a) ? a : Buffer.from(a);
98
- b = Buffer.isBuffer(b) ? b : Buffer.from(b);
99
- if (a.length !== b.length)
100
- throw new Error('Buffers must be of the same length');
101
- const l = a.length;
102
- const out = Buffer.allocUnsafe(l);
103
- for (let i = 0; i < l; i++) {
104
- out[i] = a[i] ^ b[i];
105
- }
106
- return out;
107
- };
108
- })(SASL || (exports.SASL = SASL = {}));