initial commit

This commit is contained in:
user 2022-07-06 07:23:55 -04:00
commit 251223f98e
10 changed files with 2643 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
node_modules
*.js
*.der
*.pem
*.dat
settings.json

23
config.ts Normal file
View File

@ -0,0 +1,23 @@
export interface Setting {
options: { http?: string, grpc?: string }
peers: Array<string>;
}
export interface Settings {
nodes: Record<string, Setting>;
}
const Config = {
keys: {
sign: {
private: "ed25519-sign-private.der",
public: "ed25519-sign-public.der"
},
encrypt: {
private: "x25519-encrypt-private.der",
public: "x25519-encrypt-public.der"
}
}
};
export default Config;

100
constants.ts Normal file
View File

@ -0,0 +1,100 @@
interface Header {
name: string;
offset: number;
length: number;
derived?: boolean
}
export const Constants = {
crypto:
{
RAW_KEY_LENGTH: 32,
SIGN_PRIVATE_KEY_HEADER: Buffer.from("302e020100300506032b657004220420", "hex"),
ENCRYPT_PRIVATE_KEY_HEADER: Buffer.from("302e020100300506032b656e04220420", "hex"),
PRIVATE_KEY_LENGTH: 48,
SIGN_PUBLIC_KEY_HEADER: Buffer.from("302a300506032b6570032100", "hex"),
ENCRYPT_PUBLIC_KEY_HEADER: Buffer.from("302a300506032b656e032100", "hex"),
PUBLIC_KEY_LENGTH: 44,
SIGNATURE_LENGTH: 64
},
fields: {
PAYLOAD_LENGTH_OFFSET: -1, // filled in below
TOTAL_HEADERS_LENGTH: -1,
PAYLOAD_MAX_LENGTH: -1, // 64KB - headers
headers: [
{
name: "MAGIC",
offset: 0,
length: 2
},
{
name: "PROTOCOL_VERSION",
offset: 2,
length: 1
},
{
name: "SIGNATURE_VERSION",
offset: 3,
length: 1
},
{
name: "TIMESTAMP",
offset: 4,
length: 4,
"derived": true
},
{
name: "MESSAGE_ID",
offset: 8,
length: 4
},
{
name: "PAYLOAD_TYPE",
offset: 12,
length: 1
},
{
name: "RESERVED",
offset: 13,
length: 1
},
{
name: "PAYLOAD_SIZE",
offset: 14,
length: 2,
"derived": true
}
],
PAYLOAD_OFFSET: 16
}
};
Constants.fields.PAYLOAD_LENGTH_OFFSET = <number>Constants.fields.headers.find(header => header.name === "PAYLOAD_SIZE")?.offset;
Constants.fields.TOTAL_HEADERS_LENGTH = Constants.fields.headers.reduce((prev: number, curr: Header) => prev + curr.length, 0);
Constants.fields.PAYLOAD_MAX_LENGTH = (1024 * 64) - Constants.fields.TOTAL_HEADERS_LENGTH;
/**
* Convert DER key Buffer to PEM string. FIXME: break out the validity checks.
* @param DERKey key in DER-form
* @returns key in PEM form
*/
export const DERToPEM = (DERKey: Buffer) => {
const wrap = (buf: Buffer, type: "PUBLIC" | "PRIVATE") => Buffer.from(`-----BEGIN ${type} KEY-----
${buf.toString("base64")}
-----END ${type} KEY-----
`);
if (DERKey.byteLength == Constants.crypto.PRIVATE_KEY_LENGTH) {
const header = DERKey.subarray(0, Constants.crypto.PRIVATE_KEY_LENGTH - Constants.crypto.RAW_KEY_LENGTH);
if (header.equals(Constants.crypto.ENCRYPT_PRIVATE_KEY_HEADER) || header.equals(Constants.crypto.SIGN_PRIVATE_KEY_HEADER)) {
return wrap(DERKey, "PRIVATE");
}
}
else if (DERKey.byteLength == Constants.crypto.PUBLIC_KEY_LENGTH) {
const header = DERKey.subarray(0, Constants.crypto.PUBLIC_KEY_LENGTH - Constants.crypto.RAW_KEY_LENGTH);
if (header.equals(Constants.crypto.ENCRYPT_PUBLIC_KEY_HEADER) || header.equals(Constants.crypto.SIGN_PUBLIC_KEY_HEADER)) {
return wrap(DERKey, "PUBLIC");
}
}
throw new Error("Unrecognized key type");
};

16
example-note.json Normal file
View File

@ -0,0 +1,16 @@
{
"MAGIC": 666,
"PROTOCOL_VERSION": 0,
"SIGNATURE_VERSION": 0,
"TIMESTAMP": 1656927424,
"MESSAGE_ID": 1,
"PAYLOAD_TYPE": 1,
"RESERVED": 8,
"PAYLOAD": {
"sub": "This is a note about otters",
"msg": "Otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters otters",
"rply": "Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu",
"img": "QmNrgEMcUygbKzZeZgYFosdd27VE9KnWbyUD73bKZJ3bGi",
"tag": ["introductions", "test"]
}
}

89
listen.ts Normal file
View File

@ -0,0 +1,89 @@
import fs from "fs";
import crypto from "crypto";
import { create as IpfsClient } from "ipfs-client";
import { Message } from "@libp2p/interfaces/pubsub";
import { decode } from "@msgpack/msgpack";
import CID from "cids";
import Config, { Settings } from "./config.js";
import { Constants, DERToPEM } from "./constants";
const settings = <Settings>JSON.parse(fs.readFileSync("listen.json", "utf8"));
const options = settings.nodes[process.argv[2]].options;
console.log(`Attempting to connect to: ${JSON.stringify(options, null, 4)}`);
const ipfs = IpfsClient(options);
console.log("Querying server ID...");
const { id, agentVersion } = await ipfs.id();
console.log(`Connected to server: ${id} agent: ${agentVersion}`);
let connectedToPeer = false;
const peers = await ipfs.swarm.peers();
for (const peer of peers) {
const fullAddr = `${peer.addr}/ipfs/${peer.peer.toString()}`;
if (fullAddr === settings.nodes[process.argv[2]].peers[0]) {
console.log("Already connected to remote peer");
connectedToPeer = true;
}
}
if (!connectedToPeer) {
console.log(`Attempting to connect to remote peer: ${settings.nodes[process.argv[2]].peers[0]}`);
await ipfs.swarm.connect(settings.nodes[process.argv[2]].peers[0]);
}
const publicSigningKey = fs.readFileSync(Config.keys.sign.public);
const publicKey = publicSigningKey.subarray(Constants.crypto.PUBLIC_KEY_LENGTH - Constants.crypto.RAW_KEY_LENGTH).toString("hex");
const channel = `ipsn-${publicKey}`;
console.log(`Subscribing to: ${channel}`)
await ipfs.pubsub.subscribe(channel, (msg: Message) => {
if (id.equals(msg.from)) {
console.log("Ignoring message from self.");
}
else {
console.log("Received message!");
const buffer = Buffer.from(msg.data);
const payloadLength = buffer.readUint16BE(Constants.fields.PAYLOAD_LENGTH_OFFSET);
const payload = buffer.subarray(Constants.fields.PAYLOAD_OFFSET, Constants.fields.PAYLOAD_OFFSET + payloadLength);
console.log(`Payload size: ${payload.byteLength}`);
const msgpack = <Record<string, any>>decode(payload);
const from = Buffer.from(msgpack.frm);
try {
msgpack.rply = "ipfs://"+new CID(msgpack.rply).toString();
msgpack.frm = msgpack.frm.toString("hex");
msgpack.to = msgpack.to.toString("hex");
if (msgpack.img) msgpack.img = "ipfs://" + new CID(msgpack.img).toString();
}
catch(e) {
console.error("Error parsing message", e);
return;
}
console.log(msgpack);
const signablePortion = buffer.subarray(0, Constants.fields.PAYLOAD_OFFSET + payloadLength);
const signature = buffer.subarray(Constants.fields.PAYLOAD_OFFSET + payloadLength);
console.log(`signature length: ${signature.byteLength}`);
const isFromChannelOwner = ("ipsn-" + from.toString("hex")) === channel;
console.log(`Message from channel owner? ${isFromChannelOwner}`);
try {
// const senderPublicKey = Buffer.concat([publicKeyHeader, from]);
const senderPublicKey = DERToPEM(from);
const verified = crypto.verify(null, signablePortion, senderPublicKey, signature);
console.log(`Message signature verified? ${verified}`);
}
catch (e) {
console.error("error verifying message signature.", e);
}
}
});

2163
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "ipsn",
"version": "1.0.0",
"description": "ipfs social network",
"main": "ipsn.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^18.0.1",
"typescript": "^4.7.4"
},
"dependencies": {
"@msgpack/msgpack": "^2.7.2",
"cids": "^1.1.9",
"ipfs-client": "^0.8.3"
}
}

118
send.ts Normal file
View File

@ -0,0 +1,118 @@
import fs from "fs";
import crypto from "crypto";
import { encode } from "@msgpack/msgpack";
import CID from "cids";
import { create as IpfsClient } from "ipfs-client";
import Config, { Settings } from "./config.js";
import { Constants, DERToPEM } from "./constants.js";
/**
* Generate a keypair first using the following commands:
*
* openssl genpkey -algorithm ed25519 -outform DER -out ed25519-sign-private.der
* echo -e "-----BEGIN PRIVATE KEY-----\n$( cat ed25519-sign-private.der | base64 )\n-----END PRIVATE KEY-----" | openssl pkey -pubout -outform DER -out - > ed25519-sign-public.der
*
* Keys are stored in DER because easier to validate, but easier to use PEM in
* tools so they are converted on the fly.
*/
const data = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
const privateSigningKey = fs.readFileSync(Config.keys.sign.private);
const publicSigningKey = fs.readFileSync(Config.keys.sign.private);
let buffer = Buffer.alloc(Constants.fields.TOTAL_HEADERS_LENGTH);
Constants.fields.headers.forEach((def) => {
const print = (name: string, offset: number, value: number | string) => console.log(`Writing: ${name}, offset: ${offset}, value: ${value}`);
if (def.derived) {
if (def.name === "TIMESTAMP") {
const value = Math.floor(Date.now() / 1000);
print(def.name, def.offset, value);
buffer.writeUint32BE(value, def.offset);
}
}
else {
print(def.name, def.offset, data[def.name]);
if (def.length == 1) buffer.writeUint8(data[def.name], def.offset);
else if (def.length == 2) buffer.writeUint16BE(data[def.name], def.offset);
else if (def.length == 4) buffer.writeUint32BE(data[def.name], def.offset);
else console.log(`bad: ${def.name}, offset: ${def.offset}`);
}
});
console.log("preparing payload...");
if (data.PAYLOAD_TYPE == 1) {
console.log("Payload is a note.");
data.PAYLOAD.frm = publicSigningKey;
data.PAYLOAD.to = publicSigningKey;
if (data.PAYLOAD.sub) console.log(`Subject: \`${data.PAYLOAD.sub}\``);
if (data.PAYLOAD.msg) console.log(`Message: \`${data.PAYLOAD.msg}\``);
if (data.PAYLOAD.rply) {
const cid = new CID(data.PAYLOAD.rply);
data.PAYLOAD.rply = cid.bytes;
console.log("Converting reply IPFS CID to binary before encoding.");
}
if (data.PAYLOAD.img) {
const cid = new CID(data.PAYLOAD.img);
data.PAYLOAD.img = cid.bytes;
console.log("Converting image IPFS CID to binary before encoding.");
}
}
else {
console.log("Unknown payload type.");
process.exit(1);
}
const payload = Buffer.from(encode(data.PAYLOAD));
console.log("Encoded messagepack payload: " + payload.toString("hex"));
console.log(`Writing: PAYLOAD_LENGTH: offset: 14, value: ${payload.byteLength}`);
buffer.writeUint16BE(payload.byteLength, Constants.fields.PAYLOAD_LENGTH_OFFSET); // sorry hardcode
console.log(`Writing PAYLOAD: offset: ${buffer.byteLength}, value: (omitted)`);
// append the payload data.
buffer = Buffer.concat([buffer, payload]);
console.log("Generating Ed25519 signature of data...");
const signature = crypto.sign(null, buffer, DERToPEM(privateSigningKey));
buffer = Buffer.concat([buffer, signature]);
console.log(`Entire packet length: ${buffer.byteLength}`);
console.log("Writing to file: packet.dat");
fs.writeFileSync("packet.dat", buffer);
const listenSettings = <Settings>JSON.parse(fs.readFileSync("listen.json", "utf8"));
const options = listenSettings.nodes[process.argv[2]].options;
console.log(`Attempting to connect to: ${JSON.stringify(options)}`);
const ipfs = IpfsClient(options);
const channel = "ipsn-" + publicSigningKey.subarray(12).toString("hex");
const { id, agentVersion } = await ipfs.id();
console.log(`Connected to server: ${id} agent: ${agentVersion}`);
let connectedToPeer = false;
const peers = await ipfs.swarm.peers();
for (const peer of peers) {
const fullAddr = `${peer.addr}/ipfs/${peer.peer.toString()}`;
if (fullAddr === listenSettings.nodes[process.argv[2]].peers[0]) {
console.log("Already connected to remote peer");
connectedToPeer = true;
}
}
if (!connectedToPeer) {
console.log(`Attempting to connect to peer: ${listenSettings.nodes[process.argv[2]].peers[0]}`);
await ipfs.swarm.connect(listenSettings.nodes[process.argv[2]].peers[0]);
}
console.log(`Publishing to: ${channel}`);
await ipfs.pubsub.publish(channel, buffer);
process.exit(0);

106
tsconfig.json Normal file
View File

@ -0,0 +1,106 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Command-line Options */
"help": true, /* Print this message. */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["ES2022"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ES2022", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

1
types.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module 'base58-js';