Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release v1.7.0 #266

Merged
merged 9 commits into from
Oct 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion config-overrides/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const src = file => path.join(__dirname, '../', file)
let polyfills = [
'node_modules/webextension-polyfill/dist/browser-polyfill.min.js',
'node_modules/webextension-polyfill/dist/browser-polyfill.min.js.map',
'src/polyfill/asmcrypto.js',
]

const publicDir = src('./public')
Expand Down
3 changes: 1 addition & 2 deletions config-overrides/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script src="/polyfill/browser-polyfill.min.js"></script>
<script src="/polyfill/asmcrypto.js"></script>
<script src="/firefoxFix.js"></script>
<script src="/js/env.js"></script>
<script src="/env.js"></script>
</head>
<body></body>
</html>
21 changes: 5 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "maskbook",
"license": "AGPL-3.0-or-later",
"version": "1.6.0",
"version": "1.7.0",
"private": true,
"engines": {
"node": ">=12.0.0"
Expand Down Expand Up @@ -58,7 +58,7 @@
"elliptic": "^6.4.1",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-react-hooks": "^2.0.1",
"gun": "0.2019.930",
"gun": "0.2019.422",
"husky": "^3.0.5",
"idb": "^4.0.3",
"json-stable-stringify": "^1.0.1",
Expand Down Expand Up @@ -112,16 +112,8 @@
"yargs": "^14.0.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"production": [">0.2%", "not dead", "not op_mini all"],
"development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]
},
"husky": {
"hooks": {
Expand All @@ -130,9 +122,6 @@
}
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"node scripts/lint.js",
"git add"
]
"*.{ts,tsx,js,jsx}": ["node scripts/lint.js", "git add"]
}
}
4 changes: 0 additions & 4 deletions src/background-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ import * as CryptoService from './extension/background-script/CryptoService'
import * as WelcomeService from './extension/background-script/WelcomeService'
import * as PeopleService from './extension/background-script/PeopleService'
import { decryptFromMessageWithProgress } from './extension/background-script/CryptoServices/decryptFrom'
import {
generate_ECDH_256k1_KeyPair_ByMnemonicWord,
recover_ECDH_256k1_KeyPair_ByMnemonicWord,
} from './utils/mnemonic-code'
Object.assign(window, { CryptoService, WelcomeService, PeopleService })
Object.assign(window, {
ServicesWithProgress: {
Expand Down
76 changes: 46 additions & 30 deletions src/components/DebugModeUI/PostHashDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { useAsync } from '../../utils/components/AsyncComponent'
import Services from '../../extension/service'
import { PostIVIdentifier } from '../../database/type'
import { deconstructPayload } from '../../utils/type-transform/Payload'
import { DialogContentText, DialogContent } from '@material-ui/core'

const useStyles = makeStyles({
avatar: {
Expand All @@ -28,60 +29,75 @@ export interface SimpleDialogProps {
open: boolean
onClose: (value: string) => void
friends: Person[]
hashMap: [string, string][]
hashMap: [string, string, string][]
}

function SimpleDialog(props: SimpleDialogProps) {
const { open } = props

const map = new Map<string, string>()
for (const data of props.hashMap) {
map.set(data[0], data[1])
const map = new Map<string, [string, string]>()
for (const [id, magicCode, fingerprint] of props.hashMap) {
map.set(id, [magicCode, fingerprint])
}

return (
<Dialog container={PortalShadowRoot} onClose={props.onClose} open={open}>
<DialogTitle>
Post hash for each of your friends (Appear in this list is not related to if you have shared this post
to someone or not.)
</DialogTitle>
<List>
{props.friends.map(one => {
return (
<ListItem>
<ListItemAvatar>
<Avatar person={one} />
</ListItemAvatar>
<ListItemText
primary={one.nickname || one.identifier.userId}
secondary={
<span style={{ fontFamily: 'monospace' }}>
{map.get(one.identifier.toText()) || 'Unknown'}
</span>
}
/>
</ListItem>
)
})}
</List>
<DialogTitle>Troubleshoot</DialogTitle>
<DialogContent>
<DialogContentText>
Appear in this list is not related to if you have shared this post to someone or not.
</DialogContentText>
<DialogContentText>
The "Magic Code" and the Fingerprint should be the same on your friend's Maskbook and your Maskbook.
</DialogContentText>
<DialogContentText>
If Fingerprint is not the same, it means at least one of Maskbook doesn't get the correct key of the
receiver.
</DialogContentText>
<DialogContentText>
If MagicCode is not the same, it means at least one of Maskbook calculate the post hash wrong.
</DialogContentText>
<List dense>
{props.friends.map(one => {
const [magicCode, fingerprint] = map.get(one.identifier.toText()) || ['Unknown', 'Unknown']
return (
<ListItem>
<ListItemAvatar>
<Avatar person={one} />
</ListItemAvatar>
<ListItemText
primary={one.nickname || one.identifier.userId}
secondary={
<span>
Magic code: {magicCode || 'Unknown'}
<br />
Their fingerprint: {fingerprint}
</span>
}
/>
</ListItem>
)
})}
</List>
</DialogContent>
</Dialog>
)
}

export function DebugModeUI_PostHashDialog(props: { post: string; network: string }) {
const [open, setOpen] = React.useState(false)
const payload = deconstructPayload(props.post, null)
const [hashMap, setHashMap] = useState<[string, string][]>([])
const [hashMap, setHashMap] = useState<[string, string, string][]>([])
const friends = useFriendsList()
useAsync(() => {
if (!payload) return Promise.resolve([] as typeof hashMap)
const ivID = new PostIVIdentifier(props.network, payload.iv)
return Services.Crypto.debugShowAllPossibleHashForPost(ivID)
return Services.Crypto.debugShowAllPossibleHashForPost(ivID, payload.version)
}, [props.post]).then(setHashMap)
return (
<>
<Button variant="outlined" color="primary" onClick={() => setOpen(true)}>
See what code my friends will see for this post
My friend can't see this post even I shared with them!
</Button>
<SimpleDialog hashMap={hashMap} friends={friends} open={open} onClose={() => setOpen(false)} />
</>
Expand Down
1 change: 1 addition & 0 deletions src/components/InjectedComponents/PostInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export function PostInspector(props: PostInspectorProps) {
'Who am I',
whoAmI ? `Nickname ${whoAmI.nickname || 'unknown'}, UserID ${whoAmI.identifier.userId}` : 'Unknown',
],
['My fingerprint', whoAmI ? whoAmI.fingerprint || 'Unknown' : 'unknown'],
['Post ID', props.postId || 'Unknown'],
['Post Content', props.post],
]}
Expand Down
2 changes: 1 addition & 1 deletion src/database/helpers/person.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export async function queryPeopleWithQuery(query?: Parameters<typeof queryPeople
return Promise.all(result.map(personRecordToPerson))
}

const calculateFingerprint = memoize(async function(_key: CryptoKey) {
export const calculateFingerprint = memoize(async function(_key: CryptoKey) {
const key = await CryptoKeyToJsonWebKey(_key)
if (!key) return 'Fingerprint not available'
const hash = await crypto.subtle.digest('SHA-256', encodeText(key.x! + key.y))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { PostIVIdentifier } from '../../../database/type'
import { queryPeopleDB } from '../../../database/people'
import { hashPostSalt, hashCryptoKey } from '../../../network/gun/version.2/hash'
import { hashPostSalt, hashCryptoKey, hashCryptoKeyUnstable } from '../../../network/gun/version.2/hash'
import { calculateFingerprint } from '../../../database'

export async function debugShowAllPossibleHashForPost(post: PostIVIdentifier) {
export async function debugShowAllPossibleHashForPost(post: PostIVIdentifier, payloadVersion: -38 | -39 | -40) {
const friends = await queryPeopleDB(x => x.network === post.network)
return Promise.all(
friends
Expand All @@ -11,8 +12,11 @@ export async function debugShowAllPossibleHashForPost(post: PostIVIdentifier) {
async x =>
[
x.identifier.toText(),
(await hashPostSalt(post.postIV)) + '-' + (await hashCryptoKey(x.publicKey!, true)),
] as [string, string],
(await hashPostSalt(post.postIV)) +
'-' +
(await (payloadVersion <= -39 ? hashCryptoKeyUnstable : hashCryptoKey)(x.publicKey!)),
await calculateFingerprint(x.publicKey!),
] as [string, string, string],
),
)
}
2 changes: 1 addition & 1 deletion src/extension/background-script/WorkerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ export function startWorkerService(e: SocialNetworkWorker) {
autoVerifyPost: e.autoVerifyPost,
manualVerifyPost: e.manualVerifyPost,
}
AsyncCall(impl, { serializer: Serialization, key: e.internalName, messageChannel: new MessageCenter() })
AsyncCall(impl, { serializer: Serialization, key: e.internalName, messageChannel: new MessageCenter(), log: true })
}
42 changes: 26 additions & 16 deletions src/extension/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const Services = {} as Services
export default Services

const logOptions: AsyncCallOptions['log'] = {
beCalled: false,
beCalled: true,
localError: true,
remoteError: true,
sendLocalStack: true,
Expand All @@ -27,16 +27,36 @@ const logOptions: AsyncCallOptions['log'] = {
if (!('Services' in globalThis)) {
Object.assign(globalThis, { Services })
// Sorry you should add import at '../background-service.ts'
register(Reflect.get(globalThis, 'CryptoService'), 'Crypto', MockService.CryptoService)
register(Reflect.get(globalThis, 'WelcomeService'), 'Welcome', MockService.WelcomeService)
register(Reflect.get(globalThis, 'PeopleService'), 'People', MockService.PeopleService)
register(createProxyToService('CryptoService'), 'Crypto', MockService.CryptoService)
register(createProxyToService('WelcomeService'), 'Welcome', MockService.WelcomeService)
register(createProxyToService('PeopleService'), 'People', MockService.PeopleService)
}
interface ServicesWithProgress {
// Sorry you should add import at '../background-service.ts'
decryptFrom: typeof import('./background-script/CryptoServices/decryptFrom').decryptFromMessageWithProgress
}
function createProxyToService(name: string) {
return new Proxy(
// @ts-ignore
globalThis[name] || {},
{
get(_, key) {
// @ts-ignore
const service = globalThis[name] || {}
if (key === 'methods') {
return () => {
return Object.keys(service)
.map(f => service[f].toString().split('\n')[0])
.join('\n')
}
}
return service[key]
},
},
)
}
export const ServicesWithProgress = AsyncGeneratorCall<ServicesWithProgress>(
Reflect.get(globalThis, 'ServicesWithProgress'),
createProxyToService('ServicesWithProgress'),
{
key: 'Service+',
log: logOptions,
Expand All @@ -57,21 +77,11 @@ type Service = Record<string, (...args: unknown[]) => Promise<unknown>>
function register<T extends Service>(service: T, name: keyof Services, mock?: Partial<T>) {
if (OnlyRunInContext(['content', 'options', 'debugging', 'background'], false)) {
GetContext() !== 'debugging' && console.log(`Service ${name} registered in ${GetContext()}`)
const base = service
? {
methods() {
return Object.keys(service)
.map(f => service[f].toString().split('\n')[0])
.join('\n')
},
}
: {}
Object.assign(Services, {
[name]: AsyncCall(Object.assign(base, service), {
[name]: AsyncCall(service, {
key: name,
serializer: Serialization,
log: logOptions,
preferLocalImplementation: true,
messageChannel: new MessageCenter(),
}),
})
Expand Down
2 changes: 1 addition & 1 deletion src/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "http://json.schemastore.org/chrome-manifest",
"name": "Maskbook",
"version": "1.6.0",
"version": "1.7.0",
"manifest_version": 2,
"web_accessible_resources": ["*.css", "*.js", "*.jpg", "*.png"],
"permissions": ["storage", "downloads", "webNavigation", "activeTab"],
Expand Down
35 changes: 19 additions & 16 deletions src/network/gun/version.2/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,29 @@ export const hashPostSalt = memoizePromise(async function(postSalt: string) {

const hash = (await Gun.SEA.work(postSalt, hashPair))!
return hash.substring(0, N)
})
}, undefined)

/**
* @param key - The key need to be hashed
* @param stableHash - Set this to true if you're writing new code.
* Unstable hash may cause problem but we cannot just switch to stable hash
* because it may breaks current data.
*/
export const hashCryptoKey = memoizePromise(async function(key: CryptoKey, stableHash: boolean) {
export const hashCryptoKeyUnstable = memoizePromise(async function(key: CryptoKey) {
const hashPair = `10198a2f-205f-45a6-9987-3488c80113d0`
const N = 2

if (stableHash === true) {
const jwk = await CryptoKeyToJsonWebKey(key)
if (!jwk.x || !jwk.y) throw new Error('Invalid key')
const hash = (await Gun.SEA.work(jwk.x! + jwk.y!, hashPair))!
return hash.substring(0, N)
} else {
const jwk = JSON.stringify(await CryptoKeyToJsonWebKey(key))
const hash = (await Gun.SEA.work(jwk, hashPair))!
return hash.substring(0, N)
}
})
const jwk = JSON.stringify(await CryptoKeyToJsonWebKey(key))
const hash = (await Gun.SEA.work(jwk, hashPair))!
return hash.substring(0, N)
}, undefined)

/**
* @param key - The key need to be hashed
*/
export const hashCryptoKey = memoizePromise(async function(key: CryptoKey) {
const hashPair = `10198a2f-205f-45a6-9987-3488c80113d0`
const N = 2

const jwk = await CryptoKeyToJsonWebKey(key)
if (!jwk.x || !jwk.y) throw new Error('Invalid key')
const hash = (await Gun.SEA.work(jwk.x! + jwk.y!, hashPair))!
Copy link
Contributor

@Artoria2e5 Artoria2e5 Oct 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies for being laaaaaate to the new payload party, but we really can just get away with only hashing x as long as we are on EC. Let's fix that before -38 gets released and formalized. And may I ask what's exactly in the hashPair? Is somehow derived from the name K256? If not, we should fix that with something like jwk.kty + jwk.alg as salt.

PS: I don't see the point of doing a PBKDF2 on a public key when all we need is a fingerprint. Gun.SEA.work can use SHA-256.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hashPair is a random UUID. You can think it is some type of salt but shared to generate a stable output between clients.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jwk.x or jwk.x + jwk.y is not important, we just need a hash, does the current way looks good to you?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, because by only hashing the points we are throwing away algorithmic information previously provided by hashing the entire thing. This breaks the #191 mandate of being able to stably process a multitude of curves.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can see we cut the N chars of the hash. return hash.substring(0, N).

This is not a full hash, it's more like a "partition"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Hashing the entire thing" does not mean taking the full hash. It means that we used to hash the entire JWK object, which contained information about the algorithm in jwk.kty + jwk.alg. We are not including it anymore, which is a short-sighted view especially given that the current salt has no use.

You are trying to go through this quick by dismissing everything without reading them through.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The design here is from the https://github.com/DimensionDev/Maskbook/wiki/Data-structure-on-Gun-version-2 . Maskbook is only using the a part of "feature" of the key, it should be stable, but it's content is not important

return hash.substring(0, N)
}, undefined)
Loading