Skip to content

Commit

Permalink
Use same hook fn for both functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Powersource committed Nov 24, 2023
1 parent 942eaa9 commit 5708865
Showing 1 changed file with 9 additions and 37 deletions.
46 changes: 9 additions & 37 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,36 @@ module.exports = {
init (ssb, config) {
const allowedTypes = getAllowedTypes(ssb, config)

const publishHook = (publish, args) => {
const publishHook = ({ db2 }) => (publish, args) => {
const [input, cb] = args

if (get(input, ['options', 'allowPublic']) === true) {
if (db2 ? input.allowPublic === true : get(input, ['options', 'allowPublic']) === true) {
// allowPublic and has recps, disallowed
if (hasRecps(input.content)) {
return cb(new Error('recps-guard: should not have recps && allowPublic, check your code'))
}

// allowPublic and no recps, allowed
return publish(input.content, cb)
return publish(db2 ? input : input.content, cb)
} else {
// without allowPublic, content isn't nested
const content = input
// without allowPublic, content isn't nested with db1 publish
const content = db2 ? input.content : input

// no allowPublic and has recps/can publish without recps, allowed
if (
(db2 ? (input.encryptionFormat !== undefined) : false) ||
isString(content) ||
hasRecps(content) ||
allowedTypes.has(content.type)
) return publish(content, cb)
) return publish(db2 ? input : content, cb)

// no allowPublic and no recps, disallowed
return cb(new Error(`recps-guard: public messages of type "${content.type}" not allowed`))
}
}

if (ssb.publish) {
ssb.publish.hook(publishHook)
ssb.publish.hook(publishHook({ db2: false }))

ssb.publish.hook = () => {
throw new Error('ssb-recps-guard must be the last to hook ssb.publish')
Expand All @@ -49,36 +50,7 @@ module.exports = {
}

if (ssb.db && ssb.db.create) {
ssb.db.create.hook((create, args) => {
const [input, cb] = args

if (
input.encryptionFormat !== undefined ||
isString(input.content) ||
(hasRecps(input.content) && input.allowPublic !== true) ||
allowedTypes.has(input.content.type)
) {
return create(input, cb)
}

if (input.allowPublic === true) {
if (hasRecps(input.content)) {
return cb(new Error('recps-guard: should not have recps && allowPublic, check your code'))
}

if (input.content.options) {
delete input.content.options.allowPublic

if (Object.keys(input.content.options).length === 0) {
delete input.content.options
}
}

return create(input, cb)
}

cb(new Error(`recps-guard: public messages of type "${input.content.type}" not allowed`))
})
ssb.db.create.hook(publishHook({ db2: true }))

ssb.db.create.hook = () => {
throw new Error('ssb-recps-guard must be the last to hook ssb.db.create')
Expand Down

0 comments on commit 5708865

Please sign in to comment.