Nix Archive (NAR): JavaScript parsing library

Nix Archive (NAR) is the archive format of the Nix package manager. A NAR contains a single file system object: a regular file, a symbolic link, or a directory with everything in it. Besides names, file contents and symlink targets, it only stores which regular files are executable. There are no timestamps and no other permissions.

Unlike TAR or ZIP, the format is canonical: a given file system object always has the same NAR. For example, directory entries are always sorted by name. Nix identifies the contents of each store path by the SHA-256 hash of its NAR, and binary caches serve store paths as NARs, usually compressed. GNU Guix uses the same format.

This Kaitai Struct implementation rejects the same NARs as Nix 2.36.0 with the default settings on Linux, except that it accepts entry names that contain /.

Older versions of Nix may accept more NARs. For example, Nix checks the order of directory entries only since version 2.25.0, and it limits the length of names and symlink targets and the nesting depth only since 2.35.0. Some of these checks were also backported to patch releases of older versions.

File extension

nar

KS implementation details

License: MIT

References

This page hosts a formal specification of Nix Archive (NAR) using Kaitai Struct. This specification can be automatically translated into a variety of programming languages to get a parsing library.

Usage

Runtime library

All JavaScript code generated by Kaitai Struct depends on the Kaitai Struct runtime library for JavaScript. You must add this dependency to your project before you can parse or serialize any data.

The JavaScript runtime library is available at npm:

npm install kaitai-struct

Code

See the usage examples in the JavaScript notes.

Parse structure from an ArrayBuffer:

var arrayBuffer = ...;
var data = new NixNar(new KaitaiStream(arrayBuffer));

After that, one can get various attributes from the structure by accessing fields or properties like:

data.magic // => Magic string, must be `nix-archive-1`.

JavaScript source code to parse Nix Archive (NAR)

NixNar.js

// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['exports', 'kaitai-struct/KaitaiStream'], factory);
  } else if (typeof exports === 'object' && exports !== null && typeof exports.nodeType !== 'number') {
    factory(exports, require('kaitai-struct/KaitaiStream'));
  } else {
    factory(root.NixNar || (root.NixNar = {}), root.KaitaiStream);
  }
})(typeof self !== 'undefined' ? self : this, function (NixNar_, KaitaiStream) {
/**
 * Nix Archive (NAR) is the archive format of the [Nix](https://nixos.org/)
 * package manager. A NAR contains a single file system object: a regular
 * file, a symbolic link, or a directory with everything in it. Besides
 * names, file contents and symlink targets, it only stores which regular
 * files are executable. There are
 * [no timestamps and no other permissions](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/command-ref/nix-store/dump.md?plain=1#L15-L19).
 * 
 * Unlike TAR or ZIP, the format is
 * [canonical](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/command-ref/nix-store/dump.md?plain=1#L21-L27):
 * a given file system object always has the same NAR. For example,
 * directory entries are always sorted by name. Nix identifies the contents
 * of each store path by the SHA-256 hash of its NAR, and
 * [binary caches](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/binary-cache/index.md?plain=1#L8-L10)
 * serve store paths as NARs, usually compressed.
 * [GNU Guix](https://codeberg.org/guix/guix/src/commit/ab6a9f84e783710335a29f6591f570e5e2df143c/guix/serialization.scm#L441-L446)
 * uses the same format.
 * 
 * This Kaitai Struct implementation rejects the same NARs as Nix 2.36.0
 * with the default settings on Linux, except that it accepts entry names
 * that contain `/`.
 * 
 * Older versions of Nix may accept more NARs. For example, Nix checks the
 * order of directory entries only since version 2.25.0, and it limits the
 * length of names and symlink targets and the nesting depth only since
 * 2.35.0. Some of these checks were also backported to patch releases of
 * older versions.
 * @see {@link https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/nix-archive/index.md|Git tag "2.36.0"}
 */

var NixNar = (function() {
  function NixNar(_io, _parent, _root) {
    this._io = _io;
    this._parent = _parent;
    this._root = _root || this;

    this._read();
  }
  NixNar.prototype._read = function() {
    this.magic = new PaddedStr(this._io, this, this._root);
    var _ = this.magic;
    if (!(_.body == "nix-archive-1")) {
      throw new KaitaiStream.ValidationExprError(this.magic, this._io, "/seq/0");
    }
    this.rootNode = new Node(this._io, this, this._root, 0);
  }

  /**
   * A single file system node (regular file, directory, or symlink).
   */

  var Node = NixNar.Node = (function() {
    function Node(_io, _parent, _root, depth) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;
      this.depth = depth;

      this._read();
    }
    Node.prototype._read = function() {
      this._unnamed0 = this._io.readBytes(0);
      var _ = this._unnamed0;
      if (!(this.depth < 64)) {
        throw new KaitaiStream.ValidationExprError(this._unnamed0, this._io, "/types/node/seq/0");
      }
      this.openParen = new PaddedStr(this._io, this, this._root);
      var _ = this.openParen;
      if (!(_.body == "(")) {
        throw new KaitaiStream.ValidationExprError(this.openParen, this._io, "/types/node/seq/1");
      }
      this.typeKey = new PaddedStr(this._io, this, this._root);
      var _ = this.typeKey;
      if (!(_.body == "type")) {
        throw new KaitaiStream.ValidationExprError(this.typeKey, this._io, "/types/node/seq/2");
      }
      this.typeVal = new PaddedStr(this._io, this, this._root);
      var _ = this.typeVal;
      if (!( ((_.body == "regular") || (_.body == "directory") || (_.body == "symlink")) )) {
        throw new KaitaiStream.ValidationExprError(this.typeVal, this._io, "/types/node/seq/3");
      }
      switch (this.typeVal.body) {
      case "directory":
        this.body = new TypeDirectory(this._io, this, this._root);
        break;
      case "regular":
        this.body = new TypeRegular(this._io, this, this._root);
        break;
      case "symlink":
        this.body = new TypeSymlink(this._io, this, this._root);
        break;
      }
      if (this.typeVal.body != "directory") {
        this.closeParen = new PaddedStr(this._io, this, this._root);
        var _ = this.closeParen;
        if (!(_.body == ")")) {
          throw new KaitaiStream.ValidationExprError(this.closeParen, this._io, "/types/node/seq/5");
        }
      }
    }

    /**
     * Must be `(`, a token starting the node definition.
     */

    /**
     * Must be `type`.
     */

    /**
     * Type of the node (`regular`, `directory`, or `symlink`).
     */

    /**
     * Must be `)`, a token ending the node definition. A directory node
     * has no `close_paren`: its `)` is read as the terminator at the end
     * of `body.entries`.
     */

    /**
     * Nesting depth of the node. The root node has depth 0.
     */

    return Node;
  })();

  /**
   * A byte sequence, prefixed with its length (u8le) and
   * padded with null bytes to the next 8-byte boundary.
   * 
   * Used for entry names and symlink targets, which Nix handles as raw
   * bytes, without decoding them as text.
   */

  var PaddedBytes = NixNar.PaddedBytes = (function() {
    function PaddedBytes(_io, _parent, _root) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;

      this._read();
    }
    PaddedBytes.prototype._read = function() {
      this.lenBody = this._io.readU8le();
      this.body = this._io.readBytes(this.lenBody);
      this.padding = this._io.readBytes(KaitaiStream.mod(8 - KaitaiStream.mod(this.lenBody, 8), 8));
      var _ = this.padding;
      if (!((_.length != 0 ? KaitaiStream.arrayMax(_) == 0 : true))) {
        throw new KaitaiStream.ValidationExprError(this.padding, this._io, "/types/padded_bytes/seq/2");
      }
    }

    return PaddedBytes;
  })();

  /**
   * A string, prefixed with its length (u8le) and
   * padded with null bytes to the next 8-byte boundary.
   * 
   * Used for the tokens of the format, such as `nix-archive-1`, `(` and
   * `type`. They are all ASCII.
   */

  var PaddedStr = NixNar.PaddedStr = (function() {
    function PaddedStr(_io, _parent, _root) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;

      this._read();
    }
    PaddedStr.prototype._read = function() {
      this.lenBody = this._io.readU8le();
      this.body = KaitaiStream.bytesToStr(this._io.readBytes(this.lenBody), "ASCII");
      this.padding = this._io.readBytes(KaitaiStream.mod(8 - KaitaiStream.mod(this.lenBody, 8), 8));
      var _ = this.padding;
      if (!((_.length != 0 ? KaitaiStream.arrayMax(_) == 0 : true))) {
        throw new KaitaiStream.ValidationExprError(this.padding, this._io, "/types/padded_str/seq/2");
      }
    }

    return PaddedStr;
  })();

  /**
   * A directory node, containing a list of entries. Entries must be
   * ordered by their names. Each name must be greater than the previous
   * one when compared lexicographically as arrays of unsigned bytes.
   */

  var TypeDirectory = NixNar.TypeDirectory = (function() {
    function TypeDirectory(_io, _parent, _root) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;

      this._read();
    }
    TypeDirectory.prototype._read = function() {
      this.entries = [];
      var i = 0;
      do {
        var _ = new DirEntry(this._io, this, this._root);
        this.entries.push(_);
        var _ = this.entries[i];
        if (!(( ((i != 0) && (!(_.isTerminator)))  ? (KaitaiStream.byteArrayCompare(_.body.name.body, this.entries[i - 1].body.name.body) > 0) : true))) {
          throw new KaitaiStream.ValidationExprError(this.entries[i], this._io, "/types/type_directory/seq/0");
        }
        i++;
      } while (!(_.isTerminator));
    }

    /**
     * A single entry within a directory, or the terminator, i.e. the `)`
     * token that ends the directory node.
     */

    var DirEntry = TypeDirectory.DirEntry = (function() {
      function DirEntry(_io, _parent, _root) {
        this._io = _io;
        this._parent = _parent;
        this._root = _root;

        this._read();
      }
      DirEntry.prototype._read = function() {
        this.kind = new PaddedStr(this._io, this, this._root);
        var _ = this.kind;
        if (!( ((_.body == "entry") || (_.body == ")")) )) {
          throw new KaitaiStream.ValidationExprError(this.kind, this._io, "/types/type_directory/types/dir_entry/seq/0");
        }
        if (!(this.isTerminator)) {
          this.body = new DirEntryBody(this._io, this, this._root);
        }
      }
      Object.defineProperty(DirEntry.prototype, 'isTerminator', {
        get: function() {
          if (this._m_isTerminator !== undefined)
            return this._m_isTerminator;
          this._m_isTerminator = this.kind.body == ")";
          return this._m_isTerminator;
        }
      });

      /**
       * Must be `entry` (for a child node) or `)` (for the terminator).
       */

      /**
       * The entry itself. The terminator has no `body`.
       */

      return DirEntry;
    })();

    var DirEntryBody = TypeDirectory.DirEntryBody = (function() {
      function DirEntryBody(_io, _parent, _root) {
        this._io = _io;
        this._parent = _parent;
        this._root = _root;

        this._read();
      }
      DirEntryBody.prototype._read = function() {
        this.openParen = new PaddedStr(this._io, this, this._root);
        var _ = this.openParen;
        if (!(_.body == "(")) {
          throw new KaitaiStream.ValidationExprError(this.openParen, this._io, "/types/type_directory/types/dir_entry_body/seq/0");
        }
        this.nameKey = new PaddedStr(this._io, this, this._root);
        var _ = this.nameKey;
        if (!(_.body == "name")) {
          throw new KaitaiStream.ValidationExprError(this.nameKey, this._io, "/types/type_directory/types/dir_entry_body/seq/1");
        }
        this.name = new PaddedBytes(this._io, this, this._root);
        var _ = this.name;
        if (!( ((_.body.length != 0) && (_.body.length <= 255) && ((KaitaiStream.byteArrayCompare(_.body, new Uint8Array([46])) != 0)) && ((KaitaiStream.byteArrayCompare(_.body, new Uint8Array([46, 46])) != 0)) && (KaitaiStream.arrayMin(_.body) != 0)) )) {
          throw new KaitaiStream.ValidationExprError(this.name, this._io, "/types/type_directory/types/dir_entry_body/seq/2");
        }
        this.nodeKey = new PaddedStr(this._io, this, this._root);
        var _ = this.nodeKey;
        if (!(_.body == "node")) {
          throw new KaitaiStream.ValidationExprError(this.nodeKey, this._io, "/types/type_directory/types/dir_entry_body/seq/3");
        }
        this.node = new Node(this._io, this, this._root, this._parent._parent._parent.depth + 1);
        this.closeParen = new PaddedStr(this._io, this, this._root);
        var _ = this.closeParen;
        if (!(_.body == ")")) {
          throw new KaitaiStream.ValidationExprError(this.closeParen, this._io, "/types/type_directory/types/dir_entry_body/seq/5");
        }
      }

      /**
       * Name of the entry, as raw bytes. Nix 2.36.0
       * [doesn't decode names as text](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/archive.cc#L245-L248)
       * either, and real NARs contain names that aren't valid UTF-8.
       * 
       * The name must be 1 to 255 bytes long, must not be `.` or `..`, and
       * must not contain a null byte. Nix also rejects names that contain
       * `/`, but this Kaitai Struct implementation doesn't check that: as
       * of KS 0.11, expressions can't search a byte array for a given
       * byte. A null byte can be detected anyway: 0 is the smallest
       * possible byte value, so a name contains a null byte exactly if its
       * smallest byte is 0.
       */

      /**
       * The child node.
       */

      return DirEntryBody;
    })();

    return TypeDirectory;
  })();

  /**
   * A regular file node.
   */

  var TypeRegular = NixNar.TypeRegular = (function() {
    function TypeRegular(_io, _parent, _root) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;

      this._read();
    }
    TypeRegular.prototype._read = function() {
      this.firstKey = new PaddedStr(this._io, this, this._root);
      var _ = this.firstKey;
      if (!( ((_.body == "executable") || (_.body == "contents")) )) {
        throw new KaitaiStream.ValidationExprError(this.firstKey, this._io, "/types/type_regular/seq/0");
      }
      if (this.isExecutable) {
        this.executableVal = new PaddedStr(this._io, this, this._root);
        var _ = this.executableVal;
        if (!(_.body == "")) {
          throw new KaitaiStream.ValidationExprError(this.executableVal, this._io, "/types/type_regular/seq/1");
        }
      }
      if (this.isExecutable) {
        this.contentsKey = new PaddedStr(this._io, this, this._root);
        var _ = this.contentsKey;
        if (!(_.body == "contents")) {
          throw new KaitaiStream.ValidationExprError(this.contentsKey, this._io, "/types/type_regular/seq/2");
        }
      }
      this.fileData = new FileContent(this._io, this, this._root);
    }

    /**
     * The contents of the file, prefixed with their length and padded
     * with null bytes to the next 8-byte boundary.
     */

    var FileContent = TypeRegular.FileContent = (function() {
      function FileContent(_io, _parent, _root) {
        this._io = _io;
        this._parent = _parent;
        this._root = _root;

        this._read();
      }
      FileContent.prototype._read = function() {
        this.lenContents = this._io.readU8le();
        if (this.narOffset < 0) {
          this._unnamed1 = this._io.readBytes(0);
        }
        this.contents = this._io.readBytes(this.lenContents);
        this.padding = this._io.readBytes(KaitaiStream.mod(8 - KaitaiStream.mod(this.lenContents, 8), 8));
        var _ = this.padding;
        if (!((_.length != 0 ? KaitaiStream.arrayMax(_) == 0 : true))) {
          throw new KaitaiStream.ValidationExprError(this.padding, this._io, "/types/type_regular/types/file_content/seq/3");
        }
      }

      /**
       * Offset of `contents` in the stream. It corresponds to
       * [`narOffset`](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/include/nix/util/source-accessor.hh#L134-L138)
       * in Nix.
       */
      Object.defineProperty(FileContent.prototype, 'narOffset', {
        get: function() {
          if (this._m_narOffset !== undefined)
            return this._m_narOffset;
          this._m_narOffset = this._io.pos;
          return this._m_narOffset;
        }
      });

      /**
       * This Kaitai Struct implementation keeps the contents of every
       * file in memory, so parsing a NAR needs at least as much memory
       * as all its files together.
       */

      return FileContent;
    })();

    /**
     * True if the file has the `executable` attribute.
     */
    Object.defineProperty(TypeRegular.prototype, 'isExecutable', {
      get: function() {
        if (this._m_isExecutable !== undefined)
          return this._m_isExecutable;
        this._m_isExecutable = this.firstKey.body == "executable";
        return this._m_isExecutable;
      }
    });

    /**
     * Either `executable` or `contents`.
     */

    /**
     * Must be empty.
     */

    return TypeRegular;
  })();

  /**
   * A symbolic link node.
   */

  var TypeSymlink = NixNar.TypeSymlink = (function() {
    function TypeSymlink(_io, _parent, _root) {
      this._io = _io;
      this._parent = _parent;
      this._root = _root;

      this._read();
    }
    TypeSymlink.prototype._read = function() {
      this.targetKey = new PaddedStr(this._io, this, this._root);
      var _ = this.targetKey;
      if (!(_.body == "target")) {
        throw new KaitaiStream.ValidationExprError(this.targetKey, this._io, "/types/type_symlink/seq/0");
      }
      this.targetVal = new PaddedBytes(this._io, this, this._root);
      var _ = this.targetVal;
      if (!( ((_.body.length != 0) && (_.body.length <= 4095) && (KaitaiStream.arrayMin(_.body) != 0)) )) {
        throw new KaitaiStream.ValidationExprError(this.targetVal, this._io, "/types/type_symlink/seq/1");
      }
    }

    /**
     * Must be `target`.
     */

    /**
     * The destination path of the symlink, as raw bytes. Nix 2.36.0
     * [doesn't decode targets as text](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/archive.cc#L280-L282)
     * either.
     * 
     * The target must be 1 to 4095 bytes long and must not contain a null
     * byte.
     */

    return TypeSymlink;
  })();

  /**
   * Magic string, must be `nix-archive-1`.
   */

  /**
   * The root of the archive, which is always a single node.
   */

  return NixNar;
})();
NixNar_.NixNar = NixNar;
});