stacker.news/lib/validate.js

271 lines
8.6 KiB
JavaScript
Raw Normal View History

import { string, ValidationError, number, object, array, addMethod, boolean } from 'yup'
import { BOOST_MIN, MAX_POLL_CHOICE_LENGTH, MAX_TITLE_LENGTH, MAX_POLL_NUM_CHOICES, MIN_POLL_NUM_CHOICES, SUBS_NO_JOBS, MAX_FORWARDS, BOOST_MULT } from './constants'
2023-02-08 19:38:04 +00:00
import { URL_REGEXP, WS_REGEXP } from './url'
import { SUPPORTED_CURRENCIES } from './currency'
import { NOSTR_MAX_RELAY_NUM, NOSTR_PUBKEY_BECH32, NOSTR_PUBKEY_HEX } from './nostr'
2023-09-27 01:33:54 +00:00
import * as pkg from '../fragments/users'
const { NAME_QUERY } = pkg
2023-02-08 19:38:04 +00:00
export async function ssValidate (schema, data, args) {
2023-02-08 19:38:04 +00:00
try {
if (typeof schema === 'function') {
await schema(args).validate(data)
2023-02-08 19:38:04 +00:00
} else {
await schema.validate(data)
}
} catch (e) {
2023-07-24 22:50:12 +00:00
if (e instanceof ValidationError) {
2023-02-08 19:38:04 +00:00
throw new Error(`${e.path}: ${e.message}`)
}
throw e
}
}
2023-07-24 22:50:12 +00:00
addMethod(string, 'or', function (schemas, msg) {
2023-02-08 19:38:04 +00:00
return this.test({
name: 'or',
message: msg,
test: value => {
if (Array.isArray(schemas) && schemas.length > 1) {
const resee = schemas.map(schema => schema.isValidSync(value))
return resee.some(res => res)
} else {
throw new TypeError('Schemas is not correct array schema')
}
},
exclusive: false
})
})
2023-07-24 22:50:12 +00:00
const titleValidator = string().required('required').trim().max(
2023-02-08 19:38:04 +00:00
MAX_TITLE_LENGTH,
({ max, value }) => `-${Math.abs(max - value.length)} characters remaining`
2023-02-08 19:38:04 +00:00
)
2023-07-24 22:50:12 +00:00
const intValidator = number().typeError('must be a number').integer('must be whole')
2023-02-08 19:38:04 +00:00
async function usernameExists (name, { client, models }) {
if (!client && !models) {
2023-02-08 19:38:04 +00:00
throw new Error('cannot check for user')
}
// apollo client
if (client) {
const { data } = await client.query({ query: NAME_QUERY, variables: { name } })
2023-02-08 19:38:04 +00:00
return !data.nameAvailable
}
// prisma client
const user = await models.user.findUnique({ where: { name } })
2023-02-08 19:38:04 +00:00
return !!user
}
export function advPostSchemaMembers ({ me, existingBoost = 0, ...args }) {
const boostMin = existingBoost || BOOST_MIN
2023-02-08 19:38:04 +00:00
return {
boost: intValidator
.min(boostMin, `must be ${existingBoost ? '' : 'blank or '}at least ${boostMin}`).test({
2023-02-08 19:38:04 +00:00
name: 'boost',
test: async boost => (!existingBoost && !boost) || boost % BOOST_MULT === 0,
message: `must be divisble be ${BOOST_MULT}`
2023-02-08 19:38:04 +00:00
}),
multiple forwards on a post (#403) * multiple forwards on a post first phase of the multi-forward support * update the graphql mutation for discussion posts to accept and validate multiple forwards * update the discussion form to allow multiple forwards in the UI * start working on db schema changes * uncomment db schema, add migration to create the new model, and update create_item, update_item stored procedures * Propagate updates from discussion to poll, link, and bounty forms Update the create, update poll sql functions for multi forward support * Update gql, typedefs, and resolver to return forwarded users in items responses * UI changes to show multiple forward recipients, and conditional upvote logic changes * Update notification text to reflect multiple forwards upon vote action * Disallow duplicate stacker entries * reduce duplication in populating adv-post-form initial values * Update item_act sql function to implement multi-way forwarding * Update referral functions to scale referral bonuses for forwarded users * Update notification text to reflect non-100% forwarded sats cases * Update wallet history sql queries to accommodate multi-forward use cases * Block zaps for posts you are forwarded zaps at the API layer, in addition to in the UI * Delete fwdUserId column from Item table as part of migration * Fix how we calculate stacked sats after partial forwards in wallet history * Exclude entries from wallet history that are 0 stacked sats from posts with 100% forwarded to other users * Fix wallet history query for forwarded stacked sats to be scaled by the fwd pct * Reduce duplication in adv post form, and do some style tweaks for better layout * Use MAX_FORWARDS constants * Address various PR feedback * first enhancement pass * enhancement pass too --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2023-08-23 22:44:17 +00:00
forward: array()
.max(MAX_FORWARDS, `you can only configure ${MAX_FORWARDS} forward recipients`)
.of(object().shape({
nym: string().required('must specify a stacker')
.test({
name: 'nym',
test: async name => {
if (!name || !name.length) return false
return await usernameExists(name, args)
},
message: 'stacker does not exist'
})
.test({
name: 'self',
test: async name => {
return me?.name !== name
},
message: 'cannot forward to yourself'
}),
multiple forwards on a post (#403) * multiple forwards on a post first phase of the multi-forward support * update the graphql mutation for discussion posts to accept and validate multiple forwards * update the discussion form to allow multiple forwards in the UI * start working on db schema changes * uncomment db schema, add migration to create the new model, and update create_item, update_item stored procedures * Propagate updates from discussion to poll, link, and bounty forms Update the create, update poll sql functions for multi forward support * Update gql, typedefs, and resolver to return forwarded users in items responses * UI changes to show multiple forward recipients, and conditional upvote logic changes * Update notification text to reflect multiple forwards upon vote action * Disallow duplicate stacker entries * reduce duplication in populating adv-post-form initial values * Update item_act sql function to implement multi-way forwarding * Update referral functions to scale referral bonuses for forwarded users * Update notification text to reflect non-100% forwarded sats cases * Update wallet history sql queries to accommodate multi-forward use cases * Block zaps for posts you are forwarded zaps at the API layer, in addition to in the UI * Delete fwdUserId column from Item table as part of migration * Fix how we calculate stacked sats after partial forwards in wallet history * Exclude entries from wallet history that are 0 stacked sats from posts with 100% forwarded to other users * Fix wallet history query for forwarded stacked sats to be scaled by the fwd pct * Reduce duplication in adv post form, and do some style tweaks for better layout * Use MAX_FORWARDS constants * Address various PR feedback * first enhancement pass * enhancement pass too --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2023-08-23 22:44:17 +00:00
pct: intValidator.required('must specify a percentage').min(1, 'percentage must be at least 1').max(100, 'percentage must not exceed 100')
}))
.compact((v) => !v.nym && !v.pct)
2023-02-08 19:38:04 +00:00
.test({
multiple forwards on a post (#403) * multiple forwards on a post first phase of the multi-forward support * update the graphql mutation for discussion posts to accept and validate multiple forwards * update the discussion form to allow multiple forwards in the UI * start working on db schema changes * uncomment db schema, add migration to create the new model, and update create_item, update_item stored procedures * Propagate updates from discussion to poll, link, and bounty forms Update the create, update poll sql functions for multi forward support * Update gql, typedefs, and resolver to return forwarded users in items responses * UI changes to show multiple forward recipients, and conditional upvote logic changes * Update notification text to reflect multiple forwards upon vote action * Disallow duplicate stacker entries * reduce duplication in populating adv-post-form initial values * Update item_act sql function to implement multi-way forwarding * Update referral functions to scale referral bonuses for forwarded users * Update notification text to reflect non-100% forwarded sats cases * Update wallet history sql queries to accommodate multi-forward use cases * Block zaps for posts you are forwarded zaps at the API layer, in addition to in the UI * Delete fwdUserId column from Item table as part of migration * Fix how we calculate stacked sats after partial forwards in wallet history * Exclude entries from wallet history that are 0 stacked sats from posts with 100% forwarded to other users * Fix wallet history query for forwarded stacked sats to be scaled by the fwd pct * Reduce duplication in adv post form, and do some style tweaks for better layout * Use MAX_FORWARDS constants * Address various PR feedback * first enhancement pass * enhancement pass too --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2023-08-23 22:44:17 +00:00
name: 'sum',
test: forwards => forwards ? forwards.map(fwd => Number(fwd.pct)).reduce((sum, cur) => sum + cur, 0) <= 100 : true,
multiple forwards on a post (#403) * multiple forwards on a post first phase of the multi-forward support * update the graphql mutation for discussion posts to accept and validate multiple forwards * update the discussion form to allow multiple forwards in the UI * start working on db schema changes * uncomment db schema, add migration to create the new model, and update create_item, update_item stored procedures * Propagate updates from discussion to poll, link, and bounty forms Update the create, update poll sql functions for multi forward support * Update gql, typedefs, and resolver to return forwarded users in items responses * UI changes to show multiple forward recipients, and conditional upvote logic changes * Update notification text to reflect multiple forwards upon vote action * Disallow duplicate stacker entries * reduce duplication in populating adv-post-form initial values * Update item_act sql function to implement multi-way forwarding * Update referral functions to scale referral bonuses for forwarded users * Update notification text to reflect non-100% forwarded sats cases * Update wallet history sql queries to accommodate multi-forward use cases * Block zaps for posts you are forwarded zaps at the API layer, in addition to in the UI * Delete fwdUserId column from Item table as part of migration * Fix how we calculate stacked sats after partial forwards in wallet history * Exclude entries from wallet history that are 0 stacked sats from posts with 100% forwarded to other users * Fix wallet history query for forwarded stacked sats to be scaled by the fwd pct * Reduce duplication in adv post form, and do some style tweaks for better layout * Use MAX_FORWARDS constants * Address various PR feedback * first enhancement pass * enhancement pass too --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2023-08-23 22:44:17 +00:00
message: 'the total forward percentage exceeds 100%'
})
.test({
name: 'uniqueStackers',
test: forwards => forwards ? new Set(forwards.map(fwd => fwd.nym)).size === forwards.length : true,
multiple forwards on a post (#403) * multiple forwards on a post first phase of the multi-forward support * update the graphql mutation for discussion posts to accept and validate multiple forwards * update the discussion form to allow multiple forwards in the UI * start working on db schema changes * uncomment db schema, add migration to create the new model, and update create_item, update_item stored procedures * Propagate updates from discussion to poll, link, and bounty forms Update the create, update poll sql functions for multi forward support * Update gql, typedefs, and resolver to return forwarded users in items responses * UI changes to show multiple forward recipients, and conditional upvote logic changes * Update notification text to reflect multiple forwards upon vote action * Disallow duplicate stacker entries * reduce duplication in populating adv-post-form initial values * Update item_act sql function to implement multi-way forwarding * Update referral functions to scale referral bonuses for forwarded users * Update notification text to reflect non-100% forwarded sats cases * Update wallet history sql queries to accommodate multi-forward use cases * Block zaps for posts you are forwarded zaps at the API layer, in addition to in the UI * Delete fwdUserId column from Item table as part of migration * Fix how we calculate stacked sats after partial forwards in wallet history * Exclude entries from wallet history that are 0 stacked sats from posts with 100% forwarded to other users * Fix wallet history query for forwarded stacked sats to be scaled by the fwd pct * Reduce duplication in adv post form, and do some style tweaks for better layout * Use MAX_FORWARDS constants * Address various PR feedback * first enhancement pass * enhancement pass too --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2023-08-23 22:44:17 +00:00
message: 'duplicate stackers cannot be specified to receive forwarded sats'
2023-02-08 19:38:04 +00:00
})
}
}
export function subSelectSchemaMembers () {
2023-05-11 00:26:07 +00:00
return {
2023-07-24 22:50:12 +00:00
sub: string().required('required').oneOf(SUBS_NO_JOBS, 'required')
2023-05-11 00:26:07 +00:00
}
}
// for testing advPostSchemaMembers in isolation
export function advSchema (args) {
return object({
...advPostSchemaMembers(args)
})
}
2023-05-11 00:26:07 +00:00
export function bountySchema (args) {
2023-07-24 22:50:12 +00:00
return object({
2023-02-08 19:38:04 +00:00
title: titleValidator,
bounty: intValidator
.min(1000, 'must be at least 1000')
.max(1000000, 'must be at most 1m'),
...advPostSchemaMembers(args),
2023-05-11 00:26:07 +00:00
...subSelectSchemaMembers()
2023-02-08 19:38:04 +00:00
})
}
export function discussionSchema (args) {
2023-07-24 22:50:12 +00:00
return object({
2023-02-08 19:38:04 +00:00
title: titleValidator,
...advPostSchemaMembers(args),
2023-05-11 00:26:07 +00:00
...subSelectSchemaMembers()
2023-02-08 19:38:04 +00:00
})
}
export function linkSchema (args) {
2023-07-24 22:50:12 +00:00
return object({
2023-02-08 19:38:04 +00:00
title: titleValidator,
2023-07-24 22:50:12 +00:00
url: string().matches(URL_REGEXP, 'invalid url').required('required'),
...advPostSchemaMembers(args),
2023-05-11 00:26:07 +00:00
...subSelectSchemaMembers()
2023-02-08 19:38:04 +00:00
})
}
export function pollSchema ({ numExistingChoices = 0, ...args }) {
2023-07-24 22:50:12 +00:00
return object({
2023-02-08 19:38:04 +00:00
title: titleValidator,
2023-07-24 22:50:12 +00:00
options: array().of(
string().trim().test('my-test', 'required', function (value) {
2023-02-08 19:38:04 +00:00
return (this.path !== 'options[0]' && this.path !== 'options[1]') || value
}).max(MAX_POLL_CHOICE_LENGTH,
({ max, value }) => `-${Math.abs(max - value.length)} characters remaining`
2023-02-08 19:38:04 +00:00
)
).test({
message: `at most ${MAX_POLL_NUM_CHOICES} choices`,
test: arr => arr.length <= MAX_POLL_NUM_CHOICES - numExistingChoices
}).test({
message: `at least ${MIN_POLL_NUM_CHOICES} choices required`,
test: arr => arr.length >= MIN_POLL_NUM_CHOICES - numExistingChoices
}),
...advPostSchemaMembers(args),
2023-05-11 00:26:07 +00:00
...subSelectSchemaMembers()
2023-02-08 19:38:04 +00:00
})
}
export function userSchema (args) {
2023-07-24 22:50:12 +00:00
return object({
name: string()
2023-02-08 19:38:04 +00:00
.required('required')
.matches(/^[\w_]+$/, 'only letters, numbers, and _')
.max(32, 'too long')
.test({
name: 'name',
test: async name => {
if (!name || !name.length) return false
return !(await usernameExists(name, args))
2023-02-08 19:38:04 +00:00
},
message: 'taken'
})
})
}
2023-07-24 22:50:12 +00:00
export const commentSchema = object({
text: string().required('required').trim()
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const jobSchema = object({
2023-02-08 19:38:04 +00:00
title: titleValidator,
2023-07-24 22:50:12 +00:00
company: string().required('required').trim(),
text: string().required('required').trim(),
url: string()
.or([string().email(), string().url()], 'invalid url or email')
2023-02-08 19:38:04 +00:00
.required('required'),
maxBid: intValidator.min(0, 'must be at least 0').required('required'),
2023-07-24 22:50:12 +00:00
location: string().test(
2023-02-08 19:38:04 +00:00
'no-remote',
"don't write remote, just check the box",
v => !v?.match(/\bremote\b/gi))
.when('remote', {
is: (value) => !value,
2023-07-27 00:18:42 +00:00
then: schema => schema.required('required').trim()
2023-02-08 19:38:04 +00:00
})
})
2023-07-24 22:50:12 +00:00
export const emailSchema = object({
email: string().email('email is no good').required('required')
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const urlSchema = object({
url: string().matches(URL_REGEXP, 'invalid url').required('required')
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const namedUrlSchema = object({
text: string().required('required').trim(),
url: string().matches(URL_REGEXP, 'invalid url').required('required')
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const amountSchema = object({
2023-02-08 19:38:04 +00:00
amount: intValidator.required('required').positive('must be positive')
})
2023-07-24 22:50:12 +00:00
export const settingsSchema = object({
2023-02-08 19:38:04 +00:00
tipDefault: intValidator.required('required').positive('must be positive'),
2023-07-24 22:50:12 +00:00
fiatCurrency: string().required('required').oneOf(SUPPORTED_CURRENCIES),
nostrPubkey: string().nullable()
2023-02-08 19:38:04 +00:00
.or([
2023-07-24 22:50:12 +00:00
string().nullable().matches(NOSTR_PUBKEY_HEX, 'must be 64 hex chars'),
string().nullable().matches(NOSTR_PUBKEY_BECH32, 'invalid bech32 encoding')], 'invalid pubkey'),
nostrRelays: array().of(
string().matches(WS_REGEXP, 'invalid web socket address')
2023-02-08 19:38:04 +00:00
).max(NOSTR_MAX_RELAY_NUM,
({ max, value }) => `${Math.abs(max - value.length)} too many`),
hideBookmarks: boolean(),
hideWalletBalance: boolean(),
diagnostics: boolean(),
hideIsContributor: boolean()
2023-02-08 19:38:04 +00:00
})
const warningMessage = 'If I logout, even accidentally, I will never be able to access my account again'
2023-07-24 22:50:12 +00:00
export const lastAuthRemovalSchema = object({
warning: string().matches(warningMessage, 'does not match').required('required')
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const withdrawlSchema = object({
invoice: string().required('required').trim(),
2023-02-08 19:38:04 +00:00
maxFee: intValidator.required('required').min(0, 'must be at least 0')
})
2023-07-24 22:50:12 +00:00
export const lnAddrSchema = object({
addr: string().email('address is no good').required('required'),
2023-02-08 19:38:04 +00:00
amount: intValidator.required('required').positive('must be positive'),
maxFee: intValidator.required('required').min(0, 'must be at least 0'),
comment: string()
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const bioSchema = object({
bio: string().required('required').trim()
2023-02-08 19:38:04 +00:00
})
2023-07-24 22:50:12 +00:00
export const inviteSchema = object({
2023-02-08 19:38:04 +00:00
gift: intValidator.positive('must be greater than 0').required('required'),
limit: intValidator.positive('must be positive')
})
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
2023-07-24 22:50:12 +00:00
export const pushSubscriptionSchema = object({
endpoint: string().url().required('required').trim(),
p256dh: string().required('required').trim(),
auth: string().required('required').trim()
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
})