@databricks/sql 1.15.0 → 1.16.0-rc.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.
Files changed (119) hide show
  1. package/dist/DBSQLClient.d.ts +3 -0
  2. package/dist/DBSQLClient.js +97 -56
  3. package/dist/DBSQLClient.js.map +1 -1
  4. package/dist/DBSQLLogger.d.ts +3 -0
  5. package/dist/DBSQLLogger.js +25 -0
  6. package/dist/DBSQLLogger.js.map +1 -1
  7. package/dist/DBSQLOperation.d.ts +36 -17
  8. package/dist/DBSQLOperation.js +133 -214
  9. package/dist/DBSQLOperation.js.map +1 -1
  10. package/dist/DBSQLParameter.d.ts +2 -0
  11. package/dist/DBSQLParameter.js +63 -7
  12. package/dist/DBSQLParameter.js.map +1 -1
  13. package/dist/DBSQLSession.d.ts +24 -17
  14. package/dist/DBSQLSession.js +45 -263
  15. package/dist/DBSQLSession.js.map +1 -1
  16. package/dist/connection/connections/HttpRetryPolicy.d.ts +3 -0
  17. package/dist/connection/connections/HttpRetryPolicy.js +116 -21
  18. package/dist/connection/connections/HttpRetryPolicy.js.map +1 -1
  19. package/dist/connection/connections/ThriftHttpConnection.js +18 -3
  20. package/dist/connection/connections/ThriftHttpConnection.js.map +1 -1
  21. package/dist/contracts/IBackend.d.ts +31 -0
  22. package/dist/contracts/IBackend.js +3 -0
  23. package/dist/contracts/IBackend.js.map +1 -0
  24. package/dist/contracts/IClientContext.d.ts +1 -0
  25. package/dist/contracts/IDBSQLClient.d.ts +31 -0
  26. package/dist/contracts/IDBSQLLogger.d.ts +17 -0
  27. package/dist/contracts/IDBSQLLogger.js.map +1 -1
  28. package/dist/contracts/IDBSQLSession.d.ts +24 -1
  29. package/dist/contracts/IOperation.d.ts +10 -1
  30. package/dist/contracts/IOperationBackend.d.ts +98 -0
  31. package/dist/contracts/IOperationBackend.js +3 -0
  32. package/dist/contracts/IOperationBackend.js.map +1 -0
  33. package/dist/contracts/ISessionBackend.d.ts +36 -0
  34. package/dist/contracts/ISessionBackend.js +3 -0
  35. package/dist/contracts/ISessionBackend.js.map +1 -0
  36. package/dist/contracts/InternalConnectionOptions.d.ts +72 -0
  37. package/dist/contracts/InternalConnectionOptions.js +3 -0
  38. package/dist/contracts/InternalConnectionOptions.js.map +1 -0
  39. package/dist/contracts/OperationStatus.d.ts +76 -0
  40. package/dist/contracts/OperationStatus.js +28 -0
  41. package/dist/contracts/OperationStatus.js.map +1 -0
  42. package/dist/contracts/ResultMetadata.d.ts +34 -0
  43. package/dist/contracts/ResultMetadata.js +16 -0
  44. package/dist/contracts/ResultMetadata.js.map +1 -0
  45. package/dist/errors/AuthenticationError.d.ts +1 -0
  46. package/dist/errors/AuthenticationError.js +4 -0
  47. package/dist/errors/AuthenticationError.js.map +1 -1
  48. package/dist/kernel/KernelArrowIpc.d.ts +54 -0
  49. package/dist/kernel/KernelArrowIpc.js +292 -0
  50. package/dist/kernel/KernelArrowIpc.js.map +1 -0
  51. package/dist/kernel/KernelArrowIpcDurationFix.d.ts +29 -0
  52. package/dist/kernel/KernelArrowIpcDurationFix.js +605 -0
  53. package/dist/kernel/KernelArrowIpcDurationFix.js.map +1 -0
  54. package/dist/kernel/KernelAuth.d.ts +300 -0
  55. package/dist/kernel/KernelAuth.js +463 -0
  56. package/dist/kernel/KernelAuth.js.map +1 -0
  57. package/dist/kernel/KernelBackend.d.ts +53 -0
  58. package/dist/kernel/KernelBackend.js +164 -0
  59. package/dist/kernel/KernelBackend.js.map +1 -0
  60. package/dist/kernel/KernelErrorMapping.d.ts +109 -0
  61. package/dist/kernel/KernelErrorMapping.js +249 -0
  62. package/dist/kernel/KernelErrorMapping.js.map +1 -0
  63. package/dist/kernel/KernelInputValidation.d.ts +16 -0
  64. package/dist/kernel/KernelInputValidation.js +49 -0
  65. package/dist/kernel/KernelInputValidation.js.map +1 -0
  66. package/dist/kernel/KernelLogging.d.ts +63 -0
  67. package/dist/kernel/KernelLogging.js +128 -0
  68. package/dist/kernel/KernelLogging.js.map +1 -0
  69. package/dist/kernel/KernelNativeLoader.d.ts +77 -0
  70. package/dist/kernel/KernelNativeLoader.js +178 -0
  71. package/dist/kernel/KernelNativeLoader.js.map +1 -0
  72. package/dist/kernel/KernelOperationBackend.d.ts +154 -0
  73. package/dist/kernel/KernelOperationBackend.js +640 -0
  74. package/dist/kernel/KernelOperationBackend.js.map +1 -0
  75. package/dist/kernel/KernelOperationLifecycle.d.ts +130 -0
  76. package/dist/kernel/KernelOperationLifecycle.js +245 -0
  77. package/dist/kernel/KernelOperationLifecycle.js.map +1 -0
  78. package/dist/kernel/KernelPositionalParams.d.ts +16 -0
  79. package/dist/kernel/KernelPositionalParams.js +120 -0
  80. package/dist/kernel/KernelPositionalParams.js.map +1 -0
  81. package/dist/kernel/KernelResultsProvider.d.ts +44 -0
  82. package/dist/kernel/KernelResultsProvider.js +102 -0
  83. package/dist/kernel/KernelResultsProvider.js.map +1 -0
  84. package/dist/kernel/KernelServerInfo.d.ts +44 -0
  85. package/dist/kernel/KernelServerInfo.js +73 -0
  86. package/dist/kernel/KernelServerInfo.js.map +1 -0
  87. package/dist/kernel/KernelSessionBackend.d.ts +100 -0
  88. package/dist/kernel/KernelSessionBackend.js +384 -0
  89. package/dist/kernel/KernelSessionBackend.js.map +1 -0
  90. package/dist/result/ArrowResultConverter.d.ts +31 -2
  91. package/dist/result/ArrowResultConverter.js +226 -14
  92. package/dist/result/ArrowResultConverter.js.map +1 -1
  93. package/dist/result/CloudFetchResultHandler.js +36 -8
  94. package/dist/result/CloudFetchResultHandler.js.map +1 -1
  95. package/dist/telemetry/DatabricksTelemetryExporter.js +34 -1
  96. package/dist/telemetry/DatabricksTelemetryExporter.js.map +1 -1
  97. package/dist/telemetry/telemetryTypeMappers.d.ts +1 -1
  98. package/dist/telemetry/telemetryTypeMappers.js +1 -1
  99. package/dist/telemetry/telemetryTypeMappers.js.map +1 -1
  100. package/dist/telemetry/types.d.ts +15 -0
  101. package/dist/thrift-backend/ThriftBackend.d.ts +17 -0
  102. package/dist/thrift-backend/ThriftBackend.js +80 -0
  103. package/dist/thrift-backend/ThriftBackend.js.map +1 -0
  104. package/dist/thrift-backend/ThriftOperationBackend.d.ts +70 -0
  105. package/dist/thrift-backend/ThriftOperationBackend.js +330 -0
  106. package/dist/thrift-backend/ThriftOperationBackend.js.map +1 -0
  107. package/dist/thrift-backend/ThriftSessionBackend.d.ts +36 -0
  108. package/dist/thrift-backend/ThriftSessionBackend.js +266 -0
  109. package/dist/thrift-backend/ThriftSessionBackend.js.map +1 -0
  110. package/dist/thrift-backend/wireSynthesis.d.ts +30 -0
  111. package/dist/thrift-backend/wireSynthesis.js +128 -0
  112. package/dist/thrift-backend/wireSynthesis.js.map +1 -0
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/version.js.map +1 -1
  116. package/native/kernel/README.md +97 -0
  117. package/native/kernel/index.d.ts +1069 -0
  118. package/native/kernel/index.js +325 -0
  119. package/package.json +13 -2
@@ -0,0 +1,463 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Databricks, Inc.
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.buildKernelConnectionOptions = exports.buildKernelProxyOptions = exports.buildKernelRetryOptions = exports.buildKernelHttpOptions = exports.buildKernelTlsOptions = exports.isBlankOrReserved = void 0;
20
+ const AuthenticationError_1 = __importDefault(require("../errors/AuthenticationError"));
21
+ const HiveDriverError_1 = __importDefault(require("../errors/HiveDriverError"));
22
+ const utils_1 = require("../utils");
23
+ /**
24
+ * Default local listener port for the U2M authorization-code callback.
25
+ * Hardcoded here so the override of the kernel default (8020) to the
26
+ * thrift default (8030) is invariant for kernel callers — preserving parity
27
+ * with the existing Node driver. Not exposed on the public
28
+ * `ConnectionOptions` (thrift hides `callbackPorts` from its public
29
+ * surface too — see nodejs-thrift-expert survey §B.2).
30
+ */
31
+ const U2M_DEFAULT_REDIRECT_PORT = 8030;
32
+ // U2M OAuth scopes default. Matches the standalone Thrift driver's
33
+ // `defaultOAuthScopes` (lib/connection/auth/DatabricksOAuth/OAuthScope.ts):
34
+ // `['sql', 'offline_access']`. The kernel's bare default is
35
+ // `['all-apis', 'offline_access']`; the `databricks-sql-connector` OAuth app is
36
+ // registered for the `sql` scope, so we pass the Thrift-parity scopes explicitly
37
+ // unless the caller overrides via `oauthScopes`.
38
+ const U2M_DEFAULT_SCOPES = ['sql', 'offline_access'];
39
+ // M2M OAuth scopes default. Matches the standalone Thrift driver (`getScopes`
40
+ // forces `['all-apis']` for the client-credentials flow) and the kernel's own
41
+ // M2M default (`m2m.rs` → `['all-apis']`). Overridable via `oauthScopes`
42
+ // (parity with pyo3, which forwards `scopes` on M2M).
43
+ const M2M_DEFAULT_SCOPES = ['all-apis'];
44
+ // Default OAuth client id — identical to the Thrift driver's
45
+ // `DatabricksOAuthManager.defaultClientId` and the kernel napi's own U2M default.
46
+ // Used for `oauthClientId ?? default`, mirroring Thrift's `getClientId()`.
47
+ const DEFAULT_OAUTH_CLIENT_ID = 'databricks-sql-connector';
48
+ function prependSlash(str) {
49
+ if (str.length > 0 && str.charAt(0) !== '/') {
50
+ return `/${str}`;
51
+ }
52
+ return str;
53
+ }
54
+ /**
55
+ * Reject inputs that pass `typeof === 'string' && length > 0` but are
56
+ * structurally useless as credentials: whitespace-only strings, and the
57
+ * literal strings `'undefined'` / `'null'` (case-insensitive) that buggy
58
+ * shell exports (e.g. `export FOO="$UNSET_VAR"`) produce. Surfacing
59
+ * these here means an OAuth flow's `invalid_client` from the workspace
60
+ * is always a real credential mismatch, never a malformed-input passthrough.
61
+ *
62
+ * Exported so the integration-test env-gate can reuse the same predicate
63
+ * and stay in lockstep with production (B-3 fix).
64
+ */
65
+ function isBlankOrReserved(s) {
66
+ const normalized = s.trim().toLowerCase();
67
+ return normalized.length === 0 || normalized === 'undefined' || normalized === 'null';
68
+ }
69
+ exports.isBlankOrReserved = isBlankOrReserved;
70
+ /** napi-rs marshals `maxConnections` as a `u32`; reject values it can't hold. */
71
+ const MAX_U32 = 0xffffffff;
72
+ /**
73
+ * Normalise a PEM input (`string` or `Buffer`) accepted on the public
74
+ * surface into the `Buffer` the napi shape requires. Does a light,
75
+ * ordered BEGIN…END sanity check so a truncated/headerless blob (or a
76
+ * stray page that merely contains the literals out of order, e.g. a
77
+ * proxy-intercept page) is rejected here rather than surfacing as an
78
+ * opaque kernel TLS error. The bytes are NOT fully parsed in JS — that
79
+ * is deferred to the kernel, which returns a meaningful error on a
80
+ * malformed PEM/key.
81
+ *
82
+ * `kind` selects the expected block: `'certificate'` matches a
83
+ * `CERTIFICATE` block; `'private key'` matches any `… PRIVATE KEY` block
84
+ * (PKCS#8 `PRIVATE KEY`, PKCS#1 `RSA PRIVATE KEY`, SEC1 `EC PRIVATE KEY`).
85
+ *
86
+ * Throws `HiveDriverError` when the value is empty or (for strings)
87
+ * lacks the expected PEM header.
88
+ */
89
+ function normalizePemBytes(value, optionName, kind) {
90
+ if (typeof value === 'string') {
91
+ const re = kind === 'certificate'
92
+ ? /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/
93
+ : /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z0-9 ]*PRIVATE KEY-----/;
94
+ if (!re.test(value)) {
95
+ const expected = kind === 'certificate'
96
+ ? "a '-----BEGIN CERTIFICATE-----' … '-----END CERTIFICATE-----' block"
97
+ : "a 'BEGIN … PRIVATE KEY' / 'END … PRIVATE KEY' PEM block (PKCS#8, PKCS#1, or SEC1)";
98
+ throw new HiveDriverError_1.default(`kernel backend: \`${optionName}\` string does not look like a PEM ${kind} (expected ${expected}). ` +
99
+ 'Pass PEM text or a Buffer of PEM bytes.');
100
+ }
101
+ return Buffer.from(value, 'utf8');
102
+ }
103
+ if (Buffer.isBuffer(value)) {
104
+ if (value.length === 0) {
105
+ throw new HiveDriverError_1.default(`kernel backend: \`${optionName}\` Buffer is empty.`);
106
+ }
107
+ return value;
108
+ }
109
+ throw new HiveDriverError_1.default(`kernel backend: \`${optionName}\` must be a PEM string or a Buffer.`);
110
+ }
111
+ /**
112
+ * Normalise the public TLS options into the napi shape.
113
+ *
114
+ * - `checkServerCertificate` passes through verbatim (only when set; an
115
+ * absent value leaves the kernel default, which is secure — verify on).
116
+ * - `checkServerCertificateHostname` passes through verbatim — the
117
+ * independent hostname-vs-SNI toggle (kernel applies it only when the
118
+ * master verify toggle is on). Mirrors Python's `tls_verify_hostname`.
119
+ * - `customCaCert` accepts a PEM string or `Buffer`; normalised to a
120
+ * `Buffer` via {@link normalizePemBytes}.
121
+ * - `clientCertPem` / `clientKeyPem` carry the mutual-TLS client identity.
122
+ * They must be supplied **together** — supplying only one is rejected
123
+ * here with an actionable error (rather than waiting for the kernel's
124
+ * `InvalidArgument` at `openSession`). Each accepts a PEM string or
125
+ * `Buffer`, normalised the same way.
126
+ *
127
+ * Throws `HiveDriverError` when a cert/key is empty, mis-typed, lacks the
128
+ * expected PEM header, or when only one half of the mTLS pair is set.
129
+ */
130
+ function buildKernelTlsOptions(options) {
131
+ // Read the kernel-only fields through the purpose-built internal options type
132
+ // rather than an ad-hoc inline cast, so the shape can't silently drift from
133
+ // its declaration and a typo'd key fails to compile.
134
+ const { checkServerCertificate, checkServerCertificateHostname, customCaCert, clientCertPem, clientKeyPem } = options;
135
+ const tls = {};
136
+ if (checkServerCertificate !== undefined) {
137
+ tls.checkServerCertificate = checkServerCertificate;
138
+ }
139
+ if (checkServerCertificateHostname !== undefined) {
140
+ tls.checkServerCertificateHostname = checkServerCertificateHostname;
141
+ }
142
+ if (customCaCert !== undefined) {
143
+ tls.customCaCert = normalizePemBytes(customCaCert, 'customCaCert', 'certificate');
144
+ }
145
+ // mTLS client identity. Enforce both-or-neither up front so a caller who
146
+ // sets only one gets a clear message naming the missing half, instead of
147
+ // the kernel's generic `InvalidArgument` after the FFI hop.
148
+ const hasCert = clientCertPem !== undefined;
149
+ const hasKey = clientKeyPem !== undefined;
150
+ if (hasCert !== hasKey) {
151
+ throw new HiveDriverError_1.default('kernel backend: mutual TLS requires both `clientCertPem` and `clientKeyPem`; only ' +
152
+ `\`${hasCert ? 'clientCertPem' : 'clientKeyPem'}\` was supplied. ` +
153
+ `Provide the matching ${hasCert ? 'private key (`clientKeyPem`)' : 'certificate (`clientCertPem`)'}, ` +
154
+ 'or omit both.');
155
+ }
156
+ if (hasCert && hasKey) {
157
+ tls.clientCertPem = normalizePemBytes(clientCertPem, 'clientCertPem', 'certificate');
158
+ tls.clientKeyPem = normalizePemBytes(clientKeyPem, 'clientKeyPem', 'private key');
159
+ }
160
+ return tls;
161
+ }
162
+ exports.buildKernelTlsOptions = buildKernelTlsOptions;
163
+ /**
164
+ * Build the napi HTTP options (`customHeaders`) from the public
165
+ * `customHeaders` map and `userAgentEntry`.
166
+ *
167
+ * Mirrors the Python connector's `use_kernel` path (`session.py` +
168
+ * `backend/kernel/client.py`), which:
169
+ * 1. composes a single connector `User-Agent` and **unconditionally**
170
+ * appends it last —
171
+ * `all_headers = (http_headers or []) + [("User-Agent", useragent_header)]`;
172
+ * 2. before forwarding to the kernel, **drops** the kernel-managed
173
+ * reserved names `Authorization` / `x-databricks-org-id`
174
+ * (case-insensitive) — the kernel applies the auth token itself and
175
+ * re-derives the org id from the `?o=` in the http path, and would
176
+ * otherwise skip-and-warn on every request.
177
+ *
178
+ * The result is an ordered list (the napi `Array<HeaderEntry>` shape,
179
+ * matching the kernel core `Vec<(String, String)>`): the caller's
180
+ * `customHeaders` first (minus reserved names), then the connector's
181
+ * `User-Agent` last. The connector UA is always present and, being last,
182
+ * is authoritative (the kernel folds the last `User-Agent` into its base
183
+ * UA — `DatabricksJDBCDriverOSS/...` — preserving the result-disposition
184
+ * gating token). The value is composed via the same `buildUserAgentString`
185
+ * the Thrift path uses, so the kernel UA carries the identical
186
+ * `NodejsDatabricksSqlConnector/...` identity (with `userAgentEntry`
187
+ * folded in). A caller `User-Agent` in `customHeaders` is forwarded too
188
+ * (mirroring Python, which doesn't dedupe it); the kernel's last-wins fold
189
+ * means the connector UA still wins.
190
+ */
191
+ const KERNEL_MANAGED_HEADERS = new Set(['authorization', 'x-databricks-org-id']);
192
+ // CR / LF / NUL in a header name or value enable request-splitting / header
193
+ // injection. The kernel's HTTP client (reqwest) does reject these, but only at
194
+ // connect time and with an opaque "Failed to construct HTTP client:
195
+ // InvalidArgument: failed to parse header value" error that names neither the
196
+ // offending header nor the cause. Reject them here, before the FFI hop, with a
197
+ // clear error so a caller gets actionable signal at the point they set the
198
+ // header (verified against pecotesting: the kernel otherwise surfaces the
199
+ // opaque construction error).
200
+ const FORBIDDEN_HEADER_CHARS = /[\r\n\0]/;
201
+ function validateHeaderToken(kind, headerName, token) {
202
+ if (FORBIDDEN_HEADER_CHARS.test(token)) {
203
+ throw new HiveDriverError_1.default(`kernel backend: customHeaders ${kind} for \`${headerName}\` contains a forbidden control character ` +
204
+ `(CR, LF, or NUL). Such characters enable HTTP header injection and are rejected.`);
205
+ }
206
+ }
207
+ function buildKernelHttpOptions(options) {
208
+ const { customHeaders, userAgentEntry, socketTimeout } = options;
209
+ const headers = [];
210
+ if (customHeaders) {
211
+ for (const [name, value] of Object.entries(customHeaders)) {
212
+ // Reject CR/LF/NUL in either the name or the value before forwarding —
213
+ // a clear, early error instead of the kernel's opaque connect-time throw.
214
+ validateHeaderToken('name', name, name);
215
+ validateHeaderToken('value', name, value);
216
+ // Drop kernel-managed reserved names before the FFI hop — same
217
+ // double-wall as the Python connector's `_KERNEL_MANAGED_HEADERS`.
218
+ if (KERNEL_MANAGED_HEADERS.has(name.toLowerCase())) {
219
+ continue;
220
+ }
221
+ headers.push({ name, value });
222
+ }
223
+ }
224
+ // Always append the connector's composed User-Agent last — exactly the
225
+ // Python connector's unconditional `base_headers` append.
226
+ headers.push({ name: 'User-Agent', value: (0, utils_1.buildUserAgentString)(userAgentEntry) });
227
+ const http = { customHeaders: headers };
228
+ // Per-connection socket read timeout (ms). The public `socketTimeout`
229
+ // ConnectionOption maps onto the kernel napi `socketTimeoutMs`
230
+ // (kernel `HttpConfig::request_timeout` / reqwest `Client::timeout`).
231
+ // Only forward a POSITIVE value: `socketTimeout: 0` means "disabled / wait
232
+ // indefinitely" on the Thrift path, but forwarding `0` would make reqwest
233
+ // time out immediately, so we omit it and let the kernel keep its (large)
234
+ // default — preserving the "effectively no idle timeout" semantics.
235
+ if (typeof socketTimeout === 'number' && socketTimeout > 0) {
236
+ http.socketTimeoutMs = socketTimeout;
237
+ }
238
+ return http;
239
+ }
240
+ exports.buildKernelHttpOptions = buildKernelHttpOptions;
241
+ /**
242
+ * Validate the user-supplied `ConnectionOptions` and build the
243
+ * napi-binding's connection-options shape.
244
+ *
245
+ * Supported auth modes:
246
+ * - PAT: `authType: 'access-token'` (or undefined, which already means
247
+ * PAT throughout the existing driver — see
248
+ * `DBSQLClient.createAuthProvider`).
249
+ * - OAuth M2M: `authType: 'databricks-oauth'` + `oauthClientId` +
250
+ * `oauthClientSecret`. Kernel handles OIDC discovery, client_credentials
251
+ * exchange, and re-auth on expiry internally.
252
+ * - OAuth U2M: `authType: 'databricks-oauth'` + NO `oauthClientId` and
253
+ * NO `oauthClientSecret`. Kernel runs the PKCE auth-code dance (opens
254
+ * a browser, listens on localhost:8030, exchanges the code, persists
255
+ * to `~/.config/databricks-sql-kernel/oauth/{sha256}.json`).
256
+ *
257
+ * **Flow selection — DELIBERATE DIVERGENCE FROM THRIFT.** Thrift's
258
+ * `DBSQLClient.createAuthProvider` (`DBSQLClient.ts:216`) keys off the
259
+ * *secret* (`oauthClientSecret === undefined ? U2M : M2M`), so a custom
260
+ * `oauthClientId` with no secret runs U2M with that id. kernel instead keys
261
+ * off `oauthClientId` *presence* (id present → M2M, absent → U2M). The
262
+ * trade-off: keying off the id means a caller who set an id but
263
+ * typoed/forgot the secret gets the actionable M2M "secret is required"
264
+ * error instead of being silently routed to U2M (which would hide their
265
+ * intent). The cost is two real behavioural gaps vs Thrift:
266
+ * 1. `oauthClientId` + no secret → Thrift runs U2M; kernel throws
267
+ * `AuthenticationError` (M2M secret required).
268
+ * 2. kernel U2M has NO custom-client-id support — the kernel hardcodes
269
+ * `client_id = "databricks-cli"`, and kernel rejects any `oauthClientId`
270
+ * on the U2M arm. Thrift U2M honours a custom `clientId`.
271
+ * Both are documented limitations of the M0 kernel OAuth surface, not bugs.
272
+ *
273
+ * Out of scope on the OAuth paths (rejected with a clear error):
274
+ * - `azureTenantId` / `useDatabricksOAuthInAzure` → Microsoft Entra
275
+ * direct flow. The kernel uses workspace-OIDC discovery (which works
276
+ * against Azure workspaces too — they serve `/oidc/.well-known/...`)
277
+ * and does not implement the Entra-direct scope-rewrite path.
278
+ * - `persistence` on M2M → M2M tokens are not cached (re-issuing is
279
+ * cheap; no refresh token).
280
+ * - `persistence` on U2M → custom token store is a parity gap;
281
+ * requires kernel-side `AuthConfig::External` plumbing. The kernel's
282
+ * auto-disk-cache works for the standard flow today.
283
+ *
284
+ * Ambiguity:
285
+ * - PAT path: rejects when OAuth fields (`oauthClientId` /
286
+ * `oauthClientSecret`) are simultaneously set.
287
+ * - OAuth path: rejects when `token` is set alongside OAuth fields.
288
+ *
289
+ * Throws:
290
+ * - `AuthenticationError` for missing/blank required credentials.
291
+ * - `HiveDriverError` for unsupported auth modes / Azure-direct /
292
+ * custom persistence / ambiguous combinations.
293
+ */
294
+ /**
295
+ * Convert the driver's `ClientConfig` retry knobs (milliseconds, total-attempt
296
+ * count) into the kernel's `ConnectionOptions` retry kwargs (whole seconds).
297
+ * The kernel owns the retry loop on the kernel path, so forwarding these keeps kernel
298
+ * and Thrift governed by one retry config. `retryMaxAttempts` is a TOTAL attempt
299
+ * count on both sides (the kernel converts to retries-after-first internally),
300
+ * so it passes through directly. Sub-second delays round to the nearest second
301
+ * (the kernel's granularity); all values are clamped into the napi `u32` range.
302
+ */
303
+ function buildKernelRetryOptions(config) {
304
+ const msToSecs = (ms) => Math.min(MAX_U32, Math.max(0, Math.round(ms / 1000)));
305
+ const clampU32 = (n) => Math.min(MAX_U32, Math.max(0, Math.trunc(n)));
306
+ // Only forward a knob the connector actually set to a finite number; an
307
+ // absent/garbage value is OMITTED so the kernel keeps its built-in default
308
+ // (rather than emitting NaN across the FFI). A finite-but-negative value is
309
+ // still forwarded and clamped to 0 by the helpers above.
310
+ const out = {};
311
+ if (Number.isFinite(config.retryDelayMin))
312
+ out.retryMinWaitSecs = msToSecs(config.retryDelayMin);
313
+ if (Number.isFinite(config.retryDelayMax))
314
+ out.retryMaxWaitSecs = msToSecs(config.retryDelayMax);
315
+ if (Number.isFinite(config.retryMaxAttempts))
316
+ out.retryMaxAttempts = clampU32(config.retryMaxAttempts);
317
+ if (Number.isFinite(config.retriesTimeout))
318
+ out.retryOverallTimeoutSecs = msToSecs(config.retriesTimeout);
319
+ return out;
320
+ }
321
+ exports.buildKernelRetryOptions = buildKernelRetryOptions;
322
+ /**
323
+ * Map the public `ConnectionOptions.proxy` (`{protocol, host, port, auth}` —
324
+ * the same shape the Thrift backend accepts) onto the kernel's structured napi
325
+ * proxy input. The `url` is composed from `protocol://host:port` (no embedded
326
+ * credentials); `auth.{username,password}` are forwarded as separate
327
+ * basic-auth fields (the kernel applies them via reqwest `Proxy::basic_auth`),
328
+ * avoiding any URL percent-encoding footgun. The `noProxy` host list (a driver
329
+ * option, not on the published `.d.ts`) is forwarded as `bypassHosts`. The
330
+ * kernel accepts only `http://` / `https://`; a SOCKS protocol surfaces a clear
331
+ * kernel error at connect (reqwest SOCKS support is not compiled in).
332
+ */
333
+ function buildKernelProxyOptions(options) {
334
+ var _a, _b;
335
+ const { proxy } = options;
336
+ if (!proxy) {
337
+ return {};
338
+ }
339
+ const { noProxy } = options;
340
+ const out = {
341
+ url: `${proxy.protocol}://${proxy.host}:${proxy.port}`,
342
+ };
343
+ if (((_a = proxy.auth) === null || _a === void 0 ? void 0 : _a.username) !== undefined)
344
+ out.username = proxy.auth.username;
345
+ if (((_b = proxy.auth) === null || _b === void 0 ? void 0 : _b.password) !== undefined)
346
+ out.password = proxy.auth.password;
347
+ if (typeof noProxy === 'string' && noProxy.length > 0)
348
+ out.bypassHosts = noProxy;
349
+ return { proxy: out };
350
+ }
351
+ exports.buildKernelProxyOptions = buildKernelProxyOptions;
352
+ function buildKernelConnectionOptions(options) {
353
+ var _a;
354
+ const { authType } = options;
355
+ const base = {
356
+ hostName: options.host,
357
+ httpPath: prependSlash(options.path),
358
+ // Match the NodeJS Thrift driver, which surfaces INTERVAL columns as
359
+ // strings. The kernel defaults to native Arrow interval/duration types;
360
+ // forcing the string rendering here keeps the kernel path a byte-compatible
361
+ // drop-in. Complex types are intentionally left at the kernel default
362
+ // (native Arrow) — they already decode identically to Thrift via the
363
+ // shared Arrow converter, so `complexTypesAsJson` is not forced on.
364
+ intervalsAsString: true,
365
+ // TLS knobs (server-cert verification toggle + custom CA + mTLS client
366
+ // identity). Validated and normalised (string PEM → Buffer) here so the
367
+ // napi shape only sees a Buffer.
368
+ ...buildKernelTlsOptions(options),
369
+ // HTTP headers (caller `customHeaders` + composed `User-Agent`).
370
+ ...buildKernelHttpOptions(options),
371
+ // HTTP(S) proxy — the same `ConnectionOptions.proxy` the Thrift path uses.
372
+ ...buildKernelProxyOptions(options),
373
+ };
374
+ // kernel-only pool sizing; read via cast to match how this function reads the
375
+ // other kernel-specific options (TLS) — they live on the internal options
376
+ // surface, not the published public `ConnectionOptions` `.d.ts`.
377
+ const { maxConnections } = options;
378
+ if (maxConnections !== undefined) {
379
+ if (!Number.isInteger(maxConnections) || maxConnections < 1) {
380
+ throw new HiveDriverError_1.default(`kernel backend: \`maxConnections\` must be a positive integer; got ${maxConnections}.`);
381
+ }
382
+ if (maxConnections > MAX_U32) {
383
+ throw new HiveDriverError_1.default(`kernel backend: \`maxConnections\` exceeds the napi u32 limit (${MAX_U32}); got ${maxConnections}. ` +
384
+ 'Typical pool sizes are 10-500.');
385
+ }
386
+ base.maxConnections = maxConnections;
387
+ }
388
+ const oauth = options;
389
+ if (authType === undefined || authType === 'access-token') {
390
+ const { token } = options;
391
+ if (typeof token !== 'string' || isBlankOrReserved(token)) {
392
+ throw new AuthenticationError_1.default("kernel backend: a non-empty PAT must be supplied via `token` when using `authType: 'access-token'`.");
393
+ }
394
+ if (oauth.oauthClientId !== undefined || oauth.oauthClientSecret !== undefined) {
395
+ throw new HiveDriverError_1.default('kernel backend: cannot supply both `token` and `oauthClientId`/`oauthClientSecret` ' +
396
+ "on the same connection. Pick one: 'access-token' (PAT) uses `token`; " +
397
+ "'databricks-oauth' uses the OAuth fields.");
398
+ }
399
+ return { ...base, authMode: 'Pat', token };
400
+ }
401
+ if (authType === 'databricks-oauth') {
402
+ if (options.token !== undefined) {
403
+ throw new HiveDriverError_1.default("kernel backend: cannot supply `token` alongside `authType: 'databricks-oauth'`. " +
404
+ "Use `authType: 'access-token'` for PAT, or omit `token` to use OAuth.");
405
+ }
406
+ if (oauth.azureTenantId !== undefined || oauth.useDatabricksOAuthInAzure === true) {
407
+ throw new HiveDriverError_1.default('kernel backend: Azure-direct OAuth (azureTenantId / useDatabricksOAuthInAzure) ' +
408
+ 'is not supported. The workspace-OIDC discovery path handles Azure workspaces ' +
409
+ 'today without these options.');
410
+ }
411
+ // Flow selector + client-id resolution mirror the Thrift driver EXACTLY
412
+ // (`DBSQLClient.createAuthProvider`, DBSQLClient.ts:220):
413
+ // flow = oauthClientSecret === undefined ? U2M : M2M (strict undefined)
414
+ // clientId = oauthClientId ?? defaultClientId (`??` guards null/undefined only)
415
+ // No blank/reserved normalization on the OAuth fields — a present-but-
416
+ // degenerate value (`""`, `"undefined"`, whitespace) is forwarded verbatim,
417
+ // exactly as Thrift forwards it, so the kernel path does not diverge from the
418
+ // Thrift backend. (This intentionally re-imports Thrift's env-stringification
419
+ // behaviour: a secret that resolved to `""`/`"undefined"` counts as a real
420
+ // secret ⇒ M2M, just like Thrift.)
421
+ if (oauth.oauthClientSecret === undefined) {
422
+ // U2M (browser) — no secret, exactly like Thrift.
423
+ if (oauth.persistence !== undefined) {
424
+ throw new HiveDriverError_1.default('kernel backend: `persistence` (custom OAuth token store) is not yet wired through ' +
425
+ 'to the kernel — requires `AuthConfig::External` plumbing. ' +
426
+ 'Today the kernel auto-persists U2M tokens to ' +
427
+ '`~/.config/databricks-sql-kernel/oauth/` which works for the standard flow; ' +
428
+ "the JS-supplied hook (matching thrift's `OAuthPersistence` interface) lands " +
429
+ 'when the kernel exposes it.');
430
+ }
431
+ const u2m = {
432
+ ...base,
433
+ authMode: 'OAuthU2m',
434
+ oauthRedirectPort: U2M_DEFAULT_REDIRECT_PORT,
435
+ // Scopes default to Thrift parity (`sql offline_access`); overridable.
436
+ oauthScopes: Array.isArray(oauth.oauthScopes) && oauth.oauthScopes.length > 0 ? oauth.oauthScopes : U2M_DEFAULT_SCOPES,
437
+ };
438
+ // clientId: Thrift uses `oauthClientId ?? default`. Forward it verbatim
439
+ // when set; when absent the napi applies the same default
440
+ // (`databricks-sql-connector`), so omitting it is identical to Thrift.
441
+ return oauth.oauthClientId !== undefined ? { ...u2m, oauthClientId: oauth.oauthClientId } : u2m;
442
+ }
443
+ // M2M (client credentials) — a secret is present, exactly like Thrift.
444
+ if (oauth.persistence !== undefined) {
445
+ throw new HiveDriverError_1.default('kernel backend: `persistence` is not supported on OAuth M2M ' +
446
+ '(M2M tokens have no refresh token; the kernel re-issues on expiry).');
447
+ }
448
+ return {
449
+ ...base,
450
+ authMode: 'OAuthM2m',
451
+ // Thrift: `getClientId()` = `oauthClientId ?? defaultClientId`.
452
+ oauthClientId: (_a = oauth.oauthClientId) !== null && _a !== void 0 ? _a : DEFAULT_OAUTH_CLIENT_ID,
453
+ oauthClientSecret: oauth.oauthClientSecret,
454
+ // Configurable (parity with pyo3); defaults to `['all-apis']`.
455
+ oauthScopes: Array.isArray(oauth.oauthScopes) && oauth.oauthScopes.length > 0 ? oauth.oauthScopes : M2M_DEFAULT_SCOPES,
456
+ };
457
+ }
458
+ throw new HiveDriverError_1.default(`kernel backend: unsupported auth mode '${authType}'. ` +
459
+ "Supported modes on the kernel backend today: 'access-token' (PAT) and 'databricks-oauth' " +
460
+ '(M2M with oauthClientId+oauthClientSecret, or U2M with neither).');
461
+ }
462
+ exports.buildKernelConnectionOptions = buildKernelConnectionOptions;
463
+ //# sourceMappingURL=KernelAuth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KernelAuth.js","sourceRoot":"","sources":["../../lib/kernel/KernelAuth.ts"],"names":[],"mappings":";AAAA,sCAAsC;AACtC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;AAIjC,wFAAgE;AAChE,gFAAwD;AACxD,oCAAgD;AAEhD;;;;;;;GAOG;AACH,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAEvC,mEAAmE;AACnE,4EAA4E;AAC5E,4DAA4D;AAC5D,gFAAgF;AAChF,iFAAiF;AACjF,iDAAiD;AACjD,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;AAErD,8EAA8E;AAC9E,8EAA8E;AAC9E,yEAAyE;AACzE,sDAAsD;AACtD,MAAM,kBAAkB,GAAG,CAAC,UAAU,CAAC,CAAC;AAExC,6DAA6D;AAC7D,kFAAkF;AAClF,2EAA2E;AAC3E,MAAM,uBAAuB,GAAG,0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iB,EAAE,yBAAyB;gBAC5C,uEAAuE;gBACvE,WAAW,EACT,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,kBAAkB;aAC5G,CAAC;YACF,wEAAwE;YACxE,0DAA0D;YAC1D,uEAAuE;YACvE,OAAO,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;SACjG;QAED,uEAAuE;QACvE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS,EAAE;YACnC,MAAM,IAAI,yBAAe,CACvB,8DAA8D;gBAC5D,qEAAqE,CACxE,CAAC;SACH;QACD,OAAO;YACL,GAAG,IAAI;YACP,QAAQ,EAAE,UAAU;YACpB,gEAAgE;YAChE,aAAa,EAAE,MAAA,KAAK,CAAC,aAAa,mCAAI,uBAAuB;YAC7D,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,+DAA+D;YAC/D,WAAW,EACT,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,kBAAkB;SAC5G,CAAC;KACH;IAED,MAAM,IAAI,yBAAe,CACvB,0CAA0C,QAAQ,KAAK;QACrD,2FAA2F;QAC3F,kEAAkE,CACrE,CAAC;AACJ,CAAC;AAvJD,oEAuJC"}
@@ -0,0 +1,53 @@
1
+ import IBackend from '../contracts/IBackend';
2
+ import ISessionBackend from '../contracts/ISessionBackend';
3
+ import IClientContext from '../contracts/IClientContext';
4
+ import { ConnectionOptions, OpenSessionRequest } from '../contracts/IDBSQLClient';
5
+ import { KernelNativeBinding } from './KernelNativeLoader';
6
+ export interface KernelBackendOptions {
7
+ /**
8
+ * Required. Provides the logger + config the kernel session/operation chain
9
+ * logs through. `DBSQLClient` supplies it via the kernel seam
10
+ * (`new KernelBackend({ context: this })`); unit tests pass a stub. Kept
11
+ * mandatory (rather than an `as IClientContext` downcast of `undefined`)
12
+ * so a missing context is a compile error, not a latent runtime NPE.
13
+ */
14
+ context: IClientContext;
15
+ /**
16
+ * Optional injection seam for unit tests. When provided, replaces the
17
+ * default `getKernelNative()` call so tests can swap in a mock napi
18
+ * binding without loading the `.node` artifact.
19
+ */
20
+ nativeBinding?: KernelNativeBinding;
21
+ }
22
+ /**
23
+ * kernel-backed implementation of `IBackend`.
24
+ *
25
+ * **M0 dispatch model:** the napi binding's `openSession()` already
26
+ * builds a kernel `Session` from PAT + hostname + httpPath, so there is
27
+ * no "connect" round-trip before `openSession` — `connect()` only
28
+ * captures the `ConnectionOptions` and validates that PAT auth is in
29
+ * use. The actual session open happens inside `openSession()`.
30
+ *
31
+ * **Auth validation:** delegates to `buildKernelConnectionOptions` from
32
+ * `KernelAuth`, which mirrors the existing DBSQLClient validation pattern
33
+ * (slash-prepended httpPath, AuthenticationError on missing token or
34
+ * blank OAuth credentials, HiveDriverError on unsupported authType /
35
+ * Azure-direct / ambiguous credential combinations). M2M and U2M
36
+ * routing key off `oauthClientId` presence; see KernelAuth.ts.
37
+ *
38
+ * **Why we don't use IClientContext's connectionProvider here:** that
39
+ * provider is the Thrift HTTP transport. The kernel owns its own
40
+ * reqwest+rustls stack inside the native binding, so there is no
41
+ * NodeJS-level connection state to manage on the kernel path. The
42
+ * `IClientContext` is still useful for logger + config access.
43
+ */
44
+ export default class KernelBackend implements IBackend {
45
+ private readonly context;
46
+ private readonly binding;
47
+ private nativeOptions?;
48
+ private kernelLogUnsubscribe;
49
+ constructor(options: KernelBackendOptions);
50
+ connect(options: ConnectionOptions): Promise<void>;
51
+ openSession(request: OpenSessionRequest): Promise<ISessionBackend>;
52
+ close(): Promise<void>;
53
+ }