@cclabsnz/sf-core 0.11.0 → 0.13.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.
- package/CHANGELOG.md +89 -2
- package/README.md +36 -4
- package/lib/api/ApiError.d.ts +33 -1
- package/lib/api/ApiError.js +81 -3
- package/lib/api/MetadataClientImpl.js +8 -1
- package/lib/api/RestClientImpl.js +19 -19
- package/lib/api/SoqlClientImpl.d.ts +3 -1
- package/lib/api/SoqlClientImpl.js +24 -9
- package/lib/api/ToolingClientImpl.d.ts +3 -1
- package/lib/api/ToolingClientImpl.js +18 -15
- package/lib/api/fetch/FetchRestClient.d.ts +11 -0
- package/lib/api/fetch/FetchRestClient.js +23 -0
- package/lib/api/fetch/FetchSoqlClient.d.ts +13 -0
- package/lib/api/fetch/FetchSoqlClient.js +22 -0
- package/lib/api/fetch/FetchToolingClient.d.ts +12 -0
- package/lib/api/fetch/FetchToolingClient.js +18 -0
- package/lib/api/fetch/FetchTransport.d.ts +44 -0
- package/lib/api/fetch/FetchTransport.js +96 -0
- package/lib/api/fetch/index.d.ts +31 -0
- package/lib/api/fetch/index.js +32 -0
- package/lib/api/fetch/jwtBearer.d.ts +43 -0
- package/lib/api/fetch/jwtBearer.js +115 -0
- package/lib/api/index.d.ts +2 -1
- package/lib/api/index.js +1 -1
- package/lib/api/paging.d.ts +25 -0
- package/lib/api/paging.js +62 -0
- package/lib/api/streamToFile.d.ts +7 -0
- package/lib/api/streamToFile.js +22 -0
- package/lib/crypto/bundleCrypto.d.ts +30 -1
- package/lib/crypto/bundleCrypto.js +269 -9
- package/lib/events/eventLogAccess.js +5 -2
- package/lib/fetch.d.ts +7 -0
- package/lib/fetch.js +4 -0
- package/lib/graph/validate.js +1 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/storage/ObjectStore.d.ts +26 -0
- package/lib/storage/ObjectStore.js +2 -0
- package/lib/storage/S3ObjectStoreImpl.d.ts +12 -0
- package/lib/storage/S3ObjectStoreImpl.js +122 -0
- package/lib/storage/errors.d.ts +11 -0
- package/lib/storage/errors.js +19 -0
- package/lib/storage/index.d.ts +7 -0
- package/lib/storage/index.js +4 -0
- package/lib/storage/s3Location.d.ts +29 -0
- package/lib/storage/s3Location.js +63 -0
- package/lib/storage/testing/MemoryObjectStore.d.ts +32 -0
- package/lib/storage/testing/MemoryObjectStore.js +79 -0
- package/lib/storage.d.ts +2 -0
- package/lib/storage.js +4 -0
- package/lib/storageTesting.d.ts +2 -0
- package/lib/storageTesting.js +3 -0
- package/package.json +25 -2
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { apiErrorFromResponse } from '../ApiError.js';
|
|
2
|
+
/**
|
|
3
|
+
* The fetch path's single door to the org: URL building, bearer header, timeout, one re-auth
|
|
4
|
+
* after a 401, and error mapping. GET only; there is deliberately no other verb here.
|
|
5
|
+
*/
|
|
6
|
+
export class FetchTransport {
|
|
7
|
+
authFn;
|
|
8
|
+
apiVersion;
|
|
9
|
+
// Named `fetch` so the read-only invariant's scanner sees the one call site in send().
|
|
10
|
+
fetch;
|
|
11
|
+
timeoutMs;
|
|
12
|
+
token;
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
this.authFn = opts.auth;
|
|
15
|
+
this.apiVersion = opts.apiVersion;
|
|
16
|
+
this.fetch = opts.fetch ?? globalThis.fetch;
|
|
17
|
+
this.timeoutMs = opts.timeoutMs ?? 120_000;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* GETs `path`. A path starting `/services/` is used as-is (a `nextRecordsUrl`, or `/services/data/`);
|
|
21
|
+
* any other path is prefixed with the versioned data root, matching RestClientImpl.
|
|
22
|
+
*
|
|
23
|
+
* A timeout surfaces as a TimeoutError DOMException (as AbortSignal.timeout raises), deliberately not converted
|
|
24
|
+
* to an ApiError: it is not a Salesforce error response and carries no errorCode.
|
|
25
|
+
*/
|
|
26
|
+
async get(path, accept = 'application/json') {
|
|
27
|
+
const used = this.currentToken();
|
|
28
|
+
const res = await this.send(await used, path, accept);
|
|
29
|
+
if (res.ok)
|
|
30
|
+
return res;
|
|
31
|
+
if (res.status === 401) {
|
|
32
|
+
// Release the 401's socket before the retry; its body says nothing the retry won't.
|
|
33
|
+
await res.body?.cancel().catch(() => undefined);
|
|
34
|
+
// Each call gets at most one re-auth, and concurrent 401s on the same token share one exchange.
|
|
35
|
+
const retry = await this.send(await this.refreshedToken(used), path, accept);
|
|
36
|
+
if (retry.ok)
|
|
37
|
+
return retry;
|
|
38
|
+
throw await apiErrorFromResponse(retry);
|
|
39
|
+
}
|
|
40
|
+
throw await apiErrorFromResponse(res);
|
|
41
|
+
}
|
|
42
|
+
async getJson(path) {
|
|
43
|
+
const res = await this.get(path);
|
|
44
|
+
return (await res.json());
|
|
45
|
+
}
|
|
46
|
+
async getText(path) {
|
|
47
|
+
const res = await this.get(path, '*/*');
|
|
48
|
+
return res.text();
|
|
49
|
+
}
|
|
50
|
+
/** The org's clock, from the Date header of the `/services/data/` listing. */
|
|
51
|
+
async serverDate() {
|
|
52
|
+
const res = await this.get('/services/data/');
|
|
53
|
+
const header = res.headers.get('date');
|
|
54
|
+
const parsed = header === null ? new Date(Number.NaN) : new Date(header);
|
|
55
|
+
if (Number.isNaN(parsed.getTime()))
|
|
56
|
+
throw new Error('the org response carried no usable Date header');
|
|
57
|
+
return parsed;
|
|
58
|
+
}
|
|
59
|
+
/** The cached token, fetched lazily on first use and shared by concurrent first calls. */
|
|
60
|
+
currentToken() {
|
|
61
|
+
this.token ??= this.startAuth();
|
|
62
|
+
return this.token;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A token to retry with after `used` drew a 401. Only the first caller holding `used` starts a new
|
|
66
|
+
* exchange; any later one finds the cache already moved on and reuses that.
|
|
67
|
+
*/
|
|
68
|
+
refreshedToken(used) {
|
|
69
|
+
if (this.token === used || this.token === undefined)
|
|
70
|
+
this.token = this.startAuth();
|
|
71
|
+
return this.token;
|
|
72
|
+
}
|
|
73
|
+
startAuth() {
|
|
74
|
+
const fresh = this.authFn();
|
|
75
|
+
// A failed auth must not be cached, or every later call would fail with the same rejection.
|
|
76
|
+
fresh.catch(() => {
|
|
77
|
+
if (this.token === fresh)
|
|
78
|
+
this.token = undefined;
|
|
79
|
+
});
|
|
80
|
+
return fresh;
|
|
81
|
+
}
|
|
82
|
+
send(token, path, accept) {
|
|
83
|
+
const rel = path.startsWith('/services/')
|
|
84
|
+
? path
|
|
85
|
+
: `/services/data/v${this.apiVersion}${path.startsWith('/') ? '' : '/'}${path}`;
|
|
86
|
+
// The timer covers time to response headers only and is cleared once they arrive (or the call
|
|
87
|
+
// fails), so a large body, such as an EventLogFile, streams with no time limit.
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const timer = setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), this.timeoutMs);
|
|
90
|
+
return this.fetch(`${token.instanceUrl}${rel}`, {
|
|
91
|
+
headers: { Authorization: `Bearer ${token.accessToken}`, Accept: accept },
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
}).finally(() => clearTimeout(timer));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=FetchTransport.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { type AccessToken, type JwtBearerConfig } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export type { FetchTransportOptions } from './FetchTransport.js';
|
|
11
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
12
|
+
export type { AccessToken, JwtBearerConfig, Signer } from './jwtBearer.js';
|
|
13
|
+
export type { PagingOptions } from '../paging.js';
|
|
14
|
+
export interface CreateFetchClientsOptions {
|
|
15
|
+
/** A JWT bearer config, or your own token source. */
|
|
16
|
+
auth: JwtBearerConfig | (() => Promise<AccessToken>);
|
|
17
|
+
/** API version without the leading `v`, e.g. '64.0'. */
|
|
18
|
+
apiVersion: string;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
/** Page cap for queryAll and Tooling query, child relationship pages included. Defaults to 200. */
|
|
22
|
+
maxPages?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
25
|
+
export declare function createFetchClients(opts: CreateFetchClientsOptions): {
|
|
26
|
+
soql: FetchSoqlClient;
|
|
27
|
+
tooling: FetchToolingClient;
|
|
28
|
+
rest: FetchRestClient;
|
|
29
|
+
transport: FetchTransport;
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { jwtBearerToken } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
11
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
12
|
+
export function createFetchClients(opts) {
|
|
13
|
+
const auth = typeof opts.auth === 'function'
|
|
14
|
+
? opts.auth
|
|
15
|
+
: (() => {
|
|
16
|
+
const config = opts.auth;
|
|
17
|
+
return () => jwtBearerToken(config, { fetch: opts.fetch });
|
|
18
|
+
})();
|
|
19
|
+
const transport = new FetchTransport({
|
|
20
|
+
auth,
|
|
21
|
+
apiVersion: opts.apiVersion,
|
|
22
|
+
fetch: opts.fetch,
|
|
23
|
+
timeoutMs: opts.timeoutMs,
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
soql: new FetchSoqlClient(transport, { maxPages: opts.maxPages }),
|
|
27
|
+
tooling: new FetchToolingClient(transport, { maxPages: opts.maxPages }),
|
|
28
|
+
rest: new FetchRestClient(transport),
|
|
29
|
+
transport,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** The global fetch signature, named once so the call site below can shadow `fetch` locally. */
|
|
2
|
+
type FetchFn = typeof fetch;
|
|
3
|
+
/** Signs the JWT signing input with RS256 and returns the raw signature bytes. */
|
|
4
|
+
export type Signer = (signingInput: string) => Promise<Buffer>;
|
|
5
|
+
/**
|
|
6
|
+
* A signer over a PEM held in this process.
|
|
7
|
+
*
|
|
8
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
9
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
10
|
+
* cause, so they are restored here.
|
|
11
|
+
*/
|
|
12
|
+
export declare function pemSigner(privateKeyPem: string): Signer;
|
|
13
|
+
export interface JwtBearerConfig {
|
|
14
|
+
/** External Client App consumer key. Becomes the JWT `iss`. */
|
|
15
|
+
clientId: string;
|
|
16
|
+
/** The Salesforce username to run as. Becomes the JWT `sub`. */
|
|
17
|
+
username: string;
|
|
18
|
+
/** Token endpoint host: login.salesforce.com, test.salesforce.com or a My Domain URL. */
|
|
19
|
+
loginUrl: string;
|
|
20
|
+
/** The `aud` claim. Defaults to `loginUrl`. */
|
|
21
|
+
audience?: string;
|
|
22
|
+
sign: Signer;
|
|
23
|
+
}
|
|
24
|
+
export interface AccessToken {
|
|
25
|
+
accessToken: string;
|
|
26
|
+
instanceUrl: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
30
|
+
*
|
|
31
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
32
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
33
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
34
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
35
|
+
*
|
|
36
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
37
|
+
*/
|
|
38
|
+
export declare function jwtBearerToken(config: JwtBearerConfig, deps?: {
|
|
39
|
+
fetch?: FetchFn;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
}): Promise<AccessToken>;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=jwtBearer.d.ts.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createSign } from 'node:crypto';
|
|
2
|
+
import { SalesforceApiError } from '../ApiError.js';
|
|
3
|
+
/**
|
|
4
|
+
* A signer over a PEM held in this process.
|
|
5
|
+
*
|
|
6
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
7
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
8
|
+
* cause, so they are restored here.
|
|
9
|
+
*/
|
|
10
|
+
export function pemSigner(privateKeyPem) {
|
|
11
|
+
const pem = privateKeyPem.replace(/\\n/g, '\n');
|
|
12
|
+
if (pem.trim() === '') {
|
|
13
|
+
throw new Error("The JWT signing key is empty. It is the private half of the certificate uploaded to the org's " +
|
|
14
|
+
'External Client App; without it the org cannot be reached.');
|
|
15
|
+
}
|
|
16
|
+
// Synchronous under the hood, and deliberately still a promise: other signers (a KMS) are network calls.
|
|
17
|
+
return (signingInput) => Promise.resolve(createSign('RSA-SHA256').update(signingInput).sign(pem));
|
|
18
|
+
}
|
|
19
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
|
|
20
|
+
/** base64url without padding, as JWS requires. */
|
|
21
|
+
const b64url = (input) => (typeof input === 'string' ? Buffer.from(input, 'utf8') : input)
|
|
22
|
+
.toString('base64url');
|
|
23
|
+
const truncate = (s, max = 300) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
|
|
24
|
+
/**
|
|
25
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
26
|
+
*
|
|
27
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
28
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
29
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
30
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
31
|
+
*
|
|
32
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
33
|
+
*/
|
|
34
|
+
export async function jwtBearerToken(config, deps = {}) {
|
|
35
|
+
// The assertion is a three-minute bearer credential; never let it travel over cleartext.
|
|
36
|
+
let loginProtocol;
|
|
37
|
+
try {
|
|
38
|
+
loginProtocol = new URL(config.loginUrl).protocol;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
loginProtocol = undefined;
|
|
42
|
+
}
|
|
43
|
+
if (loginProtocol !== 'https:') {
|
|
44
|
+
throw new SalesforceApiError('INVALID_LOGIN_URL', 'The login URL must be a valid https URL; nothing was signed or sent.');
|
|
45
|
+
}
|
|
46
|
+
const now = deps.now ?? Date.now;
|
|
47
|
+
const header = b64url(JSON.stringify({ alg: 'RS256' }));
|
|
48
|
+
const claims = b64url(JSON.stringify({
|
|
49
|
+
iss: config.clientId,
|
|
50
|
+
sub: config.username,
|
|
51
|
+
aud: config.audience ?? config.loginUrl,
|
|
52
|
+
exp: Math.floor(now() / 1000) + 180,
|
|
53
|
+
}));
|
|
54
|
+
const signingInput = `${header}.${claims}`;
|
|
55
|
+
const assertion = `${signingInput}.${b64url(await config.sign(signingInput))}`;
|
|
56
|
+
const body = new URLSearchParams({
|
|
57
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
58
|
+
assertion,
|
|
59
|
+
}).toString();
|
|
60
|
+
const fetch = deps.fetch ?? globalThis.fetch;
|
|
61
|
+
const res = await fetch(`${config.loginUrl.replace(/\/$/, '')}/services/oauth2/token`, {
|
|
62
|
+
method: 'POST', // invariant:allow — OAuth token exchange; authenticates, writes no org data
|
|
63
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
64
|
+
body,
|
|
65
|
+
});
|
|
66
|
+
const text = await res.text();
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(text);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new SalesforceApiError('TOKEN_ENDPOINT_NOT_JSON', truncate(text), { statusCode: res.status });
|
|
73
|
+
}
|
|
74
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
75
|
+
parsed = {};
|
|
76
|
+
if (!res.ok || typeof parsed.access_token !== 'string' || parsed.access_token === '') {
|
|
77
|
+
// Never carry a token into details, even on a failed response.
|
|
78
|
+
const { access_token: _dropped, ...safe } = parsed;
|
|
79
|
+
throw new SalesforceApiError(str(parsed.error) ?? 'TOKEN_REQUEST_FAILED', explainTokenError(parsed), {
|
|
80
|
+
statusCode: res.status,
|
|
81
|
+
details: safe,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const instanceUrl = (parsed.instance_url ?? '').replace(/\/$/, '');
|
|
85
|
+
let protocol;
|
|
86
|
+
try {
|
|
87
|
+
protocol = new URL(instanceUrl).protocol;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
protocol = undefined;
|
|
91
|
+
}
|
|
92
|
+
if (protocol !== 'https:') {
|
|
93
|
+
throw new SalesforceApiError('INVALID_INSTANCE_URL', 'The token endpoint returned an instance_url that is missing or not https; refusing to send the access token there.', { statusCode: res.status });
|
|
94
|
+
}
|
|
95
|
+
return { accessToken: parsed.access_token, instanceUrl };
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The JWT bearer flow's failures are opaque: `invalid_grant` covers at least four unrelated
|
|
99
|
+
* misconfigurations. The two that actually happen are named here.
|
|
100
|
+
*/
|
|
101
|
+
function explainTokenError(parsed) {
|
|
102
|
+
const base = str(parsed.error_description) ?? str(parsed.error) ?? 'The token request failed.';
|
|
103
|
+
if (parsed.error === 'invalid_grant') {
|
|
104
|
+
return (`${base} (for the JWT bearer flow this usually means one of: the user is not pre-authorised ` +
|
|
105
|
+
'for the External Client App (assign the permission set, or set the app policy to admin-approved ' +
|
|
106
|
+
'users); the certificate in the External Client App does not match the signing private key; the ' +
|
|
107
|
+
'username is wrong for this org; or the app was saved less than ten minutes ago and has not ' +
|
|
108
|
+
'propagated yet.)');
|
|
109
|
+
}
|
|
110
|
+
if (parsed.error === 'invalid_client_id') {
|
|
111
|
+
return `${base} (the consumer key does not match an External Client App in this org.)`;
|
|
112
|
+
}
|
|
113
|
+
return base;
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=jwtBearer.js.map
|
package/lib/api/index.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ export type { QueryResult, SoqlClient } from './SoqlClient.js';
|
|
|
2
2
|
export type { ToolingClient } from './ToolingClient.js';
|
|
3
3
|
export type { RestClient } from './RestClient.js';
|
|
4
4
|
export type { ApiError } from './ApiError.js';
|
|
5
|
-
export {
|
|
5
|
+
export type { PagingOptions } from './paging.js';
|
|
6
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
6
7
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
7
8
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
8
9
|
export { RestClientImpl } from './RestClientImpl.js';
|
package/lib/api/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { isApiError } from './ApiError.js';
|
|
1
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
2
2
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
3
3
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
4
4
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** One page of a SOQL or Tooling query response, in Salesforce's own shape. */
|
|
2
|
+
export interface QueryPage<T> {
|
|
3
|
+
totalSize: number;
|
|
4
|
+
done: boolean;
|
|
5
|
+
records: T[];
|
|
6
|
+
nextRecordsUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
9
|
+
export declare const MAX_QUERY_PAGES = 200;
|
|
10
|
+
/** Options for the query clients' paging. */
|
|
11
|
+
export interface PagingOptions {
|
|
12
|
+
/** Most pages one queryAll may follow, child relationship pages included. Defaults to MAX_QUERY_PAGES. */
|
|
13
|
+
maxPages?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
17
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
18
|
+
*
|
|
19
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
20
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
21
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
22
|
+
* toward the page cap.
|
|
23
|
+
*/
|
|
24
|
+
export declare function collectPages<T>(first: QueryPage<T>, fetchNext: (nextRecordsUrl: string) => Promise<QueryPage<T>>, opts?: PagingOptions): Promise<T[]>;
|
|
25
|
+
//# sourceMappingURL=paging.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { SalesforceApiError } from './ApiError.js';
|
|
2
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
3
|
+
export const MAX_QUERY_PAGES = 200;
|
|
4
|
+
/**
|
|
5
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
6
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
7
|
+
*
|
|
8
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
9
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
10
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
11
|
+
* toward the page cap.
|
|
12
|
+
*/
|
|
13
|
+
export async function collectPages(first, fetchNext, opts = {}) {
|
|
14
|
+
const maxPages = opts.maxPages ?? MAX_QUERY_PAGES;
|
|
15
|
+
if (!Number.isInteger(maxPages) || maxPages < 1) {
|
|
16
|
+
throw new RangeError(`maxPages must be a positive integer; got ${String(maxPages)}.`);
|
|
17
|
+
}
|
|
18
|
+
let pages = 1;
|
|
19
|
+
const follow = async (url) => {
|
|
20
|
+
if (pages >= maxPages) {
|
|
21
|
+
throw new SalesforceApiError('QUERY_TOO_LARGE', `The query returned more than ${maxPages} pages; narrow the query (for sf-evidence, a shorter time slice). No partial result is returned.`);
|
|
22
|
+
}
|
|
23
|
+
pages++;
|
|
24
|
+
return (await fetchNext(url));
|
|
25
|
+
};
|
|
26
|
+
let page = first;
|
|
27
|
+
let records = await expandChildPages(page.records ?? [], follow);
|
|
28
|
+
while (page.nextRecordsUrl) {
|
|
29
|
+
page = await follow(page.nextRecordsUrl);
|
|
30
|
+
records = records.concat(await expandChildPages(page.records ?? [], follow));
|
|
31
|
+
}
|
|
32
|
+
return records;
|
|
33
|
+
}
|
|
34
|
+
/** Each record with every partial child relationship followed to completion, in order. */
|
|
35
|
+
async function expandChildPages(records, follow) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const record of records) {
|
|
38
|
+
if (typeof record !== 'object' || record === null) {
|
|
39
|
+
out.push(record);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
let expanded;
|
|
43
|
+
for (const [key, field] of Object.entries(record)) {
|
|
44
|
+
// jsforce's test: an object with both `records` and `nextRecordsUrl` keys.
|
|
45
|
+
if (!field || typeof field !== 'object' || !('records' in field) || !('nextRecordsUrl' in field))
|
|
46
|
+
continue;
|
|
47
|
+
const child = field;
|
|
48
|
+
let all = child.records ? [...child.records] : [];
|
|
49
|
+
let next = child.records ? child.nextRecordsUrl : undefined;
|
|
50
|
+
while (next) {
|
|
51
|
+
const more = await follow(next);
|
|
52
|
+
all = all.concat(more.records ?? []);
|
|
53
|
+
next = more.nextRecordsUrl;
|
|
54
|
+
}
|
|
55
|
+
expanded ??= { ...record };
|
|
56
|
+
expanded[key] = { ...child, records: all, done: true, nextRecordsUrl: undefined };
|
|
57
|
+
}
|
|
58
|
+
out.push((expanded ?? record));
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=paging.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streams a response body to disk without ever holding it as a JS string (which would fail on logs
|
|
3
|
+
* larger than ~512 MB). Creates parent directories, never leaves a partial file behind, and returns
|
|
4
|
+
* the number of bytes written. Shared by both REST clients.
|
|
5
|
+
*/
|
|
6
|
+
export declare function streamToFile(body: ReadableStream<Uint8Array>, destPath: string): Promise<number>;
|
|
7
|
+
//# sourceMappingURL=streamToFile.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { secureFs } from '../fs/secureFs.js';
|
|
6
|
+
/**
|
|
7
|
+
* Streams a response body to disk without ever holding it as a JS string (which would fail on logs
|
|
8
|
+
* larger than ~512 MB). Creates parent directories, never leaves a partial file behind, and returns
|
|
9
|
+
* the number of bytes written. Shared by both REST clients.
|
|
10
|
+
*/
|
|
11
|
+
export async function streamToFile(body, destPath) {
|
|
12
|
+
await secureFs.mkdir(dirname(destPath), { recursive: true });
|
|
13
|
+
try {
|
|
14
|
+
await pipeline(Readable.fromWeb(body), secureFs.createWriteStream(destPath));
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
await rm(destPath, { force: true }); // never leave a partial file behind
|
|
18
|
+
throw err;
|
|
19
|
+
}
|
|
20
|
+
return (await stat(destPath)).size;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=streamToFile.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Transform } from 'node:stream';
|
|
1
2
|
/**
|
|
2
3
|
* Passphrase encryption for files that hold org data at rest (incident bundles).
|
|
3
4
|
*
|
|
@@ -8,13 +9,41 @@
|
|
|
8
9
|
* AES-256-GCM with a key from scrypt. The scrypt parameters travel in the header so they can be
|
|
9
10
|
* raised later without stranding existing files, and the whole header is authenticated as GCM
|
|
10
11
|
* additional data, so altering any byte of it fails decryption.
|
|
12
|
+
*
|
|
13
|
+
* Format, version 2 (chunked, for files too large to hold in memory):
|
|
14
|
+
*
|
|
15
|
+
* 'SFEB' | version (1) | log2(N) (1) | r (1) | p (1) | log2(chunk) (1) | salt (16) | nonce prefix (7)
|
|
16
|
+
* then one segment per chunk: ciphertext (chunk bytes, the last one 0..chunk) | tag (16)
|
|
17
|
+
*
|
|
18
|
+
* The STREAM construction (Hoang, Reyhanitabar, Rogaway, Vizár 2015), as age and Tink use it: each
|
|
19
|
+
* chunk is sealed on its own with nonce = prefix | chunk index (4, big-endian) | last-chunk flag (1),
|
|
20
|
+
* and the header is every chunk's additional data. Reordered, repeated, dropped or appended chunks,
|
|
21
|
+
* and a file cut at a chunk boundary, all fail authentication. A reader may emit the chunks before
|
|
22
|
+
* a failure, each of which authenticated, so a consumer must treat a stream error as fatal.
|
|
11
23
|
*/
|
|
24
|
+
export declare const ENCRYPTED_PREFIX: Buffer<ArrayBuffer>;
|
|
12
25
|
export declare const ENCRYPTED_MAGIC: Buffer<ArrayBuffer>;
|
|
13
26
|
export declare class DecryptionError extends Error {
|
|
14
27
|
constructor(message?: string);
|
|
15
28
|
}
|
|
16
|
-
/** Whether `buf` starts with
|
|
29
|
+
/** Whether `buf` starts with a header of a known version. Says nothing about whether it will decrypt. */
|
|
17
30
|
export declare function isEncryptedBuffer(buf: Buffer): boolean;
|
|
18
31
|
export declare function encryptWithPassphrase(plaintext: Buffer | string, passphrase: string): Buffer;
|
|
19
32
|
export declare function decryptWithPassphrase(encrypted: Buffer, passphrase: string): Buffer;
|
|
33
|
+
export type EncryptStreamOptions = {
|
|
34
|
+
/** Plaintext bytes per chunk: a power of two from 1 KiB to 16 MiB. Defaults to 64 KiB. */
|
|
35
|
+
chunkSize?: number;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* A Transform that writes version 2 of the format. It holds at most one chunk of plaintext, so a
|
|
39
|
+
* file of any size is encrypted without ever being held whole in memory.
|
|
40
|
+
*/
|
|
41
|
+
export declare function createEncryptStream(passphrase: string, options?: EncryptStreamOptions): Transform;
|
|
42
|
+
/**
|
|
43
|
+
* A Transform that reads either version. Version 2 is decrypted chunk by chunk and only
|
|
44
|
+
* authenticated plaintext is emitted; version 1 is a single sealed blob, so it is buffered whole.
|
|
45
|
+
* Any failure is a DecryptionError, and the chunks emitted before it must not be trusted as a whole
|
|
46
|
+
* file: treat a stream error as fatal.
|
|
47
|
+
*/
|
|
48
|
+
export declare function createDecryptStream(passphrase: string): Transform;
|
|
20
49
|
//# sourceMappingURL=bundleCrypto.d.ts.map
|