@rome-os/node-core 0.1.5 → 0.1.7

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/dist/local.d.ts CHANGED
@@ -11,8 +11,10 @@ export declare const callerCredentialPath: (config: NodeConfig) => string;
11
11
  export declare const daemonStatePath: (config: NodeConfig) => string;
12
12
  export interface CallerCredential {
13
13
  cloudUrl: string;
14
- token: string;
14
+ token?: string;
15
+ signerSocket?: string;
15
16
  }
17
+ export declare function callerToken(credential: CallerCredential): () => string | Promise<string>;
16
18
  export declare class CallerConfigurationError extends Error {
17
19
  readonly code: "not_configured" | "daemon_running" | "instance_token_required";
18
20
  constructor(code: "not_configured" | "daemon_running" | "instance_token_required", message: string);
package/dist/local.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { isRecord } from "./actions.js";
5
5
  import { cloudOrigin } from "./cloud.js";
6
+ import { requestSignerToken } from "./signer.js";
6
7
  import { readPrivateJson } from "./storage.js";
7
8
  export function createNodeConfig(options) {
8
9
  const directory = resolve(options.directory);
@@ -23,6 +24,10 @@ export function nodeConfigFromEnvironment(env) {
23
24
  }
24
25
  export const callerCredentialPath = (config) => join(config.directory, "caller.json");
25
26
  export const daemonStatePath = (config) => join(config.directory, "daemon.json");
27
+ export function callerToken(credential) {
28
+ const { signerSocket, token } = credential;
29
+ return signerSocket ? () => requestSignerToken(signerSocket) : () => token;
30
+ }
26
31
  export class CallerConfigurationError extends Error {
27
32
  code;
28
33
  constructor(code, message) {
@@ -32,10 +37,13 @@ export class CallerConfigurationError extends Error {
32
37
  }
33
38
  export async function readOptionalCallerCredential(config) {
34
39
  const value = await readPrivateJson(callerCredentialPath(config));
35
- if (!isRecord(value) ||
36
- typeof value.cloudUrl !== "string" ||
37
- typeof value.token !== "string" ||
38
- !/^romedev_[A-Za-z0-9_-]{43}$/.test(value.token))
40
+ if (!isRecord(value) || typeof value.cloudUrl !== "string")
41
+ return null;
42
+ if (value.version === 2)
43
+ return typeof value.signerSocket === "string" && isAbsolute(value.signerSocket)
44
+ ? { cloudUrl: cloudOrigin(value.cloudUrl), signerSocket: value.signerSocket }
45
+ : null;
46
+ if (typeof value.token !== "string" || !/^romedev_[A-Za-z0-9_-]{43}$/.test(value.token))
39
47
  return null;
40
48
  return { cloudUrl: cloudOrigin(value.cloudUrl), token: value.token };
41
49
  }
@@ -3,6 +3,7 @@ export declare const CLOSE: {
3
3
  readonly revoked: 4001;
4
4
  readonly superseded: 4002;
5
5
  readonly outputLimit: 4003;
6
+ readonly expired: 4004;
6
7
  readonly invalid: 1008;
7
8
  readonly tooLarge: 1009;
8
9
  };
package/dist/protocol.js CHANGED
@@ -3,6 +3,7 @@ export const CLOSE = {
3
3
  revoked: 4001,
4
4
  superseded: 4002,
5
5
  outputLimit: 4003,
6
+ expired: 4004,
6
7
  invalid: 1008,
7
8
  tooLarge: 1009,
8
9
  };
@@ -0,0 +1,10 @@
1
+ export declare function isJwt(value: string): boolean;
2
+ export declare class SignerError extends Error {
3
+ readonly code: "signer_unavailable" | "rate_limited";
4
+ constructor(code: "signer_unavailable" | "rate_limited");
5
+ }
6
+ export declare function requestSignerToken(socketPath: string): Promise<string>;
7
+ export declare function signerHealth(socketPath: string): Promise<{
8
+ jkt: string;
9
+ aud: string;
10
+ }>;
package/dist/signer.js ADDED
@@ -0,0 +1,52 @@
1
+ import { request } from "node:http";
2
+ import { isRecord } from "./actions.js";
3
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
4
+ export function isJwt(value) {
5
+ return value.length <= 2048 && JWT_SHAPE.test(value);
6
+ }
7
+ export class SignerError extends Error {
8
+ code;
9
+ constructor(code) {
10
+ super(code === "rate_limited"
11
+ ? "The signer is rate limited."
12
+ : "The signing service is not running.");
13
+ this.code = code;
14
+ }
15
+ }
16
+ function signerCall(socketPath, method, path) {
17
+ return new Promise((resolve, reject) => {
18
+ const req = request({ socketPath, method, path, timeout: 2000 }, (res) => {
19
+ const chunks = [];
20
+ res.on("data", (chunk) => chunks.push(chunk));
21
+ res.on("error", () => reject(new SignerError("signer_unavailable")));
22
+ res.on("end", () => {
23
+ if (res.statusCode === 200) {
24
+ try {
25
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
26
+ return;
27
+ }
28
+ catch { }
29
+ }
30
+ reject(new SignerError(res.statusCode === 429 ? "rate_limited" : "signer_unavailable"));
31
+ });
32
+ });
33
+ req.on("timeout", () => req.destroy());
34
+ req.on("error", () => reject(new SignerError("signer_unavailable")));
35
+ req.end();
36
+ });
37
+ }
38
+ export async function requestSignerToken(socketPath) {
39
+ const body = await signerCall(socketPath, "POST", "/v1/token");
40
+ if (!isRecord(body) || typeof body.token !== "string" || !isJwt(body.token))
41
+ throw new SignerError("signer_unavailable");
42
+ return body.token;
43
+ }
44
+ export async function signerHealth(socketPath) {
45
+ const body = await signerCall(socketPath, "GET", "/v1/health");
46
+ if (!isRecord(body) ||
47
+ body.ok !== true ||
48
+ typeof body.jkt !== "string" ||
49
+ typeof body.aud !== "string")
50
+ throw new SignerError("signer_unavailable");
51
+ return { jkt: body.jkt, aud: body.aud };
52
+ }
package/dist/storage.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export declare function readPrivateJson(path: string): Promise<unknown>;
2
+ export declare function ensurePrivateDirectory(dir: string): Promise<void>;
2
3
  export declare function writePrivateJson(path: string, value: unknown): Promise<void>;
3
4
  export interface CredentialStore<T> {
4
5
  load(): Promise<unknown>;
package/dist/storage.js CHANGED
@@ -13,8 +13,7 @@ export async function readPrivateJson(path) {
13
13
  throw new Error("Could not read the local credential file.");
14
14
  }
15
15
  }
16
- export async function writePrivateJson(path, value) {
17
- const dir = dirname(path);
16
+ export async function ensurePrivateDirectory(dir) {
18
17
  await mkdir(dir, { recursive: true, mode: 0o700 });
19
18
  if (process.platform === "win32") {
20
19
  const run = promisify(execFile);
@@ -37,6 +36,9 @@ export async function writePrivateJson(path, value) {
37
36
  }
38
37
  else
39
38
  await chmod(dir, 0o700);
39
+ }
40
+ export async function writePrivateJson(path, value) {
41
+ await ensurePrivateDirectory(dirname(path));
40
42
  const temporary = `${path}.${randomUUID()}.tmp`;
41
43
  try {
42
44
  await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: "wx" });
@@ -73,13 +73,27 @@ export declare function createPartFile(path: string, id?: string): Promise<{
73
73
  handle: FileHandle;
74
74
  }>;
75
75
  export declare function openDestination(path: string): Promise<Destination>;
76
+ export interface TransferResult {
77
+ code?: string;
78
+ direction?: "push" | "pull";
79
+ path?: string;
80
+ bytes?: number;
81
+ sha256?: string;
82
+ ackedBytes?: number;
83
+ replaced?: {
84
+ size: number;
85
+ mtimeMs: number;
86
+ } | null;
87
+ file?: Buffer;
88
+ }
76
89
  export declare class TransferHost {
77
90
  private options;
78
91
  private transfers;
79
92
  constructor(options?: TransferOptions & {
80
93
  limit?: number;
94
+ keepBytes?: number;
81
95
  });
82
- open(id: string, peer: string, args: unknown, send: TransferSend): Promise<void>;
96
+ open(id: string, peer: string, args: unknown, send: TransferSend): Promise<TransferResult>;
83
97
  receive(id: string, peer: string, message: TransferMessage, body: Uint8Array): void;
84
98
  abortAll(): void;
85
99
  }
package/dist/transfer.js CHANGED
@@ -349,30 +349,41 @@ export class TransferHost {
349
349
  }
350
350
  async open(id, peer, args, send) {
351
351
  if (this.transfers.has(id))
352
- return;
352
+ return { code: "duplicate_transfer" };
353
353
  const request = parseOpen(args);
354
354
  if (!request) {
355
355
  send(actionError("invalid_args", "transfer.open requires direction push or pull, a path, and a size for push."));
356
- return;
356
+ return { code: "invalid_args" };
357
357
  }
358
358
  if (this.transfers.size >= (this.options.limit ?? MAX_HOST_TRANSFERS)) {
359
359
  send(actionError("busy", "The computer is already running its maximum number of transfers."));
360
- return;
360
+ return { code: "busy" };
361
361
  }
362
- const entry = { peer, canceled: false };
362
+ const { direction, path } = request;
363
+ const keep = direction === "push" && (request.size ?? 0) <= (this.options.keepBytes ?? 0);
364
+ const entry = { peer, canceled: false, acked: 0, chunks: keep ? [] : undefined };
365
+ const result = { direction, path };
363
366
  this.transfers.set(id, entry);
364
367
  try {
365
- if (request.direction === "push") {
366
- const destination = await openDestination(request.path);
367
- if (entry.canceled)
368
- return void (await destination.cancel());
368
+ if (direction === "push") {
369
+ const existing = await stat(path).catch(() => null);
370
+ result.replaced = existing?.isFile()
371
+ ? { size: existing.size, mtimeMs: existing.mtimeMs }
372
+ : null;
373
+ const destination = await openDestination(path);
374
+ if (entry.canceled) {
375
+ await destination.cancel();
376
+ return { ...result, code: "canceled" };
377
+ }
369
378
  entry.endpoint = destination.start(send, { ...this.options, size: request.size });
370
379
  send({ type: "response", ok: true, result: {} });
371
380
  }
372
381
  else {
373
- const source = await openSource(request.path);
374
- if (entry.canceled)
375
- return void (await source.close());
382
+ const source = await openSource(path);
383
+ if (entry.canceled) {
384
+ await source.close();
385
+ return { ...result, code: "canceled" };
386
+ }
376
387
  send({
377
388
  type: "response",
378
389
  ok: true,
@@ -380,13 +391,26 @@ export class TransferHost {
380
391
  });
381
392
  entry.endpoint = source.start(send, this.options);
382
393
  }
383
- await entry.endpoint.result.catch(() => { });
394
+ const summary = await entry.endpoint.result;
395
+ return {
396
+ ...result,
397
+ bytes: summary.size,
398
+ sha256: summary.sha256,
399
+ ...(direction === "pull" ? { ackedBytes: entry.acked } : {}),
400
+ ...(entry.chunks ? { file: Buffer.concat(entry.chunks) } : {}),
401
+ };
384
402
  }
385
403
  catch (error) {
386
- if (!entry.canceled)
387
- send(error instanceof TransferError
388
- ? actionError(error.code, error.message)
389
- : actionError("io_error", "The transfer failed."));
404
+ const failure = error instanceof TransferError
405
+ ? error
406
+ : new TransferError("io_error", "The transfer failed.");
407
+ if (!entry.canceled && !entry.endpoint)
408
+ send(actionError(failure.code, failure.message));
409
+ return {
410
+ ...result,
411
+ code: failure.code,
412
+ ...(direction === "pull" ? { ackedBytes: entry.acked } : {}),
413
+ };
390
414
  }
391
415
  finally {
392
416
  this.transfers.delete(id);
@@ -396,6 +420,10 @@ export class TransferHost {
396
420
  const entry = this.transfers.get(id);
397
421
  if (!entry || entry.peer !== peer)
398
422
  return;
423
+ if (message.kind === "data")
424
+ entry.chunks?.push(Buffer.from(body));
425
+ else if (message.kind === "ack")
426
+ entry.acked = Math.max(entry.acked, message.offset);
399
427
  if (entry.endpoint)
400
428
  entry.endpoint.receive(message, body);
401
429
  else if (message.kind === "abort")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rome-os/node-core",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "JavaScript APIs for Rome device hosts and shared caller daemons",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,6 +37,10 @@
37
37
  "types": "./dist/auth.d.ts",
38
38
  "default": "./dist/auth.js"
39
39
  },
40
+ "./signer": {
41
+ "types": "./dist/signer.d.ts",
42
+ "default": "./dist/signer.js"
43
+ },
40
44
  "./socket": {
41
45
  "types": "./dist/socket.d.ts",
42
46
  "default": "./dist/socket.js"