@di-framework/cli-plugin-platform 6.1.1 → 6.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -2
- package/dist/assets/http-adapter.js +2 -5
- package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
- package/dist/assets/wit/deps/di-framework-pglite/package.wit +175 -0
- package/dist/bindings.js +7 -6
- package/dist/build.d.ts +8 -0
- package/dist/build.js +56 -4
- package/dist/console/cluster.d.ts +3 -0
- package/dist/console/cluster.js +57 -4
- package/dist/deploy.d.ts +6 -0
- package/dist/deploy.js +23 -5
- package/dist/deps.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/node-compat/console.js +16 -1
- package/dist/node-compat/crypto-subtle.d.ts +6 -0
- package/dist/node-compat/crypto-subtle.js +41 -4
- package/dist/node-compat/crypto.d.ts +3 -2
- package/dist/node-compat/crypto.js +66 -17
- package/dist/node-compat/fs.d.ts +24 -2
- package/dist/node-compat/fs.js +137 -15
- package/dist/node-compat/node-errors.d.ts +20 -0
- package/dist/node-compat/node-errors.js +73 -0
- package/dist/node-compat/storage.d.ts +3 -3
- package/dist/node-compat/wasi-random.d.ts +21 -1
- package/dist/node-compat/wasi-random.js +45 -12
- package/dist/pglite.d.ts +106 -0
- package/dist/pglite.js +347 -0
- package/dist/project.d.ts +11 -0
- package/dist/project.js +14 -1
- package/dist/secret-admission.d.ts +21 -0
- package/dist/secret-admission.js +29 -0
- package/dist/wit.d.ts +3 -0
- package/dist/wit.js +12 -0
- package/dist/workload.d.ts +29 -0
- package/dist/workload.js +157 -39
- package/package.json +2 -2
package/dist/console/cluster.js
CHANGED
|
@@ -4,11 +4,26 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { EGRESS_BINDING_NAME, egressResourceName } from '../egress.js';
|
|
5
5
|
import { captureKubectl } from '../kubernetes.js';
|
|
6
6
|
import { associationName } from '../managed-bindings.js';
|
|
7
|
+
import { kubectlStatusReason, MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE, } from '../secret-admission.js';
|
|
7
8
|
import { MANAGED_BY_LABEL, WORKLOAD_DEPLOYMENT_RESOURCE } from '../workload.js';
|
|
8
9
|
import { ConsoleError, sanitizePublicText } from './errors.js';
|
|
9
10
|
const BINDING_RESOURCE = 'servicebindings.platform.di-framework.dev';
|
|
10
11
|
/** Published by the platform controller in each tenant namespace (contract C-ROUTES). */
|
|
11
12
|
const ROUTES_CONFIG_MAP = 'di-platform-routes';
|
|
13
|
+
/**
|
|
14
|
+
* Secret names the platform controller owns. Mirrors `isManagedSecretName` (`di-binding-*`,
|
|
15
|
+
* `di-bs-*`) and the Secret names of the `backend-config` admission policy (`di-tenant-stock`,
|
|
16
|
+
* `di-platform-routes`), both in di-framework/platform `platform/platform/src/tenancy/admission.ts`.
|
|
17
|
+
*/
|
|
18
|
+
const MANAGED_SECRET_PREFIXES = ['di-binding-', 'di-bs-'];
|
|
19
|
+
const MANAGED_SECRET_NAMES = new Set(['di-tenant-stock', ROUTES_CONFIG_MAP]);
|
|
20
|
+
/** True for a Secret the platform manages; a tenant user may not replace it. */
|
|
21
|
+
export function isPlatformManagedSecretName(name) {
|
|
22
|
+
return (MANAGED_SECRET_NAMES.has(name) ||
|
|
23
|
+
MANAGED_SECRET_PREFIXES.some((prefix) => name.startsWith(prefix)));
|
|
24
|
+
}
|
|
25
|
+
// Denial messages of the platform's Secret admission policies; see `../secret-admission`.
|
|
26
|
+
export { MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE } from '../secret-admission.js';
|
|
12
27
|
export function createKubectlConsoleCluster(deps, log = () => undefined) {
|
|
13
28
|
const label = `app.kubernetes.io/managed-by=${MANAGED_BY_LABEL}`;
|
|
14
29
|
return {
|
|
@@ -39,16 +54,54 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
|
|
|
39
54
|
async patchWorkload(connection, name, ops) {
|
|
40
55
|
await kubectlOk(deps, connection, ['patch', WORKLOAD_DEPLOYMENT_RESOURCE, name, '--type=json', `-p=${JSON.stringify(ops)}`], log, 'The application could not be updated.');
|
|
41
56
|
},
|
|
57
|
+
// Tenant developers can update Secrets but not read or patch them (platform#112), so the
|
|
58
|
+
// credential is written as a whole Secret with an unconditional PUT. A Secret is not
|
|
59
|
+
// created by an update, so a missing one still answers NotFound. The console cannot see
|
|
60
|
+
// the Secret's keys, so the platform's `tenant-secret-update` admission policy refuses a
|
|
61
|
+
// replace that would drop any (409) or that targets a platform-managed name (403), and the
|
|
62
|
+
// API server refuses one that would change a non-Opaque Secret's type (409). Errors are
|
|
63
|
+
// classified by their Status reason, never by the free text that carries the name.
|
|
42
64
|
async reassignSecret(connection, name, value) {
|
|
65
|
+
if (isPlatformManagedSecretName(name)) {
|
|
66
|
+
throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
|
|
67
|
+
}
|
|
43
68
|
const directory = mkdtempSync(join(tmpdir(), 'di-console-secret-'));
|
|
44
69
|
try {
|
|
45
|
-
const path = join(directory, '
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
70
|
+
const path = join(directory, 'secret.json');
|
|
71
|
+
const document = {
|
|
72
|
+
apiVersion: 'v1',
|
|
73
|
+
kind: 'Secret',
|
|
74
|
+
metadata: { name, namespace: connection.namespace },
|
|
75
|
+
type: 'Opaque',
|
|
76
|
+
data: { credential: Buffer.from(value, 'utf8').toString('base64') },
|
|
77
|
+
};
|
|
78
|
+
writeFileSync(path, JSON.stringify(document), { mode: 0o600 });
|
|
79
|
+
const uri = `/api/v1/namespaces/${encodeURIComponent(connection.namespace)}/secrets/${encodeURIComponent(name)}`;
|
|
80
|
+
const result = await captureKubectl(deps, connection, ['replace', '--raw', uri, '-f', path], deps.cwd());
|
|
81
|
+
const reason = result.exitCode === 0 ? undefined : kubectlStatusReason(result.stderr);
|
|
82
|
+
if (reason === 'NotFound') {
|
|
49
83
|
log(sanitizePublicText(result.stderr));
|
|
50
84
|
throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
|
|
51
85
|
}
|
|
86
|
+
if (result.exitCode !== 0 && result.stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
|
|
87
|
+
log(sanitizePublicText(result.stderr));
|
|
88
|
+
throw new ConsoleError(409, 'SECRET_NOT_SINGLE_KEY', `${name} holds values other than a single credential, so it cannot be reassigned here.`);
|
|
89
|
+
}
|
|
90
|
+
if (result.exitCode !== 0 &&
|
|
91
|
+
MANAGED_SECRET_DENIALS.some((message) => result.stderr.includes(message))) {
|
|
92
|
+
log(sanitizePublicText(result.stderr));
|
|
93
|
+
throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
|
|
94
|
+
}
|
|
95
|
+
// A Secret's type is immutable, so a non-Opaque Secret cannot take the Opaque document.
|
|
96
|
+
if (reason === 'Invalid' &&
|
|
97
|
+
/\btype: Invalid value:.*field is immutable/.test(result.stderr)) {
|
|
98
|
+
log(sanitizePublicText(result.stderr));
|
|
99
|
+
throw new ConsoleError(409, 'SECRET_TYPE_MISMATCH', `${name} is not a plain (Opaque) Secret and its type cannot change, so it cannot be reassigned here.`);
|
|
100
|
+
}
|
|
101
|
+
if (reason === 'Forbidden') {
|
|
102
|
+
log(sanitizePublicText(result.stderr));
|
|
103
|
+
throw new ConsoleError(403, 'WRITES_FORBIDDEN', 'This credential cannot change the application.');
|
|
104
|
+
}
|
|
52
105
|
if (result.exitCode !== 0) {
|
|
53
106
|
log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
|
|
54
107
|
throw new ConsoleError(502, 'REQUEST_FAILED', 'The credential could not be reassigned.');
|
package/dist/deploy.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ export type WasmcloudDeployData = {
|
|
|
21
21
|
host: string;
|
|
22
22
|
};
|
|
23
23
|
endpoints?: Record<string, string>;
|
|
24
|
+
/** Where the composed PGlite provider came from: a digest pin or a local file. */
|
|
25
|
+
pglite?: {
|
|
26
|
+
source: 'local' | 'cache' | 'registry';
|
|
27
|
+
image?: string;
|
|
28
|
+
path?: string;
|
|
29
|
+
};
|
|
24
30
|
};
|
|
25
31
|
export type WasmcloudDeployResult = Omit<CommandResult, 'data' | 'text'> & {
|
|
26
32
|
data: WasmcloudDeployData;
|
package/dist/deploy.js
CHANGED
|
@@ -4,6 +4,7 @@ import { discoverScheduledJobs } from './cron.js';
|
|
|
4
4
|
import { DEFAULT_DEPS } from './deps.js';
|
|
5
5
|
import { discoverProjects, resolveApplication } from './discovery.js';
|
|
6
6
|
import { loadDeployManifest } from './manifest.js';
|
|
7
|
+
import { assertDistinctPgliteRoots } from './pglite.js';
|
|
7
8
|
import { publishComponent } from './publish.js';
|
|
8
9
|
import { resolveConnection, resolveTarget } from './target.js';
|
|
9
10
|
import { applyWorkload, deploymentResourceName } from './workload.js';
|
|
@@ -14,10 +15,12 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
|
|
|
14
15
|
const target = resolveTarget(manifest, options.target);
|
|
15
16
|
const project = resolveApplication(deps.cwd(), options.name, manifest.workspaceRoot, manifest.discovery);
|
|
16
17
|
if (project.workload) {
|
|
17
|
-
const
|
|
18
|
+
const members = [...discoverProjects(manifest.workspaceRoot, manifest.discovery).values()];
|
|
19
|
+
assertDistinctPgliteRoots(project.workload, members);
|
|
20
|
+
const path = writeWorkloadManifest(manifest.workspaceRoot, project.workload, members);
|
|
18
21
|
io.stdout.write(`Generated workload manifest ${path}\n`);
|
|
19
22
|
}
|
|
20
|
-
const build = await buildComponent(project, io, deps);
|
|
23
|
+
const build = await buildComponent(project, io, deps, { deploy: true });
|
|
21
24
|
const connection = await resolveConnection(target, manifest.workspaceRoot, manifest.path, deps);
|
|
22
25
|
io.stdout.write(`Deploying ${project.applicationName} to target ${connection.target}...\n`);
|
|
23
26
|
const image = await publishComponent(project, connection, io, deps, build.deploymentDigest);
|
|
@@ -40,6 +43,7 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
|
|
|
40
43
|
? { http: { url: connection.endpoints.http, host: project.applicationName } }
|
|
41
44
|
: {}),
|
|
42
45
|
...(connection.endpoints === undefined ? {} : { endpoints: connection.endpoints }),
|
|
46
|
+
...(build.pglite === undefined ? {} : { pglite: build.pglite }),
|
|
43
47
|
...(cronJobs.length > 0
|
|
44
48
|
? {
|
|
45
49
|
cronJobs: cronJobs.map((j) => ({
|
|
@@ -50,8 +54,22 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
|
|
|
50
54
|
}
|
|
51
55
|
: {}),
|
|
52
56
|
},
|
|
53
|
-
text:
|
|
54
|
-
|
|
55
|
-
|
|
57
|
+
text: [
|
|
58
|
+
`Deployed ${project.applicationName} to ${connection.target} (namespace ${connection.namespace}, ${image.pullReference}).`,
|
|
59
|
+
hasHttp && connection.endpoints?.http !== undefined
|
|
60
|
+
? ` HTTP: ${connection.endpoints.http} with Host: ${project.applicationName}`
|
|
61
|
+
: '',
|
|
62
|
+
pgliteText(build.pglite),
|
|
63
|
+
cronJobs.length > 0
|
|
64
|
+
? ` Scheduled jobs (${cronJobs.length}): ${cronJobs.map((j) => j.jobId).join(', ')}`
|
|
65
|
+
: '',
|
|
66
|
+
].join(''),
|
|
56
67
|
};
|
|
57
68
|
}
|
|
69
|
+
function pgliteText(pglite) {
|
|
70
|
+
if (pglite === undefined)
|
|
71
|
+
return '';
|
|
72
|
+
return pglite.path === undefined
|
|
73
|
+
? ` PGlite: ${pglite.image}.`
|
|
74
|
+
: ` PGlite: local ${pglite.path} (unverified).`;
|
|
75
|
+
}
|
package/dist/deps.js
CHANGED
|
@@ -106,7 +106,7 @@ const packageRoot = resolve(dirname(realpathSync(fileURLToPath(import.meta.url))
|
|
|
106
106
|
export function componentizeQjsPlatformPackageName() {
|
|
107
107
|
return COMPONENTIZE_QJS_PACKAGE;
|
|
108
108
|
}
|
|
109
|
-
export function componentizeQjsPlatformPackageVersion(platform = process.platform, arch = process.arch, wrapperVersion = '0.4.4-di.
|
|
109
|
+
export function componentizeQjsPlatformPackageVersion(platform = process.platform, arch = process.arch, wrapperVersion = '0.4.4-di.5') {
|
|
110
110
|
return `${wrapperVersion}-${platform}-${arch}`;
|
|
111
111
|
}
|
|
112
112
|
function platformPackageBinMatches(packageDirectory, platform, arch) {
|
package/dist/index.d.ts
CHANGED
|
@@ -29,6 +29,6 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
|
|
|
29
29
|
export { resolveConnection, resolveTarget } from './target.js';
|
|
30
30
|
export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
|
|
31
31
|
export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, type WitRequirement, } from './wit.js';
|
|
32
|
-
export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, } from './workload.js';
|
|
32
|
+
export { applyWorkload, type ControlSecretWrite, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, writeControlSecret, } from './workload.js';
|
|
33
33
|
declare const _default: import("@di-framework/cli-extension").ExtensionManifest;
|
|
34
34
|
export default _default;
|
package/dist/index.js
CHANGED
|
@@ -31,7 +31,7 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
|
|
|
31
31
|
export { resolveConnection, resolveTarget } from './target.js';
|
|
32
32
|
export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
|
|
33
33
|
export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, } from './wit.js';
|
|
34
|
-
export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, } from './workload.js';
|
|
34
|
+
export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, writeControlSecret, } from './workload.js';
|
|
35
35
|
export default defineExtension({
|
|
36
36
|
schemaVersion: 1,
|
|
37
37
|
name: 'platform',
|
|
@@ -1,15 +1,30 @@
|
|
|
1
1
|
import { log } from 'wasi:logging/logging@0.1.0-draft';
|
|
2
2
|
/** Context passed with every guest console line; the host tags it with the workload. */
|
|
3
3
|
export const CONSOLE_LOG_CONTEXT = 'console';
|
|
4
|
+
/**
|
|
5
|
+
* WIT s64/u64 values (SQLite integers, row counts, timestamps) arrive as BigInt since
|
|
6
|
+
* componentize-qjs 0.4.4-di.5, and JSON.stringify throws on BigInt.
|
|
7
|
+
*
|
|
8
|
+
* Convention: a top-level BigInt prints as Node's console does (`42n`). A BigInt nested
|
|
9
|
+
* in an object or array prints as the JSON string `"42n"` (`{"id":"42n"}`, where Node
|
|
10
|
+
* would print `{ id: 42n }`), so each line stays valid JSON for log consumers. A JSON
|
|
11
|
+
* reader therefore cannot tell BigInt `42n` from the string `"42n"`; treat a string
|
|
12
|
+
* matching `/^-?\d+n$/` as a BigInt when that matters.
|
|
13
|
+
*/
|
|
14
|
+
function bigintReplacer(_key, value) {
|
|
15
|
+
return typeof value === 'bigint' ? `${value}n` : value;
|
|
16
|
+
}
|
|
4
17
|
function formatValue(value) {
|
|
5
18
|
if (typeof value === 'string')
|
|
6
19
|
return value;
|
|
7
20
|
if (value instanceof Error)
|
|
8
21
|
return value.stack ?? `${value.name}: ${value.message}`;
|
|
22
|
+
if (typeof value === 'bigint')
|
|
23
|
+
return `${value}n`;
|
|
9
24
|
if (typeof value !== 'object' || value === null)
|
|
10
25
|
return String(value);
|
|
11
26
|
try {
|
|
12
|
-
return JSON.stringify(value);
|
|
27
|
+
return JSON.stringify(value, bigintReplacer);
|
|
13
28
|
}
|
|
14
29
|
catch {
|
|
15
30
|
return String(value);
|
|
@@ -16,6 +16,12 @@ export type GuestCryptoKey = {
|
|
|
16
16
|
bytes: Uint8Array;
|
|
17
17
|
};
|
|
18
18
|
export declare function algorithmName(algorithm: AlgorithmIdentifier): string;
|
|
19
|
+
/** Web Crypto's per-call `getRandomValues` quota, in bytes. */
|
|
20
|
+
export declare const GET_RANDOM_VALUES_MAX = 65536;
|
|
21
|
+
/**
|
|
22
|
+
* Like Node v22's `crypto.getRandomValues`: integer-type typed arrays only
|
|
23
|
+
* (`TypeMismatchError`), at most 65,536 bytes (`QuotaExceededError`).
|
|
24
|
+
*/
|
|
19
25
|
export declare function getRandomValues<T extends ArrayBufferView>(array: T): T;
|
|
20
26
|
export declare function randomUUID(): string;
|
|
21
27
|
declare function digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;
|
|
@@ -5,7 +5,7 @@ import { hmac } from '@noble/hashes/hmac.js';
|
|
|
5
5
|
import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
|
|
6
6
|
import { toArrayBuffer, toBytes } from './bytes.js';
|
|
7
7
|
import { digestSync, hashFunction, normalizeHashName } from './crypto-hash.js';
|
|
8
|
-
import { getRandomBytes } from './wasi-random.js';
|
|
8
|
+
import { fillRandom, getRandomBytes } from './wasi-random.js';
|
|
9
9
|
const HASH_OUTPUT = {
|
|
10
10
|
sha256: { noble: sha256, bits: 256 },
|
|
11
11
|
sha384: { noble: sha384, bits: 384 },
|
|
@@ -55,10 +55,47 @@ function asKey(key) {
|
|
|
55
55
|
function algorithmParams(algorithm) {
|
|
56
56
|
return typeof algorithm === 'string' ? { name: algorithm } : { ...algorithm };
|
|
57
57
|
}
|
|
58
|
+
/** Web Crypto's per-call `getRandomValues` quota, in bytes. */
|
|
59
|
+
export const GET_RANDOM_VALUES_MAX = 65_536;
|
|
60
|
+
const INTEGER_ARRAYS = [
|
|
61
|
+
'Int8Array',
|
|
62
|
+
'Uint8Array',
|
|
63
|
+
'Uint8ClampedArray',
|
|
64
|
+
'Int16Array',
|
|
65
|
+
'Uint16Array',
|
|
66
|
+
'Int32Array',
|
|
67
|
+
'Uint32Array',
|
|
68
|
+
'BigInt64Array',
|
|
69
|
+
'BigUint64Array',
|
|
70
|
+
];
|
|
71
|
+
function isIntegerTypedArray(value) {
|
|
72
|
+
if (!ArrayBuffer.isView(value))
|
|
73
|
+
return false;
|
|
74
|
+
return INTEGER_ARRAYS.some((name) => {
|
|
75
|
+
const ctor = globalThis[name];
|
|
76
|
+
return typeof ctor === 'function' && value instanceof ctor;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** A Web Crypto `DOMException`, or an Error with the same name and legacy code without one. */
|
|
80
|
+
function domException(message, name, code) {
|
|
81
|
+
const DOMExceptionCtor = globalThis
|
|
82
|
+
.DOMException;
|
|
83
|
+
if (typeof DOMExceptionCtor === 'function')
|
|
84
|
+
return new DOMExceptionCtor(message, name);
|
|
85
|
+
return Object.assign(new Error(message), { name, code });
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Like Node v22's `crypto.getRandomValues`: integer-type typed arrays only
|
|
89
|
+
* (`TypeMismatchError`), at most 65,536 bytes (`QuotaExceededError`).
|
|
90
|
+
*/
|
|
58
91
|
export function getRandomValues(array) {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
92
|
+
if (!isIntegerTypedArray(array)) {
|
|
93
|
+
throw domException('The data argument must be an integer-type TypedArray', 'TypeMismatchError', 17);
|
|
94
|
+
}
|
|
95
|
+
if (array.byteLength > GET_RANDOM_VALUES_MAX) {
|
|
96
|
+
throw domException('The requested length exceeds 65,536 bytes', 'QuotaExceededError', 22);
|
|
97
|
+
}
|
|
98
|
+
fillRandom(new Uint8Array(array.buffer, array.byteOffset, array.byteLength));
|
|
62
99
|
return array;
|
|
63
100
|
}
|
|
64
101
|
export function randomUUID() {
|
|
@@ -2,8 +2,9 @@ import { createHash, createHmac, Hash, Hmac } from './crypto-hash.js';
|
|
|
2
2
|
import { getRandomValues, randomUUID, subtle, webcrypto } from './crypto-subtle.js';
|
|
3
3
|
export { createHash, createHmac, getRandomValues, Hash, Hmac, randomUUID, subtle, webcrypto };
|
|
4
4
|
export declare function randomBytes(size: number, callback?: (error: Error | null, buffer: Uint8Array) => void): Uint8Array | undefined;
|
|
5
|
-
|
|
6
|
-
export declare function
|
|
5
|
+
type RandomTarget = ArrayBufferView | ArrayBuffer;
|
|
6
|
+
export declare function randomFillSync<T extends RandomTarget>(buffer: T, offset?: number, size?: number): T;
|
|
7
|
+
export declare function randomFill<T extends RandomTarget>(buffer: T, offset?: number | ((error: Error | null, buffer: T) => void), size?: number | ((error: Error | null, buffer: T) => void), callback?: (error: Error | null, buffer: T) => void): undefined | T;
|
|
7
8
|
export declare function randomInt(min: number, max?: number | ((error: Error | null, value: number) => void), callback?: (error: Error | null, value: number) => void): number | undefined;
|
|
8
9
|
export declare function timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean;
|
|
9
10
|
export declare const rng: typeof randomBytes;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { toBytes, toNodeBuffer } from './bytes.js';
|
|
2
2
|
import { createHash, createHmac, Hash, Hmac } from './crypto-hash.js';
|
|
3
3
|
import { getRandomValues, randomUUID, subtle, webcrypto } from './crypto-subtle.js';
|
|
4
|
-
import {
|
|
4
|
+
import { invalidArgType, outOfRange } from './node-errors.js';
|
|
5
|
+
import { fillRandom, getRandomBytes, RANDOM_SIZE_MAX } from './wasi-random.js';
|
|
5
6
|
export { createHash, createHmac, getRandomValues, Hash, Hmac, randomUUID, subtle, webcrypto };
|
|
6
7
|
function cryptoUnsupported(name) {
|
|
7
8
|
const error = new Error(`crypto.${name} is not implemented in the wasmCloud guest`);
|
|
@@ -14,6 +15,9 @@ function notImplemented(name) {
|
|
|
14
15
|
};
|
|
15
16
|
}
|
|
16
17
|
export function randomBytes(size, callback) {
|
|
18
|
+
if (callback !== undefined && typeof callback !== 'function') {
|
|
19
|
+
throw invalidArgType('callback', 'of type function', callback);
|
|
20
|
+
}
|
|
17
21
|
const bytes = toNodeBuffer(getRandomBytes(size));
|
|
18
22
|
if (typeof callback === 'function') {
|
|
19
23
|
queueMicrotask(() => callback(null, bytes));
|
|
@@ -21,34 +25,79 @@ export function randomBytes(size, callback) {
|
|
|
21
25
|
}
|
|
22
26
|
return bytes;
|
|
23
27
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
function randomTargetBytes(buffer) {
|
|
29
|
+
if (ArrayBuffer.isView(buffer)) {
|
|
30
|
+
return {
|
|
31
|
+
view: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength),
|
|
32
|
+
elementSize: buffer.BYTES_PER_ELEMENT || 1,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
if (buffer instanceof ArrayBuffer)
|
|
36
|
+
return { view: new Uint8Array(buffer), elementSize: 1 };
|
|
37
|
+
throw invalidArgType('buf', 'an instance of ArrayBuffer or ArrayBufferView', buffer);
|
|
38
|
+
}
|
|
39
|
+
/** Node v22 `assertOffset`: offsets count elements, are bounded by the byte length, and truncate. */
|
|
40
|
+
function randomOffset(offset, elementSize, byteLength) {
|
|
41
|
+
if (typeof offset !== 'number')
|
|
42
|
+
throw invalidArgType('offset', 'of type number', offset);
|
|
43
|
+
const bytes = offset * elementSize;
|
|
44
|
+
const max = Math.min(byteLength, RANDOM_SIZE_MAX);
|
|
45
|
+
if (Number.isNaN(bytes) || bytes > max || bytes < 0) {
|
|
46
|
+
throw outOfRange('offset', `>= 0 && <= ${max}`, bytes);
|
|
47
|
+
}
|
|
48
|
+
return Math.trunc(bytes);
|
|
49
|
+
}
|
|
50
|
+
/** Node v22 `assertSize`: sizes count elements and must fit after the offset. */
|
|
51
|
+
function randomSize(size, elementSize, offset, byteLength) {
|
|
52
|
+
if (typeof size !== 'number')
|
|
53
|
+
throw invalidArgType('size', 'of type number', size);
|
|
54
|
+
const bytes = size * elementSize;
|
|
55
|
+
if (Number.isNaN(bytes) || bytes > RANDOM_SIZE_MAX || bytes < 0) {
|
|
56
|
+
throw outOfRange('size', `>= 0 && <= ${RANDOM_SIZE_MAX}`, bytes);
|
|
57
|
+
}
|
|
58
|
+
if (bytes + offset > byteLength)
|
|
59
|
+
throw outOfRange('size + offset', `<= ${byteLength}`, bytes + offset);
|
|
60
|
+
return Math.trunc(bytes);
|
|
61
|
+
}
|
|
62
|
+
function fillRange(view, offset, size) {
|
|
63
|
+
if (size > 0)
|
|
64
|
+
fillRandom(view.subarray(offset, offset + size));
|
|
65
|
+
}
|
|
66
|
+
export function randomFillSync(buffer, offset = 0, size) {
|
|
67
|
+
const { view, elementSize } = randomTargetBytes(buffer);
|
|
68
|
+
const start = randomOffset(offset, elementSize, view.byteLength);
|
|
69
|
+
const length = size === undefined
|
|
70
|
+
? view.byteLength - start
|
|
71
|
+
: randomSize(size, elementSize, start, view.byteLength);
|
|
72
|
+
fillRange(view, start, length);
|
|
29
73
|
return buffer;
|
|
30
74
|
}
|
|
31
75
|
export function randomFill(buffer, offset, size, callback) {
|
|
76
|
+
const { view, elementSize } = randomTargetBytes(buffer);
|
|
32
77
|
let start = 0;
|
|
33
|
-
let length;
|
|
78
|
+
let length = view.byteLength;
|
|
34
79
|
let cb;
|
|
35
80
|
if (typeof offset === 'function')
|
|
36
81
|
cb = offset;
|
|
82
|
+
else if (typeof size === 'function') {
|
|
83
|
+
cb = size;
|
|
84
|
+
start = randomOffset(offset, elementSize, view.byteLength);
|
|
85
|
+
length = view.byteLength - start;
|
|
86
|
+
}
|
|
37
87
|
else {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
88
|
+
cb = callback;
|
|
89
|
+
start = randomOffset(offset ?? 0, elementSize, view.byteLength);
|
|
90
|
+
length =
|
|
91
|
+
size === undefined
|
|
92
|
+
? view.byteLength - start
|
|
93
|
+
: randomSize(size, elementSize, start, view.byteLength);
|
|
45
94
|
}
|
|
46
|
-
|
|
95
|
+
fillRange(view, start, length);
|
|
47
96
|
if (cb !== undefined) {
|
|
48
|
-
queueMicrotask(() => cb(null,
|
|
97
|
+
queueMicrotask(() => cb(null, buffer));
|
|
49
98
|
return undefined;
|
|
50
99
|
}
|
|
51
|
-
return
|
|
100
|
+
return buffer;
|
|
52
101
|
}
|
|
53
102
|
export function randomInt(min, max, callback) {
|
|
54
103
|
let low = 0;
|
package/dist/node-compat/fs.d.ts
CHANGED
|
@@ -42,8 +42,30 @@ export declare function fstatSync(fd: number): {
|
|
|
42
42
|
};
|
|
43
43
|
export declare function openSync(path: string, flags?: string | number, _mode?: number): number;
|
|
44
44
|
export declare function closeSync(fd: number): void;
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
type ReadOptions = {
|
|
46
|
+
offset?: number;
|
|
47
|
+
length?: number;
|
|
48
|
+
position?: number | bigint | null;
|
|
49
|
+
};
|
|
50
|
+
type WriteOptions = {
|
|
51
|
+
offset?: number;
|
|
52
|
+
length?: number;
|
|
53
|
+
position?: number | null;
|
|
54
|
+
};
|
|
55
|
+
export declare function readSync(fd: number, buffer: ArrayBufferView, ...args: [
|
|
56
|
+
offsetOrOptions?: number | ReadOptions | null,
|
|
57
|
+
length?: number,
|
|
58
|
+
position?: number | bigint | null
|
|
59
|
+
]): number;
|
|
60
|
+
/**
|
|
61
|
+
* Node v22 `fs.writeSync`, in both forms:
|
|
62
|
+
* - `writeSync(fd, buffer, offset?, length?, position?)` (or an options object), and
|
|
63
|
+
* - `writeSync(fd, string, position?, encoding?)`.
|
|
64
|
+
* Like Node (and libuv), a position that is not a non-negative safe-integer Number
|
|
65
|
+
* (BigInt, NaN, 1.5, -1, ...) writes at the current position, so it never reaches the
|
|
66
|
+
* stored descriptor's u64 offset.
|
|
67
|
+
*/
|
|
68
|
+
export declare function writeSync(fd: number, data: string | ArrayBufferView, offsetOrPosition?: number | WriteOptions | null, lengthOrEncoding?: number | string | null, requestedPosition?: number | bigint | null): number;
|
|
47
69
|
export declare function createReadStream(path: string): {
|
|
48
70
|
on(event: string, listener: (...args: unknown[]) => void): unknown;
|
|
49
71
|
once(event: string, listener: (...args: unknown[]) => void): unknown;
|
package/dist/node-compat/fs.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { invalidArgType, invalidArgValue, outOfRange, validateInteger } from './node-errors.js';
|
|
1
2
|
import { nodeCompatSeed } from './seed-virtual.js';
|
|
2
3
|
import { storage as wasiStorage } from './storage.js';
|
|
3
4
|
/** Host-mounted storage; paths outside it stay in the in-memory filesystem below. */
|
|
@@ -229,42 +230,163 @@ export function closeSync(fd) {
|
|
|
229
230
|
if (!openHandles.delete(fd))
|
|
230
231
|
throw errno('EBADF', 'close', String(fd), -9);
|
|
231
232
|
}
|
|
232
|
-
|
|
233
|
+
function validateView(buffer) {
|
|
234
|
+
if (!ArrayBuffer.isView(buffer)) {
|
|
235
|
+
throw invalidArgType('buffer', 'an instance of Buffer, TypedArray, or DataView', buffer);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function viewBytes(buffer) {
|
|
239
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Node v22 `fs.readSync` argument handling, so only valid u64 lengths and offsets reach
|
|
243
|
+
* the stored descriptor (componentize-qjs 0.4.4-di.5+ traps on any other Number):
|
|
244
|
+
* three arguments (or an object) are options; `length` is truncated with `| 0` and a
|
|
245
|
+
* zero length returns before any other check; `position` `null`/`-1`/`-1n` means the
|
|
246
|
+
* current position. Returns `null` for a zero-length read.
|
|
247
|
+
*/
|
|
248
|
+
function readRange(buffer, args) {
|
|
249
|
+
let offset = args[0];
|
|
250
|
+
let length = args[1];
|
|
251
|
+
let position = args[2];
|
|
252
|
+
if (args.length <= 1 || typeof offset === 'object') {
|
|
253
|
+
if (offset !== undefined && offset !== null && typeof offset !== 'object') {
|
|
254
|
+
throw invalidArgType('options', 'of type object', offset);
|
|
255
|
+
}
|
|
256
|
+
const options = (offset ?? {});
|
|
257
|
+
offset = options.offset ?? 0;
|
|
258
|
+
length = options.length ?? buffer.byteLength - offset;
|
|
259
|
+
position = options.position ?? null;
|
|
260
|
+
}
|
|
261
|
+
const start = offset === undefined ? 0 : validateInteger(offset, 'offset', 0);
|
|
262
|
+
const count = length | 0;
|
|
263
|
+
if (count === 0)
|
|
264
|
+
return null;
|
|
265
|
+
if (buffer.byteLength === 0) {
|
|
266
|
+
throw invalidArgValue('buffer', 'is empty and cannot be written', '<Buffer >');
|
|
267
|
+
}
|
|
268
|
+
if (count < 0)
|
|
269
|
+
throw outOfRange('length', '>= 0', count);
|
|
270
|
+
if (start + count > buffer.byteLength) {
|
|
271
|
+
throw outOfRange('length', `<= ${buffer.byteLength - start}`, count);
|
|
272
|
+
}
|
|
273
|
+
if (position === null || position === undefined)
|
|
274
|
+
return { offset: start, length: count, position: null };
|
|
275
|
+
if (typeof position === 'number') {
|
|
276
|
+
validateInteger(position, 'position', -1);
|
|
277
|
+
return { offset: start, length: count, position: position === -1 ? null : position };
|
|
278
|
+
}
|
|
279
|
+
if (typeof position === 'bigint') {
|
|
280
|
+
const max = 2n ** 63n - 1n - BigInt(count);
|
|
281
|
+
if (!(position >= -1n && position <= max)) {
|
|
282
|
+
throw outOfRange('position', `>= -1 && <= ${max}`, position);
|
|
283
|
+
}
|
|
284
|
+
return { offset: start, length: count, position: position === -1n ? null : position };
|
|
285
|
+
}
|
|
286
|
+
throw invalidArgType('position', 'of type bigint or integer', position);
|
|
287
|
+
}
|
|
288
|
+
export function readSync(fd, buffer, ...args) {
|
|
289
|
+
validateView(buffer);
|
|
290
|
+
const range = readRange(buffer, args);
|
|
291
|
+
if (range === null)
|
|
292
|
+
return 0;
|
|
233
293
|
const handle = openHandles.get(fd);
|
|
234
294
|
if (handle === undefined)
|
|
235
295
|
throw errno('EBADF', 'read', String(fd), -9);
|
|
236
|
-
const
|
|
296
|
+
const { offset, length, position } = range;
|
|
297
|
+
const start = position ?? handle.position;
|
|
237
298
|
const slice = handle.stored
|
|
238
299
|
? storage.readAt(handle.path, length, start)
|
|
239
|
-
:
|
|
240
|
-
|
|
300
|
+
: (() => {
|
|
301
|
+
const content = asBytes(nodeCompatSeed.files[handle.path] ?? '');
|
|
302
|
+
// A BigInt position beyond MAX_SAFE_INTEGER is past the end of any in-memory file.
|
|
303
|
+
if (typeof start === 'bigint' && start > BigInt(content.byteLength))
|
|
304
|
+
return new Uint8Array();
|
|
305
|
+
const from = Number(start);
|
|
306
|
+
return content.subarray(from, from + length);
|
|
307
|
+
})();
|
|
308
|
+
viewBytes(buffer).set(slice, offset);
|
|
241
309
|
if (position === null)
|
|
242
|
-
handle.position =
|
|
310
|
+
handle.position = handle.position + slice.byteLength;
|
|
243
311
|
return slice.byteLength;
|
|
244
312
|
}
|
|
245
|
-
|
|
313
|
+
/** Node's `validateOffsetLengthWrite` plus `validateInt32(length)`. */
|
|
314
|
+
function writeRange(buffer, offsetArg, lengthArg, positionArg) {
|
|
315
|
+
let offset = offsetArg;
|
|
316
|
+
let length = lengthArg;
|
|
317
|
+
let position = positionArg;
|
|
318
|
+
if (typeof offset === 'object') {
|
|
319
|
+
const options = (offset ?? {});
|
|
320
|
+
offset = options.offset ?? 0;
|
|
321
|
+
length = options.length ?? buffer.byteLength - offset;
|
|
322
|
+
position = options.position ?? null;
|
|
323
|
+
}
|
|
324
|
+
const start = offset === undefined || offset === null ? 0 : validateInteger(offset, 'offset', 0);
|
|
325
|
+
const count = typeof length === 'number' ? length : buffer.byteLength - start;
|
|
326
|
+
if (start > buffer.byteLength)
|
|
327
|
+
throw outOfRange('offset', `<= ${buffer.byteLength}`, start);
|
|
328
|
+
if (count > buffer.byteLength - start) {
|
|
329
|
+
throw outOfRange('length', `<= ${buffer.byteLength - start}`, count);
|
|
330
|
+
}
|
|
331
|
+
if (count < 0)
|
|
332
|
+
throw outOfRange('length', '>= 0', count);
|
|
333
|
+
if (!Number.isInteger(count))
|
|
334
|
+
throw outOfRange('length', 'an integer', count);
|
|
335
|
+
return { bytes: viewBytes(buffer).subarray(start, start + count), position };
|
|
336
|
+
}
|
|
337
|
+
function encodeString(data, encoding) {
|
|
338
|
+
if (encoding === 'hex' && data.length % 2 !== 0) {
|
|
339
|
+
throw invalidArgValue('encoding', `is invalid for data of length ${data.length}`, "'hex'");
|
|
340
|
+
}
|
|
341
|
+
if (typeof encoding === 'string' &&
|
|
342
|
+
typeof Buffer !== 'undefined' &&
|
|
343
|
+
Buffer.isEncoding(encoding)) {
|
|
344
|
+
const encoded = Buffer.from(data, encoding);
|
|
345
|
+
return new Uint8Array(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
346
|
+
}
|
|
347
|
+
return new TextEncoder().encode(data);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Node v22 `fs.writeSync`, in both forms:
|
|
351
|
+
* - `writeSync(fd, buffer, offset?, length?, position?)` (or an options object), and
|
|
352
|
+
* - `writeSync(fd, string, position?, encoding?)`.
|
|
353
|
+
* Like Node (and libuv), a position that is not a non-negative safe-integer Number
|
|
354
|
+
* (BigInt, NaN, 1.5, -1, ...) writes at the current position, so it never reaches the
|
|
355
|
+
* stored descriptor's u64 offset.
|
|
356
|
+
*/
|
|
357
|
+
export function writeSync(fd, data, offsetOrPosition, lengthOrEncoding, requestedPosition) {
|
|
358
|
+
let bytes;
|
|
359
|
+
let position;
|
|
360
|
+
if (ArrayBuffer.isView(data)) {
|
|
361
|
+
({ bytes, position } = writeRange(data, offsetOrPosition, lengthOrEncoding, requestedPosition));
|
|
362
|
+
}
|
|
363
|
+
else if (typeof data === 'string') {
|
|
364
|
+
bytes = encodeString(data, lengthOrEncoding);
|
|
365
|
+
position = offsetOrPosition;
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
throw invalidArgType('buffer', 'of type string or an instance of Buffer, TypedArray, or DataView', data);
|
|
369
|
+
}
|
|
246
370
|
const handle = openHandles.get(fd);
|
|
247
371
|
if (handle === undefined)
|
|
248
372
|
throw errno('EBADF', 'write', String(fd), -9);
|
|
249
|
-
const
|
|
373
|
+
const explicit = typeof position === 'number' && Number.isSafeInteger(position) && position >= 0
|
|
374
|
+
? position
|
|
375
|
+
: null;
|
|
250
376
|
if (handle.stored) {
|
|
251
|
-
const target =
|
|
377
|
+
const target = explicit ?? (handle.flags.includes('a') ? 'end' : handle.position);
|
|
252
378
|
const end = storage.writeAt(handle.path, bytes, target);
|
|
253
|
-
if (
|
|
379
|
+
if (explicit === null)
|
|
254
380
|
handle.position = end;
|
|
255
381
|
return bytes.byteLength;
|
|
256
382
|
}
|
|
257
383
|
const existing = asBytes(nodeCompatSeed.files[handle.path] ?? '');
|
|
258
|
-
const start =
|
|
259
|
-
? handle.flags.includes('a')
|
|
260
|
-
? existing.byteLength
|
|
261
|
-
: handle.position
|
|
262
|
-
: position;
|
|
384
|
+
const start = explicit ?? (handle.flags.includes('a') ? existing.byteLength : handle.position);
|
|
263
385
|
const next = new Uint8Array(Math.max(existing.byteLength, start + bytes.byteLength));
|
|
264
386
|
next.set(existing, 0);
|
|
265
387
|
next.set(bytes, start);
|
|
266
388
|
nodeCompatSeed.files[handle.path] = new TextDecoder().decode(next);
|
|
267
|
-
if (
|
|
389
|
+
if (explicit === null)
|
|
268
390
|
handle.position = start + bytes.byteLength;
|
|
269
391
|
return bytes.byteLength;
|
|
270
392
|
}
|