Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/tests-w3id.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
name: Tests [W3ID]

on:
push:
branches: [main]
paths:
- 'infrastructure/w3id/**'
pull_request:
branches: [main]
paths:
- 'infrastructure/w3id/**'

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run tests
run: pnpm -F=w3id test

10 changes: 5 additions & 5 deletions infrastructure/w3id/src/errors/errors.ts
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
export class MalformedIndexChainError extends Error {
constructor(message: string = "Malformed index chain detected") {
constructor(message = "Malformed index chain detected") {
super(message);
this.name = "MalformedIndexChainError";
}
}

export class MalformedHashChainError extends Error {
constructor(message: string = "Malformed hash chain detected") {
constructor(message = "Malformed hash chain detected") {
super(message);
this.name = "MalformedHashChainError";
}
}

export class BadSignatureError extends Error {
constructor(message: string = "Bad signature detected") {
constructor(message = "Bad signature detected") {
super(message);
this.name = "BadSignatureError";
}
}

export class BadNextKeySpecifiedError extends Error {
constructor(message: string = "Bad next key specified") {
constructor(message = "Bad next key specified") {
super(message);
this.name = "BadNextKeySpecifiedError";
}
}

export class BadOptionsSpecifiedError extends Error {
constructor(message: string = "Bad options specified") {
constructor(message = "Bad options specified") {
super(message);
this.name = "BadOptionsSpecifiedError";
}
Expand Down
122 changes: 121 additions & 1 deletion infrastructure/w3id/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
export default {};
import { IDLogManager } from "./logs/log-manager";
import type { LogEvent, Signer } from "./logs/log.types";
import type { StorageSpec } from "./logs/storage/storage-spec";
import { generateRandomAlphaNum } from "./utils/rand";
import { v4 as uuidv4 } from "uuid";
import { generateUuid } from "./utils/uuid";

export class W3ID {
constructor(
public id: string,
public logs?: IDLogManager,
) {}
}

export class W3IDBuilder {
private signer?: Signer;
private repository?: StorageSpec<LogEvent, LogEvent>;
private entropy?: string;
private namespace?: string;
private nextKeyHash?: string;
private global?: boolean = false;

/**
* Specify entropy to create the identity with
*
* @param {string} str
*/
public withEntropy(str: string): W3IDBuilder {
this.entropy = str;
return this;
}

/**
* Specify namespace to use to generate the UUIDv5
*
* @param {string} uuid
*/
public withNamespace(uuid: string): W3IDBuilder {
this.namespace = uuid;
return this;
}

/**
* Specify whether to create a global identifier or a local identifer
*
* According to the project specification there are supposed to be 2 main types of
* W3ID's ones which are tied to more permanent entities
*
* A global identifer is expected to live at the registry and starts with an \`@\`
*
* @param {boolean} isGlobal
*/
public withGlobal(isGlobal: boolean): W3IDBuilder {
this.global = isGlobal;
return this;
}

/**
* Add a logs repository to the W3ID, a rotateble key attached W3ID would need a
* repository in which the logs would be stored
*
* @param {StorageSpec<LogEvent, LogEvent>} storage
*/
public withRepository(storage: StorageSpec<LogEvent, LogEvent>): W3IDBuilder {
this.repository = storage;
return this;
}

/**
* Attach a keypair to the W3ID, a key attached W3ID would also need a repository
* to be added.
*
* @param {Signer} signer
*/
public withSigner(signer: Signer): W3IDBuilder {
this.signer = signer;
return this;
}

/**
* Specify the SHA256 hash of the next key which will sign the next log entry after
* rotation of keys
*
* @param {string} hash
*/
public withNextKeyHash(hash: string): W3IDBuilder {
this.nextKeyHash = hash;
return this;
}

/**
* Build the W3ID with provided builder options
*
* @returns Promise<W3ID>
*/
public async build(): Promise<W3ID> {
this.entropy = this.entropy ?? generateRandomAlphaNum();
this.namespace = this.namespace ?? uuidv4();
const id = `${
this.global ? "@" : ""
}${generateUuid(this.entropy, this.namespace)}`;
if (!this.signer) {
return new W3ID(id);
}
if (!this.repository)
throw new Error(
"Repository is required, pass with `withRepository` method",
);

if (!this.nextKeyHash)
throw new Error(
"NextKeyHash is required pass with `withNextKeyHash` method",
);
const logs = new IDLogManager(this.repository, this.signer);
await logs.createLogEvent({
id,
nextKeyHashes: [this.nextKeyHash],
});
return new W3ID(id, logs);
}
}
60 changes: 50 additions & 10 deletions infrastructure/w3id/src/logs/log-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import { hash } from "../utils/hash";
import {
isGenesisOptions,
isRotationOptions,
type Signer,
type CreateLogEventOptions,
type GenesisLogOptions,
type LogEvent,
Expand All@@ -28,15 +29,25 @@ import type { StorageSpec } from "./storage/storage-spec";

export class IDLogManager {
repository: StorageSpec<LogEvent, LogEvent>;
signer: Signer;

constructor(repository: StorageSpec<LogEvent, LogEvent>) {
constructor(repository: StorageSpec<LogEvent, LogEvent>, signer: Signer) {
this.repository = repository;
this.signer = signer;
}

/**
* Validate a chain of W3ID logs
*
* @param {LogEvent[]} log
* @param {VerifierCallback} verifyCallback
* @returns {Promise<true>}
*/

static async validateLogChain(
log: LogEvent[],
verifyCallback: VerifierCallback,
) {
): Promise<true> {
let currIndex = 0;
let currentNextKeyHashesSeen: string[] = [];
let lastUpdateKeysSeen: string[] = [];
Expand DownExpand Up@@ -71,11 +82,19 @@ export class IDLogManager {
return true;
}

/**
* Validate cryptographic signature on a single LogEvent
*
* @param {LogEvent} e
* @param {string[]} currentUpdateKeys
* @param {VerifierCallback} verifyCallback
* @returns {Promise<void>}
*/
private static async verifyLogEventProof(
e: LogEvent,
currentUpdateKeys: string[],
verifyCallback: VerifierCallback,
) {
): Promise<void> {
const proof = e.proof;
const copy = JSON.parse(JSON.stringify(e));
// biome-ignore lint/performance/noDelete: we need to delete proof completely
Expand All@@ -94,8 +113,15 @@ export class IDLogManager {
if (!verified) throw new BadSignatureError();
}

/**
* Append a new log entry for a W3ID
*
* @param {LogEvent[]} entries
* @param {RotationLogOptions} options
* @returns Promise<LogEvent>
*/
private async appendEntry(entries: LogEvent[], options: RotationLogOptions) {
const { signer, nextKeyHashes, nextKeySigner } = options;
const { nextKeyHashes, nextKeySigner } = options;
const latestEntry = entries[entries.length - 1];
const logHash = await hash(latestEntry);
const index = Number(latestEntry.versionId.split("-")[0]) + 1;
Expand All@@ -113,30 +139,44 @@ export class IDLogManager {
method: "w3id:v0.0.0",
};

const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;

await this.repository.create(logEvent);
this.signer = nextKeySigner;
return logEvent;
}

/**
* Create genesis entry for a W3ID log
*
* @param {GenesisLogOptions} options
* @returns Promise<LogEvent>
*/
private async createGenesisEntry(options: GenesisLogOptions) {
const { id, nextKeyHashes, signer } = options;
const { id, nextKeyHashes } = options;
const idTag = id.includes("@") ? id.split("@")[1] : id;
const logEvent: LogEvent = {
id,
versionId: `0-${id.split("@")[1]}`,
versionId: `0-${idTag}`,
versionTime: new Date(Date.now()),
updateKeys: [signer.pubKey],
updateKeys: [this.signer.pubKey],
nextKeyHashes: nextKeyHashes,
method: "w3id:v0.0.0",
};
const proof = await signer.sign(canonicalize(logEvent) as string);
const proof = await this.signer.sign(canonicalize(logEvent) as string);
logEvent.proof = proof;
await this.repository.create(logEvent);
return logEvent;
}

async createLogEvent(options: CreateLogEventOptions) {
/**
* Create a log event and save it to the repository
*
* @param {CreateLogEventOptions} options
* @returns Promise<LogEvent>
*/
async createLogEvent(options: CreateLogEventOptions): Promise<LogEvent> {
const entries = await this.repository.findMany({});
if (entries.length > 0) {
if (!isRotationOptions(options)) throw new BadOptionsSpecifiedError();
Expand Down
2 changes: 0 additions & 2 deletions infrastructure/w3id/src/logs/log.types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,14 +21,12 @@ export type Signer = {

export type RotationLogOptions = {
nextKeyHashes: string[];
signer: Signer;
nextKeySigner: Signer;
};

export type GenesisLogOptions = {
nextKeyHashes: string[];
id: string;
signer: Signer;
};

export function isGenesisOptions(
Expand Down
22 changes: 22 additions & 0 deletions infrastructure/w3id/src/utils/rand.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
/**
* Generate a random alphanumeric sequence with set length
*
* @param {number} length length of the alphanumeric string you want
* @returns {string}
*/

export function generateRandomAlphaNum(length = 16): string {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charsLength = chars.length;
const randomValues = new Uint32Array(length);

crypto.getRandomValues(randomValues);

for (let i = 0; i < length; i++) {
result += chars.charAt(randomValues[i] % charsLength);
}

return result;
}
Loading