@nanopub/nanopub-js
v0.3.2
Published
[](https://coveralls.io/github/Nanopublication/nanopub-js?branch=main)
Keywords
Readme
nanopub-js
A TypeScript library for creating, signing, publishing, and querying nanopublications.
Installation
# Using npm
npm install @nanopub/nanopub-js
# Using yarn
yarn add @nanopub/nanopub-jsUsage
See examples/ for demo apps for browser and node usage.
Using NanopubClass
import { NanopubClass, serialize } from '@nanopub/nanopub-js';
import { NamedNode, Quad, Literal } from 'n3';
// Create a nanopub from an RDF string
const npFromRdf = NanopubClass.fromRdf(rdfString, 'trig', {
privateKey,
name: 'Hello from nanopub-js',
orcid: 'https://orcid.org/0000-0000-0000-0000',
});
// Or create a nanopub from an assertion
const assertion = [
new Quad(
new NamedNode('https://example.org/subject'),
new NamedNode('https://example.org/predicate'),
new Literal('Example object')
)
];
const np = new NanopubClass({
assertion,
options: {
privateKey: process.env.MY_PRIVATE_KEY!,
name: 'Hello from nanopub-js',
orcid: 'https://orcid.org/0000-0000-0000-0000',
}
});
// Serialize (default: trig)
console.log(np.rdf());
// Or use the serialize helper
console.log(await serialize(np, 'turtle'));
console.log(await serialize(np, 'json-ld'));Signing and publishing
Nanopublications must be signed before publishing.
Calling publish() will automatically sign the nanopublication if it has not been signed yet.
// Sign the nanopublication
await np.sign();
// Check signature validity
const valid = await np.hasValidSignature();
console.log('Signature valid:', valid);
// Publish to a nanopub server (in this example, we use the test server)
const { uri, server } = await np.publish('https://test.registry.knowledgepixels.com/np/');
console.log(`Published at ${uri} on ${server}`);Private key formats
The privateKey given to a nanopub is accepted in any of the usual RSA
serializations, so a key can be passed straight from wherever it was generated:
- PEM armor around a PKCS#8 key (
-----BEGIN PRIVATE KEY-----), whatopenssl genpkey, Node'sexport({format: 'pem', type: 'pkcs8'})and pycryptodome'sexport_key('PEM', pkcs=8)produce; - PEM armor around a PKCS#1 key (
-----BEGIN RSA PRIVATE KEY-----), whatopenssl genrsaproduces, converted to PKCS#8 on the way in; - the bare base64 of the DER with no armor, with or without line breaks — the
form nanopub itself stores in
~/.nanopub/id_rsaand records in a signature.
Public keys are accepted the same way (-----BEGIN PUBLIC KEY-----,
-----BEGIN RSA PUBLIC KEY-----, or bare base64). A key that cannot be used
is reported by its format rather than as an opaque crypto error: a
passphrase-protected key, for instance, names openssl pkcs8 -topk8 -nocrypt
as the fix. The normalization is available on its own:
import { normalizePrivateKey, normalizePublicKey } from '@nanopub/nanopub-js';
normalizePrivateKey(pem); // base64 of the PKCS#8 DER, single line
normalizePublicKey(pem); // base64 of the SubjectPublicKeyInfo DER, single lineReading JSON-LD
parse() and Nanopub.fromRdf() handle TriG, Turtle and the N-Triples family through
n3, which does not parse JSON-LD. To read that syntax, pass a parser:
import jsonld from 'jsonld';
const parser = (input: string) => jsonld.toRDF(JSON.parse(input)) as Quad[];
const np = Nanopub.fromRdf(json, 'jsonld', { parser });Asking for 'jsonld' without a parser throws, rather than parsing to nothing.
Introducing a key
Before the network trusts what you publish, the key you sign with has to be
declared in an introduction nanopublication. createIntroNanopub builds one:
import { createIntroNanopub } from '@nanopub/nanopub-js';
const intro = await createIntroNanopub({
agent: 'https://orcid.org/0000-0002-1267-0234',
privateKey,
name: 'Tobias Kuhn',
});
await intro.sign();
const { uri } = await intro.publish();The agent IRI is usually an ORCID iD, but any foaf:Agent IRI works, a WebID
included. The public key is derived from the private key unless you pass
publicKey, and the introduction is self-signed by the key it declares.
Trust is granted per key rather than per agent, so an agent that already has an
approved key adds another by publishing a further introduction under the same
agent IRI. To restate existing keys alongside a new one, pass them together:
const intro = await createIntroNanopub({
agent: 'https://orcid.org/0000-0002-1267-0234',
privateKey,
keys: [
{ publicKey: existingPublicKey, keyLocation: 'https://nanodash.net/' },
{ publicKey: newPublicKey },
],
});Publishing an introduction does not by itself make the key trusted: an already trusted agent still has to endorse it.
grlc queries
A nanopublication cannot be edited after the fact, so a grlc query whose SPARQL
doesn't parse is broken permanently: it can never run, and the only remedy is
publishing a corrected version. The SPARQL carried by
https://w3id.org/kpxl/grlc/sparql is therefore checked before the
nanopublication is signed, and again before it is published — before any server
is contacted. Nanopublications published before this check existed still load
and read as before.
Where the query is broken by a character that reads as an ordinary one, which is the usual way it happens, the error names that character:
Nanopub has invalid SPARQL and cannot be signed: Invalid SPARQL as object of
https://w3id.org/kpxl/grlc/sparql: This is not valid SPARQL. The character at
line 2, column 8 is U+00A0 (NO-BREAK SPACE), which SPARQL doesn't allow there.
Characters like this one tend to slip in when a query is copied from a word
processor or a web page, and replacing them with their plain equivalents makes
the query valid again.The same check is available on its own:
import { getSparqlSyntaxError, isValidSparql, getInvalidSparql } from '@nanopub/nanopub-js';
await isValidSparql('select ?np where { ?np ?p ?o }'); // true
await getSparqlSyntaxError(query); // the description above, or null
await getInvalidSparql(np); // one entry per broken query the nanopub carriesThe check has to accept what grlc's own endpoint accepts, so it uses Traqula's SPARQL 1.1 parser configured to match RDF4J: the prefixes RDF4J declares for every query are pre-declared, and the restrictions Traqula enforces that RDF4J does not are left to the endpoint that runs the query. Measured against the 1364 grlc queries published so far, it agrees with RDF4J on all but two, and rejects none that RDF4J accepts.
The parser is loaded only when a nanopublication actually carries a grlc query, so it stays out of the bundle everything else pays for.
Using NanopubClient
import { NanopubClient } from '@nanopub/nanopub-js';
const client = new NanopubClient({
endpoints: ['https://query.knowledgepixels.com/'],
});
// Fetch a nanopublication in Trig format
const trig = await client.fetchNanopub(
'https://w3id.org/np/RAO0soO0mUWTqqMaz1QcGbdIt90MJ55RXJck8w8wGGc0U'
);
console.log(trig);
// Fetch a nanopublication in JSON-LD
const jsonld = await client.fetchNanopub(
'https://w3id.org/np/RAO0soO0mUWTqqMaz1QcGbdIt90MJ55RXJck8w8wGGc0U',
'jsonld'
);
console.log(jsonld);
// Run a text search
for await (const np of client.findNanopubsWithText('example search')) {
console.log(np);
}
// Run a pattern search
for await (const np of client.findNanopubsWithPattern(
'http://www.w3.org/2002/07/owl#Thing',
undefined,
undefined
)) {
console.log(np);
}
// Find "things" (concepts)
for await (const thing of client.findThings(
'http://www.w3.org/2002/07/owl#Class'
)) {
console.log(thing);
}
// Run a query template
for await (const row of client.runQueryTemplate(
'RAOGCU2nQzZ0aE2iXwJ20jJtnZsjVR0pfFg0qlSxYtBIA/get-news-content',
{ resource: 'https://w3id.org/spaces/knowledgepixels' }
)) {
console.log(row);
}License
This project is licensed under the MIT License.
