25 Commits

Author SHA1 Message Date
aet
c41ff54c89 New screenshot 2022-01-02 00:59:45 -05:00
aet
c5ba4c69d2 Fix build script 2022-01-02 00:54:29 -05:00
aet
d8f2cddb74 Add About screen, list of recently opened vaults, category filtering 2022-01-02 00:53:57 -05:00
aet
5883adc2c1 Allow line breaks 2021-12-28 03:12:36 -05:00
aet
82327da031 Fix i18n 2021-12-19 02:11:16 -05:00
aet
7362222f16 Fix i18n 2021-12-19 02:06:15 -05:00
aet
e16202f8b2 Add Japanese translation 2021-12-19 01:58:29 -05:00
aet
bf5bdd1f72 Add settings panel 2021-12-19 01:57:38 -05:00
aet
298482f70e Fix password field 2021-11-28 23:19:56 -05:00
aet
8f9ec73caf General improvements and bug fixes 2021-11-23 03:13:01 -05:00
aet
bdd46a530c Restructure files 2021-11-11 23:56:06 -05:00
aet
b4b21561ed Update screenshot 2021-11-08 03:04:31 -05:00
eb27e81d68 Migrate to native Node.js file access and improve UI 2021-11-08 02:59:58 -05:00
06e29eaba1 Add macOS builds 2021-11-07 23:49:51 -05:00
aet
84c4a55073 Update screenshot 2021-11-07 21:58:42 -05:00
aet
8fdf6e6e7b Replace screenshot 2021-11-07 21:51:40 -05:00
674e7ac689 Make screenshot bigger 2021-11-07 21:39:37 -05:00
aet
57d3a5056a Replace screenshot 2021-11-07 21:37:55 -05:00
aet
3a9e4e1e3d Add screenshot 2021-11-07 21:23:24 -05:00
69cd8e3ee1 Mettre à jour les liens 2021-11-07 17:27:23 -05:00
aet
fbf3c9b1bb Update README and build files 2021-11-07 17:24:15 -05:00
aet
7ee6990be1 Implement big text view and preliminary i18n 2021-11-06 21:49:54 -04:00
aet
d2ae4be194 Remove notepad 2021-11-05 12:00:40 -04:00
aet
e9b07374e5 Ajouter la version française 2021-11-05 04:22:43 -04:00
aet
fe926be0a6 Add web interface and tests 2021-11-05 03:17:18 -04:00
96 changed files with 6104 additions and 3460 deletions

View File

@ -1,2 +1,3 @@
*.opvault *.opvault
lib lib
dist

View File

@ -6,6 +6,9 @@
"node": true, "node": true,
"browser": true "browser": true
}, },
"parserOptions": {
"project": "./tsconfig.json"
},
"extends": [ "extends": [
"eslint:recommended", "eslint:recommended",
"plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended",
@ -36,6 +39,7 @@
"disallowTypeAnnotations": false "disallowTypeAnnotations": false
} }
], ],
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-types": [ "@typescript-eslint/ban-types": [
"error", "error",
{ {

BIN
.github/screenshot.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 380 KiB

4
.gitignore vendored
View File

@ -1,3 +1,4 @@
drafts
node_modules node_modules
mochawesome-report mochawesome-report
lib lib
@ -6,4 +7,5 @@ ref
*.opvault *.opvault
freddy freddy
electron/bundled electron/bundled
design.html design.html
repl.ts

View File

@ -1,5 +1,6 @@
{ {
"editor.formatOnSave": true, "editor.formatOnSave": true,
"cSpell.words": ["autolock"],
"cSpell.ignorePaths": [ "cSpell.ignorePaths": [
"**/package-lock.json", "**/package-lock.json",
"**/node_modules/**", "**/node_modules/**",
@ -9,4 +10,4 @@
".vscode-insiders", ".vscode-insiders",
"i18n.json" "i18n.json"
] ]
} }

View File

@ -1,6 +1,28 @@
# opvault.js # opvault.js
## Testing ![License](https://img.shields.io/badge/license-TBD-blue)
## Lecteur de coffres OnePassword libre
Lire vos coffres OnePassword sur nimporte quelle plateforme. Pour commencer, vous pouvez [télécharger une version compilée](../../../releases) pour votre système dexploitation, ou [suivre les instructions de compilation](#build) ci-dessous.
## OnePassword Vault Reader
Read your OnePassword vaults on all platform. To start, you can [download a prebuilt binary](../../../releases) for your OS, or [follow the build instructions](#build) below.
## Capture décran / Screenshot
<img alt="linux screenshot" src=".github/screenshot.png" width="700" />
## Build
```sh
pnpm install
cd packages/web
pnpm run bundle
```
## Test
```sh ```sh
wget -qO- https://cache.agilebits.com/security-kb/freddy-2013-12-04.tar.gz | tar xvz wget -qO- https://cache.agilebits.com/security-kb/freddy-2013-12-04.tar.gz | tar xvz
@ -8,7 +30,13 @@ mv onepassword_data freddy-2013-12-04.opvault
pnpm run test pnpm run test
``` ```
## Security ## Sécurité / Security
### Signaler un problème de sécurité
Nous encourageons le signalement responsable des vulnerabilités détectées sur nos logiciels et ferons notre possible pour reconnaître vos contributions.
Afin de signaler un problème de sécurité, veuillez envoyer un courriel à [security@aet.ac](mailto:security@aet.ac) avec le mot « SÉCURITÉ » dans le subjet.
### Reporting Security Issues ### Reporting Security Issues

View File

@ -1,280 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "aa8a7fc4",
"metadata": {},
"outputs": [],
"source": [
"import fs from \"fs\";\n",
"import { resolve } from \"path\";"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d909c03d",
"metadata": {},
"outputs": [],
"source": [
"import { OnePassword } from \"./src/index\";"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "56b32a8e-af25-4356-8e13-ba8ca840f986",
"metadata": {},
"outputs": [],
"source": [
"const instance = new OnePassword({ path: \"./freddy-2013-12-04.opvault\" });\n",
"const vault = await instance.getProfile(\"default\");\n",
"await vault.unlock(\"freddy\");\n",
"void 0;"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6c940edd-e225-4397-a92f-4fa8927854ab",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[\n",
" { ps: 0 },\n",
" {\n",
" title: 'Personal',\n",
" ainfo: 'Wendy Appleseed',\n",
" tags: [ 'Sample', 'Personal' ],\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'Hulu',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'wendy@appleseed.com',\n",
" url: 'http://www.hulu.com/',\n",
" tags: [ 'Sample' ],\n",
" ps: 66\n",
" },\n",
" {\n",
" title: \"Wendy's driver's license\",\n",
" ps: 0,\n",
" ainfo: 'D6101-40706-60905'\n",
" },\n",
" { title: 'Orders', ainfo: '10.0.1.50', tags: [ 'Sample' ], ps: 0 },\n",
" {\n",
" URLs: [ [Object] ],\n",
" tags: [ 'Sample' ],\n",
" title: 'Skype',\n",
" url: 'https://secure.skype.com/account/login?message=login_required',\n",
" ainfo: 'WendyAppleseed',\n",
" ps: 78\n",
" },\n",
" {\n",
" title: 'YouTube',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'wendy@appleseed.com',\n",
" url: 'http://www.youtube.com/login?next=/index',\n",
" tags: [ 'Sample' ],\n",
" ps: 78\n",
" },\n",
" { title: 'example.com', ps: 0, ainfo: 'wappleseed' },\n",
" {\n",
" title: 'Dropbox',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'wendy@appleseed.com',\n",
" url: 'https://www.getdropbox.com/',\n",
" tags: [ 'Sample' ],\n",
" ps: 78\n",
" },\n",
" {\n",
" title: \"Company's FTP\",\n",
" URLs: [ [Object] ],\n",
" ainfo: 'admin',\n",
" url: 'ftp://ftp.dreamhost.com',\n",
" tags: [ 'Sample' ],\n",
" ps: 60\n",
" },\n",
" {\n",
" title: 'Tumblr',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'wendy@appleseed.com',\n",
" url: 'http://www.tumblr.com/login',\n",
" tags: [ 'Sample' ],\n",
" ps: 48\n",
" },\n",
" { title: 'Social Security', ps: 0, ainfo: 'Wendy Appleseed' },\n",
" {\n",
" title: 'Last.fm',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'WendyAppleseed',\n",
" url: 'https://www.last.fm/login',\n",
" tags: [ 'Sample' ],\n",
" ps: 72\n",
" },\n",
" { title: 'Tim Hortons', ps: 0, ainfo: 'Tim Hortens' },\n",
" { title: 'Snipe Hunting License', ps: 0, ainfo: 'Wendy Appleseed' },\n",
" {\n",
" title: 'A note to Trash',\n",
" ainfo: 'Lets create a note that we will throw in the trash but not expunge.',\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'CapitalOne MasterCard ***3456',\n",
" ainfo: '1234 *********** 3456',\n",
" tags: [ 'Sample' ],\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'What is a Secure Note?',\n",
" ainfo: '',\n",
" tags: [ 'Sample' ],\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'The Unofficial Apple Weblog',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'WendyAppleseed',\n",
" url: 'http://www.tuaw.com',\n",
" tags: [ 'Sample' ],\n",
" ps: 78\n",
" },\n",
" { title: \"Wendy's passport\", ps: 0, ainfo: 'ZZ200000' },\n",
" {\n",
" title: 'Chase VISA ***4356',\n",
" ainfo: '1234 *********** 4356',\n",
" tags: [ 'Sample' ],\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'Bank of America',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'WendyAppleseed',\n",
" url: 'https://www.bankofamerica.com/',\n",
" tags: [ 'Sample', 'Personal' ],\n",
" ps: 66\n",
" },\n",
" {\n",
" title: 'A note with some attachments',\n",
" ps: 0,\n",
" ainfo: 'This note has two attachments.'\n",
" },\n",
" { title: '1Password', ainfo: '3.0', tags: [ 'Sample' ], ps: 0 },\n",
" { title: 'TextExpander', ainfo: '1.3', tags: [ 'Sample' ], ps: 0 },\n",
" {\n",
" title: 'Business',\n",
" ainfo: 'Wendy Appleseed',\n",
" tags: [ 'Business', 'Sample' ],\n",
" ps: 0\n",
" },\n",
" {\n",
" title: 'MobileMe',\n",
" URLs: [ [Object] ],\n",
" ainfo: 'wendy.appleseed@me.com',\n",
" url: 'https://www.icloud.com/',\n",
" tags: [ 'Sample' ],\n",
" ps: 66\n",
" },\n",
" { title: 'Email Account', ps: 0, ainfo: 'wendy.appleseed@me.com' },\n",
" {\n",
" title: 'Johnny Appleseed Society',\n",
" ps: 0,\n",
" ainfo: 'Wendy Appleseed'\n",
" }\n",
"]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vault.overviews.values()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "1547939f-3ee1-49df-9401-c54b8511acb4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Object: null prototype] {\n",
" async: [Function (anonymous)],\n",
" done: [Function (anonymous)],\n",
" sendResult: [Function (anonymous)],\n",
" sendError: [Function (anonymous)],\n",
" mime: [Function (anonymous)],\n",
" text: [Function (anonymous)],\n",
" html: [Function (anonymous)],\n",
" svg: [Function (anonymous)],\n",
" png: [Function (anonymous)],\n",
" jpeg: [Function (anonymous)],\n",
" json: [Function (anonymous)],\n",
" input: [Function (anonymous)],\n",
" display: [Function (anonymous)],\n",
" clear: [Function (anonymous)]\n",
"}"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"$$"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "3625d249-b27e-4990-b433-94238a60f3db",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<a href=\"#\">meow</a>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"$$.jsx(<a href=\"#\">meow</a>)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9899de99-b1a9-4f91-9d48-a63808baedc1",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "jp-Babel (Node.js)",
"language": "babel",
"name": "babel"
},
"language_info": {
"file_extension": ".js",
"mimetype": "application/javascript",
"name": "javascript",
"version": "16.10.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -1,5 +1,12 @@
# OPVault design # OPVault design
<!--
(C) AgileBits Inc.
Canonical URL: https://support.1password.com/cs/opvault-design/
This document is reformatted into Markdown for implementation reference purposes.
-->
Learn about the design of the OPVault format, used by default when syncing with iCloud or Dropbox. Learn about the design of the OPVault format, used by default when syncing with iCloud or Dropbox.
> ### Tip > ### Tip
@ -11,7 +18,7 @@ Learn about the design of the OPVault format, used by default when syncing with
The OPVault format was introduced in December 2012 and shortly thereafter became the default format for syncing with iCloud and Dropbox. The OPVault format was introduced in December 2012 and shortly thereafter became the default format for syncing with iCloud and Dropbox.
The [Agile Keychain](/cs/agile-keychain-design/) format was introduced in 2008 as a successor to using macOS Keychain integration. It proved to be much more reliable for syncing and gave us flexibility in design, efficient and reliable syncing, and portability across a variety of platforms. We designed it not only to withstand threats from 2008 but future threats as well. The [Agile Keychain](https://support.1password.com/cs/agile-keychain-design/) format was introduced in 2008 as a successor to using macOS Keychain integration. It proved to be much more reliable for syncing and gave us flexibility in design, efficient and reliable syncing, and portability across a variety of platforms. We designed it not only to withstand threats from 2008 but future threats as well.
Changes in available technology allowed us to improve on that design. And we again designed against threats that may not exist today, but which may develop in the coming years. Changes in available technology allowed us to improve on that design. And we again designed against threats that may not exist today, but which may develop in the coming years.

View File

@ -1,8 +0,0 @@
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ["chrome", "node", "electron"]) {
replaceText(`${type}-version`, process.versions[type])
}

View File

@ -1,22 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>, Chromium
<span id="chrome-version"></span>, and Electron <span id="electron-version"></span>.
<script src="bundled/index.js"></script>
</body>
</html>

View File

@ -1,44 +0,0 @@
#!/usr/bin/env node
// @ts-check
const { build } = require("esbuild")
const sassPlugin = require("esbuild-plugin-sass")
const { nodeBuiltIns } = require("esbuild-node-builtins")
const args = process.argv.slice(2)
build({
bundle: true,
define: {
"process.browser": "true",
"process.env.BLUEPRINT_NAMESPACE": '"bp4"',
global: "globalThis",
},
entryPoints: ["electron/app/index.tsx"],
inject: ["./scripts/react-shim.js"],
outdir: "electron/bundled",
external: ["path", "glob", "fs", "util"],
jsxFactory: "esbuildCreateElement",
jsxFragment: "esbuildFragment",
plugins: [
sassPlugin(),
nodeBuiltIns({
include: ["path", "fs"],
}),
],
target: ["chrome90"],
tsconfig: "./tsconfig.json",
sourcemap: "inline",
minify: process.env.NODE_ENV === "production",
banner: {
js: "/* eslint-disable */",
},
loader: {
".png": "file",
".eot": "file",
".svg": "file",
".woff": "file",
".woff2": "file",
".ttf": "file",
},
watch: args.includes("-w") || args.includes("--watch"),
})

BIN
icon.bin

Binary file not shown.

View File

@ -5,60 +5,46 @@
"repository": "https://git.aet.ac/aet/opvault.js.git", "repository": "https://git.aet.ac/aet/opvault.js.git",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "rollup -c; cp src/adapters/index.d.ts lib/adapters/; prettier --write lib >/dev/null",
"build:docs": "typedoc --out docs src/index.ts --excludePrivate",
"design": "marked -o design.html < design.md", "design": "marked -o design.html < design.md",
"test": "node --expose-gc node_modules/mocha/bin/_mocha test/**/*.test.ts", "test": "node --expose-gc node_modules/mocha/bin/_mocha test/**/*.test.ts",
"repl": "node -r ts-node/register/transpile-only src/repl.ts", "repl": "node -r ts-node/register/transpile-only src/repl.ts",
"start": "electron ./electron/index.js" "dev": "cd packages/web && yarn dev",
"bundle": "cd packages/web && yarn bundle"
}, },
"devDependencies": { "devDependencies": {
"@rollup/plugin-json": "^4.1.0", "@types/chai": "^4.3.0",
"@rollup/plugin-replace": "^3.0.0",
"@types/chai": "^4.2.22",
"@types/chai-as-promised": "^7.1.4", "@types/chai-as-promised": "^7.1.4",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/mocha": "github:whitecolor/mocha-types#da22474cf43f48a56c86f8c23a5a0ea36e295768", "@types/mocha": "github:whitecolor/mocha-types#da22474cf43f48a56c86f8c23a5a0ea36e295768",
"@types/node": "^16.10.3", "@types/node": "^17.0.6",
"@types/prompts": "^2.0.14", "@types/sinon": "^10.0.6",
"@types/react": "^17.0.30", "@types/sinon-chai": "^3.2.8",
"@types/react-dom": "^17.0.9",
"@types/sinon": "^10.0.4",
"@types/sinon-chai": "^3.2.5",
"@types/wicg-file-system-access": "^2020.9.4", "@types/wicg-file-system-access": "^2020.9.4",
"@typescript-eslint/eslint-plugin": "4.33.0", "@typescript-eslint/eslint-plugin": "5.8.1",
"@typescript-eslint/parser": "4.33.0", "@typescript-eslint/parser": "5.8.1",
"chai": "^4.3.4", "chai": "^4.3.4",
"chai-as-promised": "^7.1.1", "chai-as-promised": "^7.1.1",
"chalk": "^4.1.2", "chalk": "^4.1.2",
"electron": "^15.2.0", "eslint": "8.6.0",
"esbuild": "^0.13.6",
"esbuild-node-builtins": "^0.1.0",
"esbuild-plugin-sass": "^0.6.0",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0", "eslint-config-prettier": "8.3.0",
"eslint-import-resolver-typescript": "2.5.0", "eslint-import-resolver-typescript": "2.5.0",
"eslint-plugin-import": "2.24.2", "eslint-plugin-import": "2.25.3",
"eslint-plugin-react": "7.26.1", "eslint-plugin-react": "7.28.0",
"eslint-plugin-react-hooks": "4.2.0", "eslint-plugin-react-hooks": "4.3.0",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"marked": "^3.0.8", "marked": "^4.0.8",
"memfs": "^3.3.0", "mocha": "^9.1.3",
"mocha": "^9.1.2", "mochawesome": "^7.0.1",
"mochawesome": "^6.3.0", "prettier": "^2.5.1",
"prettier": "^2.4.1",
"prompts": "^2.4.1",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"rollup": "^2.58.0", "sass": "^1.45.2",
"rollup-plugin-ts": "^1.4.7", "sinon": "^12.0.1",
"sass": "^1.43.2",
"sinon": "^11.1.2",
"sinon-chai": "^3.7.0", "sinon-chai": "^3.7.0",
"ts-node": "^10.2.1", "tslib": "^2.3.1",
"tsconfig-paths": "^3.11.0", "ts-node": "^10.4.0",
"typedoc": "^0.22.5", "tsconfig-paths": "^3.12.0",
"typescript": "^4.4.3" "typescript": "^4.5.4"
}, },
"prettier": { "prettier": {
"arrowParens": "avoid", "arrowParens": "avoid",
@ -67,10 +53,5 @@
"semi": false, "semi": false,
"singleQuote": false, "singleQuote": false,
"trailingComma": "es5" "trailingComma": "es5"
},
"dependencies": {
"buffer": "^6.0.3",
"tiny-invariant": "1.1.0",
"tslib": "2.3.1"
} }
} }

View File

@ -0,0 +1,6 @@
{
"name": "opvault-adapters",
"dependencies": {
"opvault.js": "*"
}
}

View File

@ -1,6 +1,5 @@
import { Buffer } from "buffer" import { Buffer } from "buffer"
import createHmac from "create-hmac" import type { IAdapter, IFileSystem } from "opvault.js/src/adapter"
import type { IAdapter, IFileSystem } from "./index"
function normalize(path: string) { function normalize(path: string) {
return path.replace(/^\//, "") return path.replace(/^\//, "")
@ -15,11 +14,6 @@ function splitPath(path: string) {
export class FileSystem implements IFileSystem { export class FileSystem implements IFileSystem {
constructor(private handle: FileSystemDirectoryHandle) {} constructor(private handle: FileSystemDirectoryHandle) {}
static async create() {
const handle = await showDirectoryPicker()
return new FileSystem(handle)
}
private async getDirectoryHandle(segments: string[]) { private async getDirectoryHandle(segments: string[]) {
if (!segments.length || (segments.length === 1 && !segments[0])) { if (!segments.length || (segments.length === 1 && !segments[0])) {
return this.handle return this.handle
@ -120,5 +114,4 @@ async function success(fn: () => Promise<any>) {
export const getBrowserAdapter = (handle: FileSystemDirectoryHandle): IAdapter => ({ export const getBrowserAdapter = (handle: FileSystemDirectoryHandle): IAdapter => ({
fs: new FileSystem(handle), fs: new FileSystem(handle),
subtle: crypto.subtle, subtle: crypto.subtle,
hmacSHA256: (key, data) => createHmac("sha256", key).update(data).digest(),
}) })

View File

@ -0,0 +1,53 @@
import { Buffer } from "buffer"
import type { IAdapter, IFileSystem } from "opvault.js/src/adapter"
export class FileSystem implements IFileSystem {
private paths = new Set<string>()
private pathMap = new Map<string, File>()
constructor(list: FileList) {
for (const file of list) {
this.pathMap.set(file.webkitRelativePath, file)
this.paths.add(file.webkitRelativePath)
}
}
async readFile(path: string) {
return this.pathMap.get(path)!.text()
}
async exists(path: string): Promise<boolean> {
return this.pathMap.has(path)
}
async readBuffer(path: string): Promise<Buffer> {
const arrayBuffer = await this.pathMap.get(path)!.arrayBuffer()
return Buffer.from(arrayBuffer)
}
// eslint-disable-next-line class-methods-use-this
async writeFile(path: string, data: string): Promise<void> {
throw new Error("fs.writeFile is not supported with webkitdirectory")
}
async readdir(path: string): Promise<string[]> {
const paths = [...this.paths]
return paths
.filter(_ => _.startsWith(`${path}/`))
.map(_ => _.slice(path.length + 1))
.map(_ => _.split("/")[0])
}
async isDirectory(path: string) {
const paths = [...this.paths]
return paths.some(_ => _.startsWith(`${path}/`)) && !paths.includes(path)
}
}
/**
* Default Browser adapter.
*/
export const getBrowserAdapter = (list: FileList): IAdapter => ({
fs: new FileSystem(list),
subtle: crypto.subtle,
})

View File

@ -0,0 +1,3 @@
# opvault.js
OnePassword local vaults parser library.

View File

@ -0,0 +1,9 @@
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
code,
pre,
.tsd-signature {
font-family: D2Coding, Consolas, Menlo, Monaco, "Roboto Mono", monospace;
}

View File

@ -0,0 +1,23 @@
{
"name": "opvault.js",
"main": "src/index.ts",
"version": "0.0.1",
"license": "LGPL-3.0-or-later",
"scripts": {
"build": "rollup -c; prettier --write lib >/dev/null",
"build:docs": "typedoc --out docs src/index.ts --excludePrivate"
},
"dependencies": {
"buffer": "^6.0.3",
"tiny-invariant": "1.2.0",
"tslib": "2.3.1"
},
"devDependencies": {
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-replace": "^3.0.0",
"prettier": "^2.5.1",
"rollup": "^2.61.1",
"rollup-plugin-ts": "^2.0.4",
"typedoc": "^0.22.10"
}
}

View File

@ -8,7 +8,6 @@ import { dependencies } from "./package.json"
export default () => ({ export default () => ({
input: { input: {
index: "./src/index.ts", index: "./src/index.ts",
"adapters/node": "./src/adapters/node.ts",
}, },
external: builtinModules.concat(Object.keys(dependencies)), external: builtinModules.concat(Object.keys(dependencies)),
output: { output: {
@ -22,6 +21,8 @@ export default () => ({
preventAssignment: true, preventAssignment: true,
values: { values: {
"process.env.NODE_ENV": '"production"', "process.env.NODE_ENV": '"production"',
'require("./adapter").nodeAdapter':
'import("./adapter").then(x => x.nodeAdapter)',
}, },
}), }),
], ],

View File

@ -1,3 +1,6 @@
import { promises as fs, existsSync } from "fs"
import { webcrypto } from "crypto"
/** /**
* An object that implements basic file system functionalities. * An object that implements basic file system functionalities.
*/ */
@ -52,9 +55,20 @@ export interface IAdapter {
* `window.crypto.subtle`. * `window.crypto.subtle`.
*/ */
subtle: SubtleCrypto subtle: SubtleCrypto
}
/**
* Equivalent to `createHmac("sha256", key).update(data).digest()` /**
*/ * Default Node.js adapter. This can be used while using `opvault.js`
hmacSHA256(key: Buffer, data: Buffer): Buffer * in a Node.js environment.
*/
export const nodeAdapter: IAdapter = {
fs: {
readFile: path => fs.readFile(path, "utf-8"),
readBuffer: path => fs.readFile(path),
writeFile: fs.writeFile,
readdir: fs.readdir,
isDirectory: async path => fs.stat(path).then(x => x.isDirectory()),
exists: async path => existsSync(path),
},
subtle: (webcrypto as any).subtle,
} }

View File

@ -1,324 +0,0 @@
function bufferXor(a: Buffer, b: Buffer) {
const length = Math.min(a.length, b.length)
const buffer = Buffer.alloc(length)
for (let i = 0; i < length; ++i) {
buffer[i] = a[i] ^ b[i]
}
return buffer
}
function asUInt32Array(buf: Buffer) {
const len = (buf.length / 4) | 0
const out: number[] = new Array(len)
for (let i = 0; i < len; i++) {
out[i] = buf.readUInt32BE(i * 4)
}
return out
}
function cryptBlock(
M: number[],
keySchedule: number[],
SUB_MIX: number[][],
SBOX: number[],
nRounds: number
) {
const SUB_MIX0 = SUB_MIX[0]
const SUB_MIX1 = SUB_MIX[1]
const SUB_MIX2 = SUB_MIX[2]
const SUB_MIX3 = SUB_MIX[3]
let s0 = M[0] ^ keySchedule[0]
let s1 = M[1] ^ keySchedule[1]
let s2 = M[2] ^ keySchedule[2]
let s3 = M[3] ^ keySchedule[3]
let t0: number
let t1: number
let t2: number
let t3: number
let ksRow = 4
for (let round = 1; round < nRounds; round++) {
t0 =
SUB_MIX0[s0 >>> 24] ^
SUB_MIX1[(s1 >>> 16) & 0xff] ^
SUB_MIX2[(s2 >>> 8) & 0xff] ^
SUB_MIX3[s3 & 0xff] ^
keySchedule[ksRow++]
t1 =
SUB_MIX0[s1 >>> 24] ^
SUB_MIX1[(s2 >>> 16) & 0xff] ^
SUB_MIX2[(s3 >>> 8) & 0xff] ^
SUB_MIX3[s0 & 0xff] ^
keySchedule[ksRow++]
t2 =
SUB_MIX0[s2 >>> 24] ^
SUB_MIX1[(s3 >>> 16) & 0xff] ^
SUB_MIX2[(s0 >>> 8) & 0xff] ^
SUB_MIX3[s1 & 0xff] ^
keySchedule[ksRow++]
t3 =
SUB_MIX0[s3 >>> 24] ^
SUB_MIX1[(s0 >>> 16) & 0xff] ^
SUB_MIX2[(s1 >>> 8) & 0xff] ^
SUB_MIX3[s2 & 0xff] ^
keySchedule[ksRow++]
s0 = t0
s1 = t1
s2 = t2
s3 = t3
}
t0 =
((SBOX[s0 >>> 24] << 24) |
(SBOX[(s1 >>> 16) & 0xff] << 16) |
(SBOX[(s2 >>> 8) & 0xff] << 8) |
SBOX[s3 & 0xff]) ^
keySchedule[ksRow++]
t1 =
((SBOX[s1 >>> 24] << 24) |
(SBOX[(s2 >>> 16) & 0xff] << 16) |
(SBOX[(s3 >>> 8) & 0xff] << 8) |
SBOX[s0 & 0xff]) ^
keySchedule[ksRow++]
t2 =
((SBOX[s2 >>> 24] << 24) |
(SBOX[(s3 >>> 16) & 0xff] << 16) |
(SBOX[(s0 >>> 8) & 0xff] << 8) |
SBOX[s1 & 0xff]) ^
keySchedule[ksRow++]
t3 =
((SBOX[s3 >>> 24] << 24) |
(SBOX[(s0 >>> 16) & 0xff] << 16) |
(SBOX[(s1 >>> 8) & 0xff] << 8) |
SBOX[s2 & 0xff]) ^
keySchedule[ksRow++]
t0 = t0 >>> 0
t1 = t1 >>> 0
t2 = t2 >>> 0
t3 = t3 >>> 0
return [t0, t1, t2, t3]
}
// AES constants
const RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
const G = (function () {
// Compute double table
const d = new Array(256)
for (let j = 0; j < 256; j++) {
if (j < 128) {
d[j] = j << 1
} else {
d[j] = (j << 1) ^ 0x11b
}
}
const SBOX: number[] = []
const INV_SBOX: number[] = []
const SUB_MIX: number[][] = [[], [], [], []]
const INV_SUB_MIX: number[][] = [[], [], [], []]
// Walk GF(2^8)
let x = 0
let xi = 0
for (let i = 0; i < 256; ++i) {
// Compute sbox
let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
SBOX[x] = sx
INV_SBOX[sx] = x
// Compute multiplication
const x2 = d[x]
const x4 = d[x2]
const x8 = d[x4]
// Compute sub bytes, mix columns tables
let t = (d[sx] * 0x101) ^ (sx * 0x1010100)
SUB_MIX[0][x] = (t << 24) | (t >>> 8)
SUB_MIX[1][x] = (t << 16) | (t >>> 16)
SUB_MIX[2][x] = (t << 8) | (t >>> 24)
SUB_MIX[3][x] = t
// Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
INV_SUB_MIX[3][sx] = t
if (x === 0) {
x = xi = 1
} else {
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
}
}
return {
SBOX,
INV_SBOX,
SUB_MIX,
INV_SUB_MIX,
}
})()
class AES {
private _key: number[]
private _nRounds!: number
private _invKeySchedule!: number[]
constructor(key: Buffer) {
this._key = asUInt32Array(key)
this._reset()
}
_reset() {
const keyWords = this._key
const keySize = keyWords.length
const nRounds = keySize + 6
const ksRows = (nRounds + 1) * 4
const keySchedule: number[] = []
for (let k = 0; k < keySize; k++) {
keySchedule[k] = keyWords[k]
}
for (let k = keySize; k < ksRows; k++) {
let t = keySchedule[k - 1]
if (k % keySize === 0) {
t = (t << 8) | (t >>> 24)
t =
(G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
G.SBOX[t & 0xff]
t ^= RCON[(k / keySize) | 0] << 24
} else if (keySize > 6 && k % keySize === 4) {
t =
(G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
G.SBOX[t & 0xff]
}
keySchedule[k] = keySchedule[k - keySize] ^ t
}
const invKeySchedule = []
for (let ik = 0; ik < ksRows; ik++) {
const ksR = ksRows - ik
const tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
if (ik < 4 || ksR <= 4) {
invKeySchedule[ik] = tt
} else {
invKeySchedule[ik] =
G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
}
}
this._nRounds = nRounds
this._invKeySchedule = invKeySchedule
}
decryptBlock(buffer: Buffer) {
const M = asUInt32Array(buffer)
// swap
const m1 = M[1]
M[1] = M[3]
M[3] = m1
const out = cryptBlock(
M,
this._invKeySchedule,
G.INV_SUB_MIX,
G.INV_SBOX,
this._nRounds
)
const buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0], 0)
buf.writeUInt32BE(out[3], 4)
buf.writeUInt32BE(out[2], 8)
buf.writeUInt32BE(out[1], 12)
return buf
}
static blockSize = 4 * 4
static keySize = 256 / 8
}
class Decipher {
private _cipher: AES
private _prev: Buffer
private _cache = new Splitter()
constructor(key: Buffer, iv: Buffer) {
this._cipher = new AES(key)
this._prev = Buffer.from(iv)
}
update(data: Buffer) {
this._cache.add(data)
let chunk: Buffer | null
let thing: Buffer
const out: Buffer[] = []
while ((chunk = this._cache.get())) {
thing = this.cbc_decrypt(chunk)
out.push(thing)
}
return Buffer.concat(out)
}
setAutoPadding(setTo: boolean) {
return this
}
cbc_decrypt(block: Buffer) {
const pad = this._prev
this._prev = block
const out = this._cipher.decryptBlock(block)
return bufferXor(out, pad)
}
}
class Splitter {
cache = Buffer.allocUnsafe(0)
add(data: Buffer) {
this.cache = Buffer.concat([this.cache, data])
}
get() {
if (this.cache.length >= 16) {
const out = this.cache.slice(0, 16)
this.cache = this.cache.slice(16)
return out
}
return null
}
}
export function createDecipheriv(_suite: any, password: Buffer, iv: Buffer) {
if (iv.length !== 16) {
throw new TypeError(`invalid iv length ${iv.length}`)
}
if (password.length !== 256 / 8) {
throw new TypeError(`invalid key length ${password.length}`)
}
return new Decipher(password, iv)
}

View File

@ -1,21 +0,0 @@
import { promises as fs, existsSync } from "fs"
import { webcrypto, createHmac } from "crypto"
import type { IAdapter } from "./index"
/**
* Default Node.js adapter. This can be used while using `opvault.js`
* in a Node.js environment.
*/
export const adapter: IAdapter = {
fs: {
readFile: path => fs.readFile(path, "utf-8"),
readBuffer: path => fs.readFile(path),
writeFile: fs.writeFile,
readdir: fs.readdir,
isDirectory: async path => fs.stat(path).then(x => x.isDirectory()),
exists: async path => existsSync(path),
},
subtle: (webcrypto as any).subtle,
hmacSHA256: (key, data) => createHmac("sha256", key).update(data).digest(),
}

View File

@ -1,12 +1,12 @@
import { Buffer } from "buffer" import { Buffer } from "buffer"
import { createDecipheriv } from "../adapters/decipher" import { decryptData } from "./decipher"
import type { IAdapter } from "../adapters" import type { IAdapter } from "./adapter"
import { createEventEmitter } from "../ee" import { createEventEmitter } from "./ee"
import { HMACAssertionError } from "../errors" import { HMACAssertionError } from "./errors"
import type { i18n } from "../i18n" import type { i18n } from "./i18n"
import type { ItemDetails, Overview, Profile } from "../types" import type { ItemDetails, Overview, Profile } from "./types"
import { setIfAbsent } from "../util" import { setIfAbsent } from "./util"
import type { EncryptedItem } from "./item" import type { EncryptedItem } from "./models/item"
/** Encryption and MAC */ /** Encryption and MAC */
export interface Cipher { export interface Cipher {
@ -16,21 +16,19 @@ export interface Cipher {
hmac: Buffer hmac: Buffer
} }
export class Crypto implements IDisposable { export class Crypto {
#disposables: IDisposable[] = [] #disposables: (() => void)[] = []
#locked = true #locked = true
#master!: Cipher #master!: Cipher
#overview!: Cipher #overview!: Cipher
private subtle: SubtleCrypto private subtle: SubtleCrypto
private hmacSHA256: IAdapter["hmacSHA256"]
readonly onLock = createEventEmitter<void>() readonly onLock = createEventEmitter<void>()
constructor(private readonly i18n: i18n, adapter: IAdapter) { constructor(private readonly i18n: i18n, adapter: IAdapter) {
this.subtle = adapter.subtle this.subtle = adapter.subtle
this.hmacSHA256 = adapter.hmacSHA256
} }
async unlock(profile: Profile, masterPassword: string) { async unlock(profile: Profile, masterPassword: string) {
@ -71,7 +69,7 @@ export class Crypto implements IDisposable {
this.#locked = true this.#locked = true
this.#master = null! this.#master = null!
this.#overview = null! this.#overview = null!
this.#disposables.forEach(fn => fn.dispose()) this.#disposables.forEach(fn => fn())
this.onLock() this.onLock()
} }
@ -90,66 +88,84 @@ export class Crypto implements IDisposable {
implementation: (value: K2) => V implementation: (value: K2) => V
) => { ) => {
const map = new Map<K2, V>() const map = new Map<K2, V>()
this.#disposables.push({ this.#disposables.push(() => map.clear())
dispose: () => map.clear(),
})
return (data: K) => setIfAbsent(map, deriveArg(data), implementation) return (data: K) => setIfAbsent(map, deriveArg(data), implementation)
} }
#createWeakCache = <K extends object, V>(implementation: (value: K) => V) => { #createWeakCache = <K extends object, V>(implementation: (value: K) => V) => {
let map = new WeakMap<K, V>() let map = new WeakMap<K, V>()
this.#disposables.push({ this.#disposables.push(() => {
dispose() { map = new WeakMap()
map = new WeakMap()
},
}) })
return (data: K) => setIfAbsent(map, data, implementation) return (data: K) => setIfAbsent(map, data, implementation)
} }
decryptItemDetails = this.#createWeakCache((item: EncryptedItem) => { decryptItemDetails = this.#createWeakCache(async (item: EncryptedItem) => {
const cipher = this.deriveConcreteKey(item) const cipher = await this.deriveConcreteKey(item)
const detail = this.decryptOPData(Buffer.from(item.d, "base64"), cipher) const detail = await this.decryptOPData(Buffer.from(item.d, "base64"), cipher)
return JSON.parse(detail.toString("utf-8")) as ItemDetails return JSON.parse(detail.toString("utf-8")) as ItemDetails
}) })
decryptItemOverview = this.#createCache( decryptItemOverview = this.#createCache(
(item: EncryptedItem) => item.o, (item: EncryptedItem) => item.o,
(o: string) => { async (o: string) => {
const overview = this.decryptOPData(Buffer.from(o, "base64"), this.#overview) const overview = await this.decryptOPData(Buffer.from(o, "base64"), this.#overview)
return JSON.parse(overview.toString("utf8")) as Overview return JSON.parse(overview.toString("utf8")) as Overview
} }
) )
deriveConcreteKey = this.#createCache( deriveConcreteKey = this.#createCache(
(data: { k: string }) => data.k, (data: { k: string }) => data.k,
($k: string) => { async ($k: string) => {
const k = Buffer.from($k, "base64") const k = Buffer.from($k, "base64")
const data = k.slice(0, -32) const data = k.slice(0, -32)
this.assertHMac(data, this.#master.hmac, k.slice(-32)) await this.assertHMac(data, this.#master.hmac, k.slice(-32))
const derivedKey = decryptData(this.#master.key, data.slice(0, 16), data.slice(16)) const derivedKey = await this.decryptData(
this.#master.key,
data.slice(0, 16),
data.slice(16)
)
return splitPlainText(derivedKey) return splitPlainText(derivedKey)
} }
) )
assertHMac(data: Buffer, key: Buffer, expected: Buffer) { async assertHMac(data: Buffer, key: Buffer, expected: Buffer) {
const actual = this.hmacSHA256(key, data) const cryptoKey = await this.subtle.importKey(
if (!actual.equals(expected)) { "raw",
key,
{
name: "HMAC",
hash: {
name: "SHA-256",
},
},
false,
["verify"]
)
const verified = await this.subtle.verify("HMAC", cryptoKey, expected, data)
if (!verified) {
throw new HMACAssertionError() throw new HMACAssertionError()
} }
} }
decryptOPData(cipherText: Buffer, cipher: Cipher) { async decryptOPData(cipherText: Buffer, cipher: Cipher) {
const key = cipherText.slice(0, -32) const key = cipherText.slice(0, -32)
this.assertHMac(key, cipher.hmac, cipherText.slice(-32)) await this.assertHMac(key, cipher.hmac, cipherText.slice(-32))
const plaintext = decryptData(cipher.key, key.slice(16, 32), key.slice(32)) const plaintext = await this.decryptData(cipher.key, key.slice(16, 32), key.slice(32))
const size = readUint16(key.slice(8, 16)) const size = readUint16(key.slice(8, 16))
return plaintext.slice(-size) return plaintext.slice(-size)
} }
async decryptData(key: Buffer, iv: Buffer, data: Buffer) {
this.subtle
// return createDecipheriv("aes-256-cbc", key, iv).setAutoPadding(false).update(data)
return decryptData(key, iv, data)
}
async decryptKeys(encryptedKey: string, derived: Cipher) { async decryptKeys(encryptedKey: string, derived: Cipher) {
const buffer = Buffer.from(encryptedKey, "base64") const buffer = Buffer.from(encryptedKey, "base64")
const base = this.decryptOPData(buffer, derived) const base = await this.decryptOPData(buffer, derived)
const digest = await this.subtle.digest("SHA-512", base) const digest = await this.subtle.digest("SHA-512", base)
return splitPlainText(Buffer.from(digest)) return splitPlainText(Buffer.from(digest))
} }
@ -164,10 +180,6 @@ export const splitPlainText = (derivedKey: Buffer): Cipher => ({
hmac: derivedKey.slice(32, 64), hmac: derivedKey.slice(32, 64),
}) })
function decryptData(key: Buffer, iv: Buffer, data: Buffer) {
return createDecipheriv("aes-256-cbc", key, iv).setAutoPadding(false).update(data)
}
function readUint16({ buffer, byteOffset, length }: Buffer) { function readUint16({ buffer, byteOffset, length }: Buffer) {
return new DataView(buffer, byteOffset, length).getUint16(0, true) return new DataView(buffer, byteOffset, length).getUint16(0, true)
} }

View File

@ -0,0 +1,301 @@
/**
* Extracted from the following sources:
*
* | License | Name | Copyright |
* |---------|----------------|--------------------------------------------|
* | MIT | sha.js | (c) 2013-2018 sha.js contributors |
* | MIT | Crypto-js | (c) 2009-2013 Jeff Mott. |
* | MIT | browserify-aes | (c) 2014-2017 browserify-aes contributors |
*/
import { Buffer } from "buffer"
function bufferXor(a: Buffer, b: Buffer) {
const length = Math.min(a.length, b.length)
const buffer = Buffer.alloc(length)
for (let i = 0; i < length; ++i) {
buffer[i] = a[i] ^ b[i]
}
return buffer
}
function toUInt32Array(buf: Buffer) {
const len = (buf.length / 4) | 0
const out: number[] = new Array(len)
for (let i = 0; i < len; i++) {
out[i] = buf.readUInt32BE(i * 4)
}
return out
}
function cryptBlock(
M: number[],
keySchedule: number[],
subMix: number[][],
sbox: number[],
nRounds: number
) {
const [subMix_0, subMix_1, subMix_2, subMix_3] = subMix
let s0 = M[0] ^ keySchedule[0]
let s1 = M[1] ^ keySchedule[1]
let s2 = M[2] ^ keySchedule[2]
let s3 = M[3] ^ keySchedule[3]
let ksRow = 4
for (let round = 1; round < nRounds; round++) {
const t0 =
subMix_0[s0 >>> 24] ^
subMix_1[(s1 >>> 16) & 0xff] ^
subMix_2[(s2 >>> 8) & 0xff] ^
subMix_3[s3 & 0xff] ^
keySchedule[ksRow++]
const t1 =
subMix_0[s1 >>> 24] ^
subMix_1[(s2 >>> 16) & 0xff] ^
subMix_2[(s3 >>> 8) & 0xff] ^
subMix_3[s0 & 0xff] ^
keySchedule[ksRow++]
const t2 =
subMix_0[s2 >>> 24] ^
subMix_1[(s3 >>> 16) & 0xff] ^
subMix_2[(s0 >>> 8) & 0xff] ^
subMix_3[s1 & 0xff] ^
keySchedule[ksRow++]
const t3 =
subMix_0[s3 >>> 24] ^
subMix_1[(s0 >>> 16) & 0xff] ^
subMix_2[(s1 >>> 8) & 0xff] ^
subMix_3[s2 & 0xff] ^
keySchedule[ksRow++]
s0 = t0
s1 = t1
s2 = t2
s3 = t3
}
let t0 =
((sbox[s0 >>> 24] << 24) |
(sbox[(s1 >>> 16) & 0xff] << 16) |
(sbox[(s2 >>> 8) & 0xff] << 8) |
sbox[s3 & 0xff]) ^
keySchedule[ksRow++]
let t1 =
((sbox[s1 >>> 24] << 24) |
(sbox[(s2 >>> 16) & 0xff] << 16) |
(sbox[(s3 >>> 8) & 0xff] << 8) |
sbox[s0 & 0xff]) ^
keySchedule[ksRow++]
let t2 =
((sbox[s2 >>> 24] << 24) |
(sbox[(s3 >>> 16) & 0xff] << 16) |
(sbox[(s0 >>> 8) & 0xff] << 8) |
sbox[s1 & 0xff]) ^
keySchedule[ksRow++]
let t3 =
((sbox[s3 >>> 24] << 24) |
(sbox[(s0 >>> 16) & 0xff] << 16) |
(sbox[(s1 >>> 8) & 0xff] << 8) |
sbox[s2 & 0xff]) ^
keySchedule[ksRow++]
t0 = t0 >>> 0
t1 = t1 >>> 0
t2 = t2 >>> 0
t3 = t3 >>> 0
return [t0, t1, t2, t3]
}
// AES constants
const RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
const G = (() => {
// Compute double table
const d = new Array<number>(256)
for (let j = 0; j < 256; j++) {
if (j < 128) {
d[j] = j << 1
} else {
d[j] = (j << 1) ^ 0x11b
}
}
const sbox: number[] = []
const invSBox: number[] = []
const subMix: number[][] = [[], [], [], []]
const invSubMix: number[][] = [[], [], [], []]
// Walk GF(2^8)
let x = 0
let xi = 0
for (let i = 0; i < 256; ++i) {
// Compute sbox
let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
sbox[x] = sx
invSBox[sx] = x
// Compute multiplication
const x2 = d[x]
const x4 = d[x2]
const x8 = d[x4]
// Compute sub bytes, mix columns tables
let t = (d[sx] * 0x101) ^ (sx * 0x1010100)
subMix[0][x] = (t << 24) | (t >>> 8)
subMix[1][x] = (t << 16) | (t >>> 16)
subMix[2][x] = (t << 8) | (t >>> 24)
subMix[3][x] = t
// Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
invSubMix[0][sx] = (t << 24) | (t >>> 8)
invSubMix[1][sx] = (t << 16) | (t >>> 16)
invSubMix[2][sx] = (t << 8) | (t >>> 24)
invSubMix[3][sx] = t
if (x === 0) {
x = xi = 1
} else {
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
}
}
return {
sbox,
invSBox,
subMix,
invSubMix,
}
})()
class AES {
private key: number[]
private nRounds!: number
private invKeySchedule!: number[]
constructor(key: Buffer) {
this.key = toUInt32Array(key)
this.reset()
}
private reset() {
const keyWords = this.key
const keySize = keyWords.length
const nRounds = keySize + 6
const ksRows = (nRounds + 1) * 4
const keySchedule: number[] = []
for (let k = 0; k < keySize; k++) {
keySchedule[k] = keyWords[k]
}
for (let k = keySize; k < ksRows; k++) {
let t = keySchedule[k - 1]
if (k % keySize === 0) {
t = (t << 8) | (t >>> 24)
t =
(G.sbox[t >>> 24] << 24) |
(G.sbox[(t >>> 16) & 0xff] << 16) |
(G.sbox[(t >>> 8) & 0xff] << 8) |
G.sbox[t & 0xff]
t ^= RCON[(k / keySize) | 0] << 24
} else if (keySize > 6 && k % keySize === 4) {
t =
(G.sbox[t >>> 24] << 24) |
(G.sbox[(t >>> 16) & 0xff] << 16) |
(G.sbox[(t >>> 8) & 0xff] << 8) |
G.sbox[t & 0xff]
}
keySchedule[k] = keySchedule[k - keySize] ^ t
}
const invKeySchedule = []
for (let ik = 0; ik < ksRows; ik++) {
const ksR = ksRows - ik
const tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
if (ik < 4 || ksR <= 4) {
invKeySchedule[ik] = tt
} else {
invKeySchedule[ik] =
G.invSubMix[0][G.sbox[tt >>> 24]] ^
G.invSubMix[1][G.sbox[(tt >>> 16) & 0xff]] ^
G.invSubMix[2][G.sbox[(tt >>> 8) & 0xff]] ^
G.invSubMix[3][G.sbox[tt & 0xff]]
}
}
this.nRounds = nRounds
this.invKeySchedule = invKeySchedule
}
decryptBlock(buffer: Buffer) {
const M = toUInt32Array(buffer)
// swap
const m1 = M[1]
M[1] = M[3]
M[3] = m1
const out = cryptBlock(M, this.invKeySchedule, G.invSubMix, G.invSBox, this.nRounds)
const buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0], 0)
buf.writeUInt32BE(out[3], 4)
buf.writeUInt32BE(out[2], 8)
buf.writeUInt32BE(out[1], 12)
return buf
}
static blockSize = 4 * 4
static keySize = 256 / 8
}
function splitter() {
let cache = Buffer.allocUnsafe(0)
return {
add(data: Buffer) {
cache = Buffer.concat([cache, data])
return this
},
get() {
if (cache.length >= 16) {
const out = cache.slice(0, 16)
cache = cache.slice(16)
return out
}
return null
},
}
}
// AES-256-CBC
// == createDecipheriv("aes-256-cbc", key, iv).setAutoPadding(false).update(data)
export function decryptData(key: Buffer, iv: Buffer, data: Buffer) {
if (iv.length !== 16) {
throw new TypeError(`invalid iv length ${iv.length}`)
}
if (key.length !== 32) {
throw new TypeError(`invalid key length ${key.length}`)
}
const cipher = new AES(key)
let prev = Buffer.from(iv)
const cache = splitter().add(data)
let chunk: Buffer | null
const res: Buffer[] = []
while ((chunk = cache.get())) {
const pad = prev
prev = chunk
const out = cipher.decryptBlock(chunk)
res.push(bufferXor(out, pad))
}
return Buffer.concat(res)
}

View File

@ -1,18 +1,16 @@
export function createEventEmitter<T = void>() { export function createEventEmitter<T = void>() {
type EventListener = T extends void ? () => void : (value: T) => void type EventListener = T extends void ? () => void : (value: T) => void
type Emitter = T extends void type Emitter = T extends void
? { (): void; (listener: EventListener): IDisposable } ? { (): void; (listener: EventListener): () => void }
: { (value: T): void; (listener: EventListener): IDisposable } : { (value: T): void; (listener: EventListener): () => void }
const listeners = new Set<EventListener>() const listeners = new Set<EventListener>()
function emitter(value: T | EventListener) { function emitter(value: T | EventListener) {
if (typeof value === "function") { if (typeof value === "function") {
listeners.add(value as EventListener) listeners.add(value as EventListener)
return { return () => {
dispose() { listeners.delete(value as EventListener)
listeners.delete(value as EventListener)
},
} }
} else { } else {
listeners.forEach(fn => fn(value)) listeners.forEach(fn => fn(value))

View File

@ -4,6 +4,8 @@ export class AssertionError extends OPVaultError {}
export class HMACAssertionError extends AssertionError {} export class HMACAssertionError extends AssertionError {}
export class NotUnlockedError extends AssertionError {}
export function invariant(condition: any, message?: string): asserts condition { export function invariant(condition: any, message?: string): asserts condition {
if (!condition) { if (!condition) {
throw new AssertionError(message) throw new AssertionError(message)

View File

@ -1,6 +1,6 @@
import { resolve, extname, basename } from "path" import { resolve, extname, basename } from "path"
import invariant from "tiny-invariant" import invariant from "tiny-invariant"
import type { IFileSystem } from "./adapters" import type { IFileSystem } from "./adapter"
import { once } from "./util" import { once } from "./util"
export type OnePasswordFileManager = ReturnType<typeof OnePasswordFileManager> export type OnePasswordFileManager = ReturnType<typeof OnePasswordFileManager>

View File

@ -1,5 +1,7 @@
type integer = number type integer = number
interface IDisposable { declare namespace NodeJS {
dispose(): void interface Process {
browser?: boolean
}
} }

View File

@ -1,7 +1,6 @@
import json from "./res.json" import json from "./res.json"
const locale = const [locale] = Intl.DateTimeFormat().resolvedOptions().locale.split("-")
process.env.LOCALE || Intl.DateTimeFormat().resolvedOptions().locale.split("-")[0]
const mapValue = <T, R>( const mapValue = <T, R>(
object: Record<string, T>, object: Record<string, T>,

View File

@ -1,9 +1,12 @@
import { resolve } from "path" import { resolve } from "path"
import { Vault } from "./models/vault" import { Vault } from "./models/vault"
import type { IAdapter } from "./adapters" import type { IAdapter } from "./adapter"
import { asyncMap } from "./util" import { asyncMap } from "./util"
export type { Vault } from "./models/vault" export type { Vault } from "./models/vault"
export type { Item } from "./models/item"
export type { Attachment, AttachmentMetadata } from "./models/attachment"
export type { ItemField, ItemSection } from "./types"
export { Category, FieldType } from "./models" export { Category, FieldType } from "./models"
interface IOptions { interface IOptions {
@ -15,7 +18,7 @@ interface IOptions {
/** /**
* Adapter used to interact with the file system and cryptography modules * Adapter used to interact with the file system and cryptography modules
*/ */
adapter?: IAdapter adapter?: IAdapter | Promise<IAdapter>
} }
/** /**
@ -23,9 +26,12 @@ interface IOptions {
*/ */
export class OnePassword { export class OnePassword {
readonly #path: string readonly #path: string
readonly #adapter: IAdapter readonly #adapter: IAdapter | Promise<IAdapter>
constructor({ path, adapter = require("./adapters/node").adapter }: IOptions) { constructor({
path,
adapter = process.browser ? null! : require("./adapter").nodeAdapter,
}: IOptions) {
this.#adapter = adapter this.#adapter = adapter
this.#path = path this.#path = path
} }
@ -34,11 +40,11 @@ export class OnePassword {
* @returns A list of names of profiles of the current vault. * @returns A list of names of profiles of the current vault.
*/ */
async getProfileNames() { async getProfileNames() {
const [fs, path] = [this.#adapter.fs, this.#path] const { fs } = await this.#adapter
const children = await fs.readdir(path) const children = await fs.readdir(this.#path)
const profiles: string[] = [] const profiles: string[] = []
await asyncMap(children, async child => { await asyncMap(children, async child => {
const fullPath = resolve(path, child) const fullPath = resolve(this.#path, child)
if ( if (
(await fs.isDirectory(fullPath)) && (await fs.isDirectory(fullPath)) &&
(await fs.exists(resolve(fullPath, "profile.js"))) (await fs.exists(resolve(fullPath, "profile.js")))
@ -53,6 +59,6 @@ export class OnePassword {
* @returns A OnePassword Vault instance. * @returns A OnePassword Vault instance.
*/ */
async getProfile(profileName: string) { async getProfile(profileName: string) {
return await Vault.of(this.#path, profileName, this.#adapter) return await Vault.of(this.#path, profileName, await this.#adapter)
} }
} }

View File

@ -1,24 +1,22 @@
import { invariant } from "./errors"
export enum Category { export enum Category {
Login = 1, Login = "001",
CreditCard = 2, CreditCard = "002",
SecureNote = 3, SecureNote = "003",
Identity = 4, Identity = "004",
Password = 5, Password = "005",
Tombstone = 99, Tombstone = "099",
SoftwareLicense = 100, SoftwareLicense = "100",
BankAccount = 101, BankAccount = "101",
Database = 102, Database = "102",
DriverLicense = 103, DriverLicense = "103",
OutdoorLicense = 104, OutdoorLicense = "104",
Membership = 105, Membership = "105",
Passport = 106, Passport = "106",
Rewards = 107, Rewards = "107",
SSN = 108, SSN = "108",
Router = 109, Router = "109",
Server = 110, Server = "110",
Email = 111, Email = "111",
} }
export enum FieldType { export enum FieldType {
@ -31,9 +29,3 @@ export enum FieldType {
Checkbox = "C", Checkbox = "C",
URL = "U", URL = "U",
} }
export function getCategory(category: string) {
const int = parseInt(category)
invariant(int in Category, `Invalid category: ${category}`)
return int as Category
}

View File

@ -1,5 +1,5 @@
import { Buffer } from "buffer" import { Buffer } from "buffer"
import type { Crypto } from "./crypto" import type { Crypto } from "../crypto"
import { invariant } from "../errors" import { invariant } from "../errors"
type integer = number type integer = number
@ -52,49 +52,48 @@ export class Attachment {
file.slice(0, 6).toString("utf-8") === "OPCLDA", file.slice(0, 6).toString("utf-8") === "OPCLDA",
"Attachment must start with OPCLDA" "Attachment must start with OPCLDA"
) )
invariant( // @TODO: Re-enable this
file.readIntLE(7, 1) === 1, false &&
"The version for this attachment file format is not supported." invariant(
) file.readIntLE(7, 1) === 1,
"The version for this attachment file format is not supported."
)
} }
get icon() { get icon() {
if (this.#icon == null) {
this.#decrypt()
}
return this.#icon! return this.#icon!
} }
get file() { get file() {
if (this.#file == null) {
this.#decrypt()
}
return this.#file! return this.#file!
} }
get metadata() { get metadata() {
if (this.#metadata == null) {
this.#decrypt()
}
return this.#metadata! return this.#metadata!
} }
#decrypt() { async unlock() {
const crypto = this.#crypto const crypto = this.#crypto
const cipher = crypto.deriveConcreteKey({ k: this.#k }) const cipher = await crypto.deriveConcreteKey({ k: this.#k })
const { metadataSize, iconSize } = this const { metadataSize, iconSize } = this
const buffer = this.#buffer const buffer = this.#buffer
this.#icon = crypto.decryptOPData( this.#icon = await crypto.decryptOPData(
buffer.slice(16 + metadataSize, 16 + metadataSize + iconSize), buffer.slice(16 + metadataSize, 16 + metadataSize + iconSize),
cipher cipher
) )
this.#file = crypto.decryptOPData(buffer.slice(16 + metadataSize + iconSize), cipher) this.#file = await crypto.decryptOPData(
buffer.slice(16 + metadataSize + iconSize),
cipher
)
const metadata = JSON.parse(buffer.slice(16, 16 + metadataSize).toString("utf-8")) const metadata = JSON.parse(buffer.slice(16, 16 + metadataSize).toString("utf-8"))
metadata.overview = JSON.parse( metadata.overview = JSON.parse(
crypto (
.decryptOPData(Buffer.from(metadata.overview, "base64"), crypto.overview) await crypto.decryptOPData(
.toString() Buffer.from(metadata.overview, "base64"),
crypto.overview
)
).toString()
) )
this.#metadata = metadata this.#metadata = metadata
} }

View File

@ -1,12 +1,14 @@
import type { ItemDetails, Overview } from "../types" import type { ItemDetails, Overview } from "../types"
import type { Crypto } from "./crypto" import type { Crypto } from "../crypto"
import { Attachment } from "./attachment" import { Attachment } from "./attachment"
import { NotUnlockedError } from "../errors"
import type { Category } from "../models"
export interface EncryptedItem { export interface EncryptedItem {
category: string // "001" category: string // "001"
/** Unix seconds */ /** Unix seconds */
created: integer created: integer
d: string // "b3BkYXRhMbt" d: string // details, bass64
folder: string // 32 chars folder: string // 32 chars
hmac: string // base64 hmac: string // base64
k: string // base64 k: string // base64
@ -14,27 +16,80 @@ export interface EncryptedItem {
tx: integer // Unix seconds tx: integer // Unix seconds
updated: integer // Unix seconds updated: integer // Unix seconds
uuid: string // 32 chars uuid: string // 32 chars
fave: number
trashed?: boolean
} }
export class Item { export class Item {
#crypto: Crypto #crypto: Crypto
#data: EncryptedItem #data: EncryptedItem
#overview?: Overview
#details?: ItemDetails
attachments: Attachment[] = [] attachments: Attachment[] = []
get uuid() { // Unix milliseconds
get createdAt(): number {
return this.#data.created * 1000
}
get updatedAt(): number {
return this.#data.updated * 1000
}
get lastUsed() {
return this.#data.tx
}
get isDeleted() {
return this.#data.trashed
}
get category() {
return this.#data.category as Category
}
get uuid(): string {
return this.#data.uuid return this.#data.uuid
} }
get overview(): Overview { get overview(): Overview {
return this.#crypto.decryptItemOverview(this.#data) if (!this.#overview) {
throw new NotUnlockedError()
}
return this.#overview!
} }
get itemDetails(): ItemDetails { get details(): ItemDetails {
return this.#crypto.decryptItemDetails(this.#data) if (!this.#details) {
throw new NotUnlockedError()
}
return this.#details!
}
get fave() {
return this.#data.fave
} }
constructor(crypto: Crypto, data: EncryptedItem) { constructor(crypto: Crypto, data: EncryptedItem) {
this.#crypto = crypto this.#crypto = crypto
this.#data = data this.#data = data
crypto.onLock(() => {
this.#overview = undefined!
this.#details = undefined!
this.attachments.forEach(file => file.dispose())
})
}
/** @internal */
async _unlockOverview() {
this.#overview = await this.#crypto.decryptItemOverview(this.#data)
return this
}
/** @internal */
async _unlockDetails() {
this.#details = await this.#crypto.decryptItemDetails(this.#data)
return this
}
/** @internal */
async _unlock() {
await this._unlockOverview()
await this._unlockDetails()
return this
} }
/** @internal */ /** @internal */

View File

@ -1,9 +1,9 @@
import type { IAdapter } from "../adapters" import type { IAdapter } from "../adapter"
import { HMACAssertionError, invariant } from "../errors" import { HMACAssertionError, invariant } from "../errors"
import { OnePasswordFileManager } from "../fs" import { OnePasswordFileManager } from "../fs"
import { i18n } from "../i18n" import { i18n } from "../i18n"
import type { EncryptedItem } from "./item" import type { EncryptedItem } from "./item"
import { Crypto } from "./crypto" import { Crypto } from "../crypto"
import { Item } from "./item" import { Item } from "./item"
import type { Profile } from "../types" import type { Profile } from "../types"
import { WeakValueMap } from "../weakMap" import { WeakValueMap } from "../weakMap"
@ -85,6 +85,13 @@ export class Vault {
return this.#items.map(x => x.uuid) return this.#items.map(x => x.uuid)
} }
async *values() {
this.#crypto.assertUnlocked()
for (const item of this.#items) {
yield await item._unlock()
}
}
/** /**
* Unlock this OnePassword vault. * Unlock this OnePassword vault.
* @param masterPassword User provided master password. Only the derived * @param masterPassword User provided master password. Only the derived
@ -115,17 +122,18 @@ export class Vault {
return this.#crypto.locked return this.#crypto.locked
} }
getItem(uuid: string): Item | undefined getItem(uuid: string): Promise<Item | undefined>
getItem(filter: { title: string }): Item | undefined getItem(filter: { title: string }): Promise<Item | undefined>
getItem(filter: any) { async getItem(filter: any) {
this.#crypto.assertUnlocked() this.#crypto.assertUnlocked()
if (typeof filter === "string") { if (typeof filter === "string") {
return this.#itemsMap.get(filter) return this.#itemsMap.get(filter)?._unlock()
} else { } else {
for (const value of this.#items) { for (const _value of this.#items) {
const value = await _value._unlockOverview()
if (value.overview.title === filter.title) { if (value.overview.title === filter.title) {
return value return value._unlockDetails()
} }
} }
} }

View File

@ -23,31 +23,65 @@ export type TextField = {
value: string value: string
designation: string designation: string
name: string name: string
id?: undefined
} }
export type BooleanField = { export type BooleanField = {
type: FieldType.Checkbox type: FieldType.Checkbox
name: string name: string
value?: "✓" | string value?: "✓" | string
designation?: undefined
id?: undefined
} }
export type ItemField = export type ItemField =
| TextField | TextField
| BooleanField | BooleanField
| {
name: string
designation: "username"
value: string
id?: undefined
type?: undefined
}
| {
name: string
designation: "password"
value: string
id?: undefined
type?: undefined
}
| { | {
// @TODO: This currently catches all item fields. // @TODO: This currently catches all item fields.
type: FieldType type: FieldType
value: string value: string
designation?: string designation?: string
id?: undefined
name: string name: string
} }
declare namespace ItemSection { export namespace ItemSection {
type A = { export type A = {
guarded: "yes" guarded: "yes"
clipboardFilter?: string clipboardFilter?: string
} }
type String = { export type Address = {
k: "address"
v: {
city: string
zip: string
state: string
country: string
street: string
}
n: "address"
a: {
guarded: "yes"
}
t: "address"
}
export type String = {
k: "string" k: "string"
v: string v: string
/** Unique name */ /** Unique name */
@ -56,13 +90,13 @@ declare namespace ItemSection {
/** User-readable title */ /** User-readable title */
t: string // "first name" | "initial" | "address" | "license class" | "conditions / restrictions" | "expiry date" t: string // "first name" | "initial" | "address" | "license class" | "conditions / restrictions" | "expiry date"
} }
type Menu = { export type Menu = {
k: "menu" k: "menu"
v: string // "female" v: string // "female"
a: A a: A
t: string // "sex" t: string // "sex"
} }
type Date = { export type Date = {
k: "date" k: "date"
v: number // 359100000 v: number // 359100000
/** @example "birthdate" */ /** @example "birthdate" */
@ -71,19 +105,19 @@ declare namespace ItemSection {
/** @example "birth date" | "date of birth" */ /** @example "birth date" | "date of birth" */
t: string t: string
} }
type Gender = { export type Gender = {
k: "gender" k: "gender"
n: "sex" n: "sex"
v: string // "female" v: string // "female"
t: "sex" t: "sex"
} }
type MonthYear = { export type MonthYear = {
k: "monthYear" k: "monthYear"
n: string // "expiry_date" n: string // "expiry_date"
v: number // 2515 v: number // 2515
t: string // "expiry date" t: string // "expiry date"
} }
type Concealed = { export type Concealed = {
k: "concealed" k: "concealed"
n: "password" n: "password"
v: string v: string
@ -94,7 +128,7 @@ declare namespace ItemSection {
} }
// eslint-disable-next-line @typescript-eslint/ban-types // eslint-disable-next-line @typescript-eslint/ban-types
type Any = String | Menu | Date | Gender | MonthYear | Concealed export type Any = String | Menu | Date | Gender | MonthYear | Concealed | Address
} }
// One of them is empty?, 0C4F27910A64488BB339AED63565D148 // One of them is empty?, 0C4F27910A64488BB339AED63565D148
@ -105,7 +139,7 @@ export interface ItemDetails {
htmlMethod: "post" | "get" htmlMethod: "post" | "get"
} }
notesPlain?: string notesPlain?: string
sections: { sections?: {
/** @example "name" | "title" | "internet" */ /** @example "name" | "title" | "internet" */
name: string name: string
/** @example "Identification" | "Address" | "Internet Details" */ /** @example "Identification" | "Address" | "Internet Details" */
@ -114,6 +148,9 @@ export interface ItemDetails {
}[] }[]
/** Web form fields */ /** Web form fields */
fields?: ItemField[] fields?: ItemField[]
/** Plain password items */
backupKeys?: string[]
password?: string
} }
export interface Folder { export interface Folder {

View File

@ -1,5 +1,3 @@
import { invariant } from "./errors"
export function asyncMap<T, R>( export function asyncMap<T, R>(
list: T[], list: T[],
fn: (value: T, index: number, list: T[]) => Promise<R> fn: (value: T, index: number, list: T[]) => Promise<R>
@ -35,19 +33,3 @@ export function once<T extends (...args: any[]) => any>(fn: T): T {
} }
return res as any return res as any
} }
const cache = (): MethodDecorator => (_, key, descriptor: any) => {
if (process.env.NODE_ENV !== "production") {
invariant(typeof key === "string")
invariant(descriptor.get != null)
}
const cacheMap = new WeakMap()
const fn = descriptor.get
descriptor.get = function () {
if (!cacheMap.has(this)) {
cacheMap.set(this, fn.call(this))
}
return cacheMap.get(this)!
}
}

View File

@ -0,0 +1,3 @@
{
"extends": "../../tsconfig.json"
}

7
packages/web/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
src/third-party-licenses.json
node_modules
.DS_Store
dist
bundle
*.local
*.yml.d.ts

View File

@ -0,0 +1,29 @@
# yaml-language-server: $schema=https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json
appId: com.proteria.opvault
productName: OPVault Viewer
files:
- "**/*"
icon: dist/512x512.png
directories:
output: bundle
app: dist
buildResources: dist
mac:
category: public.app-category.productivity
target:
target: dir
arch:
- x64
- arm64
darkModeSupport: true
linux:
executableName: opvault
category: Utility
icon: 512x512.png
artifactName: ${productName}-${version}-${arch}.${ext}
target:
target: AppImage
arch:
- x64
- arm64

30
packages/web/esbuild.js Executable file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env node
// @ts-check
const { builtinModules } = require("module")
const { build } = require("esbuild")
const args = process.argv.slice(2)
build({
bundle: true,
define: {},
entryPoints: ["./src/electron/index.ts", "./src/electron/preload.ts"],
outdir: "./dist/main",
external: builtinModules.concat("electron"),
target: ["chrome96"],
tsconfig: "./tsconfig.json",
sourcemap: "external",
minify: process.env.NODE_ENV === "production",
banner: {
js: "/* eslint-disable */",
},
loader: {
".png": "file",
".eot": "file",
".svg": "file",
".woff": "file",
".woff2": "file",
".ttf": "file",
},
watch: args.includes("-w") || args.includes("--watch"),
})

17
packages/web/index.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
/>
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OPVault Viewer</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

263
packages/web/logo.svg Normal file
View File

@ -0,0 +1,263 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 128 128"
version="1.0"
id="svg11300"
height="128"
width="128"
>
<style>
.card-rect {
/* fill: #2ec27e; */
fill: #496ccf;
}
.barcode-1,
.barcode-2,
.barcode-3 {
/* stroke: #26a269; */
stroke: #7b95e1;z
}
#path1138 {
fill: #7b95e1;z
}
.barcode-1 {
stroke-width: 1.87082875;
}
.barcode-2 {
stroke-width: 3.7416575;
}
.barcode-3 {
stroke-width: 5.61248589;
}
</style>
<title id="title4162">Adwaita Icon Template</title>
<defs id="defs3">
<linearGradient id="linearGradient1296">
<stop id="stop1292" offset="0" style="stop-color: #77767b; stop-opacity: 1" />
<stop
style="stop-color: #c0bfbc; stop-opacity: 1"
offset="0.17589436"
id="stop1300"
/>
<stop
id="stop1302"
offset="0.4092612"
style="stop-color: #77767b; stop-opacity: 1"
/>
<stop id="stop1294" offset="1" style="stop-color: #3d3846; stop-opacity: 1" />
</linearGradient>
<linearGradient id="linearGradient969">
<stop style="stop-color: #f6f5f4; stop-opacity: 1" offset="0" id="stop963" />
<stop
id="stop965"
offset="0.25731823"
style="stop-color: #ffffff; stop-opacity: 1"
/>
<stop
style="stop-color: #c0bfbc; stop-opacity: 1"
offset="0.5999999"
id="stop1085"
/>
<stop
id="stop1087"
offset="0.70312482"
style="stop-color: #f6f5f4; stop-opacity: 1"
/>
<stop style="stop-color: #f6f5f4; stop-opacity: 1" offset="1" id="stop967" />
</linearGradient>
<linearGradient id="linearGradient1040">
<stop style="stop-color: #c0bfbc; stop-opacity: 1" offset="0" id="stop1036" />
<stop style="stop-color: #f6f5f4; stop-opacity: 1" offset="1" id="stop1038" />
</linearGradient>
<linearGradient
y2="249.87819"
x2="67.121834"
y1="238.30762"
x1="78.692398"
gradientTransform="translate(55.100502, 0.07106726)"
gradientUnits="userSpaceOnUse"
id="linearGradient1986"
xlink:href="#linearGradient969"
/>
<linearGradient
y2="70.300697"
x2="85.886963"
y1="67.679771"
x1="88.507896"
gradientTransform="translate(55.769701, 171.28412)"
gradientUnits="userSpaceOnUse"
id="linearGradient1988"
xlink:href="#linearGradient1040"
/>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="268"
x2="198"
y1="268"
x1="142"
id="linearGradient1039"
xlink:href="#linearGradient1296"
/>
</defs>
<metadata id="metadata4">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:creator>
<cc:Agent>
<dc:title>GNOME Design Team</dc:title>
</cc:Agent>
</dc:creator>
<dc:source />
<cc:license rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
<dc:title>Adwaita Icon Template</dc:title>
<dc:subject>
<rdf:Bag />
</dc:subject>
<dc:date />
<dc:rights>
<cc:Agent>
<dc:title />
</cc:Agent>
</dc:rights>
<dc:publisher>
<cc:Agent>
<dc:title />
</cc:Agent>
</dc:publisher>
<dc:identifier />
<dc:relation />
<dc:language />
<dc:coverage />
<dc:description />
<dc:contributor>
<cc:Agent>
<dc:title />
</cc:Agent>
</dc:contributor>
</cc:Work>
<cc:License rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g transform="translate(0, -172)" id="layer1">
<g id="layer9">
<rect
class="card-rect"
id="rect1027"
width="112"
height="63.999977"
x="8"
y="224"
rx="8"
ry="8"
/>
<g id="g1256" transform="matrix(1,0,0,1.1428571,-4.8522949e-8,-22.857143)">
<path class="barcode-1" d="m 27,230 v 14" id="path1164" />
<path class="barcode-2" d="m 32,230 v 14" id="path1166" />
<path class="barcode-1" d="m 37,230 v 14" id="path1168" />
<path class="barcode-1" d="m 41,230 v 14" id="path1170" />
<path class="barcode-2" d="m 46,230 v 14" id="path1172" />
<path class="barcode-2" d="m 56,230 v 14" id="path1174" />
<path class="barcode-1" d="m 51,230 v 14" id="path1176" />
<path class="barcode-3" d="m 63,230 v 14" id="path1178" />
<path class="barcode-1" d="m 69,230 v 14" id="path1180" />
<path class="barcode-1" d="m 73,230 v 14" id="path1182" />
<path class="barcode-1" d="m 77,230 v 14" id="path1184" />
<path class="barcode-2" d="m 82,230 v 14" id="path1186" />
<path class="barcode-1" d="m 87,230 v 14" id="path1188" />
<path class="barcode-1" d="m 99,230 v 14" id="path1190" />
<path class="barcode-3" d="m 93,230 v 14" id="path1192" />
<path class="barcode-1" d="m 103,230 v 14" id="path1194" />
<path class="barcode-1" d="m 107,230 v 14" id="path1196" />
</g>
<g
style="display: inline; fill: #f8faff; enable-background: new"
id="g1130"
transform="translate(-4.8522949e-8,12)"
>
<path
d="m 22.21582,254 1.197265,5.06836 -3.90039,-3.2793 -1.453125,2.5918 5.009765,1.6582 -5.042968,1.58985 1.433593,2.64062 3.955078,-3.30469 L 22.21582,266 h 3.410156 l -1.101562,-4.95898 3.833984,3.31445 1.476562,-2.61914 -4.978515,-1.68555 5.117187,-1.42578 -1.453125,-2.61914 -4.033203,3.08398 L 25.624023,254 Z"
id="path1940"
/>
<path
id="path1056"
d="m 38.21582,254 1.197265,5.06836 -3.90039,-3.2793 -1.453125,2.5918 5.009765,1.6582 -5.042968,1.58985 1.433593,2.64062 3.955078,-3.30469 L 38.21582,266 h 3.410156 l -1.101562,-4.95898 3.833984,3.31445 1.476562,-2.61914 -4.978515,-1.68555 5.117187,-1.42578 -1.453125,-2.61914 -4.033203,3.08398 L 41.624023,254 Z"
/>
<path
d="m 54.21582,254 1.197265,5.06836 -3.90039,-3.2793 -1.453125,2.5918 5.009765,1.6582 -5.042968,1.58985 1.433593,2.64062 3.955078,-3.30469 L 54.21582,266 h 3.410156 l -1.101562,-4.95898 3.833984,3.31445 1.476562,-2.61914 -4.978515,-1.68555 5.117187,-1.42578 -1.453125,-2.61914 -4.033203,3.08398 L 57.624023,254 Z"
id="path1062"
/>
<path
id="path1068"
d="m 70.21582,254 1.197265,5.06836 -3.90039,-3.2793 -1.453125,2.5918 5.009765,1.6582 -5.042968,1.58985 1.433593,2.64062 3.955078,-3.30469 L 70.21582,266 h 3.410156 l -1.101562,-4.95898 3.833984,3.31445 1.476562,-2.61914 -4.978515,-1.68555 5.117187,-1.42578 -1.453125,-2.61914 -4.033203,3.08398 L 73.624023,254 Z"
/>
<path
d="m 86.21582,254 1.197265,5.06836 -3.90039,-3.2793 -1.453125,2.5918 5.009765,1.6582 -5.042968,1.58985 1.433593,2.64062 3.955078,-3.30469 L 86.21582,266 h 3.410156 l -1.101562,-4.95898 3.833984,3.31445 1.476562,-2.61914 -4.978515,-1.68555 5.117187,-1.42578 -1.453125,-2.61914 -4.033203,3.08398 L 89.624023,254 Z"
id="path1074"
/>
<path
id="path1080"
d="m 102.21582,254 1.19726,5.06836 -3.900385,-3.2793 -1.453125,2.5918 5.00976,1.6582 -5.042963,1.58985 1.433593,2.64062 3.95508,-3.30469 L 102.21582,266 h 3.41016 l -1.10157,-4.95898 3.83399,3.31445 1.47656,-2.61914 -4.97851,-1.68555 5.11718,-1.42578 -1.45312,-2.61914 -4.03321,3.08398 L 105.62402,254 Z"
/>
</g>
<rect
ry="7.9999995"
rx="8"
y="200"
x="8"
height="40"
width="112"
id="rect954"
class="card-rect"
/>
<rect y="214" x="8" height="18" width="112" id="rect961" style="fill: #241f31" />
<path id="path1138" d="m 22,242 -7.2,6 7.2,6 z" />
</g>
<g id="g959-3" transform="rotate(-180,107.5,242)">
<path
style="fill: url(#linearGradient1039)"
d="m 170,296 a 28,28 0 0 1 -28,-28 28,28 0 0 1 28,-28 28,28 0 0 1 28,28 28,28 0 0 1 -28,28 z m 0.0312,-12 a 6.0312505,6.0000005 0 0 0 6.03125,-6 6.0312505,6.0000005 0 0 0 -6.03125,-6 6.0312505,6.0000005 0 0 0 -6.03125,6 6.0312505,6.0000005 0 0 0 6.03125,6 z"
id="path947-0"
/>
<g
transform="matrix(0.70710678,-0.70710678,-0.70710678,-0.70710678,243.95332,484.3158)"
id="g955-3"
>
<path
id="path1990"
d="m 125.41422,214.44366 -16.97055,16.97056 8.36742,8.36743 3.65338,-3.41768 4.24264,4.24264 h 2.82843 v 2.82843 l 2.12132,2.12132 h 4.24264 v 4.24264 h 2.82843 v 2.82842 h 5.65685 v 5.65686 h 2.82843 v 2.82843 h 12.72792 l 4.94974,-4.94976 v -4.24264 z"
style="fill: #77767b"
/>
<path
style="fill: url(#linearGradient1986)"
d="M 124,213.02944 107.02945,230 l 8.36742,8.36743 3.65338,-3.41768 4.24264,4.24264 h 2.82843 v 2.82843 l 2.12132,2.12132 h 4.24264 v 4.24264 h 2.82843 v 2.82842 h 5.65685 v 5.65686 h 2.82843 v 2.82843 h 12.72792 l 4.94974,-4.94976 v -4.24264 z"
id="path951-1"
/>
<path
style="fill: url(#linearGradient1988)"
d="m 125.74823,221.26459 c -1.79388,0.002 -2.67811,2.18243 -1.39257,3.43359 l 33.58547,33.5861 2.82844,-2.82843 -33.58579,-33.58579 c -0.37702,-0.38755 -0.89487,-0.60597 -1.43555,-0.60547 z"
id="path953-2"
/>
</g>
<path
id="path957-8"
d="m 170,298 a 28,28 0 0 0 28,-28 28,28 0 0 0 -28,-28 28,28 0 0 0 -28,28 28,28 0 0 0 28,28 z m -0.0312,-12 a 6.0312505,6.0000005 0 0 1 -6.03125,-6 6.0312505,6.0000005 0 0 1 6.03125,-6 6.0312505,6.0000005 0 0 1 6.03125,6 6.0312505,6.0000005 0 0 1 -6.03125,6 z"
style="fill: #f6f5f4"
/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

45
packages/web/package.json Normal file
View File

@ -0,0 +1,45 @@
{
"name": "opvault-web",
"version": "1.0.0",
"main": "dist/main/index.js",
"author": "proteria",
"license": "GPL-3.0-only",
"description": "OnePassword local vault viewer",
"scripts": {
"dev": "concurrently vite npm:start",
"build": "vite build",
"serve": "vite preview",
"start": "./esbuild.js && NODE_ENV=development electron --enable-transparent-visuals --disable-gpu ./dist/main/index.js",
"bundle": "./scripts/build.sh"
},
"dependencies": {
"@emotion/css": "^11.7.1",
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"buffer": "^6.0.3",
"path-browserify": "^1.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.3.1",
"react-idle-timer": "4.6.4"
},
"devDependencies": {
"@babel/core": "^7.16.7",
"@emotion/babel-plugin": "^11.7.2",
"@rollup/plugin-yaml": "^3.1.0",
"@types/react": "^17.0.37",
"@types/react-dom": "^17.0.11",
"@vitejs/plugin-react": "^1.1.3",
"@types/babel__core": "^7.1.18",
"concurrently": "^6.5.1",
"electron": "^16.0.5",
"electron-builder": "^22.14.5",
"esbuild": "^0.14.5",
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"opvault.js": "*",
"sass": "^1.45.0",
"typescript": "^4.5.4",
"vite": "^2.7.3"
}
}

View File

@ -0,0 +1,26 @@
#!/usr/bin/env node
const fs = require("fs")
const { resolve } = require("path")
const { load } = require("js-yaml")
const ymlPath = resolve(__dirname, "../src/i18n/texts.yml")
const json = load(fs.readFileSync(ymlPath, "utf-8"))
const dtsPath = ymlPath + ".d.ts"
fs.writeFileSync(
dtsPath,
`type Translation = Record<string, string>;
declare const exportee: {
${Object.entries(json)
.map(
([category, value]) =>
`${category}: {\n${Object.keys(value)
.map(key => ` ${key}: Translation;`)
.join("\n")}\n };`
)
.join("\n ")}
};
export default exportee;
`
)

View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
const fs = require("fs")
const { resolve } = require("path")
const json = require("../package.json")
json.name = "OPVault"
json.main = "main/index.js"
delete json.scripts
delete json.devDependencies
delete json.build
fs.writeFileSync(
resolve(__dirname, "../dist/package.json"),
JSON.stringify(json, null, 2)
)

View File

@ -0,0 +1,42 @@
#!/usr/bin/env node
const fs = require("fs")
const { resolve } = require("path")
const root = resolve(__dirname, "../../..")
const packages = [
root,
resolve(root, "packages/web"),
resolve(root, "packages/opvault.js"),
]
const readJSON = path => JSON.parse(fs.readFileSync(path, "utf-8"))
const infoMap = Object.fromEntries(
packages.flatMap(dir => {
const rootPkg = readJSON(resolve(dir, "package.json"))
const dependencies = Object.keys(rootPkg.dependencies || {})
return dependencies.map(dependency => {
const pkgDir = resolve(dir, "node_modules", dependency)
const pkg = readJSON(resolve(pkgDir, "package.json"))
const licenseFile = fs
.readdirSync(pkgDir)
.filter(x => x.toLowerCase().startsWith("license"))
if (licenseFile.length !== 1) {
console.error(fs.readdirSync(pkgDir))
throw new Error(`Cannot determine license file for ${pkg.name}`)
}
return [
pkg.name,
{
name: pkg.name,
author: pkg.author?.name ?? pkg.author,
license: fs.readFileSync(resolve(pkgDir, licenseFile[0]), "utf-8"),
},
]
})
})
)
fs.writeFileSync(
resolve(__dirname, "../src/third-party-licenses.json"),
JSON.stringify(infoMap, null, 2)
)

7
packages/web/scripts/build.sh Executable file
View File

@ -0,0 +1,7 @@
#!/bin/sh
./scripts/build-i18n-yml-typedef.js
./scripts/build-third-party-license.js
./scripts/build-package-json.js
npx vite build
NODE_ENV=production ./esbuild.js
./node_modules/.bin/electron-builder build

View File

@ -0,0 +1,41 @@
import * as babel from "@babel/core"
import type { PluginOption, TransformResult } from "vite"
const sourceRegex = /\.(j|t)sx?$/
export default function macrosPlugin(): PluginOption {
return {
name: "babel-macros",
enforce: "pre",
transform(source: string, filename: string) {
if (filename.includes("node_modules")) {
return undefined
}
if (!sourceRegex.test(filename)) {
return
}
const hasBabelMacro = source.includes('.macro"')
const hasEmotion = source.includes("@emotion")
if (!hasBabelMacro && !hasEmotion) {
return undefined
}
const result = babel.transformSync(source, {
filename,
parserOpts: {
plugins: ["jsx", "typescript", "decorators-legacy"],
},
plugins: [
hasBabelMacro && require.resolve("babel-plugin-macros"),
hasEmotion && require.resolve("@emotion/babel-plugin"),
].filter(Boolean),
generatorOpts: {
decoratorsBeforeExport: true,
},
babelrc: false,
configFile: false,
sourceMaps: true,
})
return result as TransformResult | null
},
}
}

52
packages/web/src/App.tsx Normal file
View File

@ -0,0 +1,52 @@
/* eslint-disable import/no-unresolved */
import { useCallback, useEffect, useState } from "react"
import type { Vault, OnePassword } from "opvault.js"
import { useIdleTimer } from "react-idle-timer/modern"
import { VaultView } from "./pages/Vault"
import { VaultPicker } from "./pages/VaultPicker"
import { Key, useStorage } from "./utils/localStorage"
export const App: React.FC = () => {
const [instance, setInstance] = useState<OnePassword>()
const [vault, setVault] = useState<Vault>()
const [enableAutoLock] = useStorage(Key.ENABLE_AUTO_LOCK)
const [autolockAfter] = useStorage(Key.AUTO_LOCK_AFTER)
const onLock = useCallback(() => {
vault?.lock()
setVault(undefined)
}, [vault])
const onAutoLock = useCallback(() => {
if (enableAutoLock) {
onLock()
}
}, [onLock, enableAutoLock])
const { reset, pause } = useIdleTimer({
timeout: autolockAfter * 1000,
onIdle: onAutoLock,
})
useEffect(() => {
if (vault) {
reset()
} else {
pause()
}
}, [vault])
if (!vault) {
return (
<VaultPicker
instance={instance}
setInstance={setInstance}
vault={vault}
setVault={setVault}
/>
)
}
return <VaultView onLock={onLock} vault={vault} />
}

View File

@ -0,0 +1,14 @@
import { useEffect, memo } from "react"
import { useLocaleContext, useTranslate } from "./i18n"
export const SideEffect = memo(() => {
const { locale } = useLocaleContext()
const t = useTranslate()
useEffect(() => {
document.documentElement.lang = locale
document.title = t.label.app_name
}, [locale])
return null
})

View File

@ -0,0 +1,65 @@
import styled from "@emotion/styled"
import { useEffect, useMemo, useState } from "react"
import { ClickableContainer } from "../components/ItemFieldValue"
import { scrollbar } from "../styles"
const Container = styled.div`
display: flex;
`
const ListContainer = styled.div`
min-width: 150px;
ul {
list-style-type: none;
margin-block-start: 0;
padding-inline-start: 0;
}
li {
line-height: 1.6em;
}
`
const LicenseText = styled.div`
flex-grow: 1;
font-family: var(--monospace);
max-height: 575px;
overflow-y: scroll;
white-space: pre-wrap;
`
export const LicenseView = () => {
const [licenseInfo, setLicenseInfo] = useState<
typeof import("../third-party-licenses.json")
>(() => ({} as any))
const names = useMemo(() => Object.keys(licenseInfo), [licenseInfo])
const [selected, setSelected] = useState<string>()
useEffect(() => {
import("../third-party-licenses.json").then(json => setLicenseInfo(json.default))
}, [])
useEffect(() => {
setSelected(names[0])
}, [names])
return (
<Container>
<ListContainer>
<ul>
{names.map(name => (
<li
key={name}
style={name === selected ? { fontWeight: 600 } : undefined}
onClick={() => setSelected(name)}
>
<ClickableContainer>{name}</ClickableContainer>
</li>
))}
</ul>
</ListContainer>
<LicenseText className={scrollbar}>
{licenseInfo[selected as any]?.license}
</LicenseText>
</Container>
)
}

View File

@ -0,0 +1,27 @@
import styled from "@emotion/styled"
import { Modal } from "../components/Modal"
import { useTranslate } from "../i18n"
import { LicenseView } from "./LicenseViewer"
const Container = styled.div`
width: 800px;
min-height: 450px;
`
const LicenseSectionHeader = styled.h3`
margin-top: 0;
`
export const About: React.FC<{
show: boolean
onHide(): void
}> = ({ show, onHide }) => {
const t = useTranslate()
return (
<Modal maxWidth={800} show={show} title={t.label.about_app} onClose={onHide}>
<Container>
<LicenseSectionHeader>Licenses</LicenseSectionHeader>
<LicenseView />
</Container>
</Modal>
)
}

View File

@ -0,0 +1,53 @@
import styled from "@emotion/styled"
import { memo, useEffect } from "react"
const Container = styled.div`
background: rgba(255, 255, 255, 0.6);
backdrop-filter: blur(4px);
border-radius: 20px;
font-family: var(--monospace);
letter-spacing: 2px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 6em;
text-align: center;
padding: 20px 25px;
word-break: break-word;
min-width: 75vw;
z-index: 2;
@media (prefers-color-scheme: dark) {
background: rgba(0, 0, 0, 0.6);
}
`
const Letter = styled.span`
&:nth-of-type(even) {
opacity: 0.8;
}
`
interface BigTextViewProps {
onClose(): void
children: string
}
export const BigTextView = memo<BigTextViewProps>(({ onClose, children }) => {
useEffect(() => {
const fn = (e: KeyboardEvent) => {
if (e.code === "Escape") {
onClose()
}
}
document.addEventListener("keydown", fn)
return () => document.removeEventListener("keydown", fn)
}, [onClose])
return (
<Container>
{children.split("").map((letter, i) => (
<Letter key={i}>{letter}</Letter>
))}
</Container>
)
})

View File

@ -0,0 +1,88 @@
import { memo } from "react"
import { Category } from "opvault.js"
import { cx, css } from "@emotion/css"
import { BsBank2, BsPeopleFill } from "react-icons/bs"
import { CgLogIn } from "react-icons/cg"
import { HiMail, HiIdentification } from "react-icons/hi"
import { RiGovernmentLine } from "react-icons/ri"
import {
FaArchive,
FaDatabase,
FaPassport,
FaServer,
FaFish,
FaGift,
FaCar,
FaWifi,
} from "react-icons/fa"
import { GrLicense, GrNotes, GrCreditCard } from "react-icons/gr"
import { MdPassword } from "react-icons/md"
function getComponent(category: Category) {
switch (category) {
case Category.BankAccount:
return BsBank2
case Category.CreditCard:
return GrCreditCard
case Category.Database:
return FaDatabase
case Category.DriverLicense:
return FaCar
case Category.Email:
return HiMail
case Category.Identity:
return HiIdentification
case Category.Login:
return CgLogIn
case Category.Membership:
return BsPeopleFill
case Category.OutdoorLicense:
return FaFish
case Category.Passport:
return FaPassport
case Category.Password:
return MdPassword
case Category.Rewards:
return FaGift
case Category.Router:
return FaWifi
case Category.SecureNote:
return GrNotes
case Category.Server:
return FaServer
case Category.SoftwareLicense:
return GrLicense
case Category.SSN:
return RiGovernmentLine
case Category.Tombstone:
return FaArchive
default:
category
}
}
export const reactIconClass = css`
fill: var(--color);
@media (prefers-color-scheme: dark) {
path:not([fill="none"]),
path[stroke] {
fill: #fff;
}
}
`
interface CategoryIconProps {
className?: string
style?: React.CSSProperties
fill?: string
category: Category
}
export const CategoryIcon = memo<CategoryIconProps>(
({ className, category, style, fill }) => {
const Component = getComponent(category)
return Component ? (
<Component className={cx(reactIconClass, className)} fill={fill} style={style} />
) : null
}
)

View File

@ -0,0 +1,51 @@
import type { ErrorInfo } from "react"
import React from "react"
import styled from "@emotion/styled"
/**
* @module ErrorBoundary
* React HOC to restrict an Error from blowing up the entire application.
*/
type State = { error?: Error; info?: ErrorInfo }
const Div = styled.div`
border: 1px solid #ddd;
border-radius: 10px;
box-shadow: rgba(0, 0, 0, 0.05) 0px 1px 1px;
margin: 20px;
padding: 20px;
`
const Header = styled.h2`
font-weight: 600;
margin: 0;
`
const Pre = styled.pre`
font-size: 15px;
line-height: 1.3em;
`
export class ErrorBoundary extends React.Component<any, State> {
state: State = {}
componentDidCatch(error: Error, info: ErrorInfo) {
this.setState({ error, info })
}
render() {
const { error, info } = this.state
if (error) {
console.error(error)
return (
<Div>
<Header>Error: {error.message}</Header>
<Pre>{info?.componentStack?.replace(/^\n/, "")}</Pre>
<Pre>{error.stack}</Pre>
</Div>
)
}
return <>{this.props.children}</>
}
}

View File

@ -0,0 +1,198 @@
import styled from "@emotion/styled"
import { useEffect, useMemo, useState } from "react"
import type { Item } from "opvault.js"
import { Category } from "opvault.js"
import { IoSearch } from "react-icons/io5"
import { ItemList } from "../components/ItemList"
import { ItemView } from "../components/Item"
import { reactIconClass } from "../components/CategoryIcon"
import { useTranslate } from "../i18n/index"
import { scrollbar } from "../styles"
const ListContainer = styled.div`
border-right: 1px solid var(--border-color);
width: 350px;
margin-right: 10px;
overflow-y: scroll;
overflow-y: overlay;
overflow-x: hidden;
@media (prefers-color-scheme: dark) {
background: #202020;
border-right-color: transparent;
}
`
const ItemContainer = styled.div`
width: calc(100% - 300px);
overflow: hidden;
`
const SearchContainer = styled.div`
text-align: center;
position: relative;
flex-grow: 1;
margin: 10px 0;
margin-right: 10px;
`
const SortContainer = styled.div`
display: flex;
margin: 10px 0;
`
const CategorySelect = styled.select`
width: 50%;
margin-left: 10px;
margin-right: 5px;
`
const SortSelect = styled.select`
width: calc(50% - 25px);
`
const SearchInput = styled.input`
--margin: 10px;
width: calc(100% - var(--margin) * 2 + 9px);
margin: 0 var(--margin);
padding-left: 2em !important;
`
const SearchIcon = styled(IoSearch)`
position: absolute;
top: 9px;
left: 20px;
`
const enum SortBy {
Name,
CreatedAt,
UpdatedAt,
}
export const FilteredVaultView: React.FC<{ items: Item[] }> = ({ items }) => {
const t = useTranslate()
const [item, setItem] = useState<Item>()
const [category, setCategory] = useState<Category>()
const [sortBy, setSortBy] = useState(SortBy.Name)
const [search, setSearch] = useState("")
useEffect(() => {
setItem(undefined)
}, [items])
const compareFn = useMemo((): ((a: Item, b: Item) => number) => {
switch (sortBy) {
case SortBy.Name:
return (a, b) => (a.overview.title ?? "").localeCompare(b?.overview.title ?? "")
case SortBy.CreatedAt:
return (a, b) => b.createdAt - a.createdAt
case SortBy.UpdatedAt:
return (a, b) => b.updatedAt - a.updatedAt
}
}, [sortBy])
const sortedItem = useMemo(() => items.slice().sort(compareFn), [items, compareFn])
const filtered = useMemo(() => {
let items = sortedItem.filter(x => x.category !== Category.Tombstone)
if (category != null) {
items = items.filter(x => x.category === category)
}
let res: Item[] = items
if (search) {
res = []
for (const x of items) {
const compare = Math.max(
stringCompare(search, x.overview.title),
stringCompare(search, x.overview.ainfo)
) as CompareResult
switch (compare) {
case CompareResult.NoMatch:
continue
case CompareResult.Includes:
res.push(x)
break
case CompareResult.Equals:
res.unshift(x)
break
}
}
}
return res
}, [sortedItem, search, category])
const categoryMap = useMemo(
(): [Category | undefined, string][] => [
[undefined, t.label.category_all],
[Category.Login, t.label.category_login],
[Category.SecureNote, t.label.category_secure_note],
[Category.CreditCard, t.label.category_credit_card],
[Category.Identity, t.label.category_identity],
[Category.Password, t.label.category_password],
[Category.Membership, t.label.category_membership],
[Category.Database, t.label.category_database],
[Category.BankAccount, t.label.category_bank_account],
[Category.Email, t.label.category_email],
[Category.SoftwareLicense, t.label.category_software_license],
[Category.SSN, t.label.category_ssn],
[Category.Passport, t.label.category_passport],
[Category.OutdoorLicense, t.label.category_outdoor_license],
[Category.DriverLicense, t.label.category_driver_license],
[Category.Rewards, t.label.category_rewards],
[Category.Router, t.label.category_router],
[Category.Server, t.label.category_server],
],
[t]
)
return (
<>
<ListContainer className={scrollbar}>
<SearchContainer>
<SearchInput
type="search"
value={search}
onChange={e => setSearch(e.currentTarget.value)}
/>
<SearchIcon className={reactIconClass} />
</SearchContainer>
<SortContainer>
<CategorySelect
value={category}
onChange={e => setCategory((e.currentTarget.value as Category) || undefined)}
>
{categoryMap.map(([value, name]) => (
<option value={value || ""} key={value}>
{name}
</option>
))}
</CategorySelect>
<SortSelect value={sortBy} onChange={e => setSortBy(+e.currentTarget.value)}>
<option value={SortBy.Name}>{t.options.sort_by_name}</option>
<option value={SortBy.CreatedAt}>{t.options.sort_by_created_at}</option>
<option value={SortBy.UpdatedAt}>{t.options.sort_by_updated_at}</option>
</SortSelect>
</SortContainer>
<ItemList items={filtered} onSelect={setItem} selected={item} />
</ListContainer>
<ItemContainer>
{item && <ItemView className={scrollbar} item={item} />}
</ItemContainer>
</>
)
}
enum CompareResult {
NoMatch,
Includes,
Equals,
}
function stringCompare(search: string, source?: string) {
if (!search) return CompareResult.Includes
if (!source) return CompareResult.NoMatch
source = source.toLocaleLowerCase()
search = search.toLocaleUpperCase()
const includes = source.includes(search.toLocaleLowerCase())
if (includes) {
return source.length === search.length ? CompareResult.Equals : CompareResult.Includes
}
return CompareResult.NoMatch
}

View File

@ -0,0 +1,183 @@
import styled from "@emotion/styled"
import type { Attachment, AttachmentMetadata, Item, ItemField } from "opvault.js"
import type { ItemDetails } from "opvault.js/src/types"
import { memo, useEffect, useState } from "react"
import { useTranslate } from "../i18n"
import { ItemNoTitle } from "../styles"
import { CategoryIcon } from "./CategoryIcon"
import { ItemDates } from "./ItemDates"
import {
ItemFieldView,
FieldContainer,
FieldTitle,
ItemDetailsFieldView,
} from "./ItemField"
import { PasswordFieldView } from "./ItemFieldValue"
import { ItemWarning } from "./ItemWarning"
interface ItemViewProps {
item: Item
className?: string
}
const Header = styled.div`
display: flex;
align-items: center;
`
const Icon = styled(CategoryIcon)`
font-size: 2em;
margin-right: 5px;
`
const SectionTitle = styled.div`
font-size: 85%;
font-weight: 600;
text-transform: uppercase;
margin: 20px 0 10px;
`
const Tag = styled.div`
display: inline-block;
margin-top: 2px;
margin-right: 5px;
border-radius: 4px;
padding: 3px 7px;
background-color: var(--label-background);
`
const ExtraField = styled(FieldContainer)`
margin-bottom: 20px;
`
const ItemTitle = styled.h2``
const Container = styled.div`
height: 100%;
overflow: auto;
padding: 0 10px;
`
const Inner = styled.div`
padding: 10px 0;
`
const AttachmentContainer = styled.div`
display: flex;
margin: 5px 0;
`
const PlainNotes = styled.p`
white-space: pre-wrap;
`
const SectionsView = memo<{ sections?: ItemDetails["sections"] }>(({ sections }) =>
sections?.length ? (
<div style={{ marginBottom: 20 }}>
{sections
.filter(s => s.fields?.some(x => x.v != null))
.map((section, i) => (
<div key={i}>
{section.title != null && <SectionTitle>{section.title}</SectionTitle>}
{section.fields?.map((field, j) => (
<ItemFieldView key={j} field={field} />
))}
</div>
))}
</div>
) : null
)
const FieldsView = memo<{ fields?: ItemField[] }>(({ fields }) =>
fields?.length ? (
<div style={{ marginBottom: 20 }}>
{fields.map((field, i) => (
<ItemDetailsFieldView key={i} field={field} />
))}
</div>
) : null
)
const TagsView = memo<{ tags?: string[] }>(({ tags }) => {
const t = useTranslate()
if (!tags?.length) return null
return (
<ExtraField>
<FieldTitle>{t.noun.tags}</FieldTitle>
<div>
{tags.map((tag, i) => (
<Tag key={i}>{tag}</Tag>
))}
</div>
</ExtraField>
)
})
const JSONView = memo<{ item: Item }>(({ item }) => (
<details>
<summary>JSON</summary>
<pre>
{JSON.stringify({ overview: item.overview, details: item.details }, null, 2)}
</pre>
</details>
))
export const ItemView = memo<ItemViewProps>(({ className, item }) => {
const t = useTranslate()
return (
<Container className={className}>
<Inner>
<ItemWarning item={item} />
<Header>
{item.details.fields == null}
<Icon category={item.category} />
<ItemTitle>
{item.overview.title || <ItemNoTitle>{t.label.no_title}</ItemNoTitle>}
</ItemTitle>
</Header>
<JSONView item={item} />
<div style={{ height: 10 }}></div>
<SectionsView sections={item.details.sections} />
<FieldsView fields={item.details.fields} />
{item.details.notesPlain != null && (
<ExtraField>
<FieldTitle>notes</FieldTitle>
<div>
<PlainNotes>{item.details.notesPlain}</PlainNotes>
</div>
</ExtraField>
)}
{item.details.password != null && (
<ExtraField>
<FieldTitle>{t.label.password}</FieldTitle>
<PasswordFieldView field={{ v: item.details.password }} />
</ExtraField>
)}
<TagsView tags={item.overview.tags} />
{item.attachments.length > 0 && (
<ExtraField>
<FieldTitle>attachments</FieldTitle>
<div>
{item.attachments.map((file, i) => (
<AttachmentView key={i} file={file} />
))}
</div>
</ExtraField>
)}
<ExtraField>
<ItemDates item={item} />
</ExtraField>
</Inner>
</Container>
)
})
function AttachmentView({ file }: { file: Attachment }) {
const [metadata, setMetadata] = useState<AttachmentMetadata>()
useEffect(() => {
file.unlock().then(() => setMetadata(file.metadata))
}, [file])
if (!metadata) return null
return <AttachmentContainer>{metadata.overview.filename}</AttachmentContainer>
}

View File

@ -0,0 +1,26 @@
import { memo } from "react"
import styled from "@emotion/styled"
import type { Item } from "opvault.js"
import { useTranslate } from "../i18n"
const Container = styled.div`
text-align: center;
font-size: 90%;
line-height: 1.5em;
opacity: 0.5;
user-select: none;
`
export const ItemDates = memo<{ item: Item }>(({ item }) => {
const t = useTranslate()
return (
<Container>
<div>
{t.label.last_updated}: {new Date(item.updatedAt).toLocaleString()}
</div>
<div>
{t.label.created_at}: {new Date(item.createdAt).toLocaleString()}
</div>
</Container>
)
})

View File

@ -0,0 +1,53 @@
import { memo } from "react"
import styled from "@emotion/styled"
import type { ItemField, ItemSection } from "opvault.js"
import { ErrorBoundary } from "./ErrorBoundary"
import { ItemFieldValue, ItemDetailsFieldValue } from "./ItemFieldValue"
export { Container as FieldContainer }
const Container: React.FC = styled.div`
padding: 5px 0;
margin-bottom: 3px;
`
export const FieldTitle: React.FC = styled.div`
font-size: 85%;
margin-bottom: 3px;
user-select: none;
`
export const ItemFieldView = memo<{
field: ItemSection.Any
}>(({ field }) => {
if (field.v == null) {
return null
}
return (
<ErrorBoundary>
<Container>
<FieldTitle>{field.t}</FieldTitle>
<ItemFieldValue field={field} />
</Container>
</ErrorBoundary>
)
})
const hideIds = new Set(["use_desktop", "use_mobile", "use_html"])
const hideNames = new Set(["remember"])
export const ItemDetailsFieldView = memo<{
field: ItemField
}>(({ field }) => {
if (field.value == null || hideIds.has(field.id!) || hideNames.has(field.name)) {
return null
}
return (
<ErrorBoundary>
<Container>
<FieldTitle>{field.name}</FieldTitle>
<ItemDetailsFieldValue field={field} />
</Container>
</ErrorBoundary>
)
})

View File

@ -0,0 +1,108 @@
import { useCallback, useEffect, useState } from "react"
import styled from "@emotion/styled"
const Container = styled.menu`
background-color: #fff;
border-radius: 3px;
box-shadow: rgb(15 15 15 / 5%) 0px 0px 0px 1px, rgb(15 15 15 / 10%) 0px 3px 6px,
rgb(15 15 15 / 20%) 0px 9px 24px;
left: 99%;
margin-block-start: 0;
min-width: 195px;
padding-inline-start: 0;
position: absolute;
top: 0;
user-select: none;
z-index: 2;
@media (prefers-color-scheme: dark) {
background-color: #3c3c3c;
box-shadow: rgb(0 0 0) 0px 2px 4px;
color: #f0f0f0;
}
& & {
display: none;
}
`
const Separator = styled.div`
border-bottom: 1px solid #777;
margin-top: 0.4em;
margin-bottom: 0.4em;
margin-left: 0.6em;
margin-right: 0.6em;
`
const Item = styled.div`
cursor: default;
font-size: 14px;
flex: 1 1 auto;
display: flex;
height: 2.3em;
align-items: center;
padding-left: 1em;
padding-right: 5px;
position: relative;
&:first-of-type {
border-radius: 3px 3px 0 0;
}
&:last-of-type {
border-radius: 0 0 3px 3px;
}
&:hover {
background-color: #ddd;
.item-field-context-menu {
display: block;
}
@media (prefers-color-scheme: dark) {
background-color: #094771;
}
}
`
function useContextMenu() {
const [show, setShow] = useState(false)
const [pos, setPos] = useState({ x: 0, y: 0 })
const onRightClick = useCallback((e: React.MouseEvent) => {
setShow(true)
e.preventDefault()
setPos({ x: e.pageX, y: e.pageY })
}, [])
useEffect(() => {
const fn = () => setShow(false)
document.addEventListener("click", fn)
return () => document.removeEventListener("click", fn)
}, [])
return {
show,
position: {
top: pos.y,
left: pos.x,
},
onRightClick,
}
}
export function useItemFieldContextMenu() {
const { onRightClick, position, show } = useContextMenu()
const ContextMenuContainer: React.FC = useCallback(
({ children }) => {
if (!show) return null
return (
<Container style={position} className="item-field-context-menu">
{children}
</Container>
)
},
[show, position]
)
return {
onRightClick,
Item,
ContextMenuContainer,
}
}

View File

@ -0,0 +1,152 @@
import styled from "@emotion/styled"
import type { ItemSection, ItemField } from "opvault.js"
import { FieldType } from "opvault.js"
import { useCallback, useMemo, useState } from "react"
import { useTranslate } from "../i18n"
import { parseMonthYear } from "../utils"
import { BigTextView } from "./BigTextView"
import { ErrorBoundary } from "./ErrorBoundary"
import { useItemFieldContextMenu } from "./ItemFieldContextMenu"
import { toast, ToastType } from "./Toast"
const Container = styled.div`
cursor: pointer;
&:hover {
color: #6fa9ff;
text-decoration: underline;
}
`
export { Container as ClickableContainer }
function useCopy(text: string) {
const t = useTranslate()
return useCallback(() => {
navigator.clipboard.writeText(text)
toast({
type: ToastType.Secondary,
message: t.tips.copied_to_clipboard,
})
}, [text, t])
}
export { Password as PasswordFieldView }
const Password: React.FC<{
field: Pick<ItemSection.Concealed, "v">
}> = ({ field }) => {
const t = useTranslate()
const [show, setShow] = useState(false)
const [bigText, showBigText] = useState(false)
const { onRightClick, ContextMenuContainer, Item } = useItemFieldContextMenu()
const onToggle = useCallback(() => setShow(x => !x), [])
const onCopy = useCopy(field.v)
const onOpenBigText = useCallback(() => {
showBigText(true)
}, [])
const onCloseBigText = useCallback(() => {
showBigText(false)
}, [])
return (
<>
<Container
onContextMenu={onRightClick}
onDoubleClick={() => setShow(x => !x)}
onClick={onCopy}
style={{
fontFamily: "var(--monospace)",
...(!show && { userSelect: "none" }),
}}
>
{show ? field.v : "·".repeat(10)}
</Container>
{bigText && <BigTextView onClose={onCloseBigText}>{field.v}</BigTextView>}
<ContextMenuContainer>
<Item onClick={onCopy}>{t.action.copy}</Item>
<Item onClick={onToggle}>{show ? t.action.hide : t.action.show}</Item>
{!bigText && (
<Item onClick={onOpenBigText}>{t.action.show_in_big_characters}</Item>
)}
</ContextMenuContainer>
</>
)
}
const MonthYear: React.FC<{ field: ItemSection.MonthYear }> = ({ field }) => {
const { year, month } = parseMonthYear(field.v)
return (
<Container>
{month.toString().padStart(2, "0")}/{year.toString().padStart(4, "0")}
</Container>
)
}
const DateView: React.FC<{ field: ItemSection.Date }> = ({ field }) => {
const date = useMemo(() => new Date(field.v * 1000), [field.v])
return <Container>{date.toLocaleDateString()}</Container>
}
const TextView: React.FC<{ value: string }> = ({ value }) => {
const { onRightClick, ContextMenuContainer, Item } = useItemFieldContextMenu()
const onCopy = useCopy(value)
return (
<>
<Container onContextMenu={onRightClick} onClick={onCopy}>
{value}
</Container>
<ContextMenuContainer>
<Item onClick={onCopy}>Copier</Item>
</ContextMenuContainer>
</>
)
}
export const ItemFieldValue: React.FC<{
field: ItemSection.Any
}> = ({ field }) => {
if (field.v == null) {
return null
}
switch (field.k) {
case "concealed":
return <Password field={field} />
case "monthYear":
return <MonthYear field={field} />
case "date":
return <DateView field={field} />
case "address":
return (
<Container style={{ whiteSpace: "pre" }}>
<div>{field.v.street}</div>
<div>
{field.v.city}, {field.v.state} ({field.v.zip})
</div>
<div>{field.v.country}</div>
</Container>
)
}
return (
<ErrorBoundary>
<TextView value={field.v} />
</ErrorBoundary>
)
}
export const ItemDetailsFieldValue: React.FC<{
field: ItemField
}> = ({ field }) => {
if (field.type === FieldType.Password || field.designation === "password") {
return <Password field={{ v: field.value } as any} />
}
return (
<ErrorBoundary>
<TextView value={field.value!} />
</ErrorBoundary>
)
}

View File

@ -0,0 +1,98 @@
import { memo } from "react"
import styled from "@emotion/styled"
import { cx } from "@emotion/css"
import type { Item } from "opvault.js"
import { AiFillStar } from "react-icons/ai"
import { CategoryIcon } from "./CategoryIcon"
import { useTranslate } from "../i18n"
import { ItemNoTitle } from "../styles"
interface ListProps {
items: Item[]
selected?: Item
onSelect(item: Item): void
}
const Container = styled.div``
const List = styled.ol`
list-style: none;
padding: 0;
`
const ItemView = styled.li`
align-items: center;
cursor: default;
display: grid;
grid-template-columns: 35px 1fr;
padding: 5px 15px;
position: relative;
transition: background-color 0.1s;
user-select: none;
&:hover {
background-color: var(--hover-background);
}
&.selected {
background-color: var(--selected-background);
}
&.trashed {
opacity: 0.6;
}
`
const ItemTitle = styled.div`
font-weight: 600;
margin-bottom: 2px;
`
const ItemDescription = styled.div`
font-size: 95%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 230px;
&.empty {
opacity: 0.4;
}
`
const Icon = styled(CategoryIcon)`
font-size: 1.5em;
`
const Favorite = styled(AiFillStar)`
bottom: 10px;
display: inline-block;
fill: #fdcc0d;
left: 10px;
opacity: 0.9;
position: absolute;
`
export const ItemList = memo<ListProps>(({ items, onSelect, selected }) => {
const t = useTranslate()
return (
<Container>
<List>
{items.map(item => (
<ItemView
key={item.uuid}
onClick={() => onSelect(item)}
className={cx({
selected: selected?.uuid === item.uuid,
trashed: item.isDeleted,
})}
>
<div>
<Icon fill="#FFF" category={item.category} />
{!!item.fave && <Favorite />}
</div>
<div>
<ItemTitle>
{item.overview.title || <ItemNoTitle>{t.label.no_title}</ItemNoTitle>}
</ItemTitle>
<ItemDescription className={cx(!item.overview.ainfo && "empty")}>
{item.overview.ainfo || "-"}
</ItemDescription>
</div>
</ItemView>
))}
</List>
</Container>
)
})

View File

@ -0,0 +1,41 @@
import styled from "@emotion/styled"
import type { Item } from "opvault.js"
import { useMemo, memo } from "react"
import { parseMonthYear } from "../utils"
const Container = styled.div`
background: #cdc7b2;
border-radius: 5px;
padding: 15px;
@media (prefers-color-scheme: dark) {
background: #575345;
}
`
export const ItemWarning = memo<{ item: Item }>(({ item }) => {
const isExpired = useMemo(() => {
const fields = item.details.sections?.flatMap(x => x.fields ?? [])
if (!fields?.length) return false
for (const field of fields) {
if (field.k === "monthYear") {
const { year, month } = parseMonthYear(field.v)
const now = new Date()
const currentYear = now.getFullYear()
return currentYear > year || (currentYear === year && now.getMonth() + 1 > month)
} else if (field.k === "date") {
const now = Date.now()
const fieldDate = new Date(field.v * 1000).valueOf()
return now > fieldDate
}
}
return false
}, [item])
if (isExpired) {
return <Container>Expired</Container>
}
return null
})

View File

@ -0,0 +1,71 @@
import styled from "@emotion/styled"
import { useCallback } from "react"
const ModalBackground = styled.div`
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(1px);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
`
const ModalBackground2 = styled.div`
z-index: 2;
width: 100%;
position: fixed;
left: 0;
top: 0;
height: 100%;
display: flex;
align-items: center;
`
const ModalContainer = styled.div`
background: var(--page-background);
box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
border-radius: 5px;
margin: 0 auto;
`
const ModalTitle = styled.div`
border-bottom: 1px solid var(--border-color);
padding: 10px 20px;
font-weight: 600;
text-align: center;
`
const ModalContent = styled.div`
padding: 15px 20px;
`
export const Modal: React.FC<{
show: boolean
title: string
maxWidth?: number
onClose(): void
}> = ({ show, children, title, maxWidth = 700, onClose }) => {
const onBackgroundClick = useCallback(
e => {
if (e.currentTarget === e.target) {
e.stopPropagation()
onClose()
}
},
[onClose]
)
if (!show) {
return null
}
return (
<>
<ModalBackground />
<ModalBackground2 onClick={onBackgroundClick}>
<ModalContainer style={{ maxWidth }}>
<ModalTitle>{title}</ModalTitle>
<ModalContent>{children}</ModalContent>
</ModalContainer>
</ModalBackground2>
</>
)
}

View File

@ -0,0 +1,24 @@
import { memo } from "react"
import styled from "@emotion/styled"
const Container = styled.div`
background: linear-gradient(to bottom, #292929, #202020);
border-bottom: 1px solid #070707;
border-radius: 5px 5px 0 0;
height: var(--titlebar-height);
-webkit-app-region: drag;
display: flex;
align-items: center;
text-align: center;
`
const Title = styled.div`
text-align: center;
font-weight: 600;
flex-grow: 1;
`
export const TitleBar = memo(() => (
<Container>
<Title>OPVault Viewer</Title>
</Container>
))

View File

@ -0,0 +1,69 @@
import styled from "@emotion/styled"
import { useEffect, useState } from "react"
export enum ToastType {
Regular = "regular",
Primary = "primary",
Secondary = "secondary",
Success = "success",
Danger = "danger",
Warning = "warning",
Info = "info",
}
interface Message {
message: string
type: ToastType
}
interface InternalMessage extends Message {
opacity: number
id: number
}
export let toast: (message: Message) => void
const Container = styled.div``
const ToastContainer = styled.div`
position: fixed;
bottom: 0;
right: 20px;
padding: 8px 12px;
border-radius: 5px;
box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 15%);
transition: opacity 1s ease-in-out, bottom 0.3s linear;
`
let lastId = 0
export const Toast: React.FC = () => {
const [list, setList] = useState<InternalMessage[]>([])
useEffect(() => {
toast = message => {
const newId = ++lastId
setList(list => list.concat({ ...message, id: newId, opacity: 1 }))
setTimeout(() => {
setList(list => list.map(x => (x.id === newId ? { ...x, opacity: 0 } : x)))
}, 1000)
}
}, [])
return (
<Container>
{list.map((message, i, { length }) => (
<ToastContainer
onTransitionEnd={e => {
if (e.propertyName === "opacity") {
setList(list => list.filter(x => x.id !== message.id))
}
}}
key={message.id}
style={{ opacity: message.opacity, bottom: 40 * (length - i) - 10 }}
className={`color-${message.type}`}
>
{message.message}
</ToastContainer>
))}
</Container>
)
}

View File

@ -1,25 +1,40 @@
// @ts-check // @ts-check
// Modules to control application life and create native browser window // Modules to control application life and create native browser window
// const path = require("path") import { join } from "path"
const { app, BrowserWindow } = require("electron") import { app, BrowserWindow, Menu } from "electron"
import "./ipc"
function createWindow() { function createWindow() {
// Create the browser window. // Create the browser window.
const mainWindow = new BrowserWindow({ const mainWindow = new BrowserWindow({
width: 800, width: 800,
height: 600, height: 650,
// frame: false,
// transparent: true,
icon: join(__dirname, "../512x512.png"),
webPreferences: { webPreferences: {
nodeIntegration: true, contextIsolation: true,
contextIsolation: false, preload: join(__dirname, "preload.js"),
// preload: path.join(__dirname, "preload.js"),
}, },
}) })
// and load the index.html of the app. mainWindow.webContents.session.enableNetworkEmulation({
mainWindow.loadFile("index.html") offline: true,
})
// Open the DevTools. Menu.setApplicationMenu(null)
// mainWindow.webContents.openDevTools()
// and load the index.html of the app.
if (process.env.NODE_ENV === "development") {
mainWindow.loadURL("http://localhost:3000")
mainWindow.webContents.openDevTools()
} else {
mainWindow.loadFile("./web/index.html")
}
if (process.env.DEBUG) {
mainWindow.webContents.openDevTools()
}
} }
// This method will be called when Electron has finished // This method will be called when Electron has finished

View File

@ -0,0 +1,9 @@
export interface IPC {
showDirectoryPicker(): Promise<string | undefined>
pathExists(path: string): Promise<boolean>
readdir(path: string): Promise<string[]>
readBuffer(path: string): Promise<Uint8Array>
readFile(path: string): Promise<string>
writeFile(path: string, data: string): Promise<void>
isDirectory(path: string): Promise<boolean>
}

View File

@ -0,0 +1,53 @@
import fs, { promises } from "fs"
import { ipcMain, dialog } from "electron"
import type { IPC } from "./ipc-types"
registerService({
async showDirectoryPicker() {
const result = await dialog.showOpenDialog({
properties: ["openDirectory", "treatPackageAsDirectory"],
})
if (result.canceled || !result.filePaths.length) return
return result.filePaths[0]
},
async pathExists(_, path) {
return fs.existsSync(path)
},
async readBuffer(_, path) {
return promises.readFile(path)
},
async readFile(_, path) {
return promises.readFile(path, "utf-8")
},
async writeFile(_, path, content) {
await promises.writeFile(path, content)
},
async readdir(_, path) {
return promises.readdir(path)
},
async isDirectory(_, path) {
const stats = await promises.stat(path)
return stats.isDirectory()
},
})
/**
* Listens to `channel`, when a new message arrives `listener` would be called
* with `listener(event, ...args)`
*/
function registerService(listeners: {
[K in keyof IPC]: (
event: Electron.IpcMainEvent,
...args: Parameters<IPC[K]>
) => ReturnType<IPC[K]>
}) {
for (const [key, value] of Object.entries(listeners)) {
ipcMain.handle(`service-${key}`, value as any)
}
}

View File

@ -0,0 +1,5 @@
import { contextBridge, ipcRenderer } from "electron"
contextBridge.exposeInMainWorld("ipcRenderer", {
invoke: ipcRenderer.invoke,
})

View File

@ -0,0 +1,87 @@
import {
createContext,
memo,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react"
import texts from "./texts.yml"
import { get, set, Key } from "../utils/localStorage"
const categories = Object.keys(texts)
const ALLOWED = new Set(["en", "fr", "ja"])
const SKIP_ITALIC = new Set(["zh_CN", "zh_TW", "ko", "ja"])
function getLocaleFromStorage() {
const key = get(Key.PREFERRED_LOCALE)
if (key && ALLOWED.has(key)) {
return key
}
}
function getNavigatorLocale() {
if (typeof navigator !== "undefined") {
for (const lang of navigator.languages) {
if (ALLOWED.has(lang)) {
return lang
}
}
}
}
function getEnvLocale() {
return getLocaleFromStorage() ?? getNavigatorLocale() ?? "en"
}
const LocaleContext = createContext<{
locale: string
setLocale(locale: string): void
}>(undefined!)
export const useLocaleContext = () => useContext(LocaleContext)
export function useTranslate() {
const { locale } = useContext(LocaleContext)
const getter = useCallback(
(category: string, key: string) => {
const obj = (texts as any)[category]
if (
process.env.NODE_ENV === "development" &&
!Object.prototype.hasOwnProperty.call(obj, key)
) {
throw new Error(`t.${key} does not exist.`)
}
return obj[key][locale]
},
[locale]
)
const t: {
[category in keyof typeof texts]: {
[key in keyof typeof texts[category]]: string
}
} = useMemo(
(): any =>
Object.fromEntries(
categories.map(category => [
category,
new Proxy({}, { get: (_, p: string) => getter(category, p) }),
])
),
[getter]
)
return t
}
export const LocaleContextProvider = memo(({ children }) => {
const [locale, setLocale] = useState(getEnvLocale)
useEffect(() => {
set(Key.PREFERRED_LOCALE, locale)
document.documentElement.lang = locale
}, [locale])
const value = useMemo(() => ({ locale, setLocale }), [locale])
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>
})

View File

@ -0,0 +1,250 @@
# /* spellchecker: disable */
label:
app_name:
en: OPVault Viewer
fr: Lecteur de coffre OPVault
ja: OPVault ビューワー
choose_a_vault:
en: Pick a vault
fr: Choisir un coffre
ja: 保管庫を選ぶ
no_vault_selected:
en: No vault is selected.
fr: Aucun coffre nest sélectionné.
ja: 選択した保管庫はありません。
last_updated:
en: Last Updated
fr: Dernière modification
ja: 更新日時
created_at:
en: Created At
fr: Créé
ja: 作成日時
password_placeholder:
en: Master Password
fr: Mot de passe principal
ja: マスターパスワード
username:
en: Username
fr: Nom dutilisateur
ja: ユーザー名
password:
en: Password
fr: Mot de passe
ja: パスワード
no_title:
en: Untitled
fr: Sans titre
ja: 無題
settings:
en: Settings
fr: Préférences
ja: 設定
language:
en: Language
fr: Langue
ja: 言語
about_app:
en: About
fr: À propos
ja: バーション情報
category_all:
en: All
fr: Tous
ja: すべて
category_login:
en: Login
fr: Connexion
ja: ログイン
category_credit_card:
en: Credit Card
fr: Carte de crédit
ja: クレジットカード
category_secure_note:
en: Secure Note
fr: Note sécurisée
ja: セキュアノート
category_identity:
en: Identity
fr: Identité
ja: 個人情報
category_password:
en: Password
fr: Mot de passe
ja: パスワード
category_tombstone:
en: Tombstone
fr: Corbeille
ja: ゴミ箱
category_software_license:
en: Software License
fr: Licence de logiciel
ja: ソフトウェアライセンス
category_bank_account:
en: BankAccount
fr: Compte bancaire
ja: 銀行口座
category_database:
en: Database
fr: Base de données
ja: データベース
category_driver_license:
en: Driver License
fr: Permis de conduire
ja: 運転免許
category_outdoor_license:
en: Outdoor License
fr: Permis de chasse ou pêche
ja: 遊漁券及び狩猟免許
category_membership:
en: Membership
fr: Adhésion
ja: 会員資格
category_passport:
en: Passport
fr: Passeport
ja: 旅券
category_rewards:
en: Rewards
fr: Programme de fidélité
ja: ポイントサービス
category_ssn:
en: Social Security Numbers
fr: N° de sécurité sociale
ja: 社会保障番号
category_router:
en: Router
fr: Routeur sans fil
ja: Wi-Fiルーター
category_server:
en: Server
fr: Serveur
ja: サーバー
category_email:
en: Email
fr: Courriel
ja: メール
options:
sort_by_name:
en: Sort by Name
fr: Trier par nom
ja: 名前順
sort_by_created_at:
en: Sort by date created
fr: Trier par date de création
ja: 作成日時順
sort_by_updated_at:
en: Sort by date modified
fr: Trier par date de modification
ja: 更新日時順
enable_autolock:
en: Auto Lock
fr: Verrouillage automatique
ja: 自動ロック
noun:
vault:
en: vault
fr: coffre
ja: 保管庫
tags:
en: tags
fr: mots-clés
ja: キーワード
seconds:
en: seconds
fr: secondes
ja:
action:
lock:
en: Lock
fr: Vérouiller
ja: ロック
unlock:
en: Unlock
fr: Déverouiller
ja: ロック解除
copy:
en: Copy
fr: Copier
ja: コピー
hide:
en: Hide
fr: Cacher
ja: 非表示
show:
en: Show
fr: Afficher
ja: 表示
show_in_big_characters:
en: Show in large characters
fr: Afficher en gros caractères
ja: 大きく表示
go_back:
en: Back
fr: Revenir
ja: 前に戻る
go_forward:
en: Forward
fr: Avancer
ja: 次に進む
clear_history:
en: Clear history
fr: Effacer lhistorique
ja: 閲覧履歴を消す
tips:
automatically_lock_after_inactivity:
en: Automatically lock after inactivity
fr: Verouiller automatiquement après un temps dinactivité
ja: 一定時間使わないときに自動的にロックする
copied_to_clipboard:
en: Copied to clipboard
fr: Copié dans le presse-papier
ja: クリップボードへコピーしました

170
packages/web/src/index.scss Normal file
View File

@ -0,0 +1,170 @@
@mixin scheme($property, $light-value, $dark-value) {
#{$property}: $light-value;
@media (prefers-color-scheme: dark) {
#{$property}: $dark-value;
}
}
body {
background: transparent;
margin: 0;
overflow: hidden;
font-size: 15px;
font-family: -apple-system, BlinkMacSystemFont, system-ui, "Roboto", "Oxygen",
"Cantarell", "Droid Sans", "Helvetica Neue", "Noto Sans CJK JP", sans-serif;
}
:root {
--page-background: #fff;
--color: #000;
--titlebar-height: 46px;
--titlebar-height: 0px;
--label-background: #ddd;
--selected-background: #d5d5d5;
--hover-background: #ddd;
--border-color: #e3e3e3;
--monospace: D2Coding, "source-code-pro", Menlo, Monaco, Consolas, "Courier New",
monospace;
}
@media (prefers-color-scheme: light) {
:root.mac {
--page-background: #f7f7f7;
}
}
html,
body,
#app {
height: 100%;
}
#app {
background-color: var(--page-background);
position: relative;
}
@media (prefers-color-scheme: dark) {
:root {
--color: #fff;
--label-background: #353535;
--selected-background: #353535;
--border-color: #333;
--hover-background: #222;
--page-background: #292929;
}
body {
color: #fff;
}
}
pre,
code {
font-family: var(--monospace);
}
input {
font-family: inherit;
font-size: inherit;
}
@mixin input {
@include scheme(background-color, #fff, #2d2d2d);
border-radius: 6px;
border: 1px solid #fff;
@include scheme(border-color, #cdc7c2, #1b1b1b);
transition: 0.1s;
&:focus {
@include scheme(border-color, #3584e480, #15539e);
}
}
input[type="search"],
input[type="input"],
input[type="number"],
input[type="password"] {
@include input;
border-radius: 6px;
color: inherit;
outline: none;
padding: 7px 8px;
&:disabled {
cursor: not-allowed;
}
}
input[type="checkbox" i] {
@include input;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05),
inset 0px -15px 10px -12px rgba(0, 0, 0, 0.05);
padding: 9px;
border-radius: 3px;
appearance: none;
position: relative;
&:checked:after {
content: "\2714";
font-size: 15px;
position: absolute;
top: 0px;
left: 3px;
color: var(--color);
}
}
button,
select,
.button {
@include scheme(background-color, #f6f5f4, #333);
border-radius: 4px;
border: 1px solid;
@include scheme(border-color, #cdc7c2, #1b1b1b);
color: inherit;
font-family: inherit;
&:hover {
@include scheme(background-color, #f9f9f8, #363636);
}
&:active {
@include scheme(background-color, #d6d1cd, #292929);
}
}
button {
font-size: 16px;
padding: 8px 15px;
box-shadow: rgb(0 0 0 / 7%) 0px 1px 2px;
transition: 0.1s;
}
button[type="submit"] {
background-color: #15539e;
color: #fff;
}
select {
padding: 5px 10px;
}
// #region color
.color-primary,
.color-secondary,
.color-info,
.color-danger {
@include scheme(color, #fff, #fafafa);
}
.color-success,
.color-warning {
@include scheme(color, #000, #111);
}
.color-primary {
@include scheme(background-color, #0b5ed7, #375a7f);
}
.color-secondary {
@include scheme(background-color, #6c757d, #626262);
}
.color-success {
@include scheme(background-color, #198754, #00bc8c);
}
.color-info {
@include scheme(background-color, #0dcaf0, #17a2b8);
}
.color-warning {
@include scheme(background-color, #ffc107, #f39c12);
}
.color-danger {
@include scheme(background-color, #dc3545, #e74c3c);
}
// #endregion

24
packages/web/src/main.tsx Normal file
View File

@ -0,0 +1,24 @@
import React from "react"
import { render } from "react-dom"
import { App } from "./App"
import { LocaleContextProvider } from "./i18n"
import { SideEffect } from "./SideEffect"
import { Toast } from "./components/Toast"
import "./index.scss"
if (navigator.platform === "MacIntel") {
document.documentElement.classList.add("mac")
}
const Root: React.FC = () => (
<React.StrictMode>
{/* <TitleBar /> */}
<LocaleContextProvider>
<SideEffect />
<App />
<Toast />
</LocaleContextProvider>
</React.StrictMode>
)
render(<Root />, document.getElementById("app"))

3
packages/web/src/modules.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
declare module "react-idle-timer/modern" {
export * from "react-idle-timer/dist/modern"
}

View File

@ -0,0 +1,112 @@
import styled from "@emotion/styled"
import { useEffect, useMemo, useState } from "react"
import type { Vault, Item } from "opvault.js"
import { AiOutlineStar } from "react-icons/ai"
import { FiLock } from "react-icons/fi"
import { Si1Password } from "react-icons/si"
import { BsGear } from "react-icons/bs"
import { useTranslate } from "../i18n/index"
import { Settings } from "../settings"
import { FilteredVaultView } from "../components/FilteredVaultView"
const Container = styled.div`
display: flex;
height: calc(100vh - var(--titlebar-height));
`
const TabContainer = styled.div`
border-right: 1px solid var(--border-color);
display: flex;
flex-direction: column;
overflow: hidden;
padding-bottom: 5px;
width: 54px;
@media (prefers-color-scheme: dark) {
background: #222;
border-right-color: transparent;
}
&&::-webkit-scrollbar {
display: none;
}
`
const TabButton = styled.button<{ active?: boolean }>`
align-items: center;
background: ${p => (p.active ? "var(--selected-background)" : "transparent")};
border-radius: ${p => (p.active ? 0 : 3)}px;
border: transparent;
box-shadow: none;
display: inline-flex;
margin-bottom: 5px;
font-size: 22px;
padding: 10px 14px;
${p => p.active && "&:hover { background: var(--selected-background); }"}
@media (prefers-color-scheme: dark) {
--selected-background: #1c1c1c;
}
`
const TabContainerMain = styled.div`
flex-grow: 1;
`
export const VaultView: React.FC<{ vault: Vault; onLock(): void }> = ({
vault,
onLock,
}) => {
const [tab, setTab] = useState(Tab.All)
const [items, setItems] = useState<Item[]>(() => [])
const [showSettings, setShowSettings] = useState(false)
const t = useTranslate()
useEffect(() => {
arrayFrom(vault.values()).then(setItems)
}, [vault])
return (
<Container>
<TabContainer>
<TabContainerMain>
<TabButton active={tab === Tab.All} onClick={() => setTab(Tab.All)}>
<Si1Password />
</TabButton>
<TabButton active={tab === Tab.Favorites} onClick={() => setTab(Tab.Favorites)}>
<AiOutlineStar />
</TabButton>
</TabContainerMain>
<TabButton onClick={onLock} title={t.action.lock}>
<FiLock />
</TabButton>
<TabButton onClick={() => setShowSettings(true)} title={t.label.settings}>
<BsGear />
</TabButton>
</TabContainer>
{tab === Tab.All ? (
<FilteredVaultView items={items} />
) : tab === Tab.Favorites ? (
<FavoriteItemsView items={items} />
) : null}
<Settings show={showSettings} onHide={() => setShowSettings(false)} />
</Container>
)
}
const FavoriteItemsView: React.FC<{ items: Item[] }> = ({ items }) => {
const favorites = useMemo(
() => items.filter(x => x.fave).sort((a, b) => a.fave - b.fave),
[items]
)
return <FilteredVaultView items={favorites} />
}
async function arrayFrom<T>(generator: AsyncGenerator<T, void, unknown>) {
const list: T[] = []
for await (const value of generator) {
list.push(value)
}
return list
}
enum Tab {
All,
Favorites,
}

View File

@ -0,0 +1,148 @@
import styled from "@emotion/styled"
import { css } from "@emotion/css"
import { useCallback, useMemo, memo, useState } from "react"
import { Si1Password } from "react-icons/si"
import { FaFolderOpen } from "react-icons/fa"
import { ImCross } from "react-icons/im"
import { MdClearAll } from "react-icons/md"
import { BsGear, BsInfoCircle } from "react-icons/bs"
import { openDirectory } from "../../utils/ipc-adapter"
import { useTranslate } from "../../i18n"
import { Key, useStorage } from "../../utils/localStorage"
import { Settings } from "../../settings"
import { About } from "../../about"
const Container = styled.div`
padding: 100px;
max-width: 600px;
margin: 0 auto;
`
const List = styled.ul`
list-style-type: none;
padding-inline-start: 0;
`
const Item = styled.li`
align-items: center;
cursor: default;
display: flex;
padding: 8px 10px;
user-select: none;
&:not(:hover):not(:active) {
background: transparent;
border-color: transparent;
}
`
const icon = css`
font-size: 1.5em;
margin-right: 10px;
`
const Text = styled.div`
flex-grow: 1;
`
const Hr = styled.hr`
border: none;
border-top: 1px solid var(--border-color);
`
const DeleteItem = styled(ImCross)`
text-align: right;
font-size: 0.7em;
opacity: 0;
${Item}:hover & {
opacity: 1;
}
`
const NonCriticalPath = styled.span`
opacity: 0.4;
`
const Path = memo(({ children }: { children: string }) => {
const segments = useMemo(() => children.split("/"), [children])
return (
<span>
{segments.map((seg, i, { length }) =>
i < length - 1 ? (
<NonCriticalPath key={i}>{seg}/</NonCriticalPath>
) : (
<span key={i}>{seg}</span>
)
)}
</span>
)
})
const enum Modal {
None,
Settings,
About,
}
export const PickOPVault: React.FC<{
setPath(path: string): void
}> = ({ setPath }) => {
const t = useTranslate()
const [modal, setModal] = useState(Modal.None)
const [list, $setList] = useStorage(Key.RECENTLY_OPENED_VAULTS)
const clearHistory = useCallback(() => {
$setList([])
}, [$setList])
const setList = useCallback(
(fn: (value: Set<string>) => void) => {
$setList(list => {
const set = new Set(list)
fn(set)
return Array.from(set)
})
},
[$setList]
)
const onClick = useCallback(async () => {
const path = await openDirectory()
if (path) {
setPath(path)
setList(set => set.add(path))
}
}, [setPath, setList])
return (
<Container>
<List>
<Item className="button" onClick={onClick}>
<FaFolderOpen className={icon} />
{t.label.choose_a_vault}
</Item>
{list.map((item, i) => (
<Item className="button" onClick={() => setPath(item)} key={i}>
<Si1Password className={icon} />
<Text>
<Path>{item}</Path>
</Text>
<DeleteItem onClick={() => setList(list => list.delete(item))} />
</Item>
))}
{list.length > 0 && (
<>
<Hr />
<Item className="button" onClick={() => clearHistory()}>
<MdClearAll className={icon} />
{t.action.clear_history}
</Item>
</>
)}
<Item className="button" onClick={() => setModal(Modal.Settings)}>
<BsGear className={icon} />
{t.label.settings}
</Item>
<Item className="button" onClick={() => setModal(Modal.About)}>
<BsInfoCircle className={icon} />
{t.label.about_app}
</Item>
</List>
<Settings show={modal === Modal.Settings} onHide={() => setModal(Modal.None)} />
<About show={modal === Modal.About} onHide={() => setModal(Modal.None)} />
</Container>
)
}

View File

@ -0,0 +1,148 @@
import type { OnePassword } from "opvault.js"
import styled from "@emotion/styled"
import React, { useCallback, useEffect, useState } from "react"
import { IoMdArrowRoundBack } from "react-icons/io"
import { FaUnlock } from "react-icons/fa"
import { useTranslate } from "../../i18n"
const Container = styled.div`
padding: 20px;
transform: translate(-50%, -50%);
position: absolute;
top: 50%;
left: 50%;
width: 500px;
`
const BackButton = styled.button`
&& {
background: transparent;
}
border: none;
box-shadow: none;
font-size: 2em;
cursor: pointer;
padding: 0;
&:hover {
svg path {
fill: var(--selected-background);
transition: 0.2s;
}
}
`
const Input = styled.input`
box-shadow: inset 0 2px 2px rgb(0 0 0 / 8%);
font-size: 1.5em;
width: calc(95.5% - 60px);
&& {
border-radius: 10px;
border-width: 1px;
padding: 15px 20px;
padding-right: 60px;
}
`
const Select = styled.select`
float: right;
`
const Submit = styled.button`
font-size: 1.8em;
&& {
background: transparent;
border: none;
box-shadow: none;
}
svg path {
fill: var(--color);
}
&:hover {
transition: 0.2s;
}
text-align: center;
position: absolute;
top: 8px;
right: 5px;
`
const VaultPath = styled.div`
margin-top: 15px;
opacity: 0.7;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`
export const Unlock: React.FC<{
instance: OnePassword
vaultPath: string
onUnlock(profile: string, password: string): void
onReturn(): void
}> = ({ onUnlock, onReturn, instance, vaultPath }) => {
const t = useTranslate()
const [profiles, setProfiles] = useState<string[]>(() => [])
const [profile, setProfile] = useState<string>()
const [password, setPassword] = useState("")
const unlock = useCallback(
(e?: React.FormEvent) => {
e?.preventDefault()
if (!profile) return
onUnlock(profile, password)
setPassword("")
},
[onUnlock, profile, password]
)
const onKeyUp = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter") {
unlock()
}
},
[unlock]
)
useEffect(() => {
instance.getProfileNames().then(profiles => {
setProfiles(profiles)
setProfile(profiles[0])
})
}, [instance])
return (
<Container>
<div style={{ marginBottom: 10 }}>
<BackButton onClick={onReturn} title={t.action.go_back}>
<IoMdArrowRoundBack />
</BackButton>
<Select
title={t.noun.vault}
value={profile}
onChange={e => setProfile(e.currentTarget.value)}
>
{profiles.map(p => (
<option key={p} value={p}>
{t.noun.vault}: {p}
</option>
))}
</Select>
</div>
<div style={{ margin: "10px 0", position: "relative" }}>
<Input
type="password"
value={password}
onChange={e => setPassword(e.currentTarget.value)}
placeholder={t.label.password_placeholder}
onKeyUp={onKeyUp}
/>
<Submit
type="submit"
disabled={!profile || !password}
onClick={unlock}
title={t.action.unlock}
>
<FaUnlock />
</Submit>
</div>
<VaultPath>{vaultPath}</VaultPath>
</Container>
)
}

View File

@ -0,0 +1,73 @@
import { useCallback, useEffect, useState } from "react"
import type { Vault } from "opvault.js"
import { OnePassword } from "opvault.js"
import { Unlock } from "./Unlock"
import { electronAdapter } from "../../utils/ipc-adapter"
import { get, remove, set, Key } from "../../utils/localStorage"
import { PickOPVault } from "./Picker"
interface VaultPickerProps {
instance: OnePassword | undefined
setInstance(value?: OnePassword): void
vault: Vault | undefined
setVault(vault?: Vault): void
}
export const VaultPicker: React.FC<VaultPickerProps> = ({
instance,
setInstance,
vault,
setVault,
}) => {
const [vaultPath, setVaultPath] = useState("")
const unlock = useCallback(
async (profile: string, password: string) => {
const vault = await instance!.getProfile(profile!)
await vault.unlock(password)
setVault(vault)
},
[instance, setVault]
)
const clearInstance = useCallback(() => {
setVaultPath("")
setInstance(undefined)
}, [setInstance])
useEffect(() => {
const existingPath = get(Key.LAST_VAULT_PATH)
if (existingPath != null) {
setVaultPath(existingPath)
}
}, [])
useEffect(() => {
if (vaultPath) {
const instance = new OnePassword({
path: vaultPath,
adapter: electronAdapter,
})
setInstance(instance)
set(Key.LAST_VAULT_PATH, vaultPath)
} else {
setInstance(undefined)
remove(Key.LAST_VAULT_PATH)
}
}, [vaultPath, setInstance])
if (!instance) {
return <PickOPVault setPath={setVaultPath} />
}
if (!vault) {
return (
<Unlock
vaultPath={vaultPath}
onReturn={clearInstance}
instance={instance}
onUnlock={unlock}
/>
)
}
return null
}

View File

@ -0,0 +1,87 @@
import styled from "@emotion/styled"
import { Modal } from "../components/Modal"
import { useLocaleContext, useTranslate } from "../i18n"
import { Key, useStorage } from "../utils/localStorage"
const FormItem = styled.div`
display: flex;
align-items: center;
margin-bottom: 13px;
`
const FormLabel = styled.div`
width: 120px;
`
const FormValue = styled.div`
display: flex;
align-items: center;
flex-grow: 1;
position: relative;
min-width: 200px;
select {
width: 100%;
}
`
const Checkbox = styled.input`
margin-left: 0;
margin-right: 8px;
`
const GhostLabel = styled.div`
opacity: 0.5;
position: absolute;
left: 37px;
pointer-events: none;
`
export const Settings: React.FC<{
show: boolean
onHide(): void
}> = ({ show, onHide }) => {
const { locale, setLocale } = useLocaleContext()
const t = useTranslate()
const [enableAutoLock, setEnableAutoLock] = useStorage(Key.ENABLE_AUTO_LOCK)
const [autolockAfter, setAutolockAfter] = useStorage(Key.AUTO_LOCK_AFTER)
return (
<Modal show={show} title={t.label.settings} onClose={onHide}>
<FormItem>
<FormLabel>{t.label.language}</FormLabel>
<FormValue>
<select
title={t.label.language}
value={locale}
onChange={e => setLocale(e.currentTarget.value)}
>
<option value="en">English</option>
<option value="fr">Français</option>
<option value="ja"></option>
</select>
</FormValue>
</FormItem>
<FormItem>
<FormLabel title={t.tips.automatically_lock_after_inactivity}>
{t.options.enable_autolock}
</FormLabel>
<FormValue>
<Checkbox
type="checkbox"
checked={enableAutoLock}
onChange={e => setEnableAutoLock(e.target.checked)}
/>
<input
type="number"
value={autolockAfter}
onChange={e => setAutolockAfter(e.target.valueAsNumber)}
disabled={!enableAutoLock}
/>
<GhostLabel>
<span style={{ opacity: 0 }}>{autolockAfter} </span>
{t.noun.seconds}
</GhostLabel>
</FormValue>
</FormItem>
</Modal>
)
}

View File

@ -0,0 +1,39 @@
import { css } from "@emotion/css"
import styled from "@emotion/styled"
export const ItemNoTitle = styled.span`
font-weight: normal;
font-style: italic;
[lang^="zh"],
[lang="ko"],
[lang="ja"] & {
font-style: normal;
}
`
export const scrollbar = css`
&&::-webkit-scrollbar {
width: 7px;
}
&&::-webkit-scrollbar-track {
background: transparent;
}
&&:hover,
&&:active {
&&::-webkit-scrollbar-thumb {
background: #8883;
transition: 0.1s;
border-radius: 6px;
@media (prefers-color-scheme: dark) {
background: #6663;
}
}
&&::-webkit-scrollbar-thumb:hover {
background: #ddd;
transition: 0.1s;
@media (prefers-color-scheme: dark) {
background: #555;
}
}
}
`

View File

@ -0,0 +1,5 @@
export function parseMonthYear(v: number) {
const year = Math.floor(v / 100)
const month = v % 100
return { year, month }
}

View File

@ -0,0 +1,31 @@
import { Buffer } from "buffer"
import type { IAdapter } from "opvault.js/src/adapters"
import type { IPC } from "../electron/ipc-types"
import { memoize } from "./memoize"
declare const ipcRenderer: Electron.IpcRenderer
export async function openDirectory() {
return ipc.showDirectoryPicker()
}
export const electronAdapter: IAdapter = {
fs: {
exists: path => ipc.pathExists(path),
readBuffer: path => ipc.readBuffer(path).then(Buffer.from),
readFile: path => ipc.readFile(path),
readdir: path => ipc.readdir(path),
writeFile: (path, data) => ipc.writeFile(path, data),
isDirectory: path => ipc.isDirectory(path),
},
subtle: crypto.subtle,
}
const ipc = new Proxy<IPC>({} as any, {
get: memoize(
(_, channel: string) =>
(...args: any[]) =>
ipcRenderer.invoke(`service-${channel}`, ...args),
(_, name) => name
),
})

View File

@ -0,0 +1,76 @@
import { useCallback, useEffect, useState } from "react"
export enum Key {
LAST_VAULT_PATH = "app.state.last_vault_path",
RECENTLY_OPENED_VAULTS = "app.state.recently_opened_vaults",
PREFERRED_LOCALE = "app.config.locale",
ENABLE_AUTO_LOCK = "app.config.enable_auto_lock",
AUTO_LOCK_AFTER = "app.config.auto_lock_after",
}
interface StoredData {
[Key.LAST_VAULT_PATH]: string
[Key.RECENTLY_OPENED_VAULTS]: string[]
[Key.PREFERRED_LOCALE]: string
[Key.ENABLE_AUTO_LOCK]: boolean
[Key.AUTO_LOCK_AFTER]: number
}
const events = new Map(Object.values(Key).map(key => [key, new Set()])) as {
get<K extends Key>(key: K): Set<(value: StoredData[Key]) => void>
}
export function useStorage<K extends Key>(key: K) {
const [state, setState] = useState(get(key)!)
useEffect(() => {
events.get(key).add(setState as any)
return () => {
events.get(key).delete(setState as any)
}
}, [key])
const setState2 = useCallback(
(value: ((value: StoredData[K]) => StoredData[K]) | StoredData[K]) => {
set(key, value)
},
[key]
)
return [state, setState2] as const
}
export function get<K extends Key>(key: K): StoredData[K] | undefined {
try {
const value = localStorage.getItem(key)
return value == null ? undefined : (JSON.parse(value!) as StoredData[K])
} catch {}
}
export function set<K extends Key>(
key: K,
value: ((value: StoredData[K]) => StoredData[K]) | StoredData[K]
) {
try {
if (typeof value === "function") {
value = value(get(key)!)
}
localStorage.setItem(key, JSON.stringify(value))
events.get(key).forEach(fn => fn(value as StoredData[K]))
} catch (e) {
console.error(e)
}
}
export function remove(key: Key) {
try {
localStorage.removeItem(key)
} catch {}
}
const defaults: typeof set = (key, value) => {
if (!(key in localStorage)) {
set(key, value)
}
}
defaults(Key.ENABLE_AUTO_LOCK, true)
defaults(Key.AUTO_LOCK_AFTER, 180)
defaults(Key.RECENTLY_OPENED_VAULTS, [])

View File

@ -0,0 +1,18 @@
export function memoize<T extends (...args: any[]) => any, K>(
fn: T,
getKey: (...args: Parameters<T>) => K
): T {
const map = new Map<K, ReturnType<T>>()
function memoized(this: any, ...args: Parameters<T>): ReturnType<T> {
const key = getKey(...args)
if (map.has(key)) {
return map.get(key)!
} else {
const value = fn.apply(this, args)
map.set(key, value)
return value
}
}
Object.defineProperty(memoized, "name", { value: fn.name })
return memoized as any
}

5
packages/web/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
/// <reference types="vite/client" />
interface Array<T> {
filter(predicate: BooleanConstructor): Exclude<T, null | undefined | 0 | "" | false>[]
}

View File

@ -0,0 +1,3 @@
{
"extends": "../../tsconfig.json"
}

View File

@ -0,0 +1,27 @@
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import yaml from "@rollup/plugin-yaml"
import babel from "./scripts/vite-babel"
// https://vitejs.dev/config/
export default defineConfig({
base: "./",
plugins: [babel(), react(), yaml()],
define: {
global: "globalThis",
"process.browser": "true",
"process.env.NODE_DEBUG": "false",
},
build: {
outDir: "dist/web",
rollupOptions: {
external: ["fs", ""],
},
},
resolve: {
alias: {
path: require.resolve("path-browserify"),
buffer: require.resolve("buffer"),
},
},
})

4522
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

45
repl.ts
View File

@ -1,45 +0,0 @@
#!/usr/bin/env -S node -r ts-node/register/transpile-only
import fs from "fs"
import chalk from "chalk"
import prompts from "prompts"
import { OnePassword } from "./src/index"
const path = "./freddy-2013-12-04.opvault"
async function main(args: string[]) {
const instance = new OnePassword({ path })
const profiles = await instance.getProfileNames()
// const { profile } = await prompts({
// type: "select",
// name: "profile",
// choices: profiles.map(t => ({ title: t, value: t })),
// message: "Which vault?",
// })
// console.log(chalk`You have chosen {green ${profile}}.`)
const profile = "default"
const vault = await instance.getProfile(profile)
// const { password } = await prompts({
// type: "invisible",
// name: "password",
// message: "Master Password?",
// })
const password = "freddy"
vault.unlock(password)
const find = vault.overviews.get("A note with some attachments")!
const item = vault.getItem(find.uuid!)!
const [attachment] = item.attachments
// console.log({ details: item.itemDetails, overview: item.overview })
// console.log(attachment.metadata)
const op = vault.getItem(vault.overviews.get("1Password")!.uuid)!
console.log(op.itemDetails.sections[0])
// console.log(vault.overviews.values())
}
main(process.argv.slice(2))

1
scripts/buffer-shim.js Normal file
View File

@ -0,0 +1 @@
module.exports = require("buffer")

1
test/decrypted.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,11 +1,9 @@
import { resolve } from "path"; import { resolve } from "path";
import { describe, it, beforeEach } from "mocha"; import { describe, it, beforeEach } from "mocha";
import { expect } from "chai"; import { expect } from "chai";
// import { fs, vol } from "memfs"
import type { Vault } from "../src/index"; import type { Vault } from "../packages/opvault.js/src/index";
import { OnePassword } from "../src/index"; import { OnePassword } from "../packages/opvault.js/src/index";
// import adapter from "../src/adapters/node";
describe("OnePassword", () => { describe("OnePassword", () => {
const freddy = resolve(__dirname, "../freddy-2013-12-04.opvault"); const freddy = resolve(__dirname, "../freddy-2013-12-04.opvault");
@ -49,9 +47,44 @@ describe("OnePassword", () => {
await vault.unlock("freddy"); await vault.unlock("freddy");
}); });
it("reads overviews", () => { it("reads notes", async () => {
const overviews = vault.overviews.values(); const item = (await vault.getItem({
expect(overviews).to.have.lengthOf(29); title: "A note with some attachments",
}))!;
expect(item).to.exist;
expect(item.uuid).to.equal("F2DB5DA3FCA64372A751E0E85C67A538");
expect(item.attachments).to.have.lengthOf(2);
expect(item.details).to.deep.equal({
notesPlain: "This note has two attachments.",
});
expect(item.overview).to.deep.equal({
title: "A note with some attachments",
ps: 0,
ainfo: "This note has two attachments.",
});
});
it("decrypts items", async () => {
const decrypted = require("./decrypted.json");
expect(vault.isLocked).to.be.false;
for (const [uuid, item] of Object.entries<any>(decrypted)) {
const actual = await vault.getItem(uuid);
expect(actual).to.exist;
expect(actual!.overview).to.deep.equal(item.overview);
expect(actual!.details).to.deep.equal(item.itemDetails);
expect(actual!.attachments).to.have.lengthOf(item.attachments.length);
for (const [i, attachment] of actual!.attachments.entries()) {
const expected = item.attachments[i];
await attachment.unlock();
expect(attachment.metadata).to.deep.equal(expected.metadata);
expect(attachment.file.toString("base64")).to.deep.equal(
expected.file
);
expect(attachment.icon.toString("base64")).to.deep.equal(
expected.icon
);
}
}
}); });
}); });
@ -64,7 +97,8 @@ describe("OnePassword", () => {
vault.lock(); vault.lock();
expect(vault.isLocked).to.be.true; expect(vault.isLocked).to.be.true;
expect(() => vault.overviews.values()).to.throw(); expect(vault.getItem("F2DB5DA3FCA64372A751E0E85C67A538")).to.eventually
.throw;
}); });
}); });
}); });

View File

@ -1,7 +1,7 @@
import { describe, it } from "mocha"; import { describe, it } from "mocha";
import { expect } from "chai"; import { expect } from "chai";
import { WeakValueMap } from "../src/weakMap"; import { WeakValueMap } from "../packages/opvault.js/src/weakMap";
declare const gc: () => void; declare const gc: () => void;

View File

@ -1,9 +1,10 @@
{ {
"compilerOptions": { "compilerOptions": {
"allowJs": false,
"declaration": true, "declaration": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"importHelpers": true, "importHelpers": true,
"jsx": "react", "jsx": "react-jsx",
"module": "commonjs", "module": "commonjs",
"moduleResolution": "node", "moduleResolution": "node",
"noEmit": true, "noEmit": true,