1.0.6 • Published 10 days ago

@teamteanpm2024/cupiditate-sunt-consectetur v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
10 days ago

Magic bytes

Build and test

Magic Bytes is a javascript library analyzing the first bytes of a file to tell you its type. Use it inside your browser or serversided using nodejs.

The procedure is based on https://en.wikipedia.org/wiki/List_of_file_signatures.

!NOTE
A small note on versioning. Strictly speaking, each new filetype which is supported by this library can break someones' API. Please note that this library adds new filetypes with minor release. This means files, which validate to "null" in some versions, may find a result in a new version.

Or in some cases the library will find more results, than before. So don't depend on the found-array size in any shape or form. Filetypes will not be remoevd tho

Installation

Run npm install @teamteanpm2024/cupiditate-sunt-consectetur

Interactive example

There is an interactive example present at https://larskoelpin.github.io/magic-bytes/.

Usage

The following functions are available:

  • filetypeinfo(bytes: number[]) Contains typeinformation like name, extension and mime type: [{typename: "zip"}, {typename: "jar"}]
  • filetypename(bytes: number[]) : Contains type names only: ["zip", "jar"]
  • filetypemime(bytes: number[]) : Contains type mime types only: ["application/zip", "application/jar"]
  • filetypeextension(bytes: number[]) : Contains type extensions only: ["zip", "jar"]

Both function return an empty array [] otherwise, which means it could not detect the file signature. Keep in mind that txt files for example fall in this category.

You don't have to load the whole file in memory. For validating a file uploaded to S3 using Lambda for example, it may be
enough to load the files first 100 bytes and validate against them. This is especially useful for big files.

see examples for practical usage.

On server:

import filetype from '@teamteanpm2024/cupiditate-sunt-consectetur'

filetype(fs.readFileSync("myimage.png")) // ["png"]

To run an HTML-Example checkout the project and run

npm install; npm run example

This opens an HTML example using magic bytes as a window variable. It kinda looks like that.

<input type="file" id="file" />

 <script src="node_modules/@teamteanpm2024/cupiditate-sunt-consectetur/dist/browser.js" type="application/javascript"></script>
<script>
    document.getElementById("file").addEventListener('change', (event, x) => {
      const fileReader = new FileReader();
      fileReader.onloadend = (f) => {
        const bytes = new Uint8Array(f.target.result);
        console.log("Possible filetypes: " + filetypeinfo(bytes))
      }
      fileReader.readAsArrayBuffer(event.target.files[0])
    })
</script>

Tests

Run npm test

Example

See examples/

How does it work

The create-snapshot.js creates a new tree. The tree has a similar shape to the following

{
  "0x47": {
    "0x49": {
      "0x46": {
        "0x38": {
          "0x37": {
            "0x61": {
              "matches": [
                {
                  "typename": "gif",
                  "mime": "image/gif",
                  "extension": "gif"
                }
              ]
            }
          },
        }
      }
    }
  }
}

It acts as a giant lookup map for the given byte signatures.

readableequalitydateextendslicedifftestingjavascriptfast-copywritableArray.prototype.flattentesturlglacierpipecacheRxJSdatatc39class-validatorECMAScript 5propertiesless.jsbluebirdArray.prototype.containsupfindLastIndexdebugcommanderconfigurableES3polyfillchineseboundtrimEndschematrimLeftassignredux-toolkitmonorepoinstalleres2016css nestingnumberES2017exit-codeStreamObject.assignlintBigInt64ArrayfunctionaltermfileredactaccessorArrayBuffer#sliceformsettingsmetadatabcryptloggerresolveparents3lazyajvruntimewatchFileauthenticationflagsString.prototype.trimrequireimmutableCSSautoscalingES2018deepfastclonefullwidthvariablesflatMapstatelesssigintprettyspinnersworkervalidatejsdomtypesafelogUint16Arraysignaleslintshammake dirECMAScript 2022valuesvariables in cssquerystringharmonycolorES2021ECMAScript 2021shimjoiUint8ClampedArrayenvStreamsexpressionpoint-freeyamlWeakMapminimalterminalclassesjson-schema-validatorString.prototype.matchAlllesscsstranspiletypanionwalkingawesomesaucelook-upsanitizationfast-clonedescriptorloadingesassertlimitencryptioncorsrecursivepropremovebootstrap cssreuseprotocontainsswfreducetsphonedirectorycoercibleregular expressionstarterescapestyled-componentsbundlingsymlinksInt32ArrayES2020folderbusyansiserializationdescriptioninternal slotbalancedbyteLengthhandlersproxyReflect.getPrototypeOfbreaklastSymbol.toStringTagprotobufkinesissymboljsyupextradragrapidformstypenamelrunodeUint8Arrayprivate datajasminesqswhichconcatFunction.prototype.nameenderMicrosoftes2015byteOffsetexit$.extendnegative zeroArray.prototype.findLastObject.keysrm -frsimpledbcharacterstoArraybabelreduxincludesfast-deep-clonenpm__proto__chromiumtapelistenersposeObservablescolumnsvpcefficientgroupByagentfetchbddcurlmakeargparsehttpslanguagedataviewarrayreact-hook-formclassnamewordbreakoperating-systemargses-abstractsequenceworkspace:*somelessstringifyrdsmodulemkdirpmimermdirtypeddeep-clonedependenciesmruwidthmobileparsertaskrequestobjectfindLastsafeuser-streamssettercorecurriedscheme-validationparentsflagsnsES2015patchinstallchaiec2css variablesharedtextdircompilerutilitiesES2019Uint32ArrayTypeScriptArray.prototype.flatMapdomreadablestreamgdprtypeerroropengrouptypesless compilerpostcss-plugincollectiondroptakees7modulesperformancedeep-copytimeunicoderatelimitroute53zodshelldynamodbkoreanelbprefixTypedArraysortexecpersistentspecdom-testing-libraryeventEmitter0weaksettouchdataViewmoveECMAScript 7findcryptinferencewhatwgconnectfsconfigbuffersjson-schemabannerfigletebsES6iterationemojiObject.valuestrimStartjesttypeofidlegradients cssflathookform
1.0.6

10 days ago

1.0.5

11 days ago

1.0.4

12 days ago

1.0.3

13 days ago

1.0.2

14 days ago

1.0.1

15 days ago

1.0.0

15 days ago