@sqrzro/server 4.0.0-alpha.5 → 4.0.0-alpha.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2ZLU4AUD.js +2 -0
- package/dist/chunk-2ZLU4AUD.js.map +1 -0
- package/dist/chunk-6GDOIHTS.js +2 -0
- package/dist/chunk-6GDOIHTS.js.map +1 -0
- package/dist/chunk-BA3BC4CD.js +2 -0
- package/dist/chunk-BA3BC4CD.js.map +1 -0
- package/dist/chunk-UCMLSO7F.js +3 -0
- package/dist/chunk-UCMLSO7F.js.map +1 -0
- package/dist/csv/index.d.ts +7 -0
- package/dist/csv/index.js +2 -0
- package/dist/csv/index.js.map +1 -0
- package/dist/database/index.d.ts +86 -37
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.d.ts +41 -10
- package/dist/forms/index.js +1 -1
- package/dist/forms/index.js.map +1 -1
- package/dist/{interfaces-BheedaEI.d.ts → interfaces-DTUqy5Oj.d.ts} +4 -3
- package/dist/interfaces-cnzok1wV.d.ts +13 -0
- package/dist/json/index.d.ts +3 -1
- package/dist/json/index.js +1 -1
- package/dist/json/index.js.map +1 -1
- package/dist/mail/index.d.ts +25 -0
- package/dist/mail/index.js +3 -0
- package/dist/mail/index.js.map +1 -0
- package/dist/proxy/index.d.ts +10 -0
- package/dist/proxy/index.js +2 -0
- package/dist/proxy/index.js.map +1 -0
- package/dist/storage/index.d.ts +32 -0
- package/dist/storage/index.js +2 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/utility/index.d.ts +8 -5
- package/dist/utility/index.js +1 -1
- package/package.json +27 -34
- package/dist/auth/index.d.ts +0 -49
- package/dist/auth/index.js +0 -2
- package/dist/auth/index.js.map +0 -1
- package/dist/auth/utility/schema.d.ts +0 -348
- package/dist/auth/utility/schema.js +0 -2
- package/dist/auth/utility/schema.js.map +0 -1
- package/dist/chunk-37TYQL5Y.js +0 -2
- package/dist/chunk-37TYQL5Y.js.map +0 -1
- package/dist/chunk-AGS5PPG2.js +0 -2
- package/dist/chunk-AGS5PPG2.js.map +0 -1
- package/dist/chunk-JI2U2EMD.js +0 -2
- package/dist/chunk-JI2U2EMD.js.map +0 -1
- package/dist/chunk-QE347FVL.js +0 -2
- package/dist/chunk-QE347FVL.js.map +0 -1
- package/dist/chunk-XSJ4OEIH.js +0 -2
- package/dist/chunk-XSJ4OEIH.js.map +0 -1
- package/dist/cli/index.d.ts +0 -1
- package/dist/cli/index.js +0 -4
- package/dist/cli/index.js.map +0 -1
- package/dist/cli/static/drizzle.config.js +0 -19
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mail/create-mail.ts","../../src/mail/utility/render-mail.ts","../../src/mail/get-mail.ts","../../src/mail/drivers/mailtrap/transform-mailtrap-recipients.ts","../../src/mail/drivers/mailtrap/index.ts","../../src/mail/drivers/mandrill/transform-mandrill-recipients.ts","../../src/mail/drivers/mandrill/index.ts","../../src/mail/drivers/sendgrid/transform-sendgrid-recipients.ts","../../src/mail/drivers/sendgrid/index.ts","../../src/mail/utility/get-sender-details.ts","../../src/mail/send-mail.ts"],"names":["createMail","subject","template","create_mail_default","renderMail","element","ReactDOMServer","resolve","ws","stream","content","write","chunk","enc","next","pipe","render_mail_default","getMail","mail","data","subjectText","get_mail_default","transformMailtrapRecipients","emails","email","transform_mailtrap_recipients_default","sendMailtrapMail","sendObject","id","key","json","mailtrap_default","transformMandrillRecipientGroup","group","type","transformMandrillRecipients","to","cc","bcc","transform_mandrill_recipients_default","sendMandrillMail","message","attachment","item","mandrill_default","transformSendgridRecipients","transform_sendgrid_recipients_default","sendSendgridMail","sgMail","response","sendgrid_default","getSenderDetails","from","matches","get_sender_details_default","DEVELOPMENT_DRIVERS","PRODUCTION_DRIVERS","DEFAULT_DEVELOPMENT_DRIVER","DEFAULT_PRODUCTION_DRIVER","driverMap","sendMail","options","html","allowedDriverAliases","defaultDriverAlias","driverAlias","driver","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OAAA,CAAA7D,CAAAA,CACA,GAAAmC,CACJ,CAAA,CAEM2B,EACF,OAAA,CAAQ,GAAA,CAAI,yBAA2B,MAAA,CAASP,CAAAA,CAAqBD,EAEnES,CAAAA,CACF,OAAA,CAAQ,IAAI,sBAAA,GAA2B,MAAA,CACjCN,EACAD,CAAAA,CAEJQ,CAAAA,CAAc,QAAQ,GAAA,CAAI,WAAA,CAC1B,OAAA,CAAQ,GAAA,CAAI,YAAY,WAAA,EAAY,CACpCD,EAEN,GAAI,CAACD,EAAqB,QAAA,CAASE,CAAW,GAAK,CAACN,CAAAA,CAAUM,CAAW,CAAA,CACrE,MAAM,IAAI,KAAA,CACN,CAAA,YAAA,EAAeA,CAAW,CAAA,sJAAA,CAC9B,CAAA,CAGJ,IAAMC,CAAAA,CAASP,EAAUM,CAAW,CAAA,CAEpC,GAAI,CAACC,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,eAAeD,CAAW,CAAA,kBAAA,CAAoB,EAGlE,OAAOC,CAAAA,CAAOvC,CAAU,CAC5B,KAEOwC,CAAAA,CAAQP","file":"index.js","sourcesContent":["import type { MailObject } from './utility/interfaces';\n\nfunction createMail<T extends object>(\n subject: string | ((data: T) => Promise<string> | string),\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement\n): MailObject<T> {\n return { subject, template };\n}\n\nexport default createMail;\n","import stream from 'node:stream';\n\nasync function renderMail(element: React.ReactElement): Promise<string> {\n const ReactDOMServer = (await import('react-dom/server')).default;\n\n return new Promise((resolve) => {\n const ws = new stream.Writable();\n let content = '';\n\n function write<T extends { toString: () => string }>(\n chunk: T,\n enc: BufferEncoding,\n next: (error?: Error | null) => void\n ): void {\n content += chunk.toString();\n next();\n }\n\n ws._write = write; // eslint-disable-line no-underscore-dangle\n\n const { pipe } = ReactDOMServer.renderToPipeableStream(element, {\n onShellReady: () => {\n pipe(ws);\n resolve(content);\n },\n });\n });\n}\n\nexport default renderMail;\n","import renderMail from './utility/render-mail';\nimport type { MailObject } from './utility/interfaces';\n\nasync function getMail<T extends object>(\n mail: MailObject<T>,\n data: T\n): Promise<{ subject: string; html: string }> {\n const { subject, template } = mail;\n\n const subjectText = typeof subject === 'function' ? await subject(data) : subject;\n\n const element = await template(data);\n const html = await renderMail(element);\n\n return {\n html,\n subject: subjectText,\n };\n}\n\nexport default getMail;\n","function transformMailtrapRecipients(emails?: string[] | string): { email: string }[] {\n if (!emails) {\n return [];\n }\n return Array.isArray(emails) ? emails.map((email) => ({ email })) : [{ email: emails }];\n}\n\nexport default transformMailtrapRecipients;\n","import type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformMailtrapRecipients from './transform-mailtrap-recipients';\n\nasync function sendMailtrapMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Mailtrap. Mail API key has not been set.');\n }\n\n /*\n * The account id and api key are both in the MAIL_API_KEY variable, separated by a `.`. We need\n * to split them.\n */\n\n const [id, key] = process.env.MAIL_API_KEY.split('.');\n\n const response = await fetch(`https://sandbox.api.mailtrap.io/api/send/${id}`, {\n method: 'POST',\n headers: { 'Api-Token': key, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n attachments: sendObject.attachments,\n bcc: transformMailtrapRecipients(sendObject.bcc),\n cc: transformMailtrapRecipients(sendObject.cc),\n from: sendObject.from,\n html: sendObject.html,\n subject: sendObject.subject,\n to: transformMailtrapRecipients(sendObject.to),\n }),\n });\n\n const json = (await response.json()) as { errors?: string[] };\n\n if (json.errors) {\n throw new Error(`Could not send mail via Mailtrap. ${json.errors[0]}.`);\n }\n\n return true;\n}\n\nexport default sendMailtrapMail;\n","function transformMandrillRecipientGroup(\n group: string[] | string,\n type: 'bcc' | 'cc' | 'to'\n): { email: string; type: 'bcc' | 'cc' | 'to' }[] {\n if (Array.isArray(group)) {\n return group.map((email) => ({ email, type }));\n }\n return [{ email: group, type }];\n}\n\nfunction transformMandrillRecipients(\n to: string[] | string,\n cc?: string[] | string,\n bcc?: string[] | string\n): { email: string; type: 'bcc' | 'cc' | 'to' }[] {\n return [\n ...transformMandrillRecipientGroup(to, 'to'),\n ...transformMandrillRecipientGroup(cc || [], 'cc'),\n ...transformMandrillRecipientGroup(bcc || [], 'bcc'),\n ];\n}\n\nexport default transformMandrillRecipients;\n","import type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformMandrillRecipients from './transform-mandrill-recipients';\n\ninterface MandrillResponse {\n status: string;\n}\n\nasync function sendMandrillMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Mandrill. Mail API key has not been set.');\n }\n\n const attachments = sendObject.attachments?.map((attachment) => ({\n content: attachment.content,\n name: attachment.filename,\n type: attachment.type,\n }));\n\n /* eslint-disable camelcase */\n const message = {\n attachments,\n from_email: sendObject.from.email,\n from_name: sendObject.from.name,\n html: sendObject.html,\n subject: sendObject.subject,\n preserve_recipients: true,\n to: transformMandrillRecipients(sendObject.to, sendObject.cc, sendObject.bcc),\n };\n /* eslint-enable camelcase */\n\n const response = await fetch('https://mandrillapp.com/api/1.0/messages/send', {\n method: 'POST',\n body: JSON.stringify({\n key: process.env.MAIL_API_KEY,\n message,\n }),\n });\n\n const json = (await response.json()) as MandrillResponse | [MandrillResponse];\n\n return Array.isArray(json)\n ? json.every((item) => item.status === 'sent')\n : json.status === 'sent';\n}\n\nexport default sendMandrillMail;\n","function transformSendgridRecipients(emails?: string[] | string): { email: string }[] {\n if (!emails) {\n return [];\n }\n return Array.isArray(emails) ? emails.map((email) => ({ email })) : [{ email: emails }];\n}\n\nexport default transformSendgridRecipients;\n","import sgMail from '@sendgrid/mail';\n\nimport type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformSendgridRecipients from './transform-sendgrid-recipients';\n\nasync function sendSendgridMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Sendgrid. Mail API key has not been set.');\n }\n\n sgMail.setApiKey(process.env.MAIL_API_KEY);\n\n const response = await sgMail.send({\n attachments: sendObject.attachments,\n bcc: transformSendgridRecipients(sendObject.bcc),\n cc: transformSendgridRecipients(sendObject.cc),\n from: sendObject.from,\n html: sendObject.html,\n to: transformSendgridRecipients(sendObject.to),\n subject: sendObject.subject,\n });\n\n if (!response[0].statusCode.toString().startsWith('2')) {\n throw new Error(`Could not send mail via Sendgrid. ${JSON.stringify(response)}`);\n }\n\n return true;\n}\n\nexport default sendSendgridMail;\n","function getSenderDetails(from?: string | null): { email: string; name: string } {\n if (!from && !process.env.MAIL_FROM) {\n throw new Error(\n 'Mail from address has not been set as an environment variable, or provided in options.'\n );\n }\n\n const matches = /^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(from || process.env.MAIL_FROM || '');\n\n if (!matches?.groups?.name || !matches?.groups?.email) {\n throw new Error(\n 'Mail from address is not the correct format. It should be \"Name <email>\".'\n );\n }\n\n return {\n email: matches.groups.email.trim(),\n name: matches.groups.name.trim(),\n };\n}\n\nexport default getSenderDetails;\n","import sendMailtrapMail from './drivers/mailtrap';\nimport sendMandrillMail from './drivers/mandrill';\nimport sendSendgridMail from './drivers/sendgrid';\n\nimport getMail from './get-mail';\n\nimport getSenderDetails from './utility/get-sender-details';\nimport type { MailDriver, MailObject, MailOptions, SendableMailObject } from './utility/interfaces';\n\nconst DEVELOPMENT_DRIVERS = ['MAILTRAP'];\nconst PRODUCTION_DRIVERS = ['MAILTRAP', 'MANDRILL', 'SENDGRID'];\n\nconst DEFAULT_DEVELOPMENT_DRIVER = 'MAILTRAP';\nconst DEFAULT_PRODUCTION_DRIVER = 'SENDGRID';\n\nconst driverMap: Record<string, MailDriver> = {\n MAILTRAP: sendMailtrapMail,\n MANDRILL: sendMandrillMail,\n SENDGRID: sendSendgridMail,\n};\n\nasync function sendMail<T extends object>(\n to: string[] | string,\n mail: MailObject<T>,\n data?: T,\n options?: MailOptions\n): Promise<boolean> {\n const from = getSenderDetails(options?.from);\n const { subject, html } = await getMail(mail, data || {});\n\n const sendObject: SendableMailObject = {\n attachments: options?.attachments,\n bcc: options?.bcc,\n cc: options?.cc,\n from,\n html,\n subject,\n to,\n };\n\n const allowedDriverAliases =\n process.env.MAIL_ENABLE_PRODUCTION === 'true' ? PRODUCTION_DRIVERS : DEVELOPMENT_DRIVERS;\n\n const defaultDriverAlias =\n process.env.MAIL_ENABLE_PRODUCTION === 'true'\n ? DEFAULT_PRODUCTION_DRIVER\n : DEFAULT_DEVELOPMENT_DRIVER;\n\n const driverAlias = process.env.MAIL_DRIVER\n ? process.env.MAIL_DRIVER.toUpperCase()\n : defaultDriverAlias;\n\n if (!allowedDriverAliases.includes(driverAlias) || !driverMap[driverAlias]) {\n throw new Error(\n `Mail driver ${driverAlias} is not supported. If you're in a production environment, you might need to set the MAIL_ENABLE_PRODUCTION environment variable to access this driver.`\n );\n }\n\n const driver = driverMap[driverAlias];\n\n if (!driver) {\n throw new Error(`Mail driver ${driverAlias} is not supported.`);\n }\n\n return driver(sendObject);\n}\n\nexport default sendMail;\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { NextRequest } from 'next/server';
|
|
2
|
+
|
|
3
|
+
interface ProxyRedirect {
|
|
4
|
+
redirect: string | number | null;
|
|
5
|
+
}
|
|
6
|
+
type ProxyFunction = (request: NextRequest) => Promise<ProxyRedirect | null>;
|
|
7
|
+
|
|
8
|
+
declare function handleProxy(request: NextRequest, functions: ProxyFunction[]): Promise<Response>;
|
|
9
|
+
|
|
10
|
+
export { type ProxyFunction, type ProxyRedirect, handleProxy };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {NextResponse}from'next/server';async function i(t,n){for(let s of n){let r=await s(t);if(r?.redirect){let{redirect:e}=r;return typeof e=="number"?new Response(null,{status:e}):NextResponse.redirect(new URL(e,t.url))}}return NextResponse.next()}var u=i;export{u as handleProxy};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/proxy/handle-proxy.ts"],"names":["handleProxy","request","functions","func","result","redirect","NextResponse","handle_proxy_default"],"mappings":"uCAKA,eAAeA,CAAAA,CAAYC,CAAAA,CAAsBC,CAAAA,CAA+C,CAC5F,IAAA,IAAWC,CAAAA,IAAQD,CAAAA,CAAW,CAC1B,IAAME,EAAS,MAAMD,CAAAA,CAAKF,CAAO,CAAA,CAEjC,GAAIG,CAAAA,EAAQ,QAAA,CAAU,CAClB,GAAM,CAAE,QAAA,CAAAC,CAAS,CAAA,CAAID,CAAAA,CAErB,OAAI,OAAOC,CAAAA,EAAa,QAAA,CACb,IAAI,QAAA,CAAS,IAAA,CAAM,CAAE,MAAA,CAAQA,CAAS,CAAC,CAAA,CAEvCC,YAAAA,CAAa,QAAA,CAAS,IAAI,GAAA,CAAID,CAAAA,CAAUJ,CAAAA,CAAQ,GAAG,CAAC,CAEnE,CACJ,CAEA,OAAOK,YAAAA,CAAa,IAAA,EACxB,CAEA,IAAOC,CAAAA,CAAQP","file":"index.js","sourcesContent":["import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\n\nimport type { ProxyFunction } from './utility/interfaces';\n\nasync function handleProxy(request: NextRequest, functions: ProxyFunction[]): Promise<Response> {\n for (const func of functions) {\n const result = await func(request);\n\n if (result?.redirect) {\n const { redirect } = result;\n\n if (typeof redirect === 'number') {\n return new Response(null, { status: redirect });\n } else {\n return NextResponse.redirect(new URL(redirect, request.url));\n }\n }\n }\n\n return NextResponse.next();\n}\n\nexport default handleProxy;\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.
|
|
3
|
+
*/
|
|
4
|
+
declare const serverStorage: {
|
|
5
|
+
/**
|
|
6
|
+
* Get an item from the cache.
|
|
7
|
+
* @param prefix The prefix to use for the cache key.
|
|
8
|
+
* @param key The key of the item to retrieve.
|
|
9
|
+
* @returns The cached item, or null if not found.
|
|
10
|
+
*/
|
|
11
|
+
getItem(prefix: string, key: string): Promise<Record<string, unknown> | null>;
|
|
12
|
+
getArray(prefix: string, key: string): Promise<string[]>;
|
|
13
|
+
setArray(prefix: string, key: string, value: string[]): Promise<void>;
|
|
14
|
+
addToArray(prefix: string, key: string, value: string): Promise<void>;
|
|
15
|
+
removeFromArray(prefix: string, key: string, value: string): Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Set an item in the cache.
|
|
18
|
+
* @param prefix The prefix to use for the cache key.
|
|
19
|
+
* @param key The key of the item to set.
|
|
20
|
+
* @param value The value of the item to set.
|
|
21
|
+
*/
|
|
22
|
+
setItem(prefix: string, key: string, value: Record<string, unknown>, ttl?: number): Promise<void>;
|
|
23
|
+
setExpiry(prefix: string, key: string, ttl: number): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Remove an item from the cache.
|
|
26
|
+
* @param prefix The prefix to use for the cache key.
|
|
27
|
+
* @param key The key of the item to remove.
|
|
28
|
+
*/
|
|
29
|
+
removeItem(prefix: string, key: string): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export { serverStorage as default };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {createClient}from'redis';var n=null;async function c(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return n||(n=createClient({url:process.env.REDIS_URL}),await n.connect(),n)}var i=c;async function g(t,r,e){if(typeof e=="number")return e;let s=await(await i()).ttl(`[${t}]:${r}`);return s<0?0:s}var o=g;var m={async getItem(t,r){let e=await(await i()).get(`[${t}]:${r}`);if(!e)return null;try{return JSON.parse(e)}catch{return null}},async getArray(t,r){return await(await i()).sMembers(`[${t}]:${r}`)},async setArray(t,r,e){await(await i()).del(`[${t}]:${r}`),await(await i()).sAdd(`[${t}]:${r}`,e);},async addToArray(t,r,e){await(await i()).sAdd(`[${t}]:${r}`,e);},async removeFromArray(t,r,e){await(await i()).sRem(`[${t}]:${r}`,e);},async setItem(t,r,e,s){let a=await o(t,r,s);await(await i()).set(`[${t}]:${r}`,JSON.stringify(e),a>0?{expiration:{type:"EX",value:a}}:void 0);},async setExpiry(t,r,e){await(await i()).expire(`[${t}]:${r}`,e);},async removeItem(t,r){await(await i()).del(`[${t}]:${r}`);}},p=m;export{p as default};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/storage/utility/get-client.ts","../../src/storage/utility/get-ttl.ts","../../src/storage/index.ts"],"names":["client","getClient","createClient","get_client_default","getTTL","prefix","key","ttl","result","get_ttl_default","serverStorage","value","itemTTL","storage_default"],"mappings":"iCAIA,IAAIA,CAAAA,CAAiD,IAAA,CAQrD,eAAeC,CAAAA,EAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,IAAI,SAAA,CACb,MAAM,IAAI,KAAA,CAAM,gEAAgE,CAAA,CAGpF,OAAID,CAAAA,GAIJA,EAASE,YAAAA,CAAa,CAClB,GAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,SACrB,CAAC,CAAA,CAED,MAAMF,CAAAA,CAAO,OAAA,EAAQ,CACdA,CAAAA,CACX,CAEA,IAAOG,CAAAA,CAAQF,CAAAA,CC3Bf,eAAeG,CAAAA,CAAOC,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA+B,CAG9E,GAAI,OAAOA,GAAQ,QAAA,CACf,OAAOA,CAAAA,CAKX,IAAMC,CAAAA,CAAS,KAAA,CAAO,MAAML,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CAIjE,OAAIE,EAAS,CAAA,CACF,CAAA,CAGJA,CACX,CAEA,IAAOC,CAAAA,CAAQL,CAAAA,CChBf,IAAMM,CAAAA,CAAgB,CAOlB,MAAM,OAAA,CAAQL,CAAAA,CAAgBC,CA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CACFN,CAAAA,CACAC,CAAAA,CACAK,CAAAA,CACAJ,CAAAA,CACa,CACb,IAAMK,EAAU,MAAMH,CAAAA,CAAOJ,CAAAA,CAAQC,CAAAA,CAAKC,CAAG,CAAA,CAE7C,KAAA,CACI,MAAMJ,CAAAA,EAAU,EAClB,GAAA,CACE,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAA,CAClB,KAAK,SAAA,CAAUK,CAAK,CAAA,CACpBC,CAAAA,CAAU,CAAA,CACJ,CACI,UAAA,CAAY,CAAE,KAAM,IAAA,CAAM,KAAA,CAAOA,CAAQ,CAC7C,CAAA,CACA,MACV,EACJ,CAAA,CAEA,MAAM,SAAA,CAAUP,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA4B,CACrE,KAAA,CAAO,MAAMJ,CAAAA,IAAa,MAAA,CAAO,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAA,CAAIC,CAAG,EAC9D,EAOA,MAAM,UAAA,CAAWF,CAAAA,CAAgBC,CAAAA,CAA4B,CACzD,KAAA,CAAO,MAAMH,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,EACtD,CACJ,EAEOO,CAAAA,CAAQH","file":"index.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './get-client';\n\nasync function getTTL(prefix: string, key: string, ttl?: number): Promise<number> {\n // If a TTL is provided, return it directly\n\n if (typeof ttl === 'number') {\n return ttl;\n }\n\n // Otherwise, get the TTL from the storage\n\n const result = await (await getClient()).ttl(`[${prefix}]:${key}`);\n\n // If the result is -2, the key does not exist. If it's -1, the key exists but has no associated expire. In both cases, we return 0.\n\n if (result < 0) {\n return 0;\n }\n\n return result;\n}\n\nexport default getTTL;\n","import getClient from './utility/get-client';\nimport getTTL from './utility/get-ttl';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async setArray(prefix: string, key: string, value: string[]): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(\n prefix: string,\n key: string,\n value: Record<string, unknown>,\n ttl?: number\n ): Promise<void> {\n const itemTTL = await getTTL(prefix, key, ttl);\n\n await (\n await getClient()\n ).set(\n `[${prefix}]:${key}`,\n JSON.stringify(value),\n itemTTL > 0\n ? {\n expiration: { type: 'EX', value: itemTTL },\n }\n : undefined\n );\n },\n\n async setExpiry(prefix: string, key: string, ttl: number): Promise<void> {\n await (await getClient()).expire(`[${prefix}]:${key}`, ttl);\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n"]}
|
package/dist/utility/index.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-
|
|
1
|
+
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
2
2
|
|
|
3
|
-
declare function ensureID<T extends string>(id: string
|
|
3
|
+
declare function ensureID<T extends string>(id: string | null | undefined, prefix: string): T;
|
|
4
4
|
|
|
5
5
|
declare function generateID<T extends string = string>(prefix?: string | null, length?: number): T;
|
|
6
6
|
|
|
7
|
-
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string>> | null): Promise<T>;
|
|
7
|
+
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string[] | string>> | Record<string, string[] | string> | null): Promise<T | null>;
|
|
8
8
|
|
|
9
|
-
declare function guardID<T extends string>(id: string
|
|
9
|
+
declare function guardID<T extends string>(id: (string | null | undefined)[], prefix: string): T[];
|
|
10
|
+
declare function guardID<T extends string>(id: string | null | undefined, prefix: string): T | null;
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
declare function syslog(alias: string, fnName: string, message: string): void;
|
|
13
|
+
|
|
14
|
+
export { ensureID, generateID, getIDFromParams, guardID, syslog };
|
package/dist/utility/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export{a as generateID,b as syslog}from'../chunk-6GDOIHTS.js';export{b as ensureID,c as getIDFromParams,a as guardID}from'../chunk-BA3BC4CD.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,25 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqrzro/server",
|
|
3
|
-
"version": "4.0.0-alpha.
|
|
3
|
+
"version": "4.0.0-alpha.51",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"license": "ISC",
|
|
8
|
-
"bin": {
|
|
9
|
-
"szserver": "./dist/cli/index.js"
|
|
10
|
-
},
|
|
11
8
|
"exports": {
|
|
12
|
-
"./
|
|
13
|
-
"types": "./dist/
|
|
14
|
-
"default": "./dist/
|
|
15
|
-
},
|
|
16
|
-
"./auth/schema": {
|
|
17
|
-
"types": "./dist/auth/utility/schema.d.ts",
|
|
18
|
-
"default": "./dist/auth/utility/schema.js"
|
|
19
|
-
},
|
|
20
|
-
"./cli": {
|
|
21
|
-
"types": "./dist/cli/index.d.ts",
|
|
22
|
-
"default": "./dist/cli/index.js"
|
|
9
|
+
"./csv": {
|
|
10
|
+
"types": "./dist/csv/index.d.ts",
|
|
11
|
+
"default": "./dist/csv/index.js"
|
|
23
12
|
},
|
|
24
13
|
"./database": {
|
|
25
14
|
"types": "./dist/database/index.d.ts",
|
|
@@ -33,6 +22,18 @@
|
|
|
33
22
|
"types": "./dist/json/index.d.ts",
|
|
34
23
|
"default": "./dist/json/index.js"
|
|
35
24
|
},
|
|
25
|
+
"./mail": {
|
|
26
|
+
"types": "./dist/mail/index.d.ts",
|
|
27
|
+
"default": "./dist/mail/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./proxy": {
|
|
30
|
+
"types": "./dist/proxy/index.d.ts",
|
|
31
|
+
"default": "./dist/proxy/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./storage": {
|
|
34
|
+
"types": "./dist/storage/index.d.ts",
|
|
35
|
+
"default": "./dist/storage/index.js"
|
|
36
|
+
},
|
|
36
37
|
"./utility": {
|
|
37
38
|
"types": "./dist/utility/index.d.ts",
|
|
38
39
|
"default": "./dist/utility/index.js"
|
|
@@ -43,32 +44,25 @@
|
|
|
43
44
|
],
|
|
44
45
|
"dependencies": {
|
|
45
46
|
"@sendgrid/mail": "^8.1.6",
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"redis": "^5.10.0",
|
|
55
|
-
"zod": "^4.1.13",
|
|
56
|
-
"@sqrzro/utility": "^4.0.0-alpha.1"
|
|
47
|
+
"@vercel/blob": "^2.4.0",
|
|
48
|
+
"csv": "^6.5.0",
|
|
49
|
+
"drizzle-orm": "^0.45.1",
|
|
50
|
+
"pg": "^8.20.0",
|
|
51
|
+
"react-dom": "^19.2.4",
|
|
52
|
+
"redis": "^5.11.0",
|
|
53
|
+
"zod": "^4.3.6",
|
|
54
|
+
"@sqrzro/utility": "^4.0.0-alpha.19"
|
|
57
55
|
},
|
|
58
56
|
"devDependencies": {
|
|
59
57
|
"@types/jest": "^29.5.14",
|
|
60
|
-
"@types/
|
|
61
|
-
"@types/
|
|
62
|
-
"@types/react": "^19.2.7",
|
|
58
|
+
"@types/pg": "^8.18.0",
|
|
59
|
+
"@types/react": "^19.2.14",
|
|
63
60
|
"@types/react-dom": "^19.2.3",
|
|
64
61
|
"jest": "^29.7.0",
|
|
65
|
-
"prettier": "^3.7.4",
|
|
66
62
|
"rimraf": "^4.4.1",
|
|
67
63
|
"ts-jest": "^29.4.6",
|
|
68
64
|
"tsup": "^8.5.1",
|
|
69
|
-
"
|
|
70
|
-
"typescript": "^5.9.3",
|
|
71
|
-
"@sqrzro/prettier-config": "^4.0.0-alpha.1"
|
|
65
|
+
"typescript": "^5.9.3"
|
|
72
66
|
},
|
|
73
67
|
"peerDependencies": {
|
|
74
68
|
"next": "^16.1.6",
|
|
@@ -79,7 +73,6 @@
|
|
|
79
73
|
"clean": "rimraf ./dist",
|
|
80
74
|
"dev": "tsup --watch",
|
|
81
75
|
"lint": "tsc --noEmit && eslint \"./src/**/*.ts\"",
|
|
82
|
-
"prettier": "prettier --write \"./src/**/*.ts\"",
|
|
83
76
|
"start": "pnpm dev",
|
|
84
77
|
"test": "jest"
|
|
85
78
|
}
|
package/dist/auth/index.d.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import { ResetType, AuthUserTable } from './utility/schema.js';
|
|
2
|
-
import { NextRequest } from 'next/server';
|
|
3
|
-
import { M as MakeNullOptional } from '../interfaces-BheedaEI.js';
|
|
4
|
-
import 'drizzle-orm/pg-core';
|
|
5
|
-
|
|
6
|
-
declare function createMFA(): Promise<void>;
|
|
7
|
-
|
|
8
|
-
declare function updatePasswordWithPassword(): Promise<void>;
|
|
9
|
-
|
|
10
|
-
declare function updatePasswordWithToken(token: string, newPassword: string): Promise<void>;
|
|
11
|
-
|
|
12
|
-
declare function createReset(type: ResetType, email: string): Promise<string | null>;
|
|
13
|
-
|
|
14
|
-
declare function validateReset(type: ResetType, token: string): Promise<boolean>;
|
|
15
|
-
|
|
16
|
-
declare function createSession(userID: string, expiresIn?: number): Promise<void>;
|
|
17
|
-
|
|
18
|
-
declare function deleteSession(): Promise<void>;
|
|
19
|
-
|
|
20
|
-
declare function deleteUserSessions(): Promise<void>;
|
|
21
|
-
|
|
22
|
-
interface AuthSession {
|
|
23
|
-
expires: Date;
|
|
24
|
-
secret: string;
|
|
25
|
-
userID: string;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
declare function uncached_validateSession(cookies?: NextRequest['cookies']): Promise<AuthSession | null>;
|
|
29
|
-
declare const validateSession: typeof uncached_validateSession;
|
|
30
|
-
|
|
31
|
-
type AuthUser = AuthUserTable;
|
|
32
|
-
type AuthUserDataWithID = MakeNullOptional<AuthUser>;
|
|
33
|
-
interface User {
|
|
34
|
-
email: string;
|
|
35
|
-
id: string;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
declare function createUser(data: AuthUserDataWithID): Promise<AuthUser | null>;
|
|
39
|
-
|
|
40
|
-
declare function deleteUser(): Promise<void>;
|
|
41
|
-
|
|
42
|
-
declare function ensureSessionUser(): Promise<User>;
|
|
43
|
-
|
|
44
|
-
declare function uncached_getSessionUser(): Promise<User | null>;
|
|
45
|
-
declare function getSessionUser(): ReturnType<typeof uncached_getSessionUser>;
|
|
46
|
-
|
|
47
|
-
declare function validateUser(email: string, password: string): Promise<string>;
|
|
48
|
-
|
|
49
|
-
export { createMFA, createReset, createSession, createUser, deleteSession, deleteUser, deleteUserSessions, ensureSessionUser, getSessionUser, updatePasswordWithPassword, updatePasswordWithToken, validateReset, validateSession, validateUser };
|
package/dist/auth/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a,e as e$1,g,b as b$1,h,d,c as c$2,f as f$1}from'../chunk-QE347FVL.js';export{k as ensureSessionUser,j as getSessionUser,i as validateSession}from'../chunk-QE347FVL.js';import {a as a$1}from'../chunk-AGS5PPG2.js';import'../chunk-37TYQL5Y.js';import {c as c$1}from'../chunk-XSJ4OEIH.js';import {e,f}from'../chunk-JI2U2EMD.js';import {eq,and,isNull,gte}from'drizzle-orm';import V from'bcryptjs';import {cookies}from'next/headers';function _(){throw new Error("Function not implemented.")}var b=_;function O(){throw new Error("Function not implemented.")}var N=O;async function W(e,t){await a.delete(f).where(and(eq(f.userID,t),eq(f.type,e)));}var l=W;var F={INVITE:c$2,MFA:d,PASSWORD:d};async function M(e$2,t){let r=e$1(),o=new Date;o.setHours(o.getHours()-F[e$2]);let n=await a.select().from(f).innerJoin(e,and(eq(e.id,f.userID),eq(e.role,r),isNull(e.deletedAt))).where(and(eq(f.id,t),eq(f.type,e$2),gte(f.createdAt,o))).limit(1);return n[0]?{...n[0].resets,user:n[0].user_credentials}:null}var c=M;var q=12;async function K(e){return V.hash(e,q)}var m=K;async function X(e$1,t){let r=await c("PASSWORD",e$1);if(!r)throw new Error("RESET_TOKEN_INVALID");await a.update(e).set({password:await m(t)}).where(eq(e.id,r.userID)),await l("PASSWORD",r.userID);}var C=X;async function Y(e){return f$1("email",e)}var w=Y;var $=48;async function j(e,t){let r=await w(t);if(!r)return null;await l(e,r.id);let o=c$1(null,$);return await a.insert(f).values({createdAt:new Date,id:o,type:e,userID:r.id}),o}var z=j;async function G(e,t){return !!await c(e,t)}var J=G;function Q(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let r="";for(let o=0;o<t.length;o++)r+=e[t[o]>>3];return r}var y=Q;var ee=24,te=3600*1e3;async function re(e,t=ee){let r=e$1(),o=y(),n=y(),P=`${o}.${n}`,R=new Date(Date.now()+t*te);await g.setItem("session",o,{expires:R,role:r,secret:await m(n),userID:e}),(await cookies()).set(b$1,P,{expires:R,httpOnly:true,path:"/",sameSite:"lax",secure:true});}var oe=re;async function ie(){let e=await h();e&&(await g.removeItem("session",e.id),(await cookies()).delete(b$1));}var ae=ie;function ne(){throw new Error("Function not implemented.")}var me=ne;async function ue(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await m(e$1.password):null}).returning();return t??null}var fe=ue;function pe(){throw new Error("Function not implemented.")}var le=pe;async function ce(e,t){let r=await w(e);if(!r?.password||!await V.compare(t,r.password))throw new a$1({email:"",password:""});return r.id}var we=ce;export{b as createMFA,z as createReset,oe as createSession,fe as createUser,ae as deleteSession,le as deleteUser,me as deleteUserSessions,N as updatePasswordWithPassword,C as updatePasswordWithToken,J as validateReset,we as validateUser};//# sourceMappingURL=index.js.map
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/auth/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/mfas/create-mfa.ts","../../src/auth/passwords/update-password-with-password.ts","../../src/auth/resets/utility/delete-user-resets.ts","../../src/auth/resets/utility/get-reset-by-id.ts","../../src/auth/utility/hash-secret.ts","../../src/auth/passwords/update-password-with-token.ts","../../src/auth/users/utility/get-user-by-email.ts","../../src/auth/resets/create-reset.ts","../../src/auth/resets/validate-reset.ts","../../src/auth/utility/create-secure-random-string.ts","../../src/auth/sessions/create-session.ts","../../src/auth/sessions/delete-session.ts","../../src/auth/sessions/delete-user-sessions.ts","../../src/auth/users/create-user.ts","../../src/auth/users/delete-user.ts","../../src/auth/users/validate-user.ts"],"names":["createMFA","create_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","db_default","authResetTable","and","eq","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","role","ensure_role_default","expiry","results","authUserTable","isNull","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","getUserByEmail","email","get_user_by_default","get_user_by_email_default","TOKEN_LENGTH","createReset","user","generate_id_default","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","expires","storage_default","cookies","AUTH_COOKIE_NAME","create_session_default","deleteSession","cookie","get_session_cookie_default","delete_session_default","deleteUserSessions","delete_user_sessions_default","createUser","data","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"obAAA,SAASA,CAAAA,EAA2B,CAChC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECJf,SAASE,CAAAA,EAA4C,CACjD,MAAM,IAAI,KAAA,CAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECIf,eAAeE,CAAAA,CAAiBC,CAAAA,CAAiBC,CAAAA,CAA+B,CAC5E,MAAMC,CAAAA,CACD,OAAOC,CAAc,CAAA,CACrB,KAAA,CAAMC,GAAAA,CAAIC,EAAAA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vC,GAAI,CAACK,CAAAA,EAAM,QAAA,EAAY,CAAE,MAAMb,CAAAA,CAAO,QAAQ6C,CAAAA,CAAUhC,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIiC,GAAAA,CAAgB,CAAE,MAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,EAGzD,OAAOjC,CAAAA,CAAK,EAChB,KAEOkC,EAAAA,CAAQH","file":"index.js","sourcesContent":["function createMFA(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default createMFA;\n","function updatePasswordWithPassword(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default updatePasswordWithPassword;\n","import { and, eq } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { authResetTable } from '../../utility/schema';\n\nimport type { ResetType } from './interfaces';\n\nasync function deleteUserResets(type: ResetType, userID: string): Promise<void> {\n await db\n .delete(authResetTable)\n .where(and(eq(authResetTable.userID, userID), eq(authResetTable.type, type)));\n}\n\nexport default deleteUserResets;\n","import { and, eq, gte, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { AuthUser } from '../../users/utility/interfaces';\nimport { AUTH_INVITE_EXPIRY_HOURS, AUTH_RESET_EXPIRY_HOURS } from '../../utility/config';\nimport ensureRole from '../../utility/ensure-role';\nimport { authResetTable, authUserTable } from '../../utility/schema';\n\nimport type { AuthReset, ResetType } from './interfaces';\n\nconst EXPIRIES: Record<ResetType, number> = {\n INVITE: AUTH_INVITE_EXPIRY_HOURS,\n MFA: AUTH_RESET_EXPIRY_HOURS,\n PASSWORD: AUTH_RESET_EXPIRY_HOURS,\n};\n\nasync function getResetByID(\n type: ResetType,\n id: string\n): Promise<(AuthReset & { user: AuthUser }) | null> {\n const role = ensureRole();\n\n const expiry = new Date();\n expiry.setHours(expiry.getHours() - EXPIRIES[type]);\n\n const results = await db\n .select()\n .from(authResetTable)\n .innerJoin(\n authUserTable,\n and(\n eq(authUserTable.id, authResetTable.userID),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .where(\n and(\n eq(authResetTable.id, id),\n eq(authResetTable.type, type),\n gte(authResetTable.createdAt, expiry)\n )\n )\n .limit(1);\n\n return results[0] ? { ...results[0].resets, user: results[0].user_credentials } : null;\n}\n\nexport default getResetByID;\n","import bcrypt from 'bcryptjs';\n\nconst PW_SALT_ROUNDS = 12;\n\nasync function hashSecret(secret: string): Promise<string> {\n return bcrypt.hash(secret, PW_SALT_ROUNDS);\n}\n\nexport default hashSecret;\n","import { eq } from 'drizzle-orm';\n\nimport db from '../../utility/db';\n\nimport deleteUserResets from '../resets/utility/delete-user-resets';\nimport getResetByID from '../resets/utility/get-reset-by-id';\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nasync function updatePasswordWithToken(token: string, newPassword: string): Promise<void> {\n const reset = await getResetByID('PASSWORD', token);\n\n if (!reset) {\n throw new Error('RESET_TOKEN_INVALID');\n }\n\n await db\n .update(authUserTable)\n .set({\n password: await hashSecret(newPassword),\n })\n .where(eq(authUserTable.id, reset.userID));\n\n await deleteUserResets('PASSWORD', reset.userID);\n}\n\nexport default updatePasswordWithToken;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string): Promise<AuthUser | null> {\n return getUserBy('email', email);\n}\n\nexport default getUserByEmail;\n","import db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authResetTable } from '../utility/schema';\n\nimport deleteUserResets from './utility/delete-user-resets';\nimport type { ResetType } from './utility/interfaces';\n\nconst TOKEN_LENGTH = 48;\n\nasync function createReset(type: ResetType, email: string): Promise<string | null> {\n const user = await getUserByEmail(email);\n\n if (!user) {\n return null;\n }\n\n await deleteUserResets(type, user.id);\n\n const id = generateID(null, TOKEN_LENGTH);\n\n await db.insert(authResetTable).values({\n createdAt: new Date(),\n id,\n type,\n userID: user.id,\n });\n\n return id;\n}\n\nexport default createReset;\n","import type { ResetType } from '../utility/schema';\n\nimport getResetByID from './utility/get-reset-by-id';\n\nasync function validateReset(type: ResetType, token: string): Promise<boolean> {\n return Boolean(await getResetByID(type, token));\n}\n\nexport default validateReset;\n","function createSecureRandomString(): string {\n\t// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)\n\tconst alphabet = \"abcdefghijkmnpqrstuvwxyz23456789\";\n\n\t// Generate 24 bytes = 192 bits of entropy.\n\t// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits\n\tconst bytes = new Uint8Array(24);\n\tcrypto.getRandomValues(bytes);\n\n\tlet id = \"\";\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\t// >> 3 \"removes\" the right-most 3 bits of the byte\n\t\tid += alphabet[bytes[i] >> 3];\n\t}\n\treturn id;\n}\n\nexport default createSecureRandomString;","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport createSecureRandomString from '../utility/create-secure-random-string';\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport ensureRole from '../utility/ensure-role';\nimport hashSecret from '../utility/hash-secret';\n\nconst DEFAULT_EXPIRES = 24;\nconst HOUR_IN_MS = 60 * 60 * 1000;\n\nasync function createSession(userID: string, expiresIn = DEFAULT_EXPIRES): Promise<void> {\n const role = ensureRole();\n\n const id = createSecureRandomString();\n const secret = createSecureRandomString();\n const token = `${id}.${secret}`;\n\n const expires = new Date(Date.now() + expiresIn * HOUR_IN_MS);\n\n await serverStorage.setItem('session', id, {\n expires,\n role,\n secret: await hashSecret(secret),\n userID,\n });\n\n (await cookies()).set(AUTH_COOKIE_NAME, token, {\n expires,\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: true,\n });\n}\n\nexport default createSession;\n","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\n\nimport getSessionCookie from './utility/get-session-cookie';\n\nasync function deleteSession(): Promise<void> {\n const cookie = await getSessionCookie();\n\n if (!cookie) {\n return;\n }\n\n await serverStorage.removeItem('session', cookie.id);\n (await cookies()).delete(AUTH_COOKIE_NAME);\n}\n\nexport default deleteSession;\n","function deleteUserSessions(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUserSessions;\n","import db from '../../utility/db';\n\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nimport type { AuthUser, AuthUserDataWithID } from './utility/interfaces';\n\nasync function createUser(data: AuthUserDataWithID): Promise<AuthUser | null> {\n const [result] = await db\n .insert(authUserTable)\n .values({ ...data, password: data.password ? await hashSecret(data.password) : null })\n .returning();\n\n return result ?? null;\n}\n\nexport default createUser;\n","function deleteUser(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUser;\n","import bcrypt from 'bcryptjs';\n\nimport ValidationError from '../../forms/utility/ValidationError';\n\nimport getUserByEmail from './utility/get-user-by-email';\n\nasync function validateUser(email: string, password: string): Promise<string> {\n const user = await getUserByEmail(email);\n\n if (!user?.password || !(await bcrypt.compare(password, user.password))) {\n throw new ValidationError({ email: '', password: '' });\n }\n\n return user.id;\n}\n\nexport default validateUser;\n"]}
|