feat: add volunteer shift signup app
Initial source, tests, migrations, and local Docker setup for the Hope Food Pantry volunteer scheduler.
No files matched your search
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
data
|
||||
.git
|
||||
.env
|
||||
.env.*
|
||||
tests
|
||||
*.log
|
||||
*.md
|
||||
!README.md
|
||||
@@ -0,0 +1,47 @@
|
||||
# Local development only. Copy to .env. Do not use these values in production.
|
||||
# Production startup rejects this session secret, the console mail driver, and the Turnstile test keys.
|
||||
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
|
||||
# Public origin only. A mount prefix belongs in BASE_PATH, not here.
|
||||
BASE_URL=http://127.0.0.1:3000
|
||||
BASE_PATH=
|
||||
|
||||
# SQLite and local backups live here. npm run dev uses ./data.
|
||||
# The container uses /data, which Compose sets. Do not point DATA_DIR at the filesystem root.
|
||||
DATA_DIR=./data
|
||||
|
||||
# At least 32 characters. Production requires a random secret:
|
||||
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
||||
SESSION_SECRET=dev-only-change-me-not-for-production-use
|
||||
|
||||
DEFAULT_TZ=America/Chicago
|
||||
|
||||
# console is development-only. postmark and ses need real credentials and are not enabled by this file.
|
||||
# TODO(D1): The pantry chooses the email provider and checks the sender and reply-to.
|
||||
MAIL_DRIVER=console
|
||||
MAIL_FROM="Hope Food Pantry <volunteer@example.invalid>"
|
||||
MAIL_REPLY_TO=volunteer@example.invalid
|
||||
POSTMARK_TOKEN=
|
||||
SES_REGION=
|
||||
SES_ACCESS_KEY_ID=
|
||||
SES_SECRET_ACCESS_KEY=
|
||||
|
||||
# Cloudflare's documented always-pass test keys. They must never be used in production.
|
||||
# TODO(D5): Replace them with the real site and secret keys for the public hostname.
|
||||
TURNSTILE_SITE_KEY=1x00000000000000000000AA
|
||||
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
|
||||
|
||||
# Used by npm run sync-brand. Missing source keeps the bundled fallback.
|
||||
BRAND_SRC="../Hope Food Pantry Website/brand"
|
||||
|
||||
# TODO(D4): Reserved for the first administrator. This step does not create that account.
|
||||
BOOTSTRAP_ADMIN_EMAIL=coordinator@example.invalid
|
||||
|
||||
# false ignores forwarding headers. See README for loopback and Docker bridge examples.
|
||||
# Do not set this to true.
|
||||
TRUST_PROXY=false
|
||||
|
||||
# 127.0.0.1 keeps npm run dev on this computer. Compose sets 0.0.0.0 inside the container.
|
||||
BIND_HOST=127.0.0.1
|
||||
@@ -0,0 +1,25 @@
|
||||
# Copy to .env on the server that runs Docker Compose. Do not use the development .env.
|
||||
# Compose forces NODE_ENV=production, DATA_DIR=/data, BIND_HOST=0.0.0.0, and TRUST_PROXY=172.30.0.0/24.
|
||||
# Fill the mail and Turnstile values before starting. Gmail is not a driver yet.
|
||||
# Generate a session secret with:
|
||||
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
||||
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
BASE_URL=https://volunteer.example.org
|
||||
BASE_PATH=
|
||||
DATA_DIR=/data
|
||||
SESSION_SECRET=
|
||||
DEFAULT_TZ=America/Chicago
|
||||
MAIL_DRIVER=postmark
|
||||
MAIL_FROM=Hope Food Pantry <volunteer@example.org>
|
||||
MAIL_REPLY_TO=volunteer@example.org
|
||||
POSTMARK_TOKEN=
|
||||
SES_REGION=
|
||||
SES_ACCESS_KEY_ID=
|
||||
SES_SECRET_ACCESS_KEY=
|
||||
TURNSTILE_SITE_KEY=
|
||||
TURNSTILE_SECRET_KEY=
|
||||
BRAND_SRC=../Hope Food Pantry Website/brand
|
||||
BOOTSTRAP_ADMIN_EMAIL=coordinator@example.org
|
||||
BIND_HOST=0.0.0.0
|
||||
@@ -0,0 +1,9 @@
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.production.example
|
||||
npm-debug.log*
|
||||
*.log
|
||||
@@ -0,0 +1,29 @@
|
||||
# Hope Volunteer. Build context is this repository. Do not copy .env into the image.
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY tsconfig.json tsconfig.build.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build \
|
||||
&& npm prune --omit=dev
|
||||
|
||||
FROM node:22-slim AS runtime
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
|
||||
COPY --from=build --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=build --chown=node:node /app/dist ./dist
|
||||
COPY --chown=node:node migrations ./migrations
|
||||
COPY --chown=node:node public ./public
|
||||
COPY --chown=node:node LICENSE ./LICENSE
|
||||
RUN mkdir -p /data && chown node:node /data
|
||||
USER node
|
||||
VOLUME /data
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "-e", "const port=process.env.PORT||'3000'; const prefix=process.env.BASE_PATH||''; fetch('http://127.0.0.1:'+port+prefix+'/healthz').then((res)=>process.exit(res.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,278 @@
|
||||
# Hope Volunteer
|
||||
|
||||
Volunteer shift signup for Hope Food Pantry in Sioux Center, Iowa.
|
||||
|
||||
Copyright (C) 2026 Hope Food Pantry
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
**This is not ready for a public launch, and it is not ready for real volunteer records.** Phase 1A has public browsing, individual signup, cancellation, queued email, and coordinator sign-in for events, one-off shifts, rosters, and cancellation. A coordinator can add a walk-in, mark attendance, and move a signup from a shift roster. A volunteer can switch shifts from their private link. An active weekly template fills shifts for the next eight weeks. A coordinator can add, change, or end a weekly template, and can remove a cancelled person, a finished empty shift, an ended template, or an event that is off the public list and already empty. A confirmed signup can receive a reminder 48 hours before the shift and again 2 hours before, and can turn reminders off without cancelling. A coordinator can download a roster for one shift, one event, or a local date range. A coordinator can set the two reminder times, the reply-to address, how many months to keep a signup, and the wording on the privacy page. After 1:00 AM Central Time, signups older than that many months lose their name and contact details in this app. After 2:30 AM Central Time, the app saves a database backup on this computer. A container can run that same app on this computer, on port 3020, without opening it to the network. This is not a public launch. Around 1:00 AM in each event's time zone, the app adds any missing weekly shifts for the next eight weeks, once that local day. Development prints mail in the server log. It does not send real email.
|
||||
|
||||
## Current step
|
||||
|
||||
| Step | State |
|
||||
| --- | --- |
|
||||
| Configuration, database, time zones, fallback brand, fake seed | Done |
|
||||
| Public event and shift pages | Done |
|
||||
| Individual signup with capacity and duplicate checks | Done |
|
||||
| Cancel your own signup from its private link | Done |
|
||||
| Confirmation and cancellation email | Done |
|
||||
| Coordinator sign-in, events, one-off shifts, roster, and cancellation | Done |
|
||||
| Add a walk-in from a shift roster | Done |
|
||||
| Mark attendance on a shift roster | Done |
|
||||
| Move a signup to another shift | Done |
|
||||
| Switch your own signup to another shift | Done |
|
||||
| Manage other signups from one private link | Disabled; requires a separate verified identity flow |
|
||||
| Add weekly shifts for the next eight weeks | Done |
|
||||
| Add, change, or end a weekly template | Done |
|
||||
| Remove a cancelled person, a finished shift, an ended template, or an empty hidden event | Done |
|
||||
| Reminder emails, 48 hours and 2 hours, with a way to stop them | Done |
|
||||
| Download a roster for a shift, an event, or a date range | Done |
|
||||
| Set reminder times, reply-to, privacy wording, and retention months | Done |
|
||||
| Refill weekly shifts around 1:00 AM in each event time zone | Done |
|
||||
| Remove personal details after the saved retention period | Done |
|
||||
| Save a database backup after 2:30 AM Central Time | Done |
|
||||
| Run the app in Docker and check that a restart keeps the database | Ready for review |
|
||||
|
||||
The core tables for later steps are already in `migrations/001_init.sql`. Behavior for those tables is not built yet. While this database only holds fake seed data, the schema can still change by replacing that first migration. After a database you care about has applied it, the app refuses to start if the file is edited. Add a new numbered file instead.
|
||||
|
||||
## Decisions still open
|
||||
|
||||
Do not treat this repository as an approved privacy policy or an approved operating setup.
|
||||
|
||||
- [ ] **D1.** The pantry chooses the email provider and verifies the sender and reply-to.
|
||||
- [ ] **D2.** Whether a group signup is essential. A shared email can already sign up more than one person on the same shift. Each person takes one spot and gets their own confirmation and private link. The same person, matched by name and email, cannot take a second spot on that shift. `group_size` stays 1. Group signup still needs its own decision: who the reservation is for, how minors work, what happens when the count changes, and who receives mail.
|
||||
- [ ] **D3.** The pantry approves privacy wording, minor and guardian requirements, and retention periods, including copies and exports.
|
||||
- [ ] **D4.** The pantry confirms the coordinator list, who owns the administrator account, and the recovery contact.
|
||||
- [ ] **D5.** Configure production Turnstile keys and the allowed hostname.
|
||||
- [ ] **D6.** The host owner confirms the offsite backup destination, who owns it, the recovery target, and a restore test.
|
||||
|
||||
## TODO(Phase 2)
|
||||
|
||||
SignUpGenius importer. Do not build this until an actual export file and the duplicate-handling rules are known.
|
||||
|
||||
Password login, waitlists, volunteer accounts, SMS, analytics, and payments are out of scope.
|
||||
|
||||
## Local setup
|
||||
|
||||
Requires Node 22.
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
npm install
|
||||
npm test
|
||||
npm run seed
|
||||
```
|
||||
|
||||
`npm run dev` serves the site on `127.0.0.1` at `BASE_URL` (from `.env`, `http://127.0.0.1:3000`). It is loopback only. Stop it with Ctrl+C.
|
||||
|
||||
Open `/` for the weekly pantry schedule. `/e/weekly-pantry` is the same seeded event. `/privacy` is the unapproved privacy notice. `/healthz` returns `{"ok":true,"database":"ok"}` and nothing else. Volunteer names, emails, and notes are not on the public list. A shift shows how many spots are filled, such as 3/5 spots filled. A shift with space left uses a soft green label. A full shift uses a soft red label.
|
||||
|
||||
An open shift has a signup form. It asks for one person. Another person can use the same email and takes another spot. The same person cannot take a second spot. It asks for a parent or guardian when the volunteer is under 18. The form needs JavaScript because of the Turnstile check. Wait a few seconds after the page loads before submitting. The confirmation page shows a private link and says a confirmation email is queued. That page works without JavaScript. Cancel this signup there to open the spot again. A cancellation email is queued, and a confirmation that has not been sent yet is dropped. That person can sign up again once the cancellation is saved. Someone else can use the email while the first signup is still confirmed. A cancelled signup stays on that private page until the link expires. A private link controls only that signup. Use the separate link for each signup.
|
||||
|
||||
With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. Postmark and SES are implemented and stay unselected until the pantry chooses a provider.
|
||||
|
||||
Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password.
|
||||
|
||||
After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling keeps the roster. It does not delete the shift or the signup. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued.
|
||||
|
||||
On an open shift, **Add a walk-in** records one person who is here. It takes one spot, uses the same person rule as the public form, and queues a confirmation email. The name stays off the public list. A full, cancelled, or ended shift does not take a walk-in.
|
||||
|
||||
On a confirmed signup, **Attended** and **No-show** record whether that person came. **Clear** removes the mark. The mark stays on the roster. It does not send email, and it does not change how many spots are open. A cancelled signup cannot be marked.
|
||||
|
||||
**Move to** puts that person on another open shift in the same event. The first shift gets its spot back and keeps the signup as cancelled. The other shift takes one spot. A change email is queued, and a reminder that is still waiting is dropped. The old private link stops working. The new link is in the change email. A full, cancelled, or ended shift cannot receive the person. A shift that already has that person cannot receive them again. Someone else at the same email can. A failed move leaves them on the original shift.
|
||||
|
||||
On the private signup page, **Switch to** does the same thing for the volunteer. The next page has the new link. A full, cancelled, ended, or unpublished shift is not offered. A switch is rejected if that name and email already occupy the destination shift. The destination list does not reveal which other shifts match those details. If the switch cannot be saved, the original signup stays.
|
||||
|
||||
Public switching permits 10 validated attempts per IP per 10-minute window and 5 per recipient per local calendar day (`DEFAULT_TZ`). Volunteer and guardian addresses share the same recipient counter; a shared address is counted once. These HMAC-keyed counters live in SQLite and survive link changes, new signup IDs, and restarts. A blocked request returns HTTP 429 with `Retry-After`, leaves the signup unchanged, and queues no email. Invalid origins, invalid proofs, and completed replays do not spend recipient allowances. Valid attempts that fail because a destination is full or unavailable still count. Viewing or cancelling a signup remains available when switching is limited. Coordinator roster moves use their authenticated workflow and are not subject to these public switch limits.
|
||||
|
||||
**Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies, email, and guardian copies. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately.
|
||||
|
||||
**Add weekly shifts**, on a coordinator event page, fills the next eight weeks from that event's active weekly templates. Starting the app does the same thing for every event. A shift that is already on that date stays as it is, including a cancelled one, so the template cannot recreate it. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped.
|
||||
|
||||
**Add a weekly template** saves a repeating role, day, and time. **Edit this template** changes later weeks only. Shifts already on the schedule keep their role, time, and number of spots. **End this template** stops later weeks from being added. It does not cancel shifts already listed, and it does not email anyone.
|
||||
|
||||
**Remove from roster** deletes a cancelled signup, including the name, email, and notes. A confirmed signup has to be cancelled first. **Remove this shift** deletes a cancelled or ended shift after the roster is empty. If that date came from a weekly template that is still active, the next weekly fill can add the date again. **Remove this template** deletes an ended template. The shifts stay on the schedule and are no longer tied to that weekly pattern. **Remove this event** asks for confirmation, then deletes that event and the shifts, weekly templates, and signups on it, including names and emails. An event on the public list comes off that list. It does not send email. Other events stay.
|
||||
|
||||
A reminder is queued at each saved time before a confirmed signup, while the shift has not started. The defaults are 48 hours before and 2 hours before. The check runs every five minutes. If the app was off and more than one reminder is already due, only the closest one is sent. A person who signs up after an earlier reminder was due does not get that missed reminder. A reminder is not sent after the shift starts. Changing the shift, moving the signup, or cancelling it drops a reminder that has not been sent yet. Mail that was already accepted cannot be recalled. **Stop reminder emails**, on the private signup page or in the reminder itself, turns reminders off for that signup. The signup stays. Confirmation, change, and cancellation emails still arrive. The reminder asks the person to use the link in the confirmation email to cancel. Mail sent to the reply-to address is read by the pantry.
|
||||
|
||||
**Download this roster**, on a shift, and **Download this event**, on an event, save a spreadsheet of the signups. **Download this date range**, on the coordinator page, uses each event's local shift date. The file includes cancelled signups and attendance. A cell that would be a spreadsheet formula is saved as text. The download is not cached. A copy on a coordinator's computer is outside this app, and the app does not delete it later.
|
||||
|
||||
**Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration.
|
||||
|
||||
Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and **Add weekly shifts**, still fill the schedule as well.
|
||||
|
||||
After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, guardian, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. The minor answer is cleared. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk.
|
||||
|
||||
Finished mail loses its recipient, subject, and body 30 days after it was sent, cancelled, or given up on. Mail that is still waiting after 30 days is cancelled and cleared, so it is not sent late. Mail for a signup is cleared in the same cleanup that removes that signup's details. A sign-in message is cleared once its link is used or expired. Every hour, the app clears those sign-in messages, finished mail past 30 days, expired sign-in sessions, used or expired sign-in links, and rate-limit counters older than about two days. Audit notes older than 24 months are deleted. Those notes are counts and ids. Starting the app runs this cleanup before it accepts requests. If 1:00 AM happens twice when the clocks change, the second hour does not run it again. A restart after 1:00 AM still runs it when that date was missed.
|
||||
|
||||
After 2:30 AM Central Time, once that local date, the app saves a copy of the database in the backups folder next to the live database. The copy is made with SQLite's backup tool, then stored as one ordinary database file, so it stays consistent even while the app is running. Copying `app.db` by itself is not a substitute. The app keeps 14 daily copies and 8 Sunday copies. A copy made before a signup is cleared still has the old details until that copy is old enough to be removed. These files stay on this computer. The app does not encrypt them and does not send them anywhere else. Offsite storage is still decision D6.
|
||||
|
||||
If 2:30 AM does not exist when the clocks spring forward, the backup runs once the local clock is past 2:30. A second check the same day does not save another copy. A failed backup leaves the older copies in place and tries again on the next check. A backup taken before a migration in production is a separate file and is not removed by this schedule. The coordinator page says when the newest daily copy was saved, or that it is behind.
|
||||
|
||||
`npm run seed` refuses to run when `NODE_ENV=production`. The people in the seed are fake and use `@example.invalid` addresses. The weekly template is stored. The seed command itself does not add those weekly shifts; starting the app does. Seeding again refuses until you delete the development database file.
|
||||
|
||||
`npm run sync-brand` copies `BRAND_SRC/tokens.css` and `fonts/` into `public/brand/`. The sibling website does not have that brand directory yet. A missing source keeps the bundled tokens and prints a warning. Font files are copied unchanged. No fonts are downloaded from Google.
|
||||
|
||||
## Configuration
|
||||
|
||||
`.env.example` lists every variable. The app reads them only through `src/config.ts`.
|
||||
|
||||
`BASE_URL` is the public origin, such as `http://127.0.0.1:3000` or `https://example.org`. `BASE_PATH` is an optional mount prefix, empty by default or `/volunteer` later. A path on `BASE_URL` is rejected so the prefix lives in one place. Trailing slashes are removed. Routes, assets, cookie paths, and future mail links all go through `src/url.ts`.
|
||||
|
||||
Production startup rejects:
|
||||
|
||||
- missing configuration
|
||||
- `http://` or a local hostname in `BASE_URL`
|
||||
- Cloudflare's documented Turnstile test keys
|
||||
- `MAIL_DRIVER=console`
|
||||
- missing credentials for Postmark or SES when that driver is selected
|
||||
- a session secret shorter than 32 characters, a placeholder, or a secret that does not look random
|
||||
|
||||
Development may use the console driver and the always-pass Turnstile test keys in `.env.example`. Those keys are not a launch setting. The console driver prints mail in the development server log and does not contact a provider. Choosing Postmark or SES is a separate decision, and this copy of the app must not send real mail until that is configured on purpose.
|
||||
|
||||
`DATA_DIR` defaults to `/data`. Local development uses `./data`. The database file is `app.db` inside that directory.
|
||||
|
||||
`BOOTSTRAP_ADMIN_EMAIL` is the address used to create the first administrator, and only when no coordinator exists yet. The app does not overwrite an existing account. Password login is not built. `password_hash` stays empty.
|
||||
|
||||
## Time
|
||||
|
||||
`src/time.ts` uses `@js-temporal/polyfill`. Node 22 does not provide a stable Temporal API. The polyfill rejects a local time that falls in a daylight-saving gap or overlap instead of moving it.
|
||||
|
||||
Stored instants look like `2026-01-15T15:00:00.000Z`. Local dates stay `YYYY-MM-DD`. Local times stay `HH:MM`. Weekday `0` is Sunday. A 9:00 shift in `America/Chicago` stays 9:00 local in January and in July. The default zone is `America/Chicago`.
|
||||
|
||||
Shifts in this version must start and end on the same day. Overnight templates are later work. A coordinator can add, change, or end a weekly template. Ending it does not cancel shifts already on the schedule. The eight-week fill also runs around 1:00 AM in each event's time zone, once that local date. It still runs when the app starts and when a coordinator uses Add weekly shifts.
|
||||
|
||||
## Database
|
||||
|
||||
SQLite runs in WAL mode with foreign keys on. Migrations in `migrations/` are applied once, in order, at startup. Each applied file is stored with a SHA-256 checksum. A failed migration stops startup and rolls back that file. In production, a database that already has migrations is backed up with SQLite's backup API before a new migration runs. Copying the live `app.db` file by itself is not a consistent backup while WAL mode is on.
|
||||
|
||||
There is no cascade delete. A shift that still has signups cannot be deleted out from under the roster. A coordinator cancels a signup or a shift first. Removing a cancelled person, then an empty finished shift, is a separate step. Removing an ended template leaves its shifts in place. An event can be removed only when it is off the public list and nothing remains on it.
|
||||
|
||||
Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. A minor who is not anonymized needs a guardian name and email. `group_size` cannot be anything but 1.
|
||||
|
||||
`reminders_sent.queued_at` means the reminder was queued. `sent_at` means a provider accepted it. Queueing mail is not delivery. A closer reminder that replaces an older overdue one is stored as not sent.
|
||||
|
||||
## Client IP and a future Caddy proxy
|
||||
|
||||
`TRUST_PROXY` defaults to `false`. Forwarding headers from the public internet are ignored, and the client address is the TCP peer.
|
||||
|
||||
Do not set `TRUST_PROXY=true`. Name the proxy:
|
||||
|
||||
- `loopback` when Caddy on the same machine connects to a non-Docker process on `127.0.0.1`
|
||||
- the Compose subnet, `172.30.0.0/24`, when the app is in a container. The peer is the bridge gateway under Docker, or the container's own address under rootless Podman, and never `127.0.0.1` inside the container
|
||||
|
||||
With `TRUST_PROXY=false` behind a proxy, every visitor arrives from the proxy's address and shares one set of rate limits. Eleven sign-in requests in an hour would then lock out every coordinator. Production startup prints a warning when `TRUST_PROXY` is false and the app listens on `0.0.0.0`.
|
||||
|
||||
The app reads `X-Forwarded-For` only from that peer, and only when the header is a single IP. Caddy has to replace any client-supplied forwarding header. A list of addresses is ignored, because the left-most address can be forged if the proxy appends instead of replacing. `BASE_URL` decides https links. A client cannot turn on secure cookies by sending `X-Forwarded-Proto`.
|
||||
|
||||
## Docker
|
||||
|
||||
The image is built from this repository with `docker build -t hope-volunteer .`. It uses Node 22, compiles the app, keeps production packages, and runs as the image's `node` user, which is uid 1000. The database and backups live in `/data`. The image does not contain `.env`.
|
||||
|
||||
`compose.yaml` publishes `127.0.0.1:3020` to port 3000 inside the container. It sets production mode, `DATA_DIR=/data`, and `BIND_HOST=0.0.0.0` so the published port can connect. `npm run dev` stays on `127.0.0.1`. Compose reads the other settings from `.env`. The development `.env` in this project will not start the container, because production refuses the console mail driver, the Turnstile test keys, and an `http://` address.
|
||||
|
||||
Create the data directory before the first start and give it to uid 1000. Do not make it writable by everyone:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
sudo chown 1000:1000 data
|
||||
sudo chmod 700 data
|
||||
```
|
||||
|
||||
Copy `.env.production.example` to `.env` on the server and fill in the mail provider, Turnstile keys, public `https` address, and session secret. Protect the filled `.env` with `chmod 600 .env`. Then:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`http://127.0.0.1:3020/healthz` should return `{"ok":true,"database":"ok"}`. A restart keeps `./data`. Backups are written under `./data/backups` by that same user. Copying only `app.db` while the app is running is not a consistent backup. Restoring a saved copy is described in `scripts/restore-backup.md`. Sending those copies off this computer is still decision D6.
|
||||
|
||||
When Caddy is on the host and the app is in a container, `TRUST_PROXY` is the Compose subnet, not `loopback`. `compose.yaml` pins the network to `172.30.0.0/24` and sets `TRUST_PROXY=172.30.0.0/24`. Under Docker the peer is the gateway, `172.30.0.1`. Under rootless Podman 5 with pasta, the port forwarder connects from the container's own address on that network, such as `172.30.0.2`. Trusting the subnet covers both. Only this service is on that network, and the port is published on `127.0.0.1` only. Do not attach other containers to it. If that subnet is already used on the host, change the subnet, gateway, and `TRUST_PROXY` together. Check it once on the real host: send requests through Caddy from two clients and confirm one is not limited by the other's attempts. The Caddy snippets below stay on the host. They are not started by Compose. HTTPS ends at Caddy. The container does not obtain a certificate.
|
||||
|
||||
Gmail is not a mail driver. Production still expects Postmark or SES until that choice is built.
|
||||
|
||||
```caddy
|
||||
volunteer.example.org {
|
||||
request_body {
|
||||
max_size 65536
|
||||
}
|
||||
@private_links path /m/* /u/* /login/link/*
|
||||
log_skip @private_links
|
||||
reverse_proxy 127.0.0.1:3020 {
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
header_up -X-Forwarded-Host
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For a `/volunteer` prefix, forward the path through to the app. Do not strip it if `BASE_PATH=/volunteer`.
|
||||
|
||||
```caddy
|
||||
example.org {
|
||||
@private_links path /volunteer/m/* /volunteer/u/* /volunteer/login/link/*
|
||||
log_skip @private_links
|
||||
@volunteer path /volunteer /volunteer/*
|
||||
handle @volunteer {
|
||||
request_body {
|
||||
max_size 65536
|
||||
}
|
||||
reverse_proxy 127.0.0.1:3020 {
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security and deployment checks
|
||||
|
||||
Every response has a Content Security Policy, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and a `Permissions-Policy` that turns off camera, microphone, location, payment, and USB. When `BASE_URL` is https, responses also send `Strict-Transport-Security: max-age=31536000` for this host only. It does not use `includeSubDomains`, so other pantry subdomains are not affected.
|
||||
|
||||
The app limits request bodies to 64 KiB before parsing. Caddy examples apply the same limit. Rejected origins and rate-limited signup/login requests do not parse and redisplay submitted fields. Turnstile has a 10-second deadline; Postmark and SES have 15-second deadlines. A mail timeout is an uncertain delivery, not an automatic resend. SES automatic retries are disabled to avoid duplicate sends after ambiguous failures.
|
||||
|
||||
Compose uses a read-only root filesystem, drops all capabilities, prevents privilege escalation, and limits the container to 512 MiB memory, one CPU, and 100 processes. `/data` remains writable and `/tmp` is a bounded temporary filesystem. Adjust resource limits using measured usage. The app runs as uid 1000. Local snapshots remain on the same disk and are not an offsite backup.
|
||||
|
||||
Before deployment, verify these on the actual host:
|
||||
|
||||
- Set `TRUST_PROXY` to the observed Docker bridge peer, then verify different clients have independent limits and forged forwarding headers cannot change their identity.
|
||||
- Confirm the public HTTPS origin, real Turnstile hostname/action checks, and coordinator/volunteer mail delivery.
|
||||
- Validate the Caddyfile before reloading it. The examples use [request_body](https://caddyserver.com/docs/caddyfile/directives/request_body) and [log_skip](https://caddyserver.com/docs/caddyfile/directives/log_skip). Do not enable debug logging or record bearer URLs in upstream/CDN logs. The skip rules protect matched access logs, not every possible diagnostic log.
|
||||
- Restrict access to `.env`, `/data`, and backup copies. The app runs with umask `077`, so the database, its WAL files, and new backups are readable only by uid 1000. At startup it also sets `0600` on an existing database and backup files it owns. Select an offsite destination, protect its credentials, and restore a snapshot into a separate temporary database before relying on it.
|
||||
|
||||
## Brand
|
||||
|
||||
`public/brand/tokens.css` is the bundled fallback from the October 14, 2026 specification. `public/css/app.css` uses those variables. Lexend and Charm are named in the font stack and fall back to `system-ui` and `cursive` until OFL files are synced into `public/brand/fonts/`. Ink `#222` on yellow `#f9e194` is about 15.7:1.
|
||||
|
||||
## Host recovery
|
||||
|
||||
There is no web page that resets a coordinator. On the machine that holds the database, this revokes that person's sessions and unused sign-in links:
|
||||
|
||||
```bash
|
||||
node --env-file=.env --import tsx scripts/recover-coordinator.mjs coordinator@example.invalid
|
||||
```
|
||||
|
||||
If they cannot reach the old mailbox, replace the address and revoke the old sessions in the same step:
|
||||
|
||||
```bash
|
||||
node --env-file=.env --import tsx scripts/recover-coordinator.mjs old@example.invalid --replace new@example.invalid
|
||||
```
|
||||
|
||||
In the container, run the built copy. It uses the container's configuration and database, and the running app sees the change at once:
|
||||
|
||||
```bash
|
||||
docker compose exec hope-volunteer node dist/recover-coordinator.js old@example.invalid --replace new@example.invalid
|
||||
```
|
||||
|
||||
There is one administrator. The address set in `BOOTSTRAP_ADMIN_EMAIL` at the first production start becomes that account. Changing `.env` later does not change it. Use `--replace` to move the account to another address. Before the pantry's mailbox becomes the sign-in address, turn on 2-Step Verification for it: anyone who can read that inbox can sign in.
|
||||
|
||||
The command prints the coordinator id, not the address. It does not deactivate anyone. Deactivating coordinators in the browser is not built. Do not delete the last administrator without another one ready. The person then requests a new sign-in link at `/login`.
|
||||
|
||||
## What is still unverified
|
||||
|
||||
Real inbox delivery, a production host, and a public launch. The container was checked on this computer with a temporary database, separate from the development database: it starts, the weekly page loads, `/healthz` answers, a path prefix is included in that health address, and a restart keeps the database. The development settings were refused. This computer does not have the Docker daemon running, so that check used Podman. It has not been deployed. Decision D6 is still open. The console driver only prints mail. Gmail is not connected. The privacy page is waiting on decision D3 and is not a privacy policy. A real Turnstile hostname check still needs the production keys from decision D5. Development uses Cloudflare's always-pass test keys. Those keys succeed with hostname `example.com` and no action, so the hostname and action checks apply to real keys. Coordinator sign-in is covered here with the console driver, not with a real inbox.
|
||||
@@ -0,0 +1,37 @@
|
||||
services:
|
||||
hope-volunteer:
|
||||
build: .
|
||||
image: hope-volunteer
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
DATA_DIR: /data
|
||||
PORT: "3000"
|
||||
BIND_HOST: 0.0.0.0
|
||||
# The published port arrives from this network: the gateway under Docker,
|
||||
# the container's own address under rootless Podman. See README before changing the subnet.
|
||||
TRUST_PROXY: 172.30.0.0/24
|
||||
volumes:
|
||||
- ./data:/data
|
||||
ports:
|
||||
- "127.0.0.1:3020:3000"
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
pids_limit: 100
|
||||
tmpfs:
|
||||
- /tmp:size=16m,mode=1777
|
||||
restart: unless-stopped
|
||||
|
||||
# A fixed subnet keeps the gateway, and so TRUST_PROXY, the same when the network is recreated.
|
||||
networks:
|
||||
default:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.30.0.0/24
|
||||
gateway: 172.30.0.1
|
||||
@@ -0,0 +1,322 @@
|
||||
-- Hope Volunteer core schema.
|
||||
-- Instants are UTC text: YYYY-MM-DDTHH:MM:SS.SSSZ
|
||||
-- Local dates are YYYY-MM-DD. Local times are HH:MM. Weekday 0 is Sunday.
|
||||
-- Foreign keys and WAL are enabled on each connection, not in this file.
|
||||
-- Applied files are checksummed. Add a new migration instead of editing this one
|
||||
-- after it has been applied to a database you need to keep.
|
||||
-- Deletes do not cascade. Cancelling a shift keeps the roster.
|
||||
|
||||
CREATE TABLE coordinators (
|
||||
id INTEGER PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE CHECK (
|
||||
instr(email, '@') > 1
|
||||
AND email = lower(email)
|
||||
AND instr(email, ' ') = 0
|
||||
),
|
||||
name TEXT NOT NULL CHECK (length(trim(name)) > 0),
|
||||
role TEXT NOT NULL CHECK (role IN ('admin', 'coordinator')),
|
||||
-- Password login is deferred. Leave this NULL.
|
||||
password_hash TEXT NULL,
|
||||
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id_hash TEXT PRIMARY KEY,
|
||||
coordinator_id INTEGER NOT NULL REFERENCES coordinators (id) ON DELETE NO ACTION,
|
||||
csrf TEXT NOT NULL CHECK (length(csrf) > 0),
|
||||
expires_at TEXT NOT NULL CHECK (
|
||||
expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
last_seen_at TEXT NOT NULL CHECK (
|
||||
last_seen_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE login_tokens (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
coordinator_id INTEGER NOT NULL REFERENCES coordinators (id) ON DELETE NO ACTION,
|
||||
expires_at TEXT NOT NULL CHECK (
|
||||
expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
used_at TEXT NULL CHECK (
|
||||
used_at IS NULL
|
||||
OR used_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE events (
|
||||
id INTEGER PRIMARY KEY,
|
||||
slug TEXT NOT NULL UNIQUE CHECK (
|
||||
length(slug) BETWEEN 1 AND 80
|
||||
AND slug NOT GLOB '*[^a-z0-9-]*'
|
||||
AND slug NOT GLOB '-*'
|
||||
AND slug NOT GLOB '*-'
|
||||
),
|
||||
title TEXT NOT NULL CHECK (length(trim(title)) > 0),
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
location TEXT NOT NULL DEFAULT '',
|
||||
tz TEXT NOT NULL CHECK (length(trim(tz)) > 0),
|
||||
published INTEGER NOT NULL DEFAULT 0 CHECK (published IN (0, 1)),
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE shift_templates (
|
||||
id INTEGER PRIMARY KEY,
|
||||
event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE NO ACTION,
|
||||
role TEXT NOT NULL CHECK (length(trim(role)) > 0),
|
||||
weekday INTEGER NOT NULL CHECK (weekday BETWEEN 0 AND 6),
|
||||
start_local TEXT NOT NULL CHECK (
|
||||
start_local GLOB '[0-9][0-9]:[0-5][0-9]'
|
||||
AND start_local < '24:00'
|
||||
),
|
||||
end_local TEXT NOT NULL CHECK (
|
||||
end_local GLOB '[0-9][0-9]:[0-5][0-9]'
|
||||
AND end_local < '24:00'
|
||||
),
|
||||
capacity INTEGER NOT NULL CHECK (capacity > 0),
|
||||
starts_on TEXT NOT NULL CHECK (starts_on GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'),
|
||||
ends_on TEXT NULL CHECK (
|
||||
ends_on IS NULL
|
||||
OR ends_on GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
|
||||
),
|
||||
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
|
||||
revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
|
||||
CHECK (end_local > start_local)
|
||||
);
|
||||
|
||||
CREATE TABLE shifts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE NO ACTION,
|
||||
template_id INTEGER NULL REFERENCES shift_templates (id) ON DELETE NO ACTION,
|
||||
occurrence_date TEXT NULL CHECK (
|
||||
occurrence_date IS NULL
|
||||
OR occurrence_date GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
|
||||
),
|
||||
template_revision INTEGER NULL CHECK (template_revision IS NULL OR template_revision > 0),
|
||||
role TEXT NOT NULL CHECK (length(trim(role)) > 0),
|
||||
starts_at_utc TEXT NOT NULL CHECK (
|
||||
starts_at_utc GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
ends_at_utc TEXT NOT NULL CHECK (
|
||||
ends_at_utc GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
capacity INTEGER NOT NULL CHECK (capacity > 0),
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
cancelled INTEGER NOT NULL DEFAULT 0 CHECK (cancelled IN (0, 1)),
|
||||
manually_modified INTEGER NOT NULL DEFAULT 0 CHECK (manually_modified IN (0, 1)),
|
||||
version INTEGER NOT NULL DEFAULT 1 CHECK (version > 0),
|
||||
CHECK (ends_at_utc > starts_at_utc),
|
||||
-- A generated occurrence keeps its date even when cancelled, so regeneration cannot recreate it.
|
||||
CHECK (
|
||||
(
|
||||
template_id IS NULL
|
||||
AND occurrence_date IS NULL
|
||||
AND template_revision IS NULL
|
||||
)
|
||||
OR (
|
||||
template_id IS NOT NULL
|
||||
AND occurrence_date IS NOT NULL
|
||||
AND template_revision IS NOT NULL
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Includes cancelled occurrences. One-off shifts stay outside this index.
|
||||
CREATE UNIQUE INDEX shifts_one_row_per_occurrence
|
||||
ON shifts (template_id, occurrence_date)
|
||||
WHERE template_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX shifts_by_event_start ON shifts (event_id, starts_at_utc);
|
||||
|
||||
CREATE TABLE signups (
|
||||
id INTEGER PRIMARY KEY,
|
||||
shift_id INTEGER NOT NULL REFERENCES shifts (id) ON DELETE NO ACTION,
|
||||
name TEXT NULL,
|
||||
email TEXT NULL,
|
||||
email_norm TEXT NULL,
|
||||
phone TEXT NULL,
|
||||
is_minor INTEGER NOT NULL DEFAULT 0 CHECK (is_minor IN (0, 1)),
|
||||
guardian_name TEXT NULL,
|
||||
guardian_email TEXT NULL,
|
||||
-- TODO(D2): Individual signup only. group_size stays 1 until the pantry says groups are required.
|
||||
group_size INTEGER NOT NULL DEFAULT 1 CHECK (group_size = 1),
|
||||
notes TEXT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('confirmed', 'cancelled')),
|
||||
manage_token_hash TEXT NULL UNIQUE,
|
||||
token_expires_at TEXT NULL CHECK (
|
||||
token_expires_at IS NULL
|
||||
OR token_expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
reminders_off INTEGER NOT NULL DEFAULT 0 CHECK (reminders_off IN (0, 1)),
|
||||
attended INTEGER NULL CHECK (attended IS NULL OR attended IN (0, 1)),
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
updated_at TEXT NOT NULL CHECK (
|
||||
updated_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
anonymized_at TEXT NULL CHECK (
|
||||
anonymized_at IS NULL
|
||||
OR anonymized_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
CHECK (
|
||||
(
|
||||
anonymized_at IS NULL
|
||||
AND name IS NOT NULL
|
||||
AND length(trim(name)) > 0
|
||||
AND email IS NOT NULL
|
||||
AND email_norm IS NOT NULL
|
||||
)
|
||||
OR (
|
||||
anonymized_at IS NOT NULL
|
||||
AND name IS NULL
|
||||
AND email IS NULL
|
||||
AND email_norm IS NULL
|
||||
AND phone IS NULL
|
||||
AND guardian_name IS NULL
|
||||
AND guardian_email IS NULL
|
||||
AND notes IS NULL
|
||||
AND manage_token_hash IS NULL
|
||||
AND token_expires_at IS NULL
|
||||
)
|
||||
),
|
||||
CHECK (
|
||||
anonymized_at IS NOT NULL
|
||||
OR is_minor = 0
|
||||
OR (
|
||||
guardian_name IS NOT NULL
|
||||
AND length(trim(guardian_name)) > 0
|
||||
AND guardian_email IS NOT NULL
|
||||
AND length(trim(guardian_email)) > 0
|
||||
)
|
||||
),
|
||||
CHECK (
|
||||
email_norm IS NULL
|
||||
OR (
|
||||
email_norm = lower(email_norm)
|
||||
AND instr(email_norm, ' ') = 0
|
||||
AND instr(email_norm, '@') > 1
|
||||
AND instr(email_norm, char(10)) = 0
|
||||
AND instr(email_norm, char(13)) = 0
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- NULL email_norm does not collide, so anonymized rows can share a shift.
|
||||
CREATE UNIQUE INDEX signups_one_confirmed_email_per_shift
|
||||
ON signups (shift_id, email_norm)
|
||||
WHERE status = 'confirmed' AND email_norm IS NOT NULL;
|
||||
|
||||
CREATE INDEX signups_by_shift ON signups (shift_id, status);
|
||||
|
||||
CREATE INDEX signups_by_email_norm
|
||||
ON signups (email_norm)
|
||||
WHERE email_norm IS NOT NULL;
|
||||
|
||||
CREATE TABLE outbox (
|
||||
id INTEGER PRIMARY KEY,
|
||||
dedupe_key TEXT NOT NULL UNIQUE,
|
||||
signup_id INTEGER NULL REFERENCES signups (id) ON DELETE NO ACTION,
|
||||
shift_id INTEGER NULL REFERENCES shifts (id) ON DELETE NO ACTION,
|
||||
-- confirmation, changed, cancelled, reminder, magic_link, manage_recovery
|
||||
kind TEXT NOT NULL CHECK (
|
||||
kind IN ('confirmation', 'changed', 'cancelled', 'reminder', 'magic_link', 'manage_recovery')
|
||||
),
|
||||
-- Pending mail can contain raw manage or login links. Treat the row as sensitive.
|
||||
to_email TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
body_text TEXT NOT NULL,
|
||||
body_html TEXT NOT NULL,
|
||||
headers_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(headers_json)),
|
||||
send_after TEXT NOT NULL CHECK (
|
||||
send_after GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
|
||||
status TEXT NOT NULL CHECK (
|
||||
status IN ('pending', 'sending', 'sent', 'failed', 'cancelled', 'delivery_unknown')
|
||||
),
|
||||
provider_id TEXT NULL,
|
||||
last_error TEXT NULL,
|
||||
created_at TEXT NOT NULL CHECK (
|
||||
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
claimed_at TEXT NULL CHECK (
|
||||
claimed_at IS NULL
|
||||
OR claimed_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
lease_expires_at TEXT NULL CHECK (
|
||||
lease_expires_at IS NULL
|
||||
OR lease_expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
-- sent_at means the provider accepted the message, not that the person received it.
|
||||
sent_at TEXT NULL CHECK (
|
||||
sent_at IS NULL
|
||||
OR sent_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
delivery_unknown_at TEXT NULL CHECK (
|
||||
delivery_unknown_at IS NULL
|
||||
OR delivery_unknown_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_by_status_send_after ON outbox (status, send_after);
|
||||
|
||||
-- queued_at means the reminder was queued. sent_at means the provider accepted it.
|
||||
-- kind here is the offset identity, such as 48h, together with shift_version.
|
||||
CREATE TABLE reminders_sent (
|
||||
signup_id INTEGER NOT NULL REFERENCES signups (id) ON DELETE NO ACTION,
|
||||
kind TEXT NOT NULL CHECK (length(kind) > 0),
|
||||
shift_version INTEGER NOT NULL CHECK (shift_version > 0),
|
||||
outbox_id INTEGER NOT NULL REFERENCES outbox (id) ON DELETE NO ACTION,
|
||||
queued_at TEXT NOT NULL CHECK (
|
||||
queued_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
sent_at TEXT NULL CHECK (
|
||||
sent_at IS NULL
|
||||
OR sent_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
PRIMARY KEY (signup_id, kind, shift_version)
|
||||
);
|
||||
|
||||
CREATE TABLE audit (
|
||||
id INTEGER PRIMARY KEY,
|
||||
coordinator_id INTEGER NULL REFERENCES coordinators (id) ON DELETE NO ACTION,
|
||||
action TEXT NOT NULL CHECK (length(action) > 0),
|
||||
detail_json TEXT NOT NULL CHECK (json_valid(detail_json)),
|
||||
at TEXT NOT NULL CHECK (
|
||||
at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX audit_by_time ON audit (at);
|
||||
|
||||
CREATE TABLE rate_hits (
|
||||
key TEXT NOT NULL,
|
||||
window_start TEXT NOT NULL CHECK (
|
||||
window_start GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
count INTEGER NOT NULL CHECK (count >= 0),
|
||||
PRIMARY KEY (key, window_start)
|
||||
);
|
||||
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value_json TEXT NOT NULL CHECK (json_valid(value_json)),
|
||||
updated_at TEXT NOT NULL CHECK (
|
||||
updated_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_by_coordinator ON sessions (coordinator_id);
|
||||
CREATE INDEX login_tokens_by_coordinator ON login_tokens (coordinator_id);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- A repeated submit of the same form reuses this key instead of taking another spot.
|
||||
ALTER TABLE signups ADD COLUMN operation_key TEXT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX signups_operation_key
|
||||
ON signups (operation_key)
|
||||
WHERE operation_key IS NOT NULL;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- One successful daily job per scope and local date. A repeated clock hour does not run it again.
|
||||
CREATE TABLE job_runs (
|
||||
job TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
local_date TEXT NOT NULL CHECK (local_date GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'),
|
||||
ran_at TEXT NOT NULL CHECK (
|
||||
ran_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||
),
|
||||
PRIMARY KEY (job, scope, local_date)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- A shared inbox can sign up more than one person on the same shift.
|
||||
-- The same person, matched by name without regard to case, still takes only one spot.
|
||||
DROP INDEX signups_one_confirmed_email_per_shift;
|
||||
|
||||
CREATE UNIQUE INDEX signups_one_confirmed_person_per_shift
|
||||
ON signups (shift_id, email_norm, name COLLATE NOCASE)
|
||||
WHERE status = 'confirmed' AND email_norm IS NOT NULL AND name IS NOT NULL;
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "hope-volunteer",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Volunteer shift signup for Hope Food Pantry in Sioux Center, Iowa.",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx watch --env-file=.env src/main.ts",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node --env-file=.env dist/main.js",
|
||||
"test": "vitest run",
|
||||
"sync-brand": "node scripts/sync-brand.mjs",
|
||||
"seed": "node --env-file=.env --import tsx scripts/seed-dev.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-sesv2": "^3.1151.0",
|
||||
"@hono/node-server": "^2.1.5",
|
||||
"@js-temporal/polyfill": "^0.5.1",
|
||||
"better-sqlite3": "^13.0.3",
|
||||
"hono": "^4.13.13",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^9.6.0",
|
||||
"@types/node": "^26.6.5",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^7.0.2",
|
||||
"vitest": "^5.0.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"source": null,
|
||||
"syncedAt": null,
|
||||
"note": "Bundled Lexend (variable, latin) and Charm (400 and 700, latin) so the app matches hopefoodpantrysc.org without loading fonts from Google. Both families are under the SIL Open Font License; the license text is beside the font files.",
|
||||
"fonts": [
|
||||
{
|
||||
"file": "lexend-latin.woff2",
|
||||
"bytes": 39680,
|
||||
"sha256": "b7e7538f59bff1812841d7627f8e49e70fe86438f9f7b397a028c0d05301c874"
|
||||
},
|
||||
{
|
||||
"file": "charm-400.woff2",
|
||||
"bytes": 20108,
|
||||
"sha256": "a5b1aaccacbe192e382f24fa211f57013e8844a32124f08d685262c49edff9f8"
|
||||
},
|
||||
{
|
||||
"file": "charm-700.woff2",
|
||||
"bytes": 20476,
|
||||
"sha256": "3146c99b01bc5fb2537a2b7e10a1953f4c5a614780e3a6d1124b7e884b315cd3"
|
||||
}
|
||||
],
|
||||
"licenses": [
|
||||
{
|
||||
"file": "fonts/Lexend-OFL.txt",
|
||||
"bytes": 4314,
|
||||
"sha256": "18aabf190848725e2576eefb5c29ba06aac1029d02132252a7f312eac2e50cf3"
|
||||
},
|
||||
{
|
||||
"file": "fonts/Charm-OFL.txt",
|
||||
"bytes": 4314,
|
||||
"sha256": "18aabf190848725e2576eefb5c29ba06aac1029d02132252a7f312eac2e50cf3"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Font files synced from the brand source are stored in this directory.
|
||||
@@ -0,0 +1,93 @@
|
||||
Google Inc.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Google Inc.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,19 @@
|
||||
/* Hope Volunteer brand tokens
|
||||
Source: bundled fallback from the October 14, 2026 specification
|
||||
Synced: not synced
|
||||
This is the fallback. scripts/sync-brand.mjs replaces this file when BRAND_SRC contains tokens.css.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--hope-blue-50:#f4fafd;
|
||||
--hope-blue-75:#ecf7fc;
|
||||
--hope-blue-100:#e4f3fb;
|
||||
--hope-yellow:#f9e194;
|
||||
--hope-gold:#fbcd62;
|
||||
--hope-ink:#222;
|
||||
--hope-ink-2:#444;
|
||||
--hope-border:#b6c2c9;
|
||||
--hope-border-2:#cddbe2;
|
||||
--font-body:"Lexend",system-ui,sans-serif;
|
||||
--font-script:"Charm",cursive;
|
||||
}
|
||||
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
class="ionicon"
|
||||
viewBox="0 0 512 512"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
sodipodi:docname="close.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="1.8945312"
|
||||
inkscape:cx="255.47217"
|
||||
inkscape:cy="256.00001"
|
||||
inkscape:window-width="2226"
|
||||
inkscape:window-height="1179"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1" />
|
||||
<path
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="32"
|
||||
d="M368 368L144 144M368 144L144 368"
|
||||
id="path1"
|
||||
style="fill:none;fill-opacity:1;stroke:#222222;stroke-opacity:1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
enable-background="new 0 0 64 64"
|
||||
height="64px"
|
||||
id="Layer_1"
|
||||
version="1.1"
|
||||
viewBox="0 0 64 64"
|
||||
width="64px"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="facebook.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><defs
|
||||
id="defs1" /><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="15.5625"
|
||||
inkscape:cx="31.967871"
|
||||
inkscape:cy="32"
|
||||
inkscape:window-width="2259"
|
||||
inkscape:window-height="1199"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="Layer_1" /><path
|
||||
d="M32,7.174C18.311,7.174,7.174,18.311,7.174,32c0,13.689,11.137,24.826,24.826,24.826c13.689,0,24.826-11.137,24.826-24.826 C56.826,18.311,45.689,7.174,32,7.174z M38.174,32.874h-4.039c0,6.453,0,14.398,0,14.398h-5.985c0,0,0-7.868,0-14.398h-2.845v-5.088 h2.845v-3.291c0-2.357,1.12-6.04,6.04-6.04l4.433,0.017v4.939c0,0-2.695,0-3.219,0c-0.524,0-1.268,0.262-1.268,1.386v2.99h4.56 L38.174,32.874z"
|
||||
id="path1"
|
||||
style="fill:#222222;fill-opacity:1" /></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="56.7px"
|
||||
id="Layer_1"
|
||||
style="enable-background:new 0 0 56.7 56.7;"
|
||||
version="1.1"
|
||||
viewBox="0 0 56.7 56.7"
|
||||
width="56.7px"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="instagram.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><defs
|
||||
id="defs2" /><sodipodi:namedview
|
||||
id="namedview2"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="17.566137"
|
||||
inkscape:cx="28.378464"
|
||||
inkscape:cy="28.35"
|
||||
inkscape:window-width="2259"
|
||||
inkscape:window-height="1199"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="Layer_1" /><g
|
||||
id="g2"
|
||||
style="fill:#222222;fill-opacity:1"><circle
|
||||
cx="28.1"
|
||||
cy="30"
|
||||
r="4.4"
|
||||
id="circle1"
|
||||
style="fill:#222222;fill-opacity:1" /><path
|
||||
d="M33.6,19.2h-11c-1.6,0-3,0.5-3.9,1.4c-0.9,0.9-1.4,2.3-1.4,3.9v11c0,1.6,0.5,3,1.5,4c1,0.9,2.3,1.4,3.9,1.4h10.9 c1.6,0,3-0.5,3.9-1.4c1-0.9,1.5-2.3,1.5-3.9v-11c0-1.6-0.5-2.9-1.4-3.9C36.6,19.7,35.3,19.2,33.6,19.2z M28.1,36.8 c-3.8,0-6.8-3.1-6.8-6.8c0-3.8,3.1-6.8,6.8-6.8S35,26.2,35,30C35,33.8,31.9,36.8,28.1,36.8z M35.2,24.5c-0.9,0-1.6-0.7-1.6-1.6 s0.7-1.6,1.6-1.6s1.6,0.7,1.6,1.6S36.1,24.5,35.2,24.5z"
|
||||
id="path1"
|
||||
style="fill:#222222;fill-opacity:1" /><path
|
||||
d="M28.3,5.2c-13.6,0-24.6,11-24.6,24.6c0,13.6,11,24.6,24.6,24.6c13.6,0,24.6-11,24.6-24.6C53,16.2,41.9,5.2,28.3,5.2z M41.4,35.6c0,2.3-0.8,4.3-2.2,5.7c-1.4,1.4-3.4,2.1-5.6,2.1H22.7c-2.2,0-4.2-0.7-5.6-2.1c-1.5-1.4-2.2-3.4-2.2-5.7v-11 c0-4.6,3.1-7.8,7.8-7.8h11c2.3,0,4.2,0.8,5.6,2.2c1.4,1.4,2.1,3.3,2.1,5.6V35.6z"
|
||||
id="path2"
|
||||
style="fill:#222222;fill-opacity:1" /></g></svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
class="ionicon"
|
||||
viewBox="0 0 512 512"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
sodipodi:docname="menu.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="1.8945312"
|
||||
inkscape:cx="255.47217"
|
||||
inkscape:cy="256.00001"
|
||||
inkscape:window-width="2226"
|
||||
inkscape:window-height="1179"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1" />
|
||||
<path
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-linecap="round"
|
||||
stroke-miterlimit="10"
|
||||
stroke-width="32"
|
||||
d="M80 160h352M80 256h352M80 352h352"
|
||||
id="path1"
|
||||
style="stroke:#222222;stroke-opacity:1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,121 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
width="23"
|
||||
height="30"
|
||||
id="screenshot-e54a0bcf-30e2-8041-8006-cb975f859ff4"
|
||||
viewBox="0 0 23 30"
|
||||
fill="none"
|
||||
version="1.1"
|
||||
sodipodi:docname="right-arrow.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs3" />
|
||||
<sodipodi:namedview
|
||||
id="namedview3"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="32.533333"
|
||||
inkscape:cx="11.495902"
|
||||
inkscape:cy="15"
|
||||
inkscape:window-width="2226"
|
||||
inkscape:window-height="1179"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="screenshot-e54a0bcf-30e2-8041-8006-cb975f859ff4" />
|
||||
<g
|
||||
id="shape-e54a0bcf-30e2-8041-8006-cb975f859ff4"
|
||||
class="ionicon"
|
||||
rx="0"
|
||||
ry="0"
|
||||
style="fill:#000000"
|
||||
transform="rotate(-90,11.5,14.999952)">
|
||||
<g
|
||||
id="shape-e54a0bcf-30e2-8041-8006-cb975f860eb4"
|
||||
style="display:none">
|
||||
<g
|
||||
class="fills"
|
||||
id="fills-e54a0bcf-30e2-8041-8006-cb975f860eb4">
|
||||
<rect
|
||||
width="23"
|
||||
height="30"
|
||||
x="0"
|
||||
style="fill:none"
|
||||
ry="0"
|
||||
fill="none"
|
||||
rx="0"
|
||||
y="0"
|
||||
id="rect1" />
|
||||
</g>
|
||||
<g
|
||||
fill="none"
|
||||
id="strokes-279c4329-e789-8027-8007-013b01dd0c82-e54a0bcf-30e2-8041-8006-cb975f860eb4"
|
||||
class="strokes">
|
||||
<g
|
||||
class="inner-stroke-shape"
|
||||
id="g2">
|
||||
<defs
|
||||
id="defs1">
|
||||
<clipPath
|
||||
id="inner-stroke-render-2-e54a0bcf-30e2-8041-8006-cb975f860eb4-0">
|
||||
<use
|
||||
href="#stroke-shape-render-2-e54a0bcf-30e2-8041-8006-cb975f860eb4-0"
|
||||
id="use1" />
|
||||
</clipPath>
|
||||
<rect
|
||||
rx="0"
|
||||
ry="0"
|
||||
x="0"
|
||||
y="0"
|
||||
width="23"
|
||||
height="30"
|
||||
id="stroke-shape-render-2-e54a0bcf-30e2-8041-8006-cb975f860eb4-0"
|
||||
style="fill:none;stroke:#222222;stroke-width:6;stroke-opacity:1" />
|
||||
</defs>
|
||||
<use
|
||||
href="#stroke-shape-render-2-e54a0bcf-30e2-8041-8006-cb975f860eb4-0"
|
||||
clip-path="url(#inner-stroke-render-2-e54a0bcf-30e2-8041-8006-cb975f860eb4-0)"
|
||||
id="use2" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g
|
||||
id="shape-e54a0bcf-30e2-8041-8006-cb975f86b21b">
|
||||
<g
|
||||
class="fills"
|
||||
id="fills-e54a0bcf-30e2-8041-8006-cb975f86b21b">
|
||||
<path
|
||||
d="m 5.03125,15.703125 6.46875,8.4375 6.46875,-8.4375 M 11.5,22.96875 V 5.859375"
|
||||
fill="none"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
style="fill:none"
|
||||
id="path2" />
|
||||
</g>
|
||||
<g
|
||||
fill="none"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
id="strokes-279c4329-e789-8027-8007-013b01de3225-e54a0bcf-30e2-8041-8006-cb975f86b21b"
|
||||
class="strokes">
|
||||
<g
|
||||
class="stroke-shape"
|
||||
id="g3">
|
||||
<path
|
||||
d="m 5.03125,15.703125 6.46875,8.4375 6.46875,-8.4375 M 11.5,22.96875 V 5.859375"
|
||||
style="fill:none;stroke:#222222;stroke-width:3;stroke-opacity:1"
|
||||
id="path3" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.7 KiB |
@@ -0,0 +1 @@
|
||||
<?xml version="1.0"?><svg viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg"><g id="Solid"><path d="M46.79248,24.23a4.05389,4.05389,0,0,0-5.689-.14l-7.69872,6.84a5.25608,5.25608,0,0,1,.58993,2.43,5.39055,5.39055,0,0,1-3.4794,5.02l-6.46895,2.43a1.00694,1.00694,0,0,1-1.27975-.59.98322.98322,0,0,1,.57986-1.28l6.46895-2.43A3.38021,3.38021,0,0,0,31.995,33.36,3.45753,3.45753,0,0,0,28.63555,30H9.99866A1.99982,1.99982,0,0,0,7.999,28H3.99966A1.99982,1.99982,0,0,0,2,30V46a1.99986,1.99986,0,0,0,1.99966,2H7.999a1.99986,1.99986,0,0,0,1.99967-2H14.048l1.24979.51A19.61328,19.61328,0,0,0,37.924,40.87l9.10846-11.01A4.20182,4.20182,0,0,0,46.79248,24.23ZM12.99816,44H9.99866V32h2.9995ZM30.41809,2a8.59142,8.59142,0,0,0-5.42194,1.9082A8.59147,8.59147,0,0,0,19.5742,2a8.68822,8.68822,0,0,0-8.66651,8.68945c0,9.14258,13.03,16.85059,13.58463,17.17481a1.00289,1.00289,0,0,0,1.00765,0C26.05456,27.54,39.08461,19.832,39.08461,10.68945A8.68822,8.68822,0,0,0,30.41809,2Zm-1.772,18.6571a.98319.98319,0,0,1-.65022.2229.99554.99554,0,0,1-.65047-1.7423c3.70153-3.1709,5.74025-6.17188,5.74025-8.44825A2.68158,2.68158,0,0,0,30.41809,8a1,1,0,0,1,0-2,4.68337,4.68337,0,0,1,4.66719,4.68945C35.08528,14.3681,31.584,18.13953,28.64605,20.6571Z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 110 KiB |
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
width="1920"
|
||||
height="345"
|
||||
id="screenshot-b28d1092-3bc7-8036-8006-f30481bca546"
|
||||
viewBox="-0 0 1920 345"
|
||||
fill="none"
|
||||
version="1.1"
|
||||
sodipodi:docname="wave-secondary.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs3" />
|
||||
<sodipodi:namedview
|
||||
id="namedview2"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="0.54375"
|
||||
inkscape:cx="1545.7471"
|
||||
inkscape:cy="80.91954"
|
||||
inkscape:window-width="1280"
|
||||
inkscape:window-height="732"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="screenshot-b28d1092-3bc7-8036-8006-f30481bca546" />
|
||||
<path
|
||||
d="m 1920,273.54883 -0.1328,11.59179 C 1841.6891,328.15877 1744.1902,344.94184 1634.5938,345 H 1920 Z"
|
||||
style="opacity:1;fill:#e4f3fb;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path7" />
|
||||
<path
|
||||
d="M 1633.4492,345 C 1094.9992,344.71467 265.60465,-57.844514 0,262.64844 V 345 Z"
|
||||
style="opacity:1;fill:#e4f3fb;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path6" />
|
||||
<path
|
||||
d="M 1920,167.05469 C 1494.0823,469.27673 327.70703,-128.02979 0,238.30078 v 24.34766 C 265.60465,-57.844514 1094.9992,344.71467 1633.4492,345 h 1.1446 c 109.5964,-0.0582 207.0953,-16.84123 285.2734,-59.85938 L 1920,273.54883 Z"
|
||||
style="opacity:1;fill:#f4fafd;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path5" />
|
||||
<path
|
||||
d="M 1918.7988,1.2734375 C 1558.9042,380.95114 345.17035,-152.55479 0,194 v 13 31.30078 C 327.70703,-128.02979 1494.0823,469.27673 1920,167.05469 V 1.2734375 Z"
|
||||
style="opacity:1;fill:#f9e194;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
width="1920"
|
||||
height="345"
|
||||
id="screenshot-b28d1092-3bc7-8036-8006-f30481bca546"
|
||||
viewBox="-0 0 1920 345"
|
||||
fill="none"
|
||||
version="1.1"
|
||||
sodipodi:docname="wave.svg"
|
||||
inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs3" />
|
||||
<sodipodi:namedview
|
||||
id="namedview2"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:zoom="0.54375"
|
||||
inkscape:cx="898.3908"
|
||||
inkscape:cy="79.08046"
|
||||
inkscape:window-width="2259"
|
||||
inkscape:window-height="1199"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="screenshot-b28d1092-3bc7-8036-8006-f30481bca546" />
|
||||
<path
|
||||
d="m 1920,273.54883 -0.1328,11.59179 C 1841.6891,328.15877 1744.1902,344.94184 1634.5938,345 H 1920 Z"
|
||||
style="opacity:1;fill:#f4fafd;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path7" />
|
||||
<path
|
||||
d="M 1633.4492,345 C 1094.9992,344.71467 265.60465,-57.844514 0,262.64844 V 345 Z"
|
||||
style="opacity:1;fill:#f4fafd;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path6" />
|
||||
<path
|
||||
d="M 1920,167.05469 C 1494.0823,469.27673 327.70703,-128.02979 0,238.30078 v 24.34766 C 265.60465,-57.844514 1094.9992,344.71467 1633.4492,345 h 1.1446 c 109.5964,-0.0582 207.0953,-16.84123 285.2734,-59.85938 L 1920,273.54883 Z"
|
||||
style="opacity:1;fill:#e4f3fb;stroke-width:1.5;stroke-linecap:square"
|
||||
id="path5" />
|
||||
<path
|
||||
d="M 1918.7988,1.2734375 C 1558.9042,380.95114 345.17035,-152.55479 0,194 v 13 31.30078 C 327.70703,-128.02979 1494.0823,469.27673 1920,167.05469 V 1.2734375 Z"
|
||||
style="opacity:1;fill:#f9e194;stroke-width:1.5;stroke-linecap:square;fill-opacity:1"
|
||||
id="path4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,129 @@
|
||||
(function () {
|
||||
var dialog = document.getElementById('confirm');
|
||||
if (!dialog || typeof dialog.showModal !== 'function') return;
|
||||
var form = document.getElementById('confirm-form');
|
||||
var title = document.getElementById('confirm-title');
|
||||
var detail = document.getElementById('confirm-detail');
|
||||
var body = document.getElementById('confirm-body');
|
||||
var note = document.getElementById('confirm-note');
|
||||
var submit = document.getElementById('confirm-submit');
|
||||
var cancel = document.getElementById('confirm-cancel');
|
||||
var error = document.getElementById('confirm-error');
|
||||
if (!form || !title || !detail || !body || !note || !submit || !cancel) return;
|
||||
|
||||
var text = function (link, name) {
|
||||
return link.getAttribute(name) || '';
|
||||
};
|
||||
|
||||
var chosenFor = function (name) {
|
||||
return document.querySelectorAll('input[data-pick="' + name + '"]:checked');
|
||||
};
|
||||
|
||||
var fill = function (link) {
|
||||
form.querySelectorAll('[data-picked]').forEach(function (input) {
|
||||
input.remove();
|
||||
});
|
||||
form.action = text(link, 'data-confirm-action') || link.getAttribute('href') || '';
|
||||
title.textContent = text(link, 'data-confirm-title') || 'Remove';
|
||||
body.textContent = text(link, 'data-confirm-body');
|
||||
var when = text(link, 'data-confirm-detail');
|
||||
detail.textContent = when;
|
||||
detail.hidden = when === '';
|
||||
var extra = text(link, 'data-confirm-note');
|
||||
note.textContent = extra;
|
||||
note.hidden = extra === '';
|
||||
var label = text(link, 'data-confirm-submit');
|
||||
submit.textContent = label || 'Remove';
|
||||
submit.hidden = label === '';
|
||||
submit.disabled = label === '';
|
||||
cancel.textContent = label === '' ? 'Close' : 'Cancel';
|
||||
if (error) {
|
||||
error.textContent = '';
|
||||
error.hidden = true;
|
||||
}
|
||||
var pick = link.getAttribute('data-confirm-pick');
|
||||
if (!pick) return;
|
||||
var chosen = chosenFor(pick);
|
||||
var weekly = false;
|
||||
chosen.forEach(function (box) {
|
||||
var input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = pick + '[]';
|
||||
input.value = box.value;
|
||||
input.setAttribute('data-picked', '');
|
||||
form.appendChild(input);
|
||||
if (box.getAttribute('data-weekly') === 'true') weekly = true;
|
||||
});
|
||||
detail.textContent = chosen.length === 1 ? '1 selected' : chosen.length + ' selected';
|
||||
detail.hidden = false;
|
||||
var weeklyNote = text(link, 'data-confirm-note-weekly');
|
||||
if (weekly && weeklyNote) {
|
||||
note.textContent = weeklyNote;
|
||||
note.hidden = false;
|
||||
}
|
||||
};
|
||||
|
||||
var show = function () {
|
||||
if (dialog.open) dialog.close();
|
||||
dialog.showModal();
|
||||
dialog.classList.add('is-modal');
|
||||
var focus = submit.hidden ? cancel : submit;
|
||||
if (focus) focus.focus();
|
||||
};
|
||||
|
||||
var syncPicks = function () {
|
||||
document.querySelectorAll('[data-confirm-pick]').forEach(function (control) {
|
||||
var name = control.getAttribute('data-confirm-pick');
|
||||
control.hidden = !name || chosenFor(name).length === 0;
|
||||
});
|
||||
document.querySelectorAll('[data-pick-all]').forEach(function (all) {
|
||||
var name = all.getAttribute('data-pick-all');
|
||||
if (!name) return;
|
||||
var boxes = document.querySelectorAll('input[data-pick="' + name + '"]');
|
||||
var checked = chosenFor(name);
|
||||
all.checked = boxes.length > 0 && checked.length === boxes.length;
|
||||
all.indeterminate = checked.length > 0 && checked.length < boxes.length;
|
||||
});
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-confirm]').forEach(function (link) {
|
||||
link.addEventListener('click', function (event) {
|
||||
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
var pick = link.getAttribute('data-confirm-pick');
|
||||
if (pick && chosenFor(pick).length === 0) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
fill(link);
|
||||
show();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-pick-all]').forEach(function (all) {
|
||||
all.addEventListener('change', function () {
|
||||
var name = all.getAttribute('data-pick-all');
|
||||
if (!name) return;
|
||||
var checked = all.checked;
|
||||
document.querySelectorAll('input[data-pick="' + name + '"]').forEach(function (box) {
|
||||
box.checked = checked;
|
||||
});
|
||||
syncPicks();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('input[data-pick]').forEach(function (box) {
|
||||
box.addEventListener('change', syncPicks);
|
||||
});
|
||||
|
||||
dialog.addEventListener('click', function (event) {
|
||||
if (event.target === dialog) dialog.close();
|
||||
});
|
||||
|
||||
dialog.addEventListener('close', function () {
|
||||
if (!dialog.open) dialog.classList.remove('is-modal');
|
||||
});
|
||||
|
||||
syncPicks();
|
||||
if (dialog.open) show();
|
||||
})();
|
||||
@@ -0,0 +1,65 @@
|
||||
(function () {
|
||||
var key = 'hope-place';
|
||||
var place = null;
|
||||
try {
|
||||
var raw = sessionStorage.getItem(key);
|
||||
if (raw) {
|
||||
sessionStorage.removeItem(key);
|
||||
place = JSON.parse(raw);
|
||||
}
|
||||
} catch (err) {
|
||||
place = null;
|
||||
}
|
||||
var restore = place && place.path === location.pathname && typeof place.y === 'number' && place.y > 0;
|
||||
if (restore && 'scrollRestoration' in history) history.scrollRestoration = 'manual';
|
||||
|
||||
var scrollToY = function (y) {
|
||||
var root = document.documentElement;
|
||||
var previous = root.style.scrollBehavior;
|
||||
root.style.scrollBehavior = 'auto';
|
||||
window.scrollTo(0, y);
|
||||
root.scrollTop = y;
|
||||
if (document.body) document.body.scrollTop = y;
|
||||
root.style.scrollBehavior = previous;
|
||||
};
|
||||
|
||||
if (restore) scrollToY(place.y);
|
||||
|
||||
document.addEventListener(
|
||||
'submit',
|
||||
function (event) {
|
||||
var form = event.target;
|
||||
if (!form || !form.hasAttribute || !form.hasAttribute('data-keep-place')) return;
|
||||
var y = window.scrollY || document.documentElement.scrollTop || (document.body ? document.body.scrollTop : 0) || 0;
|
||||
try {
|
||||
sessionStorage.setItem(key, JSON.stringify({ path: location.pathname, y: y }));
|
||||
} catch (err) {}
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
var bind = function () {
|
||||
if (restore) scrollToY(place.y);
|
||||
if (location.search.indexOf('notice=') !== -1) {
|
||||
try {
|
||||
var url = new URL(location.href);
|
||||
if (url.searchParams.has('notice')) {
|
||||
url.searchParams.delete('notice');
|
||||
history.replaceState(null, '', url.pathname + url.search + url.hash);
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
document.querySelectorAll('[data-dismiss-notice]').forEach(function (button) {
|
||||
button.addEventListener('click', function () {
|
||||
var notice = button.closest('[data-notice]');
|
||||
if (notice) notice.remove();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bind);
|
||||
else bind();
|
||||
window.addEventListener('load', function () {
|
||||
if (restore) scrollToY(place.y);
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,54 @@
|
||||
(function () {
|
||||
bindCalendar();
|
||||
var boxes = document.querySelectorAll('[data-under-18]');
|
||||
for (var i = 0; i < boxes.length; i += 1) bind(boxes[i]);
|
||||
|
||||
function bindCalendar() {
|
||||
var calendar = document.querySelector('.shift-calendar');
|
||||
var weeks = document.querySelectorAll('.cal-week');
|
||||
if (!calendar || !weeks.length) return;
|
||||
calendar.classList.add('js');
|
||||
var wide = window.matchMedia('(min-width: 42.001em) and (max-width: 75em)');
|
||||
var syncAll = function () {
|
||||
for (var i = 0; i < weeks.length; i += 1) syncWeek(weeks[i], wide.matches);
|
||||
};
|
||||
for (var i = 0; i < weeks.length; i += 1) {
|
||||
var details = weeks[i].querySelectorAll('details.day-reveal');
|
||||
for (var j = 0; j < details.length; j += 1) details[j].addEventListener('toggle', syncAll);
|
||||
}
|
||||
if (wide.addEventListener) wide.addEventListener('change', syncAll);
|
||||
syncAll();
|
||||
}
|
||||
|
||||
function syncWeek(week, wide) {
|
||||
var tray = week.querySelector('.week-tray');
|
||||
if (!tray) return;
|
||||
var details = week.querySelectorAll('details.day-reveal');
|
||||
for (var i = 0; i < details.length; i += 1) {
|
||||
var detail = details[i];
|
||||
var date = detail.getAttribute('data-date');
|
||||
if (!date || !detail.parentNode) continue;
|
||||
var drawer = week.querySelector('.shift-drawer[data-date="' + date + '"]');
|
||||
if (!drawer) continue;
|
||||
if (wide && detail.open) {
|
||||
if (drawer.parentNode !== tray) tray.appendChild(drawer);
|
||||
} else if (drawer.parentNode === tray) {
|
||||
detail.parentNode.appendChild(drawer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bind(box) {
|
||||
var form = box.form;
|
||||
if (!form) return;
|
||||
var guardian = form.querySelector('[data-guardian]');
|
||||
if (!guardian) return;
|
||||
var inputs = guardian.querySelectorAll('input');
|
||||
var sync = function () {
|
||||
var on = box.checked;
|
||||
for (var j = 0; j < inputs.length; j += 1) inputs[j].required = on;
|
||||
};
|
||||
box.addEventListener('change', sync);
|
||||
sync();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,34 @@
|
||||
(function () {
|
||||
var dialog = document.getElementById('new-event');
|
||||
if (!dialog || typeof dialog.showModal !== 'function') return;
|
||||
|
||||
var show = function () {
|
||||
if (dialog.open) dialog.close();
|
||||
dialog.showModal();
|
||||
dialog.classList.add('is-modal');
|
||||
var field = dialog.querySelector('input[name="title"]');
|
||||
if (field) field.focus();
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-open-event]').forEach(function (link) {
|
||||
link.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
if (dialog.open && dialog.classList.contains('is-modal')) {
|
||||
var field = dialog.querySelector('input[name="title"]');
|
||||
if (field) field.focus();
|
||||
return;
|
||||
}
|
||||
show();
|
||||
});
|
||||
});
|
||||
|
||||
dialog.addEventListener('click', function (event) {
|
||||
if (event.target === dialog) dialog.close();
|
||||
});
|
||||
|
||||
dialog.addEventListener('close', function () {
|
||||
if (!dialog.open) dialog.classList.remove('is-modal');
|
||||
});
|
||||
|
||||
if (dialog.open) show();
|
||||
})();
|
||||
@@ -0,0 +1,2 @@
|
||||
// Development entry point. The command itself is src/recover-coordinator.ts, which the image builds into dist/.
|
||||
import '../src/recover-coordinator.ts';
|
||||
@@ -0,0 +1,39 @@
|
||||
# Restore a local backup
|
||||
|
||||
This puts a saved copy back into the live data directory on this computer. It does not test an offsite copy. Offsite storage is still decision D6.
|
||||
|
||||
Stop the app first. A restore while Hope Volunteer is running can leave a half-written database.
|
||||
|
||||
1. Stop the container, or stop `npm run dev` if that is what is running.
|
||||
2. Copy the current data directory aside, including `app.db`, `app.db-wal`, and `app.db-shm`, so you can put it back if the restore is wrong.
|
||||
3. Pick one file from `data/backups`. Daily copies are named `daily-YYYY-MM-DD.db`. Sunday copies are named `weekly-YYYY-MM-DD.db`. A file named `pre-migrate-` is the database from before a production migration, not the daily schedule.
|
||||
4. Check the file before replacing the live database:
|
||||
|
||||
```bash
|
||||
sqlite3 data/backups/daily-YYYY-MM-DD.db "PRAGMA integrity_check;"
|
||||
```
|
||||
|
||||
The result should be `ok`.
|
||||
5. Replace the live database with that file. Remove any `app.db-wal` and `app.db-shm` left from the old live database. The saved copy is one file and does not need those sidecars.
|
||||
|
||||
```bash
|
||||
rm -f data/app.db data/app.db-wal data/app.db-shm
|
||||
cp data/backups/daily-YYYY-MM-DD.db data/app.db
|
||||
```
|
||||
|
||||
6. While the app is still stopped, revoke sign-in cookies from the restored copy and hold mail that was waiting. Otherwise a restored cookie still signs a coordinator in, and waiting messages are sent after startup.
|
||||
|
||||
```bash
|
||||
sqlite3 data/app.db "DELETE FROM sessions; DELETE FROM login_tokens; UPDATE outbox SET status = 'cancelled', last_error = 'Held after a restore.' WHERE status IN ('pending', 'sending');"
|
||||
```
|
||||
|
||||
7. If Docker runs the app, the `node` user inside the image must be able to write the data directory. That user is uid 1000. Do not make the directory writable by everyone.
|
||||
|
||||
```bash
|
||||
sudo chown 1000:1000 data data/app.db
|
||||
sudo chmod 750 data
|
||||
```
|
||||
|
||||
8. Start the app again. Startup still removes personal details that are past the retention period. Check `/healthz` and a roster before treating the restore as finished.
|
||||
|
||||
A backup taken before a cleanup still contains the old names and email addresses. Restoring it brings those details back into the live database.
|
||||
@@ -0,0 +1,6 @@
|
||||
import { runSeedCli } from '../src/dev/seed.ts';
|
||||
|
||||
runSeedCli().catch((err) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const HEADER_RE = /^\/\* Hope Volunteer brand tokens[\s\S]*?\*\/\r?\n+/;
|
||||
const LICENSE_NAMES = new Set(['OFL.txt', 'OFL.md', 'LICENSE', 'LICENSE.txt', 'LICENSE.md']);
|
||||
|
||||
/**
|
||||
* Copy tokens.css and fonts from BRAND_SRC into public/brand.
|
||||
* This is a development and build-prep step, not a runtime dependency.
|
||||
* A missing source keeps the files already in public/brand.
|
||||
*/
|
||||
export function syncBrand({ source, dest, syncedAt }) {
|
||||
const resolvedSource = path.resolve(source);
|
||||
const resolvedDest = path.resolve(dest);
|
||||
const warnings = [];
|
||||
if (!fs.existsSync(resolvedSource) || !fs.statSync(resolvedSource).isDirectory()) {
|
||||
warnings.push(
|
||||
`Brand source not found at ${resolvedSource}. Keeping the existing assets in ${resolvedDest}.`,
|
||||
);
|
||||
return { copied: false, warnings, fonts: [] };
|
||||
}
|
||||
|
||||
fs.mkdirSync(resolvedDest, { recursive: true });
|
||||
const tokensPath = path.join(resolvedSource, 'tokens.css');
|
||||
if (!isFile(tokensPath)) {
|
||||
warnings.push(`No tokens.css in ${resolvedSource}. Keeping the current tokens.css.`);
|
||||
} else {
|
||||
const css = fs.readFileSync(tokensPath, 'utf8');
|
||||
const body = css.replace(HEADER_RE, '');
|
||||
const header = `/* Hope Volunteer brand tokens\n Source: ${resolvedSource}\n Synced: ${syncedAt}\n Generated by scripts/sync-brand.mjs. Do not add this header to font files.\n*/\n`;
|
||||
replaceFile(path.join(resolvedDest, 'tokens.css'), header + body);
|
||||
}
|
||||
|
||||
const fontsDest = path.join(resolvedDest, 'fonts');
|
||||
fs.mkdirSync(fontsDest, { recursive: true });
|
||||
const fonts = [];
|
||||
const fontsSource = path.join(resolvedSource, 'fonts');
|
||||
if (fs.existsSync(fontsSource) && fs.statSync(fontsSource).isDirectory()) {
|
||||
for (const entry of fs.readdirSync(fontsSource, { withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
const from = path.join(fontsSource, entry.name);
|
||||
const to = path.join(fontsDest, entry.name);
|
||||
replaceFile(to, fs.readFileSync(from));
|
||||
fonts.push(fileRecord(entry.name, to));
|
||||
}
|
||||
}
|
||||
|
||||
const licenses = [];
|
||||
for (const name of LICENSE_NAMES) {
|
||||
const from = path.join(resolvedSource, name);
|
||||
if (!isFile(from)) continue;
|
||||
const to = path.join(resolvedDest, name);
|
||||
replaceFile(to, fs.readFileSync(from));
|
||||
licenses.push(fileRecord(name, to));
|
||||
}
|
||||
|
||||
const manifest = {
|
||||
source: resolvedSource,
|
||||
syncedAt,
|
||||
note:
|
||||
fonts.length === 0
|
||||
? 'No self-hosted font files were in the source. The app falls back to system-ui and cursive. Files already in the destination that were not in the source were left in place.'
|
||||
: 'Files already in the destination that were not in the source were left in place.',
|
||||
fonts,
|
||||
licenses,
|
||||
};
|
||||
replaceFile(path.join(resolvedDest, 'fonts.manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
return { copied: true, warnings, fonts };
|
||||
}
|
||||
|
||||
function replaceFile(destination, contents) {
|
||||
const temporary = `${destination}.next`;
|
||||
fs.writeFileSync(temporary, contents);
|
||||
fs.renameSync(temporary, destination);
|
||||
}
|
||||
|
||||
function fileRecord(file, fullPath) {
|
||||
const bytes = fs.readFileSync(fullPath);
|
||||
return {
|
||||
file,
|
||||
bytes: bytes.length,
|
||||
sha256: crypto.createHash('sha256').update(bytes).digest('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
function isFile(file) {
|
||||
return fs.existsSync(file) && fs.statSync(file).isFile();
|
||||
}
|
||||
|
||||
function readEnvFile(file) {
|
||||
if (!fs.existsSync(file)) return;
|
||||
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed === '' || trimmed.startsWith('#')) continue;
|
||||
const eq = trimmed.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
const key = trimmed.slice(0, eq).trim();
|
||||
let value = trimmed.slice(eq + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
if (process.env[key] === undefined) process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const entry = process.argv[1];
|
||||
if (entry && import.meta.url === pathToFileURL(path.resolve(entry)).href) {
|
||||
readEnvFile(path.join(projectRoot, '.env'));
|
||||
const source = process.env.BRAND_SRC ?? '../Hope Food Pantry Website/brand';
|
||||
const result = syncBrand({
|
||||
source,
|
||||
dest: path.join(projectRoot, 'public/brand'),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
for (const warning of result.warnings) console.warn(warning);
|
||||
if (result.copied) console.log(`Brand sync wrote ${result.fonts.length} font file(s).`);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { assertSameDayShift, LocalTimeError } from '../time.js';
|
||||
|
||||
export type EventValues = {
|
||||
title: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: boolean;
|
||||
};
|
||||
|
||||
export type EventInput = {
|
||||
title: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: boolean;
|
||||
};
|
||||
|
||||
export type ShiftValues = {
|
||||
role: string;
|
||||
date: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: string;
|
||||
};
|
||||
|
||||
export type ShiftInput = {
|
||||
role: string;
|
||||
date: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: number;
|
||||
};
|
||||
|
||||
export function eventValuesFrom(body: Record<string, unknown>, fallbackTz: string): EventValues {
|
||||
return {
|
||||
title: text(body, 'title'),
|
||||
slug: text(body, 'slug'),
|
||||
description: text(body, 'description'),
|
||||
location: text(body, 'location'),
|
||||
tz: text(body, 'tz') || fallbackTz,
|
||||
published: text(body, 'published') === 'yes',
|
||||
};
|
||||
}
|
||||
|
||||
export function parseEvent(values: EventValues): { ok: true; value: EventInput } | { ok: false; error: string } {
|
||||
const title = values.title.trim();
|
||||
if (title.length === 0) return { ok: false, error: 'Enter a title.' };
|
||||
if (title.length > 120) return { ok: false, error: 'Use a shorter title.' };
|
||||
const slug = values.slug.trim() ? normalizeSlug(values.slug) : normalizeSlug(title);
|
||||
if (!validSlug(slug)) return { ok: false, error: 'Use a public address with lowercase letters, numbers, and hyphens.' };
|
||||
const description = values.description.trim();
|
||||
if (description.length > 2000) return { ok: false, error: 'Use a shorter description.' };
|
||||
const location = values.location.trim();
|
||||
if (location.length > 200) return { ok: false, error: 'Use a shorter location.' };
|
||||
const tz = values.tz.trim();
|
||||
if (tz.length === 0) return { ok: false, error: 'Enter a time zone.' };
|
||||
return { ok: true, value: { title, slug, description, location, tz, published: values.published } };
|
||||
}
|
||||
|
||||
export function shiftValuesFrom(body: Record<string, unknown>): ShiftValues {
|
||||
return {
|
||||
role: text(body, 'role'),
|
||||
date: text(body, 'date'),
|
||||
start: clock(text(body, 'start')),
|
||||
end: clock(text(body, 'end')),
|
||||
capacity: text(body, 'capacity'),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseShift(values: ShiftValues): { ok: true; value: ShiftInput } | { ok: false; error: string } {
|
||||
const role = values.role.trim();
|
||||
if (role.length === 0) return { ok: false, error: 'Enter a role.' };
|
||||
if (role.length > 80) return { ok: false, error: 'Use a shorter role.' };
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(values.date)) return { ok: false, error: 'Enter a date.' };
|
||||
if (!/^\d{2}:\d{2}$/.test(values.start)) return { ok: false, error: 'Enter a start time as HH:MM.' };
|
||||
if (!/^\d{2}:\d{2}$/.test(values.end)) return { ok: false, error: 'Enter an end time as HH:MM.' };
|
||||
if (!/^[1-9][0-9]*$/.test(values.capacity)) return { ok: false, error: 'Enter a capacity of at least 1.' };
|
||||
const capacity = Number(values.capacity);
|
||||
if (!Number.isSafeInteger(capacity) || capacity > 500) return { ok: false, error: 'Capacity cannot be more than 500.' };
|
||||
return { ok: true, value: { role, date: values.date, start: values.start, end: values.end, capacity } };
|
||||
}
|
||||
|
||||
export type TemplateValues = {
|
||||
role: string;
|
||||
weekday: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: string;
|
||||
startsOn: string;
|
||||
endsOn: string;
|
||||
};
|
||||
|
||||
export type TemplateInput = {
|
||||
role: string;
|
||||
weekday: number;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: number;
|
||||
startsOn: string;
|
||||
endsOn: string | null;
|
||||
};
|
||||
|
||||
export function templateValuesFrom(body: Record<string, unknown>): TemplateValues {
|
||||
return {
|
||||
role: text(body, 'role'),
|
||||
weekday: text(body, 'weekday'),
|
||||
start: clock(text(body, 'start')),
|
||||
end: clock(text(body, 'end')),
|
||||
capacity: text(body, 'capacity'),
|
||||
startsOn: text(body, 'startsOn'),
|
||||
endsOn: text(body, 'endsOn'),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseTemplate(values: TemplateValues): { ok: true; value: TemplateInput } | { ok: false; error: string } {
|
||||
const role = values.role.trim();
|
||||
if (role.length === 0) return { ok: false, error: 'Enter a role.' };
|
||||
if (role.length > 80) return { ok: false, error: 'Use a shorter role.' };
|
||||
if (!/^[0-6]$/.test(values.weekday)) return { ok: false, error: 'Choose a day.' };
|
||||
try {
|
||||
assertSameDayShift(values.start, values.end);
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) return { ok: false, error: err.message };
|
||||
throw err;
|
||||
}
|
||||
if (!calendarDate(values.startsOn)) return { ok: false, error: 'Enter the first date.' };
|
||||
const endsOn = values.endsOn.trim();
|
||||
if (endsOn.length > 0 && !calendarDate(endsOn)) return { ok: false, error: 'Enter an end date, or leave it blank.' };
|
||||
if (endsOn.length > 0 && endsOn < values.startsOn) {
|
||||
return { ok: false, error: 'The end date must be on or after the first date.' };
|
||||
}
|
||||
if (!/^[1-9][0-9]*$/.test(values.capacity)) return { ok: false, error: 'Enter a capacity of at least 1.' };
|
||||
const capacity = Number(values.capacity);
|
||||
if (!Number.isSafeInteger(capacity) || capacity > 500) return { ok: false, error: 'Capacity cannot be more than 500.' };
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
role,
|
||||
weekday: Number(values.weekday),
|
||||
start: values.start,
|
||||
end: values.end,
|
||||
capacity,
|
||||
startsOn: values.startsOn,
|
||||
endsOn: endsOn.length > 0 ? endsOn : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSlug(input: string): string {
|
||||
return input
|
||||
.normalize('NFC')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 80)
|
||||
.replace(/-+$/g, '');
|
||||
}
|
||||
|
||||
function validSlug(slug: string): boolean {
|
||||
return slug.length >= 1 && slug.length <= 80 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug);
|
||||
}
|
||||
|
||||
function calendarDate(value: string): boolean {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
try {
|
||||
Temporal.PlainDate.from(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function text(body: Record<string, unknown>, name: string): string {
|
||||
const value = body[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function clock(value: string): string {
|
||||
return /^([01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/.test(value) ? value.slice(0, 5) : value;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { bodyLimit } from 'hono/body-limit';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { registerAdmin } from './admin-http.js';
|
||||
import { readSession } from './auth/session.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { EmptySchedulePage, EventPage, Layout, NotFoundPage, PrivacyPage, ProblemPage } from './pages.js';
|
||||
import { getPublishedEvent } from './schedule.js';
|
||||
import { privacyParagraphs, readPantrySettings } from './settings.js';
|
||||
import { registerReminderOff } from './reminder-http.js';
|
||||
import { registerPublicSignup } from './signup-http.js';
|
||||
import { securityHeaders } from './security.js';
|
||||
import { nowUtc } from './time.js';
|
||||
import { appPath } from './url.js';
|
||||
|
||||
export function publicDirectory(): string {
|
||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../public');
|
||||
}
|
||||
|
||||
export function createApp(
|
||||
config: AppConfig,
|
||||
db: Database.Database,
|
||||
options?: {
|
||||
now?: string;
|
||||
publicDir?: string;
|
||||
clientIp?: (c: Context) => string | null;
|
||||
verifyTurnstile?: Parameters<typeof registerPublicSignup>[1]['verifyTurnstile'];
|
||||
},
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
const now = () => options?.now ?? nowUtc();
|
||||
const publicDir = options?.publicDir ?? publicDirectory();
|
||||
|
||||
app.use('*', securityHeaders({ https: config.secureCookies }));
|
||||
app.use('*', bodyLimit({
|
||||
maxSize: 64 * 1024,
|
||||
onError: (c) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.text('Request body too large.', 413);
|
||||
},
|
||||
}));
|
||||
app.use(appPath(config, '/css/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/brand/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/img/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/js/*'), staticFiles(config, publicDir));
|
||||
|
||||
app.get(appPath(config, '/healthz'), (c) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
db.prepare('SELECT 1 AS ok').get();
|
||||
return c.json({ ok: true, database: 'ok' });
|
||||
} catch {
|
||||
return c.json({ ok: false, database: 'unavailable' }, 503);
|
||||
}
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/'), (c) => {
|
||||
const at = now();
|
||||
const event = getPublishedEvent(db, 'weekly-pantry', at);
|
||||
if (!event) {
|
||||
return page(c, config, db, at, 'Weekly pantry · Hope Volunteer', <EmptySchedulePage />);
|
||||
}
|
||||
return page(
|
||||
c,
|
||||
config,
|
||||
db,
|
||||
at,
|
||||
`${event.title} · Hope Volunteer`,
|
||||
<EventPage config={config} event={event} now={at} month={c.req.query('month')} path="/" />,
|
||||
);
|
||||
});
|
||||
|
||||
if (config.basePath !== '') {
|
||||
app.get(`${config.basePath}/`, (c) => c.redirect(config.basePath, 302));
|
||||
}
|
||||
|
||||
app.get(appPath(config, '/privacy'), (c) => {
|
||||
const paragraphs = privacyParagraphs(readPantrySettings(db, config.mail.replyTo).privacyText);
|
||||
return page(c, config, db, now(), 'Privacy · Hope Volunteer', <PrivacyPage paragraphs={paragraphs} />);
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/e/:slug'), (c) => {
|
||||
const at = now();
|
||||
const slug = c.req.param('slug') ?? '';
|
||||
const event = getPublishedEvent(db, slug, at);
|
||||
if (!event) return page(c, config, db, at, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
return page(
|
||||
c,
|
||||
config,
|
||||
db,
|
||||
at,
|
||||
`${event.title} · Hope Volunteer`,
|
||||
<EventPage config={config} event={event} now={at} month={c.req.query('month')} />,
|
||||
);
|
||||
});
|
||||
|
||||
registerPublicSignup(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
verifyTurnstile: options?.verifyTurnstile,
|
||||
});
|
||||
|
||||
registerReminderOff(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
});
|
||||
|
||||
registerAdmin(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
verifyTurnstile: options?.verifyTurnstile,
|
||||
});
|
||||
|
||||
app.notFound((c) => page(c, config, db, now(), 'That page is not available · Hope Volunteer', <NotFoundPage />, 404));
|
||||
app.onError((err, c) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
return page(c, config, db, now(), 'Something went wrong · Hope Volunteer', <ProblemPage />, 500);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
function page(
|
||||
c: Context,
|
||||
config: AppConfig,
|
||||
db: Database.Database,
|
||||
now: string,
|
||||
title: string,
|
||||
body: Child,
|
||||
status: 200 | 404 | 500 = 200,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const account = readSession(db, c.req.header('cookie'), now);
|
||||
return c.html(
|
||||
<Layout config={config} title={title} path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function staticFiles(config: AppConfig, publicDir: string) {
|
||||
return serveStatic({
|
||||
root: publicDir,
|
||||
onFound: (_path, c) => {
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
},
|
||||
rewriteRequestPath: (requestPath) => {
|
||||
if (config.basePath !== '' && requestPath.startsWith(config.basePath)) {
|
||||
return requestPath.slice(config.basePath.length) || '/';
|
||||
}
|
||||
return requestPath;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
/** Records an admin or host action. Detail is ids and counts only, never addresses or notes. */
|
||||
export function writeAudit(
|
||||
db: Database.Database,
|
||||
coordinatorId: number | null,
|
||||
action: string,
|
||||
detail: Record<string, number>,
|
||||
now: string,
|
||||
): void {
|
||||
const json = JSON.stringify(detail);
|
||||
if (json.includes('@')) throw new Error('Audit detail cannot include an email address.');
|
||||
db.prepare('INSERT INTO audit (coordinator_id, action, detail_json, at) VALUES (?, ?, ?, ?)').run(
|
||||
coordinatorId,
|
||||
action,
|
||||
json,
|
||||
now,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { isUniqueConstraint } from '../sqlite-error.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
|
||||
/**
|
||||
* Inserts one administrator when the coordinators table is empty.
|
||||
* A later start does not overwrite that account, even if the configured address changed.
|
||||
*/
|
||||
export function bootstrapAdmin(db: Database.Database, email: string, now: string): { created: boolean } {
|
||||
const normalized = normalizeEmail(email);
|
||||
try {
|
||||
return db.transaction(() => {
|
||||
const count = db.prepare('SELECT COUNT(*) AS n FROM coordinators').get() as { n: number };
|
||||
if (count.n > 0) return { created: false };
|
||||
const inserted = db
|
||||
.prepare(
|
||||
`INSERT INTO coordinators (email, name, role, password_hash, active, created_at)
|
||||
VALUES (?, 'Administrator', 'admin', NULL, 1, ?)`,
|
||||
)
|
||||
.run(normalized, now);
|
||||
writeAudit(db, null, 'bootstrap', { coordinatorId: Number(inserted.lastInsertRowid) }, now);
|
||||
return { created: true };
|
||||
}).immediate();
|
||||
} catch (err) {
|
||||
if (isUniqueConstraint(err)) return { created: false };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { queueMagicLink } from '../mail/queue.js';
|
||||
import type { MailIdentity } from '../mail/types.js';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
import { insertSession } from './session.js';
|
||||
|
||||
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{20,128}$/;
|
||||
const LOGIN_PROOF = 'hope-login-v1\0';
|
||||
const LINK_MINUTES = 15;
|
||||
|
||||
export function requestMagicLink(
|
||||
db: Database.Database,
|
||||
input: { email: string; now: string; mail: MailIdentity },
|
||||
): { queued: boolean } {
|
||||
let emailNorm: string;
|
||||
try {
|
||||
emailNorm = normalizeEmail(input.email);
|
||||
} catch {
|
||||
return { queued: false };
|
||||
}
|
||||
return db.transaction(() => {
|
||||
const coordinator = db
|
||||
.prepare('SELECT id AS id, active AS active FROM coordinators WHERE email = ?')
|
||||
.get(emailNorm) as { id: number; active: number } | undefined;
|
||||
if (!coordinator || coordinator.active !== 1) return { queued: false };
|
||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, coordinator.id);
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const tokenHash = sha256(token);
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(input.now).add({ minutes: LINK_MINUTES }));
|
||||
db.prepare(
|
||||
`INSERT INTO login_tokens (token_hash, coordinator_id, expires_at, used_at, created_at)
|
||||
VALUES (?, ?, ?, NULL, ?)`,
|
||||
).run(tokenHash, coordinator.id, expiresAt, input.now);
|
||||
queueMagicLink(db, { email: emailNorm, token, tokenHash, mail: input.mail, now: input.now });
|
||||
return { queued: true };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/** Reads a sign-in link without using it. Email scanners that only open the link stop here. */
|
||||
export function loginLinkOpen(db: Database.Database, token: string, now: string): boolean {
|
||||
const row = lookup(db, token);
|
||||
return Boolean(row && row.used_at === null && row.expires_at > now && row.active === 1);
|
||||
}
|
||||
|
||||
export function consumeLoginLink(
|
||||
db: Database.Database,
|
||||
token: string,
|
||||
now: string,
|
||||
): { ok: true; sessionToken: string; csrf: string } | { ok: false } {
|
||||
if (!TOKEN_SHAPE.test(token)) return { ok: false };
|
||||
const hash = sha256(token);
|
||||
return db.transaction((): { ok: true; sessionToken: string; csrf: string } | { ok: false } => {
|
||||
const row = lookup(db, token);
|
||||
if (!row || row.used_at !== null || row.expires_at <= now || row.active !== 1) return { ok: false };
|
||||
const used = db
|
||||
.prepare(
|
||||
`UPDATE login_tokens
|
||||
SET used_at = ?
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?`,
|
||||
)
|
||||
.run(now, hash, now);
|
||||
if (used.changes !== 1) return { ok: false };
|
||||
const session = insertSession(db, row.coordinator_id, now);
|
||||
writeAudit(db, row.coordinator_id, 'login', {}, now);
|
||||
return { ok: true as const, sessionToken: session.token, csrf: session.csrf };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
export function issueLoginProof(secret: string, token: string): string {
|
||||
return createHmac('sha256', secret).update(`${LOGIN_PROOF}${token}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function loginProofMatches(secret: string, token: string, proof: string): boolean {
|
||||
const expected = issueLoginProof(secret, token);
|
||||
if (!TOKEN_SHAPE.test(proof) || !TOKEN_SHAPE.test(expected)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(proof);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
function lookup(db: Database.Database, token: string): { coordinator_id: number; expires_at: string; used_at: string | null; active: number } | null {
|
||||
if (!TOKEN_SHAPE.test(token)) return null;
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT t.coordinator_id AS coordinator_id, t.expires_at AS expires_at, t.used_at AS used_at, c.active AS active
|
||||
FROM login_tokens t
|
||||
JOIN coordinators c ON c.id = t.coordinator_id
|
||||
WHERE t.token_hash = ?`,
|
||||
)
|
||||
.get(sha256(token)) as
|
||||
| { coordinator_id: number; expires_at: string; used_at: string | null; active: number }
|
||||
| undefined;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
|
||||
/**
|
||||
* Host-only recovery. There is no web page for this.
|
||||
* Revokes sessions and unused sign-in links. Optionally replaces the sign-in address.
|
||||
*/
|
||||
export function recoverCoordinator(
|
||||
db: Database.Database,
|
||||
input: { email: string; replaceWith?: string; now: string },
|
||||
): { coordinatorId: number } {
|
||||
const email = normalizeEmail(input.email);
|
||||
const next = input.replaceWith ? normalizeEmail(input.replaceWith) : null;
|
||||
return db.transaction(() => {
|
||||
const row = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(email) as { id: number } | undefined;
|
||||
if (!row) throw new Error('No coordinator has that address.');
|
||||
if (next && next !== email) {
|
||||
const taken = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(next);
|
||||
if (taken) throw new Error('Another coordinator already uses the new address.');
|
||||
db.prepare('UPDATE coordinators SET email = ? WHERE id = ?').run(next, row.id);
|
||||
}
|
||||
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(row.id);
|
||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, row.id);
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email IN (?, ?)`,
|
||||
).run('A host recovery replaced this sign-in link.', email, next ?? email);
|
||||
writeAudit(db, null, 'host.recover', { coordinatorId: row.id }, input.now);
|
||||
return { coordinatorId: row.id };
|
||||
}).immediate();
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { cookiePath } from '../url.js';
|
||||
|
||||
export const SESSION_COOKIE = 'hope_session';
|
||||
const SESSION_SECONDS = 14 * 24 * 60 * 60;
|
||||
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{20,128}$/;
|
||||
|
||||
export type CoordinatorSession = {
|
||||
coordinatorId: number;
|
||||
role: 'admin' | 'coordinator';
|
||||
csrf: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type CookieConfig = { basePath: string; secureCookies: boolean };
|
||||
|
||||
export function insertSession(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
now: string,
|
||||
): { token: string; csrf: string } {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const csrf = randomBytes(32).toString('base64url');
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(now).add({ seconds: SESSION_SECONDS }));
|
||||
db.prepare(
|
||||
`INSERT INTO sessions (id_hash, coordinator_id, csrf, expires_at, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
).run(sha256(token), coordinatorId, csrf, expiresAt, now, now);
|
||||
return { token, csrf };
|
||||
}
|
||||
|
||||
/** Absolute 14-day expiry. last_seen_at updates, and expires_at does not move. */
|
||||
export function readSession(db: Database.Database, cookieHeader: string | undefined, now: string): CoordinatorSession | null {
|
||||
const token = readCookie(cookieHeader, SESSION_COOKIE);
|
||||
if (!token || !TOKEN_SHAPE.test(token)) return null;
|
||||
const hash = sha256(token);
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT s.csrf AS csrf, s.expires_at AS expires_at, c.id AS id, c.role AS role, c.name AS name, c.active AS active
|
||||
FROM sessions s
|
||||
JOIN coordinators c ON c.id = s.coordinator_id
|
||||
WHERE s.id_hash = ?`,
|
||||
)
|
||||
.get(hash) as
|
||||
| { csrf: string; expires_at: string; id: number; role: string; name: string; active: number }
|
||||
| undefined;
|
||||
if (!row || row.active !== 1 || row.expires_at <= now) return null;
|
||||
if (row.role !== 'admin' && row.role !== 'coordinator') return null;
|
||||
db.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?').run(now, hash);
|
||||
return { coordinatorId: row.id, role: row.role, csrf: row.csrf, name: row.name };
|
||||
}
|
||||
|
||||
export function revokeSession(db: Database.Database, cookieHeader: string | undefined): void {
|
||||
const token = readCookie(cookieHeader, SESSION_COOKIE);
|
||||
if (!token || !TOKEN_SHAPE.test(token)) return;
|
||||
db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(sha256(token));
|
||||
}
|
||||
|
||||
export function csrfMatches(expected: string, received: string): boolean {
|
||||
if (!TOKEN_SHAPE.test(expected) || !TOKEN_SHAPE.test(received)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
export function sessionSetCookie(config: CookieConfig, token: string): string {
|
||||
return `${SESSION_COOKIE}=${token}; HttpOnly; SameSite=Lax; Path=${cookiePath(config)}; Max-Age=${SESSION_SECONDS}${secureFlag(config)}`;
|
||||
}
|
||||
|
||||
export function sessionClearCookie(config: CookieConfig): string {
|
||||
return `${SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=${cookiePath(config)}; Max-Age=0${secureFlag(config)}`;
|
||||
}
|
||||
|
||||
function secureFlag(config: CookieConfig): string {
|
||||
return config.secureCookies ? '; Secure' : '';
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(';')) {
|
||||
const separator = part.indexOf('=');
|
||||
if (separator === -1) continue;
|
||||
if (part.slice(0, separator).trim() !== name) continue;
|
||||
return part.slice(separator + 1).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { todayInZone } from './time.js';
|
||||
|
||||
const WEEKDAY_LONG = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const;
|
||||
const MONTH_LONG = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
] as const;
|
||||
|
||||
export const WEEKDAY_SHORT = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;
|
||||
|
||||
export type CalendarDay = {
|
||||
date: string;
|
||||
day: number;
|
||||
weekday: string;
|
||||
inMonth: boolean;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type CalendarMonth = {
|
||||
id: string;
|
||||
label: string;
|
||||
weeks: CalendarDay[][];
|
||||
};
|
||||
|
||||
/** Sunday-first month grid. Leading and trailing days belong to the neighboring months. */
|
||||
export function calendarMonth(monthId: string): CalendarMonth {
|
||||
const month = Temporal.PlainYearMonth.from(monthId);
|
||||
const first = month.toPlainDate({ day: 1 });
|
||||
const last = month.toPlainDate({ day: month.daysInMonth });
|
||||
const start = first.subtract({ days: first.dayOfWeek % 7 });
|
||||
const weeks: CalendarDay[][] = [];
|
||||
let cursor = start;
|
||||
while (Temporal.PlainDate.compare(cursor, last) <= 0) {
|
||||
const days: CalendarDay[] = [];
|
||||
for (let index = 0; index < 7; index += 1) {
|
||||
days.push(toCalendarDay(cursor, month));
|
||||
cursor = cursor.add({ days: 1 });
|
||||
}
|
||||
weeks.push(days);
|
||||
}
|
||||
const monthName = MONTH_LONG[month.month - 1];
|
||||
if (!monthName) throw new Error(`${monthId} is not a month.`);
|
||||
return {
|
||||
id: month.toString(),
|
||||
label: `${monthName} ${month.year}`,
|
||||
weeks,
|
||||
};
|
||||
}
|
||||
|
||||
/** Months that contain at least one shift, earliest first. */
|
||||
export function monthsCovering(dates: string[]): string[] {
|
||||
return [...new Set(dates.map((date) => date.slice(0, 7)))].sort();
|
||||
}
|
||||
|
||||
const MONTH_ID = /^\d{4}-\d{2}$/;
|
||||
|
||||
export function parseMonthId(value: string | undefined): string | null {
|
||||
if (!value || !MONTH_ID.test(value)) return null;
|
||||
try {
|
||||
return Temporal.PlainYearMonth.from(value).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The requested month when it has shifts, otherwise the month of today or the nearest later month. */
|
||||
export function chooseCalendarMonth(requested: string | undefined, dates: string[], today: string): string {
|
||||
const months = monthsCovering(dates);
|
||||
const parsed = parseMonthId(requested);
|
||||
if (parsed && months.includes(parsed)) return parsed;
|
||||
const todayMonth = today.slice(0, 7);
|
||||
if (months.includes(todayMonth)) return todayMonth;
|
||||
return months.find((month) => month >= todayMonth) ?? months.at(-1) ?? todayMonth;
|
||||
}
|
||||
|
||||
export function monthStep(current: string, dates: string[]): { previous: string | null; next: string | null } {
|
||||
const months = monthsCovering(dates);
|
||||
const index = months.indexOf(current);
|
||||
if (index === -1) {
|
||||
return {
|
||||
previous: [...months].reverse().find((month) => month < current) ?? null,
|
||||
next: months.find((month) => month > current) ?? null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
previous: index > 0 ? (months[index - 1] ?? null) : null,
|
||||
next: months[index + 1] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function calendarToday(timeZone: string, nowUtc: string): string {
|
||||
return todayInZone(timeZone, Temporal.Instant.from(nowUtc));
|
||||
}
|
||||
|
||||
function toCalendarDay(date: Temporal.PlainDate, month: Temporal.PlainYearMonth): CalendarDay {
|
||||
const weekdayName = WEEKDAY_LONG[date.dayOfWeek % 7];
|
||||
const monthName = MONTH_LONG[date.month - 1];
|
||||
if (!weekdayName || !monthName) throw new Error(`${date.toString()} is not a calendar day.`);
|
||||
return {
|
||||
date: date.toString(),
|
||||
day: date.day,
|
||||
weekday: weekdayName,
|
||||
inMonth: date.year === month.year && date.month === month.month,
|
||||
label: `${weekdayName}, ${monthName} ${date.day}, ${date.year}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Ties a cancel POST to the manage page we rendered for this link.
|
||||
* Knowing the address is not enough. The field is not a second manage token.
|
||||
*/
|
||||
export function issueCancelToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-cancel-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function issueSwitchToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-switch-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function issueReminderPageToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-reminder-page-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function cancelTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueCancelToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
export function switchTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueSwitchToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
export function reminderPageTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueReminderPageToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
function tokenMatches(expected: string, received: string): boolean {
|
||||
if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
/**
|
||||
* Client IP comes from the TCP peer unless that peer is a configured proxy.
|
||||
* A trusted proxy must replace X-Forwarded-For with one client address.
|
||||
* A list of addresses is ignored, because the left-most value is attacker-controlled
|
||||
* when a proxy appends instead of replacing.
|
||||
*/
|
||||
|
||||
export type TrustProxy = { mode: 'disabled' } | { mode: 'list'; entries: TrustEntry[] };
|
||||
|
||||
export type TrustEntry =
|
||||
| { type: 'loopback' }
|
||||
| { type: 'ipv4'; network: number; bits: number }
|
||||
| { type: 'ipv6'; address: string };
|
||||
|
||||
export function parseTrustProxy(value: string | undefined): TrustProxy {
|
||||
const raw = (value ?? '').trim();
|
||||
if (raw === '' || /^(false|0|no|off)$/i.test(raw)) return { mode: 'disabled' };
|
||||
if (/^(true|1|yes|on)$/i.test(raw)) {
|
||||
throw new Error(
|
||||
'TRUST_PROXY cannot be true. Name the proxy instead, for example loopback or 172.18.0.1.',
|
||||
);
|
||||
}
|
||||
const entries: TrustEntry[] = [];
|
||||
for (const part of raw.split(',')) {
|
||||
const item = part.trim();
|
||||
if (item === '') continue;
|
||||
if (/^loopback$/i.test(item)) {
|
||||
entries.push({ type: 'loopback' });
|
||||
continue;
|
||||
}
|
||||
entries.push(parseAddressOrCidr(item));
|
||||
}
|
||||
if (entries.length === 0) throw new Error('TRUST_PROXY is empty.');
|
||||
return { mode: 'list', entries };
|
||||
}
|
||||
|
||||
export function clientAddress(
|
||||
trust: TrustProxy,
|
||||
remoteAddress: string | null | undefined,
|
||||
forwardedFor: string | null | undefined,
|
||||
): string {
|
||||
const peer = normalizeIp(remoteAddress);
|
||||
if (!peer) return 'unknown';
|
||||
if (trust.mode === 'disabled' || !isTrustedPeer(trust, peer)) return peer;
|
||||
return singleForwardedAddress(forwardedFor) ?? peer;
|
||||
}
|
||||
|
||||
export function normalizeIp(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
let ip = value.trim();
|
||||
if (ip.startsWith('[') && ip.endsWith(']')) ip = ip.slice(1, -1);
|
||||
const zone = ip.indexOf('%');
|
||||
if (zone !== -1) ip = ip.slice(0, zone);
|
||||
const lower = ip.toLowerCase();
|
||||
if (lower.startsWith('::ffff:')) {
|
||||
const mapped = lower.slice('::ffff:'.length);
|
||||
if (isIP(mapped) === 4) return mapped;
|
||||
}
|
||||
if (isIP(ip) === 4) return ip;
|
||||
if (isIP(lower) === 6) return lower;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseAddressOrCidr(value: string): TrustEntry {
|
||||
if (value.includes(':')) {
|
||||
if (value.includes('/')) {
|
||||
throw new Error(`TRUST_PROXY does not accept an IPv6 range (${value}). Use an exact IPv6 address or loopback.`);
|
||||
}
|
||||
const address = normalizeIp(value);
|
||||
if (!address || isIP(address) !== 6) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
return { type: 'ipv6', address };
|
||||
}
|
||||
const [base, bitsText] = value.split('/');
|
||||
if (!base || value.split('/').length > 2) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
const bits = bitsText === undefined ? 32 : Number(bitsText);
|
||||
if (!Number.isInteger(bits) || bits < 8 || bits > 32) {
|
||||
throw new Error(`TRUST_PROXY prefix for ${value} must be from 8 through 32 so it cannot trust the whole internet.`);
|
||||
}
|
||||
const network = ipv4ToInt(base);
|
||||
if (network === null) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
const mask = (0xffffffff << (32 - bits)) >>> 0;
|
||||
return { type: 'ipv4', network: (network & mask) >>> 0, bits };
|
||||
}
|
||||
|
||||
function isTrustedPeer(trust: Extract<TrustProxy, { mode: 'list' }>, peer: string): boolean {
|
||||
return trust.entries.some((entry) => matchesEntry(entry, peer));
|
||||
}
|
||||
|
||||
function matchesEntry(entry: TrustEntry, peer: string): boolean {
|
||||
if (entry.type === 'loopback') {
|
||||
if (peer === '::1') return true;
|
||||
const value = ipv4ToInt(peer);
|
||||
if (value === null) return false;
|
||||
return (value >>> 24) === 127;
|
||||
}
|
||||
if (entry.type === 'ipv6') return peer === entry.address;
|
||||
const value = ipv4ToInt(peer);
|
||||
if (value === null) return false;
|
||||
const mask = (0xffffffff << (32 - entry.bits)) >>> 0;
|
||||
return ((value & mask) >>> 0) === entry.network;
|
||||
}
|
||||
|
||||
function singleForwardedAddress(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const parts = value.split(',').map((part) => part.trim()).filter((part) => part !== '');
|
||||
if (parts.length !== 1) return null;
|
||||
return normalizeIp(parts[0]);
|
||||
}
|
||||
|
||||
function ipv4ToInt(ip: string): number | null {
|
||||
if (isIP(ip) !== 4) return null;
|
||||
const parts = ip.split('.').map((part) => Number(part));
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return null;
|
||||
const a = parts[0];
|
||||
const b = parts[1];
|
||||
const c = parts[2];
|
||||
const d = parts[3];
|
||||
if (a === undefined || b === undefined || c === undefined || d === undefined) return null;
|
||||
return ((a * 2 ** 24) + (b * 2 ** 16) + (c * 2 ** 8) + d) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import path from 'node:path';
|
||||
import { z } from 'zod';
|
||||
import { parseTrustProxy, type TrustProxy } from './client-ip.js';
|
||||
import { EmailAddressError, normalizeEmail } from './email.js';
|
||||
import { assertValidTimeZone, LocalTimeError } from './time.js';
|
||||
|
||||
/**
|
||||
* All configuration is read here. Production refuses Cloudflare test keys,
|
||||
* console mail, non-https origins, and weak session secrets.
|
||||
*/
|
||||
|
||||
export const DATABASE_FILENAME = 'app.db';
|
||||
|
||||
/** Documented Cloudflare Turnstile test keys. Development and test only. */
|
||||
export const TURNSTILE_TEST_SITE_KEYS = [
|
||||
'1x00000000000000000000AA',
|
||||
'1x00000000000000000000BB',
|
||||
'2x00000000000000000000AB',
|
||||
'2x00000000000000000000BB',
|
||||
'3x00000000000000000000FF',
|
||||
] as const;
|
||||
|
||||
export const TURNSTILE_TEST_SECRET_KEYS = [
|
||||
'1x0000000000000000000000000000000AA',
|
||||
'2x0000000000000000000000000000000AA',
|
||||
'3x0000000000000000000000000000000AA',
|
||||
] as const;
|
||||
|
||||
const TEST_KEY_PATTERN = /^[123]x0{10,}[0-9a-z]*$/i;
|
||||
const WEAK_SECRET_MARKERS = [
|
||||
'change-me',
|
||||
'changeme',
|
||||
'password',
|
||||
'secret',
|
||||
'placeholder',
|
||||
'dev-only',
|
||||
'qwerty',
|
||||
'letmein',
|
||||
];
|
||||
|
||||
export class ConfigError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'ConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export type MailDriver = 'console' | 'postmark' | 'ses';
|
||||
|
||||
export type AppConfig = {
|
||||
nodeEnv: 'development' | 'test' | 'production';
|
||||
port: number;
|
||||
baseUrl: string;
|
||||
basePath: string;
|
||||
dataDir: string;
|
||||
databaseFile: string;
|
||||
sessionSecret: string;
|
||||
secureCookies: boolean;
|
||||
defaultTimeZone: string;
|
||||
mail: {
|
||||
driver: MailDriver;
|
||||
from: string;
|
||||
replyTo: string;
|
||||
postmarkToken: string | null;
|
||||
ses: { region: string; accessKeyId: string; secretAccessKey: string } | null;
|
||||
};
|
||||
turnstile: { siteKey: string; secretKey: string };
|
||||
brandSrc: string;
|
||||
bootstrapAdminEmail: string;
|
||||
trustProxy: TrustProxy;
|
||||
/** 127.0.0.1 for local development. 0.0.0.0 inside Docker so the published localhost port can connect. */
|
||||
bindHost: '127.0.0.1' | '0.0.0.0';
|
||||
};
|
||||
|
||||
const schema = z.object({
|
||||
NODE_ENV: z.enum(['development', 'test', 'production'], {
|
||||
errorMap: () => ({ message: 'NODE_ENV must be development, test, or production.' }),
|
||||
}),
|
||||
PORT: z.string().regex(/^[0-9]+$/, 'PORT must be a whole number.'),
|
||||
BASE_URL: z.string().min(1, 'BASE_URL is required.'),
|
||||
BASE_PATH: z.string(),
|
||||
DATA_DIR: z.string().min(1, 'DATA_DIR is required.'),
|
||||
SESSION_SECRET: z.string().min(32, 'SESSION_SECRET must be at least 32 characters.'),
|
||||
DEFAULT_TZ: z.string().min(1, 'DEFAULT_TZ is required.'),
|
||||
MAIL_DRIVER: z.enum(['console', 'postmark', 'ses'], {
|
||||
errorMap: () => ({ message: 'MAIL_DRIVER must be console, postmark, or ses.' }),
|
||||
}),
|
||||
MAIL_FROM: z.string().min(1, 'MAIL_FROM is required.'),
|
||||
MAIL_REPLY_TO: z.string().min(1, 'MAIL_REPLY_TO is required.'),
|
||||
POSTMARK_TOKEN: z.string(),
|
||||
SES_REGION: z.string(),
|
||||
SES_ACCESS_KEY_ID: z.string(),
|
||||
SES_SECRET_ACCESS_KEY: z.string(),
|
||||
TURNSTILE_SITE_KEY: z.string().min(1, 'TURNSTILE_SITE_KEY is required.'),
|
||||
TURNSTILE_SECRET_KEY: z.string().min(1, 'TURNSTILE_SECRET_KEY is required.'),
|
||||
BRAND_SRC: z.string().min(1, 'BRAND_SRC is required.'),
|
||||
BOOTSTRAP_ADMIN_EMAIL: z.string().min(1, 'BOOTSTRAP_ADMIN_EMAIL is required.'),
|
||||
TRUST_PROXY: z.string(),
|
||||
BIND_HOST: z.string(),
|
||||
});
|
||||
|
||||
export function isTurnstileTestKey(value: string): boolean {
|
||||
return (
|
||||
TURNSTILE_TEST_SITE_KEYS.some((key) => key === value) ||
|
||||
TURNSTILE_TEST_SECRET_KEYS.some((key) => key === value) ||
|
||||
TEST_KEY_PATTERN.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
const parsed = schema.safeParse({
|
||||
NODE_ENV: blank(env.NODE_ENV),
|
||||
PORT: blank(env.PORT) ?? '3000',
|
||||
BASE_URL: blank(env.BASE_URL),
|
||||
BASE_PATH: (env.BASE_PATH ?? '').trim(),
|
||||
DATA_DIR: blank(env.DATA_DIR) ?? '/data',
|
||||
SESSION_SECRET: (env.SESSION_SECRET ?? '').trim(),
|
||||
DEFAULT_TZ: blank(env.DEFAULT_TZ) ?? 'America/Chicago',
|
||||
MAIL_DRIVER: blank(env.MAIL_DRIVER),
|
||||
MAIL_FROM: blank(env.MAIL_FROM),
|
||||
MAIL_REPLY_TO: blank(env.MAIL_REPLY_TO),
|
||||
POSTMARK_TOKEN: (env.POSTMARK_TOKEN ?? '').trim(),
|
||||
SES_REGION: (env.SES_REGION ?? '').trim(),
|
||||
SES_ACCESS_KEY_ID: (env.SES_ACCESS_KEY_ID ?? '').trim(),
|
||||
SES_SECRET_ACCESS_KEY: (env.SES_SECRET_ACCESS_KEY ?? '').trim(),
|
||||
TURNSTILE_SITE_KEY: blank(env.TURNSTILE_SITE_KEY),
|
||||
TURNSTILE_SECRET_KEY: blank(env.TURNSTILE_SECRET_KEY),
|
||||
BRAND_SRC: blank(env.BRAND_SRC) ?? '../Hope Food Pantry Website/brand',
|
||||
BOOTSTRAP_ADMIN_EMAIL: blank(env.BOOTSTRAP_ADMIN_EMAIL),
|
||||
TRUST_PROXY: blank(env.TRUST_PROXY) ?? 'false',
|
||||
BIND_HOST: blank(env.BIND_HOST) ?? '127.0.0.1',
|
||||
});
|
||||
if (!parsed.success) {
|
||||
throw new ConfigError(formatProblems(parsed.error.issues.map((issue) => issue.message)));
|
||||
}
|
||||
const input = parsed.data;
|
||||
const problems: string[] = [];
|
||||
const port = Number(input.PORT);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
problems.push('PORT must be from 1 through 65535.');
|
||||
}
|
||||
const baseUrl = normalizeBaseUrl(input.BASE_URL, input.NODE_ENV, problems);
|
||||
const basePath = normalizeBasePath(input.BASE_PATH, problems);
|
||||
const dataDir = path.resolve(input.DATA_DIR);
|
||||
if (dataDir === path.parse(dataDir).root) {
|
||||
problems.push('DATA_DIR must be a directory for this app, not the filesystem root.');
|
||||
}
|
||||
let defaultTimeZone = input.DEFAULT_TZ;
|
||||
try {
|
||||
defaultTimeZone = assertValidTimeZone(input.DEFAULT_TZ);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof LocalTimeError ? err.message : 'DEFAULT_TZ is not a recognized IANA time zone.');
|
||||
}
|
||||
const sessionProblems = sessionSecretProblems(input.SESSION_SECRET, input.NODE_ENV);
|
||||
problems.push(...sessionProblems);
|
||||
const from = parseFrom(input.MAIL_FROM, problems);
|
||||
const replyTo = parseReplyTo(input.MAIL_REPLY_TO, problems);
|
||||
const mail = resolveMail(input, problems);
|
||||
// TODO(D5): Production must use the real Turnstile keys for the public hostname.
|
||||
if (input.NODE_ENV === 'production' && isTurnstileTestKey(input.TURNSTILE_SITE_KEY)) {
|
||||
problems.push('TURNSTILE_SITE_KEY is a Cloudflare test key. Production requires the real site key for the pantry hostname.');
|
||||
}
|
||||
if (input.NODE_ENV === 'production' && isTurnstileTestKey(input.TURNSTILE_SECRET_KEY)) {
|
||||
problems.push('TURNSTILE_SECRET_KEY is a Cloudflare test key. Production requires the real secret key for the pantry hostname.');
|
||||
}
|
||||
if (input.TURNSTILE_SITE_KEY.length < 20 || input.TURNSTILE_SECRET_KEY.length < 20) {
|
||||
problems.push('TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY do not look like Turnstile keys.');
|
||||
}
|
||||
let bootstrapAdminEmail = '';
|
||||
try {
|
||||
// TODO(D4): Validated only. This step does not create the administrator account.
|
||||
bootstrapAdminEmail = normalizeEmail(input.BOOTSTRAP_ADMIN_EMAIL);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof EmailAddressError ? 'BOOTSTRAP_ADMIN_EMAIL must be an email address.' : 'BOOTSTRAP_ADMIN_EMAIL is invalid.');
|
||||
}
|
||||
let trustProxy: TrustProxy = { mode: 'disabled' };
|
||||
try {
|
||||
trustProxy = parseTrustProxy(input.TRUST_PROXY);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof Error ? err.message : 'TRUST_PROXY is invalid.');
|
||||
}
|
||||
if (input.BIND_HOST !== '127.0.0.1' && input.BIND_HOST !== '0.0.0.0') {
|
||||
problems.push('BIND_HOST must be 127.0.0.1 or 0.0.0.0.');
|
||||
}
|
||||
if (problems.length > 0 || !baseUrl || basePath === null || !from || !replyTo || !mail) {
|
||||
throw new ConfigError(formatProblems(problems));
|
||||
}
|
||||
return {
|
||||
nodeEnv: input.NODE_ENV,
|
||||
port,
|
||||
baseUrl: baseUrl.origin,
|
||||
basePath,
|
||||
dataDir,
|
||||
databaseFile: path.join(dataDir, DATABASE_FILENAME),
|
||||
sessionSecret: input.SESSION_SECRET,
|
||||
secureCookies: baseUrl.secure,
|
||||
defaultTimeZone,
|
||||
mail: {
|
||||
driver: input.MAIL_DRIVER,
|
||||
from,
|
||||
replyTo,
|
||||
postmarkToken: mail.postmarkToken,
|
||||
ses: mail.ses,
|
||||
},
|
||||
turnstile: {
|
||||
siteKey: input.TURNSTILE_SITE_KEY,
|
||||
secretKey: input.TURNSTILE_SECRET_KEY,
|
||||
},
|
||||
brandSrc: input.BRAND_SRC,
|
||||
bootstrapAdminEmail,
|
||||
trustProxy,
|
||||
bindHost: input.BIND_HOST === '0.0.0.0' ? '0.0.0.0' : '127.0.0.1',
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(
|
||||
value: string,
|
||||
nodeEnv: 'development' | 'test' | 'production',
|
||||
problems: string[],
|
||||
): { origin: string; secure: boolean } | null {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
problems.push('BASE_URL must be an absolute origin, such as http://127.0.0.1:3000 or https://example.org.');
|
||||
return null;
|
||||
}
|
||||
if (url.username || url.password) problems.push('BASE_URL must not include a username or password.');
|
||||
if (url.search || url.hash) problems.push('BASE_URL must not include a query or hash.');
|
||||
if (url.pathname !== '/' && url.pathname !== '') {
|
||||
problems.push('BASE_URL is the public origin only. Put a mount prefix such as /volunteer in BASE_PATH.');
|
||||
}
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
||||
problems.push('BASE_URL must start with http:// or https://.');
|
||||
return null;
|
||||
}
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (nodeEnv === 'production') {
|
||||
if (url.protocol !== 'https:') problems.push('Production BASE_URL must use https.');
|
||||
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.local') || !host.includes('.')) {
|
||||
problems.push('Production BASE_URL must be the public hostname, not a local address.');
|
||||
}
|
||||
}
|
||||
return { origin: url.origin, secure: url.protocol === 'https:' };
|
||||
}
|
||||
|
||||
function normalizeBasePath(input: string, problems: string[]): string | null {
|
||||
const trimmed = input.trim();
|
||||
if (trimmed === '' || trimmed === '/') return '';
|
||||
let value = trimmed;
|
||||
if (value.endsWith('/')) value = value.slice(0, -1);
|
||||
if (!value.startsWith('/')) {
|
||||
problems.push('BASE_PATH must start with /, or be empty.');
|
||||
return null;
|
||||
}
|
||||
if (value.includes('//') || value.includes('\\') || value.includes('?') || value.includes('#') || value.includes('..')) {
|
||||
problems.push('BASE_PATH must be a simple prefix such as /volunteer.');
|
||||
return null;
|
||||
}
|
||||
if (!/^\/(?:[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)$/.test(value)) {
|
||||
problems.push('BASE_PATH must be a simple prefix such as /volunteer.');
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sessionSecretProblems(secret: string, nodeEnv: 'development' | 'test' | 'production'): string[] {
|
||||
if (nodeEnv !== 'production') return [];
|
||||
const problems: string[] = [];
|
||||
const lower = secret.toLowerCase();
|
||||
if (WEAK_SECRET_MARKERS.some((marker) => lower.includes(marker))) {
|
||||
problems.push(
|
||||
'SESSION_SECRET looks like a placeholder. Generate a random one with: node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'base64url\'))"',
|
||||
);
|
||||
}
|
||||
if (new Set(secret).size < 16) {
|
||||
problems.push('SESSION_SECRET does not look random enough for production.');
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
function parseFrom(value: string, problems: string[]): string | null {
|
||||
if (/[\r\n]/.test(value)) {
|
||||
problems.push('MAIL_FROM must not contain a line break.');
|
||||
return null;
|
||||
}
|
||||
const named = /^(.*?)<\s*([^>]+)\s*>\s*$/.exec(value.trim());
|
||||
try {
|
||||
if (!named) return normalizeEmail(value);
|
||||
const display = (named[1] ?? '').trim().replace(/^"|"$/g, '');
|
||||
const address = normalizeEmail(named[2] ?? '');
|
||||
if (/[<>]/.test(display)) {
|
||||
problems.push('MAIL_FROM has an invalid display name.');
|
||||
return null;
|
||||
}
|
||||
return display === '' ? address : `${display} <${address}>`;
|
||||
} catch {
|
||||
problems.push('MAIL_FROM must be an email address, or a name and address such as Hope Food Pantry <volunteer@example.org>.');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseReplyTo(value: string, problems: string[]): string | null {
|
||||
if (value.includes('<') || value.includes('>')) {
|
||||
problems.push('MAIL_REPLY_TO must be an email address without a display name.');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return normalizeEmail(value);
|
||||
} catch {
|
||||
problems.push('MAIL_REPLY_TO must be an email address.');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveMail(
|
||||
input: z.infer<typeof schema>,
|
||||
problems: string[],
|
||||
): { postmarkToken: string | null; ses: AppConfig['mail']['ses'] } | null {
|
||||
// TODO(D1): The pantry chooses the provider and verifies the sender and reply-to before real mail is enabled.
|
||||
if (input.NODE_ENV === 'production' && input.MAIL_DRIVER === 'console') {
|
||||
problems.push('MAIL_DRIVER=console is only for development. Choose postmark or ses after the pantry confirms the email provider.');
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'postmark') {
|
||||
const token = requireCredential(input.POSTMARK_TOKEN, 'POSTMARK_TOKEN', problems);
|
||||
if (!token) return null;
|
||||
return { postmarkToken: token, ses: null };
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'ses') {
|
||||
if (!/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) {
|
||||
problems.push('SES_REGION must look like us-east-1.');
|
||||
}
|
||||
const accessKeyId = requireCredential(input.SES_ACCESS_KEY_ID, 'SES_ACCESS_KEY_ID', problems);
|
||||
const secretAccessKey = requireCredential(input.SES_SECRET_ACCESS_KEY, 'SES_SECRET_ACCESS_KEY', problems);
|
||||
if (!accessKeyId || !secretAccessKey || !/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) return null;
|
||||
return {
|
||||
postmarkToken: null,
|
||||
ses: { region: input.SES_REGION, accessKeyId, secretAccessKey },
|
||||
};
|
||||
}
|
||||
return { postmarkToken: null, ses: null };
|
||||
}
|
||||
|
||||
function requireCredential(value: string, label: string, problems: string[]): string | null {
|
||||
if (value === '') {
|
||||
problems.push(`${label} is required for the selected mail driver.`);
|
||||
return null;
|
||||
}
|
||||
if (/^(change-me|changeme|placeholder|secret|token|password|example)$/i.test(value)) {
|
||||
problems.push(`${label} is still a placeholder.`);
|
||||
return null;
|
||||
}
|
||||
if (value.length < 16) {
|
||||
problems.push(`${label} is too short.`);
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function formatProblems(problems: string[]): string {
|
||||
const unique = [...new Set(problems.filter((problem) => problem.trim() !== ''))];
|
||||
return `Configuration is invalid:\n- ${unique.join('\n- ')}`;
|
||||
}
|
||||
|
||||
function blank(value: string | undefined): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed === '' ? undefined : trimmed;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
|
||||
const COOKIE = 'hope_confirm';
|
||||
const MAX_AGE_SECONDS = 900;
|
||||
|
||||
export type ConfirmationSeal = {
|
||||
signupId: number;
|
||||
shiftId: number;
|
||||
token: string;
|
||||
expiresAtMs: number;
|
||||
};
|
||||
|
||||
export function sealConfirmation(secret: string, payload: ConfirmationSeal): string {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', cookieKey(secret), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([iv, tag, ciphertext]).toString('base64url');
|
||||
}
|
||||
|
||||
export function openConfirmation(secret: string, cookieHeader: string | undefined, nowMs: number): ConfirmationSeal | null {
|
||||
const raw = readCookie(cookieHeader, COOKIE);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const bytes = Buffer.from(raw, 'base64url');
|
||||
if (bytes.length < 12 + 16 + 2) return null;
|
||||
const iv = bytes.subarray(0, 12);
|
||||
const tag = bytes.subarray(12, 28);
|
||||
const ciphertext = bytes.subarray(28);
|
||||
const decipher = createDecipheriv('aes-256-gcm', cookieKey(secret), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
const json = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
||||
const parsed = JSON.parse(json) as Partial<ConfirmationSeal>;
|
||||
if (!parsed || typeof parsed.signupId !== 'number' || typeof parsed.shiftId !== 'number') return null;
|
||||
if (typeof parsed.token !== 'string' || typeof parsed.expiresAtMs !== 'number') return null;
|
||||
if (parsed.expiresAtMs <= nowMs) return null;
|
||||
return {
|
||||
signupId: parsed.signupId,
|
||||
shiftId: parsed.shiftId,
|
||||
token: parsed.token,
|
||||
expiresAtMs: parsed.expiresAtMs,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function confirmationCookie(value: string, path: string, secure: boolean): string {
|
||||
const parts = [
|
||||
`${COOKIE}=${value}`,
|
||||
'HttpOnly',
|
||||
'SameSite=Lax',
|
||||
`Path=${path}`,
|
||||
`Max-Age=${MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (secure) parts.push('Secure');
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
function cookieKey(secret: string): Buffer {
|
||||
return createHash('sha256').update(`hope-confirm-v1\0${secret}`).digest();
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(';')) {
|
||||
const separator = part.indexOf('=');
|
||||
if (separator === -1) continue;
|
||||
if (part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import { mkdir, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import Database from 'better-sqlite3';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
const MIGRATION_NAME = /^(\d{3,})_[a-z0-9_]+\.sql$/;
|
||||
|
||||
export class MigrationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'MigrationError';
|
||||
}
|
||||
}
|
||||
|
||||
export type ApplyMigrationsOptions = {
|
||||
migrationsDir: string;
|
||||
now?: string;
|
||||
backupBeforePending?: () => Promise<void>;
|
||||
};
|
||||
|
||||
export function defaultMigrationsDir(): string {
|
||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../migrations');
|
||||
}
|
||||
|
||||
export function configureConnection(db: Database.Database): void {
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
}
|
||||
|
||||
export function openDatabaseFile(file: string): Database.Database {
|
||||
try {
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
} catch (err) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. Could not create the data directory ${path.dirname(file)}. ${messageOf(err)}`,
|
||||
);
|
||||
}
|
||||
const db = new Database(file);
|
||||
configureConnection(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export async function openAppDatabase(
|
||||
config: AppConfig,
|
||||
options?: { migrationsDir?: string },
|
||||
): Promise<Database.Database> {
|
||||
const db = openDatabaseFile(config.databaseFile);
|
||||
try {
|
||||
await applyMigrations(db, {
|
||||
migrationsDir: options?.migrationsDir ?? defaultMigrationsDir(),
|
||||
backupBeforePending:
|
||||
config.nodeEnv === 'production' ? () => backupBeforeProductionMigration(db, config.dataDir) : undefined,
|
||||
});
|
||||
const quick = db.pragma('quick_check', { simple: true });
|
||||
if (quick !== 'ok') {
|
||||
throw new MigrationError(`Startup aborted. Database integrity check failed: ${String(quick)}`);
|
||||
}
|
||||
return db;
|
||||
} catch (err) {
|
||||
db.close();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function backupDatabase(db: Database.Database, destination: string): Promise<void> {
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
try {
|
||||
await db.backup(destination);
|
||||
const check = new Database(destination);
|
||||
try {
|
||||
check.pragma('wal_checkpoint(TRUNCATE)');
|
||||
const mode = check.pragma('journal_mode = DELETE', { simple: true });
|
||||
if (mode !== 'delete') throw new Error(`journal mode stayed ${String(mode)}`);
|
||||
const result = check.pragma('integrity_check', { simple: true });
|
||||
if (result !== 'ok') throw new Error(`integrity check returned ${String(result)}`);
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
await rm(`${destination}-wal`, { force: true });
|
||||
await rm(`${destination}-shm`, { force: true });
|
||||
} catch (err) {
|
||||
await rm(destination, { force: true });
|
||||
await rm(`${destination}-wal`, { force: true });
|
||||
await rm(`${destination}-shm`, { force: true });
|
||||
throw new Error(`Backup ${destination} failed. ${messageOf(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyMigrations(
|
||||
db: Database.Database,
|
||||
options: ApplyMigrationsOptions,
|
||||
): Promise<{ applied: string[] }> {
|
||||
const foreignKeys = Number(db.pragma('foreign_keys', { simple: true }));
|
||||
if (foreignKeys !== 1) {
|
||||
throw new MigrationError('Startup aborted. foreign_keys must be ON before migrations run.');
|
||||
}
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
checksum TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
)`);
|
||||
const files = listMigrationFiles(options.migrationsDir);
|
||||
verifyAppliedChecksums(db, files, options.migrationsDir);
|
||||
const appliedNames = new Set(
|
||||
(db.prepare('SELECT name FROM schema_migrations').all() as { name: string }[]).map((row) => row.name),
|
||||
);
|
||||
const pending = files.filter((file) => !appliedNames.has(file.name));
|
||||
// A brand-new database has nothing to preserve. Later production migrations
|
||||
// snapshot the existing file before any new SQL runs.
|
||||
if (pending.length > 0 && appliedNames.size > 0 && options.backupBeforePending) {
|
||||
try {
|
||||
await options.backupBeforePending();
|
||||
} catch (err) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. The database was not migrated because the pre-migration backup failed. ${messageOf(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const applied: string[] = [];
|
||||
for (const file of pending) {
|
||||
const apply = db.transaction(() => {
|
||||
db.exec(file.sql);
|
||||
db.prepare('INSERT INTO schema_migrations (name, checksum, applied_at) VALUES (?, ?, ?)').run(
|
||||
file.name,
|
||||
file.checksum,
|
||||
options.now ?? nowUtc(),
|
||||
);
|
||||
});
|
||||
try {
|
||||
apply();
|
||||
} catch (err) {
|
||||
throw new MigrationError(`Startup aborted. Migration ${file.name} failed: ${messageOf(err)}`);
|
||||
}
|
||||
applied.push(file.name);
|
||||
}
|
||||
return { applied };
|
||||
}
|
||||
|
||||
async function backupBeforeProductionMigration(db: Database.Database, dataDir: string): Promise<void> {
|
||||
const destination = path.join(dataDir, 'backups', `pre-migrate-${backupStamp()}.db`);
|
||||
await backupDatabase(db, destination);
|
||||
}
|
||||
|
||||
function backupStamp(now = nowUtc()): string {
|
||||
return now.replace(/[-:]/g, '').replace('.', '');
|
||||
}
|
||||
|
||||
type MigrationFile = { name: string; sql: string; checksum: string };
|
||||
|
||||
function listMigrationFiles(migrationsDir: string): MigrationFile[] {
|
||||
if (!existsSync(migrationsDir)) {
|
||||
throw new MigrationError(`Startup aborted. Migrations directory is missing: ${migrationsDir}`);
|
||||
}
|
||||
const names = readdirSync(migrationsDir).filter((name) => name !== '.gitkeep');
|
||||
const files: MigrationFile[] = [];
|
||||
const numbers = new Map<string, string>();
|
||||
for (const name of names) {
|
||||
const match = MIGRATION_NAME.exec(name);
|
||||
if (!match) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${name} is not a numbered migration. Use a name like 002_description.sql.`,
|
||||
);
|
||||
}
|
||||
const number = match[1];
|
||||
if (!number) throw new MigrationError(`Startup aborted. Could not read the migration number in ${name}.`);
|
||||
const previous = numbers.get(number);
|
||||
if (previous) {
|
||||
throw new MigrationError(`Startup aborted. Duplicate migration number ${number} on ${previous} and ${name}.`);
|
||||
}
|
||||
numbers.set(number, name);
|
||||
const full = path.join(migrationsDir, name);
|
||||
const bytes = readFileSync(full);
|
||||
const sql = bytes.toString('utf8');
|
||||
if (/^\s*(BEGIN|COMMIT|ROLLBACK|PRAGMA)\b/im.test(sql)) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${name} must not contain BEGIN, COMMIT, ROLLBACK, or PRAGMA. The runner handles those.`,
|
||||
);
|
||||
}
|
||||
files.push({
|
||||
name,
|
||||
sql,
|
||||
checksum: createHash('sha256').update(bytes).digest('hex'),
|
||||
});
|
||||
}
|
||||
files.sort((a, b) => {
|
||||
const aNumber = Number(MIGRATION_NAME.exec(a.name)?.[1] ?? 0);
|
||||
const bNumber = Number(MIGRATION_NAME.exec(b.name)?.[1] ?? 0);
|
||||
return aNumber - bNumber || a.name.localeCompare(b.name);
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
function verifyAppliedChecksums(db: Database.Database, files: MigrationFile[], migrationsDir: string): void {
|
||||
const byName = new Map(files.map((file) => [file.name, file]));
|
||||
const applied = db.prepare('SELECT name, checksum FROM schema_migrations').all() as {
|
||||
name: string;
|
||||
checksum: string;
|
||||
}[];
|
||||
for (const row of applied) {
|
||||
const file = byName.get(row.name);
|
||||
if (!file) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. The database has applied ${row.name}, but that file is missing from ${migrationsDir}.`,
|
||||
);
|
||||
}
|
||||
if (file.checksum !== row.checksum) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${row.name} changed after it was applied. Add a new numbered migration instead of editing an applied file.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function messageOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { openAppDatabase } from '../db.js';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { loadConfig } from '../config.js';
|
||||
import {
|
||||
addLocalDays,
|
||||
localShiftToUtc,
|
||||
nowUtc,
|
||||
todayInZone,
|
||||
weekdayIndex,
|
||||
} from '../time.js';
|
||||
|
||||
export const SEED_EMAIL_DOMAIN = 'example.invalid';
|
||||
|
||||
export type SeedResult = {
|
||||
eventId: number;
|
||||
slug: string;
|
||||
templateId: number;
|
||||
shiftIds: number[];
|
||||
signupIds: number[];
|
||||
};
|
||||
|
||||
export function assertDevelopmentSeed(env: NodeJS.ProcessEnv): void {
|
||||
if (env.NODE_ENV === 'production') {
|
||||
throw new Error(
|
||||
'Refusing to seed because NODE_ENV=production. Seed data is fake and is only for local development.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function seedDevelopment(
|
||||
db: Database.Database,
|
||||
config: AppConfig,
|
||||
options?: { today?: string },
|
||||
): SeedResult {
|
||||
if (config.nodeEnv === 'production') {
|
||||
throw new Error(
|
||||
'Refusing to seed because NODE_ENV=production. Seed data is fake and is only for local development.',
|
||||
);
|
||||
}
|
||||
const existing = db.prepare('SELECT COUNT(*) AS n FROM events').get() as { n: number };
|
||||
if (existing.n > 0) {
|
||||
throw new Error(
|
||||
'Refusing to seed because this database already has events. Delete the development database file if you want a fresh seed.',
|
||||
);
|
||||
}
|
||||
|
||||
const timeZone = config.defaultTimeZone;
|
||||
const today = options?.today ?? todayInZone(timeZone);
|
||||
const createdAt = nowUtc();
|
||||
const weekday = weekdayIndex(today, timeZone);
|
||||
const shiftDates = [1, 3, 6].map((days) => addLocalDays(today, days));
|
||||
const roles = ['Sorting', 'Distribution', 'Intake'] as const;
|
||||
const capacities = [3, 4, 2] as const;
|
||||
|
||||
const insert = db.transaction((): SeedResult => {
|
||||
const event = db
|
||||
.prepare(
|
||||
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
|
||||
VALUES ('weekly-pantry', 'Weekly pantry', '', '', ?, 1, ?)`,
|
||||
)
|
||||
.run(timeZone, createdAt);
|
||||
const eventId = insertId(event);
|
||||
const template = db
|
||||
.prepare(
|
||||
`INSERT INTO shift_templates (
|
||||
event_id, role, weekday, start_local, end_local, capacity, starts_on, ends_on, active, revision
|
||||
) VALUES (?, 'Sorting', ?, '09:00', '12:00', 6, ?, NULL, 1, 1)`,
|
||||
)
|
||||
.run(eventId, weekday, today);
|
||||
const templateId = insertId(template);
|
||||
const shiftIds: number[] = [];
|
||||
for (let index = 0; index < shiftDates.length; index += 1) {
|
||||
const date = shiftDates[index];
|
||||
const role = roles[index];
|
||||
const capacity = capacities[index];
|
||||
if (!date || !role || !capacity) throw new Error('Seed shift list is incomplete.');
|
||||
const times = localShiftToUtc(date, '09:00', '12:00', timeZone);
|
||||
const shift = db
|
||||
.prepare(
|
||||
`INSERT INTO shifts (
|
||||
event_id, template_id, occurrence_date, template_revision, role,
|
||||
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
|
||||
) VALUES (?, NULL, NULL, NULL, ?, ?, ?, ?, 'Development seed. Not a real pantry shift.', 0, 0, 1)`,
|
||||
)
|
||||
.run(eventId, role, times.startsAtUtc, times.endsAtUtc, capacity);
|
||||
shiftIds.push(insertId(shift));
|
||||
}
|
||||
const firstShift = shiftIds[0];
|
||||
if (firstShift === undefined) throw new Error('Seed did not create a shift.');
|
||||
const signupIds = insertFakeSignups(db, firstShift, createdAt);
|
||||
return { eventId, slug: 'weekly-pantry', templateId, shiftIds, signupIds };
|
||||
});
|
||||
return insert();
|
||||
}
|
||||
|
||||
export async function runSeedCli(env: NodeJS.ProcessEnv = process.env): Promise<void> {
|
||||
assertDevelopmentSeed(env);
|
||||
const config = loadConfig(env);
|
||||
const db = await openAppDatabase(config);
|
||||
try {
|
||||
const result = seedDevelopment(db, config);
|
||||
console.log('Seeded fake development data.');
|
||||
console.log(`Database: ${config.databaseFile}`);
|
||||
console.log(
|
||||
`Event ${result.slug}: ${result.shiftIds.length} one-off shifts and ${result.signupIds.length} fake signups.`,
|
||||
);
|
||||
console.log('Each signup is one person. Another person can use the same email. Group size is fixed at 1.');
|
||||
console.log('The weekly template is stored. Starting the app adds its shifts for the next eight weeks.');
|
||||
console.log('No coordinator account was created.');
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: string): number[] {
|
||||
// TODO(D2): These rows are individual signups. Do not invent group reservations here.
|
||||
// TODO(D4): Seed data does not create coordinator accounts.
|
||||
const people = [
|
||||
{
|
||||
name: 'Fake Volunteer Ada',
|
||||
email: `ada.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: '712-555-0101',
|
||||
isMinor: 0,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
notes: 'Fake note for development.',
|
||||
status: 'confirmed',
|
||||
},
|
||||
{
|
||||
name: 'Fake Volunteer Ben',
|
||||
email: `ben.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: null,
|
||||
isMinor: 1,
|
||||
guardianName: 'Fake Guardian Pat',
|
||||
guardianEmail: `pat.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
notes: null,
|
||||
status: 'confirmed',
|
||||
},
|
||||
{
|
||||
name: 'Fake Volunteer Cam',
|
||||
email: `cam.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: null,
|
||||
isMinor: 0,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
notes: null,
|
||||
status: 'cancelled',
|
||||
},
|
||||
];
|
||||
const statement = db.prepare(
|
||||
`INSERT INTO signups (
|
||||
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
||||
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
||||
attended, created_at, updated_at, anonymized_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
||||
);
|
||||
return people.map((person) =>
|
||||
insertId(
|
||||
statement.run(
|
||||
shiftId,
|
||||
person.name,
|
||||
person.email,
|
||||
normalizeEmail(person.email),
|
||||
person.phone,
|
||||
person.isMinor,
|
||||
person.guardianName,
|
||||
person.guardianEmail,
|
||||
person.notes,
|
||||
person.status,
|
||||
createdAt,
|
||||
createdAt,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function insertId(result: { lastInsertRowid: number | bigint }): number {
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export class EmailAddressError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'EmailAddressError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Trim, Unicode normalize, and lowercase. Dots and plus-tags are kept. */
|
||||
export function normalizeEmail(input: string): string {
|
||||
const normalized = input.normalize('NFC').trim().toLowerCase();
|
||||
if (
|
||||
normalized.length === 0 ||
|
||||
/\s/.test(normalized) ||
|
||||
!normalized.includes('@') ||
|
||||
normalized.startsWith('@') ||
|
||||
normalized.endsWith('@')
|
||||
) {
|
||||
throw new EmailAddressError('Enter an email address.');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatInstantInZone } from './time.js';
|
||||
|
||||
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const MAX_RANGE_DAYS = 366;
|
||||
const FORMULA = /^[\s\u0000-\u001F\u007F]*[=+\-@]/;
|
||||
|
||||
const COLUMNS = [
|
||||
'Date',
|
||||
'Start',
|
||||
'End',
|
||||
'Time zone',
|
||||
'Role',
|
||||
'Name',
|
||||
'Email',
|
||||
'Phone',
|
||||
'Group size',
|
||||
'Minor',
|
||||
'Guardian name',
|
||||
'Guardian email',
|
||||
'Notes',
|
||||
'Status',
|
||||
'Attended',
|
||||
] as const;
|
||||
|
||||
export type RosterExport = { csv: string; rows: number };
|
||||
|
||||
type RosterRecord = {
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
tz: string;
|
||||
role: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
group_size: number;
|
||||
is_minor: number;
|
||||
guardian_name: string | null;
|
||||
guardian_email: string | null;
|
||||
notes: string | null;
|
||||
status: string;
|
||||
attended: number | null;
|
||||
anonymized_at: string | null;
|
||||
};
|
||||
|
||||
const ROSTER_SQL = `SELECT s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc, e.tz AS tz, s.role AS role,
|
||||
su.name AS name, su.email AS email, su.phone AS phone, su.group_size AS group_size,
|
||||
su.is_minor AS is_minor, su.guardian_name AS guardian_name, su.guardian_email AS guardian_email,
|
||||
su.notes AS notes, su.status AS status, su.attended AS attended, su.anonymized_at AS anonymized_at
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id`;
|
||||
|
||||
/** A spreadsheet cell that would otherwise be a formula is prefixed so it stays text. */
|
||||
export function csvCell(value: string): string {
|
||||
const safe = FORMULA.test(value) ? `'${value}` : value;
|
||||
if (/[",\r\n]/.test(safe)) return `"${safe.replaceAll('"', '""')}"`;
|
||||
return safe;
|
||||
}
|
||||
|
||||
export function exportShiftRoster(db: Database.Database, shiftId: number): RosterExport | null {
|
||||
const shift = db.prepare('SELECT id FROM shifts WHERE id = ?').get(shiftId);
|
||||
if (!shift) return null;
|
||||
const rows = db
|
||||
.prepare(`${ROSTER_SQL} WHERE s.id = ? ORDER BY su.id`)
|
||||
.all(shiftId) as RosterRecord[];
|
||||
return renderRoster(rows);
|
||||
}
|
||||
|
||||
export function exportEventRoster(db: Database.Database, eventId: number): RosterExport | null {
|
||||
const event = db.prepare('SELECT id FROM events WHERE id = ?').get(eventId);
|
||||
if (!event) return null;
|
||||
const rows = db
|
||||
.prepare(`${ROSTER_SQL} WHERE e.id = ? ORDER BY s.starts_at_utc, s.id, su.id`)
|
||||
.all(eventId) as RosterRecord[];
|
||||
return renderRoster(rows);
|
||||
}
|
||||
|
||||
export function exportDateRange(
|
||||
db: Database.Database,
|
||||
from: string,
|
||||
to: string,
|
||||
): { ok: true; export: RosterExport } | { ok: false; error: string } {
|
||||
const start = parseDate(from);
|
||||
const end = parseDate(to);
|
||||
if (!start || !end) return { ok: false, error: 'Use real dates.' };
|
||||
if (Temporal.PlainDate.compare(end, start) < 0) return { ok: false, error: 'The end date is before the start date.' };
|
||||
if (start.until(end, { largestUnit: 'days' }).days > MAX_RANGE_DAYS) {
|
||||
return { ok: false, error: 'Choose a range of one year or less.' };
|
||||
}
|
||||
const lower = `${start.subtract({ days: 2 }).toString()}T00:00:00.000Z`;
|
||||
const upper = `${end.add({ days: 2 }).toString()}T23:59:59.999Z`;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`${ROSTER_SQL}
|
||||
WHERE s.starts_at_utc >= ? AND s.starts_at_utc <= ?
|
||||
ORDER BY s.starts_at_utc, s.id, su.id`,
|
||||
)
|
||||
.all(lower, upper) as RosterRecord[];
|
||||
const kept = rows.filter((row) => {
|
||||
const local = formatInstantInZone(row.starts_at_utc, row.tz).date;
|
||||
return local >= start.toString() && local <= end.toString();
|
||||
});
|
||||
return { ok: true, export: renderRoster(kept) };
|
||||
}
|
||||
|
||||
export function dateStamp(value: string): number | null {
|
||||
const date = parseDate(value);
|
||||
if (!date) return null;
|
||||
return date.year * 10000 + date.month * 100 + date.day;
|
||||
}
|
||||
|
||||
function renderRoster(rows: RosterRecord[]): RosterExport {
|
||||
const lines = [COLUMNS.map(csvCell).join(','), ...rows.map((row) => present(row).map(csvCell).join(','))];
|
||||
return { csv: `\uFEFF${lines.join('\r\n')}\r\n`, rows: rows.length };
|
||||
}
|
||||
|
||||
function present(row: RosterRecord): string[] {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
return [
|
||||
start.date,
|
||||
start.timeLabel,
|
||||
end.timeLabel,
|
||||
`${row.tz} (${start.abbreviation})`,
|
||||
row.role,
|
||||
row.name ?? '',
|
||||
row.email ?? '',
|
||||
row.phone ?? '',
|
||||
String(row.group_size),
|
||||
row.anonymized_at ? '' : row.is_minor === 1 ? 'Yes' : 'No',
|
||||
row.guardian_name ?? '',
|
||||
row.guardian_email ?? '',
|
||||
row.notes ?? '',
|
||||
row.status === 'cancelled' ? 'Cancelled' : 'Confirmed',
|
||||
row.attended === 1 ? 'Attended' : row.attended === 0 ? 'No-show' : '',
|
||||
];
|
||||
}
|
||||
|
||||
function parseDate(value: string): Temporal.PlainDate | null {
|
||||
if (!DATE.test(value)) return null;
|
||||
try {
|
||||
const date = Temporal.PlainDate.from(value);
|
||||
return date.toString() === value ? date : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/** Supplemental bot signal. Not authentication. */
|
||||
export const MIN_FILL_MS = 3000;
|
||||
const MAX_AGE_MS = 2 * 60 * 60 * 1000;
|
||||
const CLOCK_SKEW_MS = 5000;
|
||||
|
||||
export type FormClaims = {
|
||||
shiftId: number;
|
||||
issuedAt: number;
|
||||
operationId: string;
|
||||
};
|
||||
|
||||
export type FormTokenResult =
|
||||
| { ok: true; claims: FormClaims }
|
||||
| { ok: false; reason: 'invalid' | 'too_fast' | 'expired' };
|
||||
|
||||
export function newOperationId(): string {
|
||||
return randomBytes(16).toString('base64url');
|
||||
}
|
||||
|
||||
export function issueFormToken(secret: string, claims: FormClaims): string {
|
||||
const payload = Buffer.from(
|
||||
JSON.stringify({
|
||||
v: 1,
|
||||
shiftId: claims.shiftId,
|
||||
issuedAt: claims.issuedAt,
|
||||
operationId: claims.operationId,
|
||||
}),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
return `${payload}.${sign(secret, payload)}`;
|
||||
}
|
||||
|
||||
export function readFormToken(
|
||||
secret: string,
|
||||
token: string,
|
||||
shiftId: number,
|
||||
nowMs: number,
|
||||
minFillMs = MIN_FILL_MS,
|
||||
): FormTokenResult {
|
||||
const opened = openFormToken(secret, token, nowMs, minFillMs);
|
||||
if (!opened.ok) return opened;
|
||||
if (opened.claims.shiftId !== shiftId) return { ok: false, reason: 'invalid' };
|
||||
return opened;
|
||||
}
|
||||
|
||||
export function openFormToken(secret: string, token: string, nowMs: number, minFillMs = MIN_FILL_MS): FormTokenResult {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 2) return { ok: false, reason: 'invalid' };
|
||||
const payload = parts[0];
|
||||
const signature = parts[1];
|
||||
if (!payload || !signature || !safeEqual(sign(secret, payload), signature)) {
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
} catch {
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
if (!isClaims(parsed)) return { ok: false, reason: 'invalid' };
|
||||
if (parsed.issuedAt > nowMs + CLOCK_SKEW_MS) return { ok: false, reason: 'invalid' };
|
||||
const age = nowMs - parsed.issuedAt;
|
||||
if (age < minFillMs) return { ok: false, reason: 'too_fast' };
|
||||
if (age > MAX_AGE_MS) return { ok: false, reason: 'expired' };
|
||||
return {
|
||||
ok: true,
|
||||
claims: { shiftId: parsed.shiftId, issuedAt: parsed.issuedAt, operationId: parsed.operationId },
|
||||
};
|
||||
}
|
||||
|
||||
function isClaims(value: unknown): value is FormClaims & { v: 1 } {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
record.v === 1 &&
|
||||
typeof record.shiftId === 'number' &&
|
||||
Number.isSafeInteger(record.shiftId) &&
|
||||
record.shiftId > 0 &&
|
||||
typeof record.issuedAt === 'number' &&
|
||||
Number.isSafeInteger(record.issuedAt) &&
|
||||
typeof record.operationId === 'string' &&
|
||||
/^[A-Za-z0-9_-]{16,80}$/.test(record.operationId)
|
||||
);
|
||||
}
|
||||
|
||||
function sign(secret: string, payload: string): string {
|
||||
return createHmac('sha256', secret).update(payload).digest('base64url');
|
||||
}
|
||||
|
||||
function safeEqual(expected: string, received: string): boolean {
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { copyFile, mkdir, rename, rm } from 'node:fs/promises';
|
||||
import { readdirSync, unlinkSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import Database from 'better-sqlite3';
|
||||
import { writeAudit } from '../auth/audit.js';
|
||||
import { backupDatabase } from '../db.js';
|
||||
import { formatInstantInZone } from '../time.js';
|
||||
|
||||
/** Central Time. 2:30 is missing on the spring-forward morning, so the clock comparison is used. */
|
||||
export const BACKUP_ZONE = 'America/Chicago';
|
||||
export const BACKUP_LOCAL_TIME = '02:30';
|
||||
export const DAILY_KEEP = 14;
|
||||
export const WEEKLY_KEEP = 8;
|
||||
|
||||
export function backupDirectory(dataDir: string): string {
|
||||
return path.join(dataDir, 'backups');
|
||||
}
|
||||
|
||||
const JOB = 'backup';
|
||||
const POLL_MS = 60 * 1000;
|
||||
const SNAPSHOT = /^(daily|weekly)-(\d{4}-\d{2}-\d{2})\.db$/;
|
||||
const MONTHS = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
] as const;
|
||||
|
||||
export type BackupCopy = (db: Database.Database, destination: string) => Promise<void>;
|
||||
|
||||
export type BackupResult = {
|
||||
ran: boolean;
|
||||
date: string;
|
||||
weekly: boolean;
|
||||
prunedDaily: number;
|
||||
prunedWeekly: number;
|
||||
};
|
||||
|
||||
export type BackupStatus = {
|
||||
state: 'saved' | 'waiting' | 'behind';
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves one consistent database copy per Central Time date, after 2:30.
|
||||
* A failed attempt does not remove older copies and does not record the day,
|
||||
* so the next check can try again. Sunday's copy is also kept as a weekly file.
|
||||
*/
|
||||
export async function runDueBackup(
|
||||
db: Database.Database,
|
||||
backupsDir: string,
|
||||
now: string,
|
||||
copy: BackupCopy = backupDatabase,
|
||||
): Promise<BackupResult> {
|
||||
const skipped: BackupResult = { ran: false, date: '', weekly: false, prunedDaily: 0, prunedWeekly: 0 };
|
||||
const clock = formatInstantInZone(now, BACKUP_ZONE);
|
||||
if (clock.time24 < BACKUP_LOCAL_TIME || alreadyRan(db, clock.date)) return skipped;
|
||||
const partial = path.join(backupsDir, `daily-${clock.date}.db.partial`);
|
||||
const daily = path.join(backupsDir, `daily-${clock.date}.db`);
|
||||
try {
|
||||
await copy(db, partial);
|
||||
await mkdir(backupsDir, { recursive: true });
|
||||
await rename(partial, daily);
|
||||
const weekly = clock.weekday === 0;
|
||||
if (weekly) await copySnapshot(daily, path.join(backupsDir, `weekly-${clock.date}.db`));
|
||||
const prunedDaily = pruneSnapshots(backupsDir, 'daily', DAILY_KEEP);
|
||||
const prunedWeekly = pruneSnapshots(backupsDir, 'weekly', WEEKLY_KEEP);
|
||||
markRan(db, clock.date, now);
|
||||
try {
|
||||
writeAudit(db, null, 'backup.save', { prunedDaily, prunedWeekly }, now);
|
||||
} catch {
|
||||
console.error('The database backup was saved, but the audit note was not recorded.');
|
||||
}
|
||||
return { ran: true, date: clock.date, weekly, prunedDaily, prunedWeekly };
|
||||
} catch (err) {
|
||||
await rm(partial, { force: true });
|
||||
console.error(err instanceof Error ? err.message : 'Database backup failed.');
|
||||
return skipped;
|
||||
}
|
||||
}
|
||||
|
||||
/** Newest daily copy, and whether today's backup is still expected later. */
|
||||
export function describeBackup(backupsDir: string, now: string): BackupStatus {
|
||||
const newest = newestSnapshot(backupsDir, 'daily');
|
||||
const clock = formatInstantInZone(now, BACKUP_ZONE);
|
||||
if (!newest) {
|
||||
const state = clock.time24 < BACKUP_LOCAL_TIME ? 'waiting' : 'behind';
|
||||
return { state, text: 'No database backup has been saved yet.' };
|
||||
}
|
||||
const label = prettyDate(newest);
|
||||
const savedToday = newest >= clock.date;
|
||||
const savedYesterday = newest >= previousDate(clock.date) && clock.time24 < BACKUP_LOCAL_TIME;
|
||||
if (savedToday || savedYesterday) return { state: 'saved', text: `Database backup saved ${label}.` };
|
||||
return { state: 'behind', text: `Database backup is behind. The newest saved copy is ${label}.` };
|
||||
}
|
||||
|
||||
export function startBackupRunner(
|
||||
db: Database.Database,
|
||||
backupsDir: string,
|
||||
now: () => string,
|
||||
): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await runDueBackup(db, backupsDir, now());
|
||||
if (result.ran) console.log(`Saved the database backup for ${result.date}.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Database backup failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
})();
|
||||
};
|
||||
const timer = setInterval(tick, POLL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function copySnapshot(source: string, destination: string): Promise<void> {
|
||||
const partial = `${destination}.partial`;
|
||||
try {
|
||||
await copyFile(source, partial);
|
||||
const check = new Database(partial, { readonly: true, fileMustExist: true });
|
||||
try {
|
||||
const result = check.pragma('integrity_check', { simple: true });
|
||||
if (result !== 'ok') throw new Error('Sunday backup failed the integrity check.');
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
await rename(partial, destination);
|
||||
} catch (err) {
|
||||
await rm(partial, { force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function pruneSnapshots(backupsDir: string, kind: 'daily' | 'weekly', keep: number): number {
|
||||
const matched = listSnapshots(backupsDir, kind);
|
||||
const extra = matched.slice(keep);
|
||||
for (const file of extra) unlinkSync(path.join(backupsDir, file.name));
|
||||
return extra.length;
|
||||
}
|
||||
|
||||
function newestSnapshot(backupsDir: string, kind: 'daily' | 'weekly'): string | null {
|
||||
return listSnapshots(backupsDir, kind)[0]?.date ?? null;
|
||||
}
|
||||
|
||||
function listSnapshots(backupsDir: string, kind: 'daily' | 'weekly'): { name: string; date: string }[] {
|
||||
let names: string[] = [];
|
||||
try {
|
||||
names = readdirSync(backupsDir);
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
||||
throw err;
|
||||
}
|
||||
return names
|
||||
.map((name) => {
|
||||
const match = SNAPSHOT.exec(name);
|
||||
if (!match || match[1] !== kind || !match[2]) return null;
|
||||
return { name, date: match[2] };
|
||||
})
|
||||
.filter((row): row is { name: string; date: string } => row !== null)
|
||||
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
|
||||
}
|
||||
|
||||
function prettyDate(iso: string): string {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
||||
const month = match ? MONTHS[Number(match[2]) - 1] : undefined;
|
||||
if (!match || !month) return iso;
|
||||
return `${month} ${Number(match[3])}, ${match[1]}`;
|
||||
}
|
||||
|
||||
function previousDate(iso: string): string {
|
||||
return Temporal.PlainDate.from(iso).subtract({ days: 1 }).toString();
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, BACKUP_ZONE, localDate);
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, BACKUP_ZONE, localDate, now);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { expandTemplates } from '../recurrence.js';
|
||||
import { formatInstantInZone } from '../time.js';
|
||||
|
||||
/** Local time after which that event's day gets its weekly fill. */
|
||||
export const REFILL_LOCAL_TIME = '01:00';
|
||||
|
||||
const JOB = 'template.expand';
|
||||
const INTERVAL_MS = 60 * 1000;
|
||||
|
||||
export type DailyExpandResult = {
|
||||
zones: string[];
|
||||
created: number;
|
||||
skipped: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Fills active weekly templates once each local date, after 01:00 in that
|
||||
* event's time zone. A restart later the same day still fills if that date
|
||||
* has not been recorded. The check uses the clock, not a 24-hour timer.
|
||||
*/
|
||||
export function runDueTemplateExpansion(db: Database.Database, now: string): DailyExpandResult {
|
||||
const zones = db.prepare('SELECT DISTINCT tz AS tz FROM events ORDER BY tz').all() as { tz: string }[];
|
||||
const ran: string[] = [];
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const zone of zones) {
|
||||
let date = '';
|
||||
let time = '';
|
||||
try {
|
||||
const clock = formatInstantInZone(now, zone.tz);
|
||||
date = clock.date;
|
||||
time = clock.time24;
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill could not read an event time zone.');
|
||||
continue;
|
||||
}
|
||||
if (time < REFILL_LOCAL_TIME || alreadyRan(db, zone.tz, date)) continue;
|
||||
try {
|
||||
const result = expandTemplates(db, now, { timeZone: zone.tz });
|
||||
markRan(db, zone.tz, date, now);
|
||||
created += result.created;
|
||||
skipped.push(...result.skipped);
|
||||
ran.push(zone.tz);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
|
||||
}
|
||||
}
|
||||
return { zones: ran, created, skipped };
|
||||
}
|
||||
|
||||
/** Checks about once a minute. A check that is still running is not started again. */
|
||||
export function startDailyExpansionRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
const result = runDueTemplateExpansion(db, now());
|
||||
if (result.created > 0) {
|
||||
console.log(`Added ${result.created} weekly shifts for the next eight weeks.`);
|
||||
}
|
||||
for (const skip of result.skipped) console.error(skip);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, timeZone: string, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, timeZone, localDate);
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, timeZone: string, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, timeZone, localDate, now);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from '../auth/audit.js';
|
||||
import { purgeRateHits } from '../rate-limit.js';
|
||||
import { readRetentionMonths } from '../settings.js';
|
||||
import { formatInstantInZone, formatUtc } from '../time.js';
|
||||
|
||||
/** Central Time, once each local date, after the weekly refill hour. */
|
||||
export const RETENTION_ZONE = 'America/Chicago';
|
||||
export const RETENTION_LOCAL_TIME = '01:00';
|
||||
/** Volunteer mail keeps its recipient and body this long after it is finished. */
|
||||
export const OUTBOX_KEEP_DAYS = 30;
|
||||
/** Audit rows are counts and ids. They are kept for two years, separate from signup retention. */
|
||||
export const AUDIT_KEEP_MONTHS = 24;
|
||||
|
||||
const JOB = 'retention';
|
||||
const POLL_MS = 60 * 1000;
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
|
||||
export type RetentionResult = {
|
||||
signups: number;
|
||||
messages: number;
|
||||
sessions: number;
|
||||
loginTokens: number;
|
||||
auditRows: number;
|
||||
rateHits: number;
|
||||
};
|
||||
|
||||
type OutboxRow = {
|
||||
id: number;
|
||||
signup_id: number | null;
|
||||
kind: string;
|
||||
status: string;
|
||||
dedupe_key: string;
|
||||
created_at: string;
|
||||
sent_at: string | null;
|
||||
delivery_unknown_at: string | null;
|
||||
claimed_at: string | null;
|
||||
lease_expires_at: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes personal details that are past their keep period. Safe to run more
|
||||
* than once. A name is cleared in the live database only. Downloaded files,
|
||||
* inboxes, and older copies of the database file are outside this cleanup.
|
||||
*/
|
||||
export function runRetention(db: Database.Database, now: string): RetentionResult {
|
||||
const result = db.transaction((): RetentionResult => {
|
||||
const signups = anonymizeSignups(db, now);
|
||||
const login = purgeLoginPayloadsIn(db, now);
|
||||
const auditRows = purgeAudit(db, now);
|
||||
const rateHits = purgeRateHits(db, now);
|
||||
const changed = signups + login.messages + login.sessions + login.loginTokens + auditRows;
|
||||
if (changed > 0) {
|
||||
writeAudit(db, null, 'retention.cleanup', {
|
||||
signups,
|
||||
messages: login.messages,
|
||||
sessions: login.sessions,
|
||||
loginTokens: login.loginTokens,
|
||||
auditRows,
|
||||
}, now);
|
||||
}
|
||||
return { signups, messages: login.messages, sessions: login.sessions, loginTokens: login.loginTokens, auditRows, rateHits };
|
||||
}).immediate();
|
||||
if (result.signups > 0) console.log(`Removed personal details from ${result.signups} old signups.`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Sign-in links, expired sessions, and expired sign-in messages. The hourly check uses this. */
|
||||
export function purgeLoginPayloads(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
|
||||
return db.transaction(() => purgeLoginPayloadsIn(db, now)).immediate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the cleanup once per Central Time date, after 1:00. When 1:00 happens
|
||||
* twice, the second hour does nothing. A start before 1:00 does not record
|
||||
* the day, so the 1:00 run can still happen.
|
||||
*/
|
||||
export function runDueRetention(db: Database.Database, now: string): { ran: boolean; result: RetentionResult } {
|
||||
const clock = formatInstantInZone(now, RETENTION_ZONE);
|
||||
const empty = { signups: 0, messages: 0, sessions: 0, loginTokens: 0, auditRows: 0, rateHits: 0 };
|
||||
if (clock.time24 < RETENTION_LOCAL_TIME || alreadyRan(db, clock.date)) return { ran: false, result: empty };
|
||||
try {
|
||||
const result = runRetention(db, now);
|
||||
markRan(db, clock.date, now);
|
||||
return { ran: true, result };
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
|
||||
return { ran: false, result: empty };
|
||||
}
|
||||
}
|
||||
|
||||
export function startRetentionRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
return startRunner(POLL_MS, () => {
|
||||
const due = runDueRetention(db, now());
|
||||
return due.ran ? due.result.messages : 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** Expired sign-in messages, finished mail past 30 days, and rate-limit counters. Signup names stay on the daily run. */
|
||||
export function startHourlyCleanupRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
return startRunner(HOUR_MS, () => {
|
||||
const login = purgeLoginPayloads(db, now());
|
||||
purgeRateHits(db, now());
|
||||
return login.messages;
|
||||
});
|
||||
}
|
||||
|
||||
function startRunner(intervalMs: number, tickBody: () => number): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
const messages = tickBody();
|
||||
if (messages > 0) console.log(`Removed personal details from ${messages} old messages.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function anonymizeSignups(db: Database.Database, now: string): number {
|
||||
const months = readRetentionMonths(db);
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, s.ends_at_utc AS ends_at_utc, e.tz AS tz
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE su.anonymized_at IS NULL`,
|
||||
)
|
||||
.all() as { id: number; ends_at_utc: string; tz: string }[];
|
||||
const update = db.prepare(
|
||||
`UPDATE signups
|
||||
SET name = NULL, email = NULL, email_norm = NULL, phone = NULL, is_minor = 0,
|
||||
guardian_name = NULL, guardian_email = NULL, notes = NULL,
|
||||
manage_token_hash = NULL, token_expires_at = NULL,
|
||||
anonymized_at = ?, updated_at = ?
|
||||
WHERE id = ? AND anonymized_at IS NULL`,
|
||||
);
|
||||
let count = 0;
|
||||
for (const row of rows) {
|
||||
let due = false;
|
||||
try {
|
||||
const ended = Temporal.Instant.from(row.ends_at_utc).toZonedDateTimeISO(row.tz);
|
||||
due = Temporal.Instant.compare(Temporal.Instant.from(now), ended.add({ months }).toInstant()) >= 0;
|
||||
} catch {
|
||||
console.error('Retention skipped a signup because its event time zone is not valid.');
|
||||
continue;
|
||||
}
|
||||
if (!due) continue;
|
||||
count += update.run(now, now, row.id).changes;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function purgeLoginPayloadsIn(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
|
||||
const messages = purgeOutbox(db, now);
|
||||
const sessions = db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes;
|
||||
const loginTokens = db
|
||||
.prepare('DELETE FROM login_tokens WHERE used_at IS NOT NULL OR expires_at <= ?')
|
||||
.run(now).changes;
|
||||
return { messages, sessions, loginTokens };
|
||||
}
|
||||
|
||||
function purgeOutbox(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(Temporal.Instant.from(now).subtract({ hours: OUTBOX_KEEP_DAYS * 24 }));
|
||||
const liveMagic = new Set(
|
||||
(
|
||||
db
|
||||
.prepare(
|
||||
`SELECT token_hash AS token_hash FROM login_tokens
|
||||
WHERE used_at IS NULL AND expires_at > ?`,
|
||||
)
|
||||
.all(now) as { token_hash: string }[]
|
||||
).map((row) => row.token_hash),
|
||||
);
|
||||
const anonymized = new Set(
|
||||
(db.prepare('SELECT id AS id FROM signups WHERE anonymized_at IS NOT NULL').all() as { id: number }[]).map((row) => row.id),
|
||||
);
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT id AS id, signup_id AS signup_id, kind AS kind, status AS status, dedupe_key AS dedupe_key,
|
||||
created_at AS created_at, sent_at AS sent_at, delivery_unknown_at AS delivery_unknown_at,
|
||||
claimed_at AS claimed_at, lease_expires_at AS lease_expires_at
|
||||
FROM outbox
|
||||
WHERE dedupe_key NOT LIKE 'purged:%'`,
|
||||
)
|
||||
.all() as OutboxRow[];
|
||||
const update = db.prepare(
|
||||
`UPDATE outbox
|
||||
SET dedupe_key = ?, to_email = '', subject = '', body_text = '', body_html = '',
|
||||
headers_json = '{}', last_error = NULL,
|
||||
status = CASE WHEN status IN ('pending', 'sending') THEN 'cancelled' ELSE status END
|
||||
WHERE id = ?`,
|
||||
);
|
||||
let count = 0;
|
||||
for (const row of rows) {
|
||||
if (!messageDue(row, now, cutoff, liveMagic, anonymized)) continue;
|
||||
count += update.run(`purged:${row.id}`, row.id).changes;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function messageDue(row: OutboxRow, now: string, cutoff: string, liveMagic: Set<string>, anonymized: Set<number>): boolean {
|
||||
if (row.status === 'sending' && row.lease_expires_at && row.lease_expires_at > now) return false;
|
||||
if (row.signup_id !== null && anonymized.has(row.signup_id)) return true;
|
||||
if (row.kind === 'magic_link') {
|
||||
const hash = row.dedupe_key.startsWith('magic_link:') ? row.dedupe_key.slice('magic_link:'.length) : '';
|
||||
return hash.length === 0 || !liveMagic.has(hash);
|
||||
}
|
||||
const stamp = contentStamp(row);
|
||||
return stamp !== null && stamp <= cutoff;
|
||||
}
|
||||
|
||||
function contentStamp(row: OutboxRow): string | null {
|
||||
if (row.status === 'sent') return row.sent_at ?? row.created_at;
|
||||
if (row.status === 'delivery_unknown') return row.delivery_unknown_at ?? row.claimed_at ?? row.created_at;
|
||||
if (row.status === 'pending' || row.status === 'sending' || row.status === 'failed' || row.status === 'cancelled') {
|
||||
return row.claimed_at ?? row.created_at;
|
||||
}
|
||||
return row.created_at;
|
||||
}
|
||||
|
||||
function purgeAudit(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(
|
||||
Temporal.Instant.from(now).toZonedDateTimeISO(RETENTION_ZONE).subtract({ months: AUDIT_KEEP_MONTHS }).toInstant(),
|
||||
);
|
||||
return db.prepare('DELETE FROM audit WHERE at <= ?').run(cutoff).changes;
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ready FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, RETENTION_ZONE, localDate);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, RETENTION_ZONE, localDate, now);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Mailer, OutboundMail } from './types.js';
|
||||
|
||||
/** Development mailbox. The message is accepted locally and printed. It is not delivered to a person. */
|
||||
export function createConsoleMailer(write: (line: string) => void = (line) => console.log(line)): Mailer {
|
||||
return {
|
||||
async send(message: OutboundMail) {
|
||||
const extra = Object.entries(message.headers ?? {}).map(([name, value]) => `${name}: ${value}`);
|
||||
write([
|
||||
'Mail console driver accepted a message.',
|
||||
`To: ${message.to}`,
|
||||
`Subject: ${message.subject}`,
|
||||
...extra,
|
||||
message.text,
|
||||
].join('\n'));
|
||||
return { result: 'sent', providerId: null };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const LEASE_MS = 2 * 60 * 1000;
|
||||
const MAX_ATTEMPTS = 5;
|
||||
const BATCH = 20;
|
||||
|
||||
type ClaimedRow = {
|
||||
id: number;
|
||||
signup_id: number | null;
|
||||
kind: string;
|
||||
dedupe_key: string;
|
||||
to_email: string;
|
||||
subject: string;
|
||||
body_text: string;
|
||||
body_html: string;
|
||||
headers_json: string;
|
||||
attempts: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Claims due confirmation, change, cancellation, reminder, and sign-in mail, then sends outside the database transaction.
|
||||
* An expired sending lease becomes delivery_unknown and is not sent again.
|
||||
* sent_at means the provider accepted the message.
|
||||
*/
|
||||
export async function deliverDueMail(
|
||||
db: Database.Database,
|
||||
mailer: Mailer,
|
||||
now: string,
|
||||
random: () => number = Math.random,
|
||||
): Promise<number> {
|
||||
let accepted = 0;
|
||||
for (let index = 0; index < BATCH; index += 1) {
|
||||
const claimed = claimNext(db, now);
|
||||
if (!claimed) break;
|
||||
const reason = obsoleteReason(db, claimed, now);
|
||||
if (reason) {
|
||||
settle(db, claimed.id, { result: 'failed', error: reason }, now, random, 'cancelled');
|
||||
continue;
|
||||
}
|
||||
let delivery: MailDelivery;
|
||||
try {
|
||||
delivery = await mailer.send(outbound(claimed));
|
||||
} catch (err) {
|
||||
delivery = { result: 'unknown', error: redactMailError(err instanceof Error ? err.message : 'Mail send failed.') };
|
||||
}
|
||||
settle(db, claimed.id, delivery, now, random);
|
||||
if (delivery.result === 'sent') accepted += 1;
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
export function retryDelayMs(attempts: number, random: () => number): number {
|
||||
const base = Math.min(30_000 * 2 ** Math.max(0, attempts - 1), 15 * 60 * 1000);
|
||||
const unit = random();
|
||||
const jitter = 0.8 + (Number.isFinite(unit) ? Math.min(1, Math.max(0, unit)) : 0) * 0.4;
|
||||
return Math.round(base * jitter);
|
||||
}
|
||||
|
||||
function claimNext(db: Database.Database, now: string): ClaimedRow | null {
|
||||
const leaseEnd = formatUtc(Temporal.Instant.from(now).add({ milliseconds: LEASE_MS }));
|
||||
return db.transaction(() => {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'delivery_unknown', delivery_unknown_at = ?, last_error = ?
|
||||
WHERE status = 'sending' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?`,
|
||||
).run(now, 'The sending lease expired before a result was recorded.', now);
|
||||
const next = db
|
||||
.prepare(
|
||||
`SELECT id AS id
|
||||
FROM outbox
|
||||
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link')
|
||||
ORDER BY id
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(now) as { id: number } | undefined;
|
||||
if (!next) return null;
|
||||
const claimed = db
|
||||
.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'sending', attempts = attempts + 1, claimed_at = ?, lease_expires_at = ?
|
||||
WHERE id = ? AND status = 'pending'`,
|
||||
)
|
||||
.run(now, leaseEnd, next.id);
|
||||
if (claimed.changes !== 1) return null;
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT id, signup_id, kind, dedupe_key, to_email, subject, body_text, body_html, headers_json, attempts
|
||||
FROM outbox WHERE id = ?`,
|
||||
)
|
||||
.get(next.id) as ClaimedRow;
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||
if (row.kind === 'magic_link') return magicLinkReason(db, row, now);
|
||||
if (row.signup_id === null) return 'The signup is no longer available.';
|
||||
const signup = db
|
||||
.prepare(
|
||||
`SELECT su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
||||
su.reminders_off AS reminders_off,
|
||||
s.cancelled AS shift_cancelled, s.version AS version, s.starts_at_utc AS starts_at_utc
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
WHERE su.id = ?`,
|
||||
)
|
||||
.get(row.signup_id) as
|
||||
| {
|
||||
status: string;
|
||||
token_expires_at: string | null;
|
||||
anonymized_at: string | null;
|
||||
reminders_off: number;
|
||||
shift_cancelled: number;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
}
|
||||
| undefined;
|
||||
if (!signup || signup.anonymized_at) return 'The signup is no longer available.';
|
||||
if (row.kind === 'reminder') return reminderReason(row, signup, now);
|
||||
if (!signup.token_expires_at || signup.token_expires_at <= now) return 'The manage link expired before this message was sent.';
|
||||
if (row.kind === 'confirmation' && (signup.status !== 'confirmed' || signup.shift_cancelled === 1)) {
|
||||
return 'The signup changed before this message was sent.';
|
||||
}
|
||||
if (row.kind === 'changed') {
|
||||
const version = changedVersion(row.dedupe_key);
|
||||
if (signup.status !== 'confirmed' || signup.shift_cancelled === 1 || version !== signup.version) {
|
||||
return 'The shift changed again before this message was sent.';
|
||||
}
|
||||
}
|
||||
if (row.kind === 'cancelled' && signup.status !== 'cancelled') return 'The signup is not cancelled.';
|
||||
return null;
|
||||
}
|
||||
|
||||
function magicLinkReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||
const match = /^magic_link:([a-f0-9]{64})$/.exec(row.dedupe_key);
|
||||
const hash = match?.[1];
|
||||
if (!hash) return 'The sign-in link is no longer available.';
|
||||
const token = db
|
||||
.prepare(
|
||||
`SELECT t.used_at AS used_at, t.expires_at AS expires_at, c.active AS active
|
||||
FROM login_tokens t
|
||||
JOIN coordinators c ON c.id = t.coordinator_id
|
||||
WHERE t.token_hash = ?`,
|
||||
)
|
||||
.get(hash) as { used_at: string | null; expires_at: string; active: number } | undefined;
|
||||
if (!token || token.used_at !== null || token.expires_at <= now || token.active !== 1) {
|
||||
return 'The sign-in link is no longer available.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function reminderReason(
|
||||
row: ClaimedRow,
|
||||
signup: { status: string; reminders_off: number; shift_cancelled: number; version: number; starts_at_utc: string; token_expires_at: string | null },
|
||||
now: string,
|
||||
): string | null {
|
||||
const version = reminderVersion(row.dedupe_key);
|
||||
if (signup.status !== 'confirmed' || signup.reminders_off === 1) {
|
||||
return signup.reminders_off === 1
|
||||
? 'Reminders were turned off before this message was sent.'
|
||||
: 'The signup changed before this reminder was sent.';
|
||||
}
|
||||
if (signup.shift_cancelled === 1 || version !== signup.version) return 'The shift changed before this reminder was sent.';
|
||||
if (signup.starts_at_utc <= now) return 'The shift started before this reminder was sent.';
|
||||
if (!signup.token_expires_at || signup.token_expires_at <= now) return 'The manage link expired before this message was sent.';
|
||||
return null;
|
||||
}
|
||||
|
||||
function reminderVersion(dedupeKey: string): number | null {
|
||||
const match = /^reminder:v([1-9][0-9]*):/.exec(dedupeKey);
|
||||
if (!match?.[1]) return null;
|
||||
const value = Number(match[1]);
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
}
|
||||
|
||||
function changedVersion(dedupeKey: string): number | null {
|
||||
const match = /^changed:v([1-9][0-9]*):/.exec(dedupeKey);
|
||||
if (!match?.[1]) return null;
|
||||
const value = Number(match[1]);
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
}
|
||||
|
||||
function outbound(row: ClaimedRow): OutboundMail {
|
||||
const stored = JSON.parse(row.headers_json) as Record<string, string>;
|
||||
const headers: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(stored)) {
|
||||
if (key === 'From' || key === 'Reply-To' || typeof value !== 'string') continue;
|
||||
headers[key] = value;
|
||||
}
|
||||
return {
|
||||
from: stored.From ?? '',
|
||||
to: row.to_email,
|
||||
replyTo: stored['Reply-To'] ?? '',
|
||||
subject: row.subject,
|
||||
text: row.body_text,
|
||||
html: row.body_html,
|
||||
headers,
|
||||
};
|
||||
}
|
||||
|
||||
function settle(
|
||||
db: Database.Database,
|
||||
id: number,
|
||||
delivery: MailDelivery,
|
||||
now: string,
|
||||
random: () => number,
|
||||
force?: 'cancelled',
|
||||
): void {
|
||||
if (force === 'cancelled') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(delivery.result === 'failed' ? delivery.error : 'The message was not sent.', id);
|
||||
return;
|
||||
}
|
||||
if (delivery.result === 'sent') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'sent', provider_id = ?, sent_at = ?, last_error = NULL, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(delivery.providerId, now, id);
|
||||
db.prepare('UPDATE reminders_sent SET sent_at = ? WHERE outbox_id = ? AND sent_at IS NULL').run(now, id);
|
||||
return;
|
||||
}
|
||||
const attempts = db.prepare('SELECT attempts AS attempts FROM outbox WHERE id = ?').get(id) as { attempts: number };
|
||||
const error = redactMailError(delivery.error);
|
||||
if (delivery.result === 'unknown') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'delivery_unknown', delivery_unknown_at = ?, last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(now, error, id);
|
||||
console.error(`Mail result unknown for outbox ${id}.`);
|
||||
return;
|
||||
}
|
||||
if (delivery.result === 'retry' && attempts.attempts < MAX_ATTEMPTS) {
|
||||
const sendAfter = formatUtc(Temporal.Instant.from(now).add({ milliseconds: retryDelayMs(attempts.attempts, random) }));
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'pending', send_after = ?, last_error = ?, claimed_at = NULL, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(sendAfter, error, id);
|
||||
return;
|
||||
}
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'failed', last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(error, id);
|
||||
console.error(`Mail result failed for outbox ${id}.`);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { createConsoleMailer } from './console.js';
|
||||
import { createPostmarkMailer } from './postmark.js';
|
||||
import { createSesMailer } from './ses.js';
|
||||
import type { Mailer } from './types.js';
|
||||
|
||||
export function createMailer(config: AppConfig): Mailer {
|
||||
if (config.mail.driver === 'console') return createConsoleMailer();
|
||||
if (config.mail.driver === 'postmark') {
|
||||
if (!config.mail.postmarkToken) throw new Error('POSTMARK_TOKEN is required for the postmark mail driver.');
|
||||
return createPostmarkMailer(config.mail.postmarkToken);
|
||||
}
|
||||
if (!config.mail.ses) throw new Error('SES credentials are required for the ses mail driver.');
|
||||
return createSesMailer({
|
||||
region: config.mail.ses.region,
|
||||
accessKeyId: config.mail.ses.accessKeyId,
|
||||
secretAccessKey: config.mail.ses.secretAccessKey,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Escape text that came from a person before it is placed in HTML mail. */
|
||||
export function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
/** Keep a subject on one line so a name cannot add mail headers. */
|
||||
export function singleLine(value: string): string {
|
||||
return value.replace(/[\u0000-\u001F\u007F]+/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const ENDPOINT = 'https://api.postmarkapp.com/email';
|
||||
|
||||
/**
|
||||
* Postmark's send API. There is no idempotency key that makes a second POST harmless,
|
||||
* so a duplicate is prevented by the outbox dedupe key, not by Postmark.
|
||||
*/
|
||||
export function createPostmarkMailer(token: string, fetchImpl: typeof fetch = fetch): Mailer {
|
||||
return {
|
||||
async send(message: OutboundMail): Promise<MailDelivery> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchImpl(ENDPOINT, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
redirect: 'error',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Postmark-Server-Token': token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
From: message.from,
|
||||
To: message.to,
|
||||
Subject: message.subject,
|
||||
TextBody: message.text,
|
||||
HtmlBody: message.html,
|
||||
ReplyTo: message.replyTo,
|
||||
MessageStream: 'outbound',
|
||||
...(message.headers && Object.keys(message.headers).length > 0
|
||||
? { Headers: Object.entries(message.headers).map(([Name, Value]) => ({ Name, Value })) }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
const messageText = err instanceof Error ? err.message : 'Postmark request failed.';
|
||||
const uncertain = err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
|
||||
return {
|
||||
result: uncertain ? 'unknown' : 'retry',
|
||||
error: redactMailError(messageText),
|
||||
};
|
||||
}
|
||||
if (response.status === 408 || response.status === 504) {
|
||||
return { result: 'unknown', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
if (response.status === 429 || response.status >= 500) {
|
||||
return { result: 'retry', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
let payload: { ErrorCode?: number; Message?: string; MessageID?: string } = {};
|
||||
try {
|
||||
payload = (await response.json()) as typeof payload;
|
||||
} catch {
|
||||
return { result: response.ok ? 'unknown' : 'failed', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
if (response.ok && (payload.ErrorCode === undefined || payload.ErrorCode === 0)) {
|
||||
return { result: 'sent', providerId: payload.MessageID ?? null };
|
||||
}
|
||||
return { result: 'failed', error: redactMailError(payload.Message || `Postmark responded ${response.status}.`) };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { absoluteUrl } from '../url.js';
|
||||
import { renderCancellation, renderChanged, renderConfirmation, renderMagicLink, renderMoved, renderSwitched, type MailShift } from './templates.js';
|
||||
import type { MailIdentity } from './types.js';
|
||||
|
||||
export type QueuedSignup = {
|
||||
signupId: number;
|
||||
shiftId: number;
|
||||
shiftVersion: number;
|
||||
token: string;
|
||||
volunteerName: string;
|
||||
volunteerEmail: string;
|
||||
guardianEmail: string | null;
|
||||
shift: MailShift;
|
||||
mail: MailIdentity;
|
||||
now: string;
|
||||
linkNote?: string;
|
||||
};
|
||||
|
||||
/** Inserts one row per recipient. The same logical message does not get a second row. */
|
||||
export function queueConfirmation(db: Database.Database, input: QueuedSignup): void {
|
||||
queue(db, 'confirmation', input, (audience) => renderConfirmation({
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
}));
|
||||
}
|
||||
|
||||
export function queueCancellation(db: Database.Database, input: QueuedSignup): void {
|
||||
queue(db, 'cancelled', input, (audience) => renderCancellation({
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
linkNote: input.linkNote,
|
||||
}));
|
||||
}
|
||||
|
||||
export function queueChanged(db: Database.Database, input: QueuedSignup, reason: 'edit' | 'move' | 'switch' = 'edit'): void {
|
||||
queue(db, 'changed', input, (audience) => {
|
||||
const letter = {
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
};
|
||||
if (reason === 'move') return renderMoved(letter);
|
||||
if (reason === 'switch') return renderSwitched(letter);
|
||||
return renderChanged(letter);
|
||||
});
|
||||
}
|
||||
|
||||
export function queueMagicLink(
|
||||
db: Database.Database,
|
||||
input: { email: string; token: string; tokenHash: string; mail: MailIdentity; now: string },
|
||||
): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
|
||||
).run('A newer sign-in link replaced this message.', input.email);
|
||||
const rendered = renderMagicLink({
|
||||
signInUrl: absoluteUrl(input.mail, `/login/link/${input.token}`),
|
||||
replyTo: input.mail.replyTo,
|
||||
});
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at
|
||||
) VALUES (?, NULL, NULL, 'magic_link', ?, ?, ?, ?, ?, ?, 0, 'pending', ?)`,
|
||||
).run(
|
||||
`magic_link:${input.tokenHash}`,
|
||||
input.email,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
|
||||
input.now,
|
||||
input.now,
|
||||
);
|
||||
}
|
||||
|
||||
/** Pending confirmation or change mail is obsolete after the signup is cancelled. Sent mail cannot be recalled. */
|
||||
export function cancelPendingConfirmations(db: Database.Database, signupId: number): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE signup_id = ? AND kind IN ('confirmation', 'changed') AND status = 'pending'`,
|
||||
).run('The signup was cancelled before this message was sent.', signupId);
|
||||
}
|
||||
|
||||
/** A reminder still waiting is not sent after the signup moves, is cancelled, or turns reminders off. Sent mail cannot be recalled. */
|
||||
export function cancelPendingReminders(
|
||||
db: Database.Database,
|
||||
signupId: number,
|
||||
reason = 'The signup moved before this reminder was sent.',
|
||||
): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE signup_id = ? AND kind = 'reminder' AND status = 'pending'`,
|
||||
).run(reason, signupId);
|
||||
}
|
||||
|
||||
function queue(
|
||||
db: Database.Database,
|
||||
kind: 'confirmation' | 'cancelled' | 'changed',
|
||||
input: QueuedSignup,
|
||||
render: (audience: 'volunteer' | 'guardian') => { subject: string; text: string; html: string },
|
||||
): void {
|
||||
for (const recipient of recipients(input.volunteerEmail, input.guardianEmail)) {
|
||||
const audience = recipient === input.volunteerEmail ? 'volunteer' : 'guardian';
|
||||
const rendered = render(audience);
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
).run(
|
||||
`${kind}:v${input.shiftVersion}:${input.signupId}:${recipient}`,
|
||||
input.signupId,
|
||||
input.shiftId,
|
||||
kind,
|
||||
recipient,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
|
||||
input.now,
|
||||
input.now,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function recipients(volunteerEmail: string, guardianEmail: string | null): string[] {
|
||||
if (!guardianEmail || guardianEmail === volunteerEmail) return [volunteerEmail];
|
||||
return [volunteerEmail, guardianEmail];
|
||||
}
|
||||
|
||||
function manageUrl(input: QueuedSignup): string {
|
||||
return absoluteUrl(input.mail, `/m/${input.token}`);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Drop addresses and manage links before an error is stored or logged. */
|
||||
export function redactMailError(value: string): string {
|
||||
return value
|
||||
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]')
|
||||
.replace(/\/m\/[A-Za-z0-9_-]{10,}/g, '/m/[token]')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 300);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { deliverDueMail } from './deliver.js';
|
||||
import type { Mailer } from './types.js';
|
||||
|
||||
const INTERVAL_MS = 30_000;
|
||||
|
||||
/**
|
||||
* One in-process pass every 30 seconds. A pass that is still running is not started again.
|
||||
* Already accepted mail cannot be recalled.
|
||||
*/
|
||||
export function startOutboxRunner(db: Database.Database, mailer: Mailer, now: () => string): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
void deliverDueMail(db, mailer, now())
|
||||
.catch((err: unknown) => {
|
||||
console.error(err instanceof Error ? err.message : 'Mail delivery failed.');
|
||||
})
|
||||
.finally(() => {
|
||||
running = false;
|
||||
});
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const PERMANENT = new Set([
|
||||
'MessageRejected',
|
||||
'MailFromDomainNotVerifiedException',
|
||||
'AccountSuspendedException',
|
||||
'SendingPausedException',
|
||||
]);
|
||||
|
||||
const RETRYABLE = new Set([
|
||||
'TooManyRequestsException',
|
||||
'LimitExceededException',
|
||||
'ServiceUnavailableException',
|
||||
'InternalFailure',
|
||||
]);
|
||||
|
||||
export type SesSender = {
|
||||
send(command: SendEmailCommand, options?: { abortSignal?: AbortSignal }): Promise<{ MessageId?: string }>;
|
||||
};
|
||||
|
||||
/** SESv2 SendEmail. Acceptance is MessageId, not proof the person received the mail. */
|
||||
export function createSesMailer(options: {
|
||||
region: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
client?: SesSender;
|
||||
}): Mailer {
|
||||
const client = options.client ?? new SESv2Client({
|
||||
maxAttempts: 1,
|
||||
region: options.region,
|
||||
credentials: {
|
||||
accessKeyId: options.accessKeyId,
|
||||
secretAccessKey: options.secretAccessKey,
|
||||
},
|
||||
});
|
||||
return {
|
||||
async send(message: OutboundMail): Promise<MailDelivery> {
|
||||
try {
|
||||
const result = await client.send(new SendEmailCommand({
|
||||
FromEmailAddress: message.from,
|
||||
Destination: { ToAddresses: [message.to] },
|
||||
ReplyToAddresses: [message.replyTo],
|
||||
Content: {
|
||||
Simple: {
|
||||
Subject: { Data: message.subject, Charset: 'UTF-8' },
|
||||
Body: {
|
||||
Text: { Data: message.text, Charset: 'UTF-8' },
|
||||
Html: { Data: message.html, Charset: 'UTF-8' },
|
||||
},
|
||||
...(message.headers && Object.keys(message.headers).length > 0
|
||||
? { Headers: Object.entries(message.headers).map(([Name, Value]) => ({ Name, Value })) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}), { abortSignal: AbortSignal.timeout(15_000) });
|
||||
return { result: 'sent', providerId: result.MessageId ?? null };
|
||||
} catch (err) {
|
||||
return mapSesError(err);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mapSesError(err: unknown): MailDelivery {
|
||||
const name = err instanceof Error ? err.name : '';
|
||||
const error = redactMailError(err instanceof Error ? err.message : 'SES request failed.');
|
||||
if (PERMANENT.has(name)) return { result: 'failed', error };
|
||||
if (RETRYABLE.has(name)) return { result: 'retry', error };
|
||||
if (name === 'TimeoutError' || name === 'AbortError') return { result: 'unknown', error };
|
||||
return { result: 'unknown', error };
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import { escapeHtml, singleLine } from './html.js';
|
||||
|
||||
export type MailShift = {
|
||||
role: string;
|
||||
eventTitle: string;
|
||||
location: string;
|
||||
whenLabel: string;
|
||||
};
|
||||
|
||||
export type RenderedMail = {
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Confirmation and cancellation letters.
|
||||
* Email clients do not load the app stylesheet, so the HTML repeats the fallback
|
||||
* ink and blue from public/brand/tokens.css.
|
||||
*/
|
||||
export function renderConfirmation(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name} is signed up for ${role}` : `You're signed up for ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} is signed up for ${role}. You are listed as the parent or guardian.`
|
||||
: `You are signed up for ${role}.`;
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: 'You can cancel or switch this signup from that link. Use the separate link for each signup.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderCancellation(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
linkNote?: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian'
|
||||
? `${name}'s signup for ${role} is cancelled`
|
||||
: `Your signup for ${role} is cancelled`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name}'s signup for ${role} is cancelled. The spot is open for someone else.`
|
||||
: `Your signup for ${role} is cancelled. The spot is open for someone else.`;
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: input.linkNote ?? 'That link opens the cancelled signup.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderChanged(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s ${role} shift has changed` : `Your ${role} shift has changed`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `The time or place for ${name}'s ${role} shift has changed.`
|
||||
: `The time or place for your ${role} shift has changed.`;
|
||||
return changedLetter(input, subject, hello);
|
||||
}
|
||||
|
||||
export function renderMoved(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s signup was moved to ${role}` : `Your signup was moved to ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `A coordinator moved ${name}'s signup to a different shift.`
|
||||
: 'A coordinator moved your signup to a different shift.';
|
||||
return changedLetter(input, subject, hello);
|
||||
}
|
||||
|
||||
export function renderSwitched(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s signup was switched to ${role}` : `Your signup was switched to ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} switched this signup to a different shift.`
|
||||
: 'You switched this signup to a different shift.';
|
||||
return changedLetter(input, subject, hello);
|
||||
}
|
||||
|
||||
function changedLetter(
|
||||
input: { audience: 'volunteer' | 'guardian'; volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
||||
subject: string,
|
||||
hello: string,
|
||||
): RenderedMail {
|
||||
const name = singleLine(input.volunteerName);
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: 'This link replaces the earlier one. The previous link no longer works.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderReminder(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
unsubscribeUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = `Reminder: ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} is still signed up for ${role}. You are listed as the parent or guardian.`
|
||||
: `You are still signed up for ${role}.`;
|
||||
const cancelNote = 'To cancel, use the link in your confirmation email.';
|
||||
const stopNote = `To stop reminder emails for this signup, open ${input.unsubscribeUrl}. The pantry reads mail sent to ${input.replyTo}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.`;
|
||||
const greeting = input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`;
|
||||
const when = input.shift.whenLabel;
|
||||
const place = input.shift.location.trim();
|
||||
const lines = [
|
||||
greeting,
|
||||
'',
|
||||
hello,
|
||||
'',
|
||||
input.shift.eventTitle,
|
||||
when,
|
||||
...(place ? [place] : []),
|
||||
'',
|
||||
cancelNote,
|
||||
'',
|
||||
stopNote,
|
||||
'',
|
||||
'Hope Food Pantry',
|
||||
];
|
||||
const htmlPlace = place ? `<br>${escapeHtml(place)}` : '';
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>${escapeHtml(greeting)}</p>
|
||||
<p>${escapeHtml(hello)}</p>
|
||||
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||
<p>${escapeHtml(cancelNote)}</p>
|
||||
<p><a href="${escapeHtml(input.unsubscribeUrl)}" style="color:#222">Stop reminder emails</a></p>
|
||||
<p>The pantry reads mail sent to ${escapeHtml(input.replyTo)}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject, text: lines.join('\n'), html };
|
||||
}
|
||||
|
||||
export function renderMagicLink(input: { signInUrl: string; replyTo: string }): RenderedMail {
|
||||
const subject = 'Sign in to Hope Volunteer';
|
||||
const hello = 'Use this link to sign in. It expires in 15 minutes and works once.';
|
||||
const note = 'Opening the link does not sign you in. Use the button on the page. If you did not ask for this, you can ignore it.';
|
||||
const text = ['Hello,', '', hello, '', input.signInUrl, '', note, `Replies go to ${input.replyTo}.`, '', 'Hope Food Pantry'].join('\n');
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>Hello,</p>
|
||||
<p>${escapeHtml(hello)}</p>
|
||||
<p><a href="${escapeHtml(input.signInUrl)}" style="color:#222">Sign in</a></p>
|
||||
<p>${escapeHtml(note)} Replies go to ${escapeHtml(input.replyTo)}.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject, text, html };
|
||||
}
|
||||
|
||||
function render(input: {
|
||||
subject: string;
|
||||
greeting: string;
|
||||
hello: string;
|
||||
shift: MailShift;
|
||||
linkLabel: string;
|
||||
linkNote: string;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const when = input.shift.whenLabel;
|
||||
const place = input.shift.location.trim();
|
||||
const lines = [
|
||||
input.greeting,
|
||||
'',
|
||||
input.hello,
|
||||
'',
|
||||
input.shift.eventTitle,
|
||||
when,
|
||||
...(place ? [place] : []),
|
||||
'',
|
||||
`${input.linkLabel}:`,
|
||||
input.manageUrl,
|
||||
'',
|
||||
input.linkNote,
|
||||
`Replies go to ${input.replyTo}.`,
|
||||
'',
|
||||
'Hope Food Pantry',
|
||||
];
|
||||
const htmlPlace = place ? `<br>${escapeHtml(place)}` : '';
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(input.subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>${escapeHtml(input.greeting)}</p>
|
||||
<p>${escapeHtml(input.hello)}</p>
|
||||
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||
<p><a href="${escapeHtml(input.manageUrl)}" style="color:#222">${escapeHtml(input.linkLabel)}</a></p>
|
||||
<p>${escapeHtml(input.linkNote)} Replies go to ${escapeHtml(input.replyTo)}.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject: input.subject, text: lines.join('\n'), html };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export type MailIdentity = {
|
||||
baseUrl: string;
|
||||
basePath: string;
|
||||
from: string;
|
||||
replyTo: string;
|
||||
};
|
||||
|
||||
export type OutboundMail = {
|
||||
from: string;
|
||||
to: string;
|
||||
replyTo: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
/** sent: the provider accepted the message. That is not proof the person received it. */
|
||||
export type MailDelivery =
|
||||
| { result: 'sent'; providerId: string | null }
|
||||
| { result: 'retry'; error: string }
|
||||
| { result: 'failed'; error: string }
|
||||
| { result: 'unknown'; error: string };
|
||||
|
||||
export type Mailer = {
|
||||
send(message: OutboundMail): Promise<MailDelivery>;
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import { chmodSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { serve } from '@hono/node-server';
|
||||
import type { ServerType } from '@hono/node-server';
|
||||
import { bootstrapAdmin } from './auth/bootstrap.js';
|
||||
import { createApp } from './app.js';
|
||||
import { ConfigError, loadConfig } from './config.js';
|
||||
import { MigrationError, openAppDatabase } from './db.js';
|
||||
import { createMailer } from './mail/driver.js';
|
||||
import { startOutboxRunner } from './mail/run.js';
|
||||
import { startDailyExpansionRunner } from './jobs/daily-expand.js';
|
||||
import { backupDirectory, startBackupRunner } from './jobs/backup.js';
|
||||
import { runRetention, startHourlyCleanupRunner, startRetentionRunner } from './jobs/retention.js';
|
||||
import { expandTemplates } from './recurrence.js';
|
||||
import { startReminderRunner } from './reminders-run.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
// The database, its WAL files, and backups hold volunteer contact details. Owner only.
|
||||
process.umask(0o077);
|
||||
|
||||
async function main(): Promise<void> {
|
||||
let database: Awaited<ReturnType<typeof openAppDatabase>> | undefined;
|
||||
try {
|
||||
const config = loadConfig(process.env);
|
||||
if (config.nodeEnv === 'production' && config.trustProxy.mode === 'disabled' && config.bindHost === '0.0.0.0') {
|
||||
console.warn(
|
||||
'TRUST_PROXY is false. Behind Caddy every visitor shares one address and one set of rate limits. Set TRUST_PROXY to the proxy peer.',
|
||||
);
|
||||
}
|
||||
database = await openAppDatabase(config);
|
||||
restrictDataFiles(config.databaseFile, backupDirectory(config.dataDir));
|
||||
const startedAt = nowUtc();
|
||||
const created = bootstrapAdmin(database, config.bootstrapAdminEmail, startedAt);
|
||||
if (created.created) {
|
||||
console.log('Created the first administrator. Sign in with the address in BOOTSTRAP_ADMIN_EMAIL.');
|
||||
}
|
||||
const expanded = expandTemplates(database, startedAt);
|
||||
if (expanded.created > 0) {
|
||||
console.log(`Added ${expanded.created} weekly shifts for the next eight weeks.`);
|
||||
}
|
||||
for (const skip of expanded.skipped) console.error(skip);
|
||||
runRetention(database, startedAt);
|
||||
const app = createApp(config, database);
|
||||
const mail = startOutboxRunner(database, createMailer(config), nowUtc);
|
||||
const reminders = startReminderRunner(
|
||||
database,
|
||||
{ baseUrl: config.baseUrl, basePath: config.basePath, from: config.mail.from, replyTo: config.mail.replyTo },
|
||||
config.sessionSecret,
|
||||
nowUtc,
|
||||
);
|
||||
const refill = startDailyExpansionRunner(database, nowUtc);
|
||||
const retention = startRetentionRunner(database, nowUtc);
|
||||
const hourly = startHourlyCleanupRunner(database, nowUtc);
|
||||
const backup = startBackupRunner(database, backupDirectory(config.dataDir), nowUtc);
|
||||
const server = serve({
|
||||
fetch: app.fetch,
|
||||
port: config.port,
|
||||
hostname: config.bindHost,
|
||||
});
|
||||
console.log(`Hope Volunteer is at ${config.baseUrl}${config.basePath || '/'} (bound to ${config.bindHost}:${config.port}).`);
|
||||
waitForShutdown(server, database, () => {
|
||||
mail.stop();
|
||||
reminders.stop();
|
||||
refill.stop();
|
||||
retention.stop();
|
||||
hourly.stop();
|
||||
backup.stop();
|
||||
});
|
||||
} catch (err) {
|
||||
database?.close();
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(message);
|
||||
if (!(err instanceof ConfigError || err instanceof MigrationError) || !message.includes('Startup aborted.')) {
|
||||
console.error('Startup aborted.');
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Files created before the umask above may still be readable by others. */
|
||||
function restrictDataFiles(databaseFile: string, backups: string): void {
|
||||
const files = [databaseFile, `${databaseFile}-wal`, `${databaseFile}-shm`];
|
||||
try {
|
||||
for (const entry of readdirSync(backups, { withFileTypes: true })) {
|
||||
if (entry.isFile()) files.push(path.join(backups, entry.name));
|
||||
}
|
||||
} catch {
|
||||
// No backups yet.
|
||||
}
|
||||
for (const file of files) {
|
||||
try {
|
||||
chmodSync(file, 0o600);
|
||||
} catch {
|
||||
// Missing, or owned by someone else. The host owner fixes that.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function waitForShutdown(server: ServerType, database: { close: () => void }, stopMail: () => void): void {
|
||||
let stopping = false;
|
||||
const shutdown = () => {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
stopMail();
|
||||
let finished = false;
|
||||
const finish = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
database.close();
|
||||
process.exit(0);
|
||||
};
|
||||
server.close(finish);
|
||||
setTimeout(finish, 1000).unref();
|
||||
};
|
||||
server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
console.error(err.message);
|
||||
console.error('Startup aborted.');
|
||||
database.close();
|
||||
process.exit(1);
|
||||
});
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Context } from 'hono';
|
||||
|
||||
/**
|
||||
* A form POST must come from this site.
|
||||
* Origin: null is an opaque origin, not a match for BASE_URL.
|
||||
* Sec-Fetch-Site is set by the browser. same-origin and none are not cross-site forgery.
|
||||
*/
|
||||
export function originAllowed(c: Context, baseUrl: string): boolean {
|
||||
const origin = c.req.header('origin');
|
||||
if (origin && origin !== 'null') return origin === baseUrl;
|
||||
const site = c.req.header('sec-fetch-site');
|
||||
if (site === 'same-origin' || site === 'none') return true;
|
||||
const referer = c.req.header('referer');
|
||||
if (!referer) return false;
|
||||
try {
|
||||
return new URL(referer).origin === baseUrl;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
import type { Child } from 'hono/jsx';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { WEEKDAY_SHORT, calendarMonth, calendarToday, chooseCalendarMonth, monthStep, type CalendarDay } from './calendar.js';
|
||||
import { spotsSentence, type PublicEvent, type PublicShift } from './schedule.js';
|
||||
import type { SignupErrors, SignupValues } from './signup-form.js';
|
||||
import type { MoveTarget } from './admin/store.js';
|
||||
import type { ManageView } from './signup.js';
|
||||
import { appPath } from './url.js';
|
||||
|
||||
const PANTRY_SITE = 'https://hopefoodpantrysc.org';
|
||||
|
||||
function asset(config: AppConfig, file: string): string {
|
||||
return appPath(config, file);
|
||||
}
|
||||
|
||||
export function Layout(props: {
|
||||
config: AppConfig;
|
||||
title: string;
|
||||
path?: string;
|
||||
turnstile?: boolean;
|
||||
account?: { csrf: string } | null;
|
||||
children?: Child;
|
||||
}) {
|
||||
const home = appPath(props.config, '/');
|
||||
const privacy = appPath(props.config, '/privacy');
|
||||
const coordinator = appPath(props.config, props.account ? '/admin' : '/login');
|
||||
const logo = asset(props.config, '/img/logo.png');
|
||||
const menu = asset(props.config, '/img/icons/menu.svg');
|
||||
const close = asset(props.config, '/img/icons/close.svg');
|
||||
const facebook = asset(props.config, '/img/icons/facebook.svg');
|
||||
const instagram = asset(props.config, '/img/icons/instagram.svg');
|
||||
const wave = asset(props.config, '/img/wave-secondary.svg');
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{props.title}</title>
|
||||
<link rel="icon" href={asset(props.config, '/img/favicons/favicon.png')} />
|
||||
<link rel="apple-touch-icon" href={asset(props.config, '/img/favicons/favicon-apple.png')} />
|
||||
<link rel="stylesheet" href={appPath(props.config, '/brand/tokens.css')} />
|
||||
<link rel="stylesheet" href={appPath(props.config, '/css/app.css')} />
|
||||
<script src={appPath(props.config, '/js/desk.js')} />
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#content">
|
||||
Skip to content
|
||||
</a>
|
||||
<header class="site-header">
|
||||
<a class="logo-link" href={`${PANTRY_SITE}/`}>
|
||||
<img class="logo" src={logo} alt="Hope Food Pantry" />
|
||||
</a>
|
||||
<input class="nav-toggle" id="nav-toggle" type="checkbox" />
|
||||
<label class="btn-mobile-nav" for="nav-toggle">
|
||||
<img class="icon-mobile-nav icon-open" src={menu} alt="" />
|
||||
<img class="icon-mobile-nav icon-close" src={close} alt="" />
|
||||
<span class="sr-only">Menu</span>
|
||||
</label>
|
||||
<div class="header-side">
|
||||
<nav aria-label="Primary">
|
||||
<ul class="nav-links">
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/`}>
|
||||
Home
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/about.html`}>
|
||||
About
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/faq.html`}>
|
||||
FAQ
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Volunteering
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/#contact`}>
|
||||
Contact
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="btn" href="https://donorbox.org/hope-food-pantry-1">
|
||||
Donate
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<ul class="utility-links">
|
||||
<li>
|
||||
<a href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Calendar
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={privacy} aria-current={props.path === privacy ? 'page' : undefined}>
|
||||
Privacy
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={coordinator}>Coordinator</a>
|
||||
</li>
|
||||
{props.account ? (
|
||||
<li>
|
||||
<form method="post" action={appPath(props.config, '/logout')} class="utility-logout">
|
||||
<input type="hidden" name="csrf" value={props.account.csrf} />
|
||||
<button type="submit">Log out</button>
|
||||
</form>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</div>
|
||||
</header>
|
||||
<main id="content" tabIndex={-1}>
|
||||
{props.children}
|
||||
</main>
|
||||
<footer class="site-footer">
|
||||
<img class="footer-wave" src={wave} alt="" />
|
||||
<div class="footer-nav">
|
||||
<div class="footer-brand">
|
||||
<a class="logo-link" href={`${PANTRY_SITE}/`}>
|
||||
<img class="logo" src={logo} alt="Hope Food Pantry" />
|
||||
</a>
|
||||
<p class="equal-text">
|
||||
Hope Food Pantry is an{' '}
|
||||
<a href="https://www.usda.gov/sites/default/files/documents/ad-475a.pdf" target="_blank" rel="noopener noreferrer">
|
||||
equal opportunity provider.
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
<a href="tel:+17125409351">712-540-9351</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="mailto:hopepantry@gmail.com">hopepantry@gmail.com</a>
|
||||
</p>
|
||||
<div class="social-links">
|
||||
<a href="https://www.facebook.com/schopefoodpantry" target="_blank" rel="noopener noreferrer">
|
||||
<span class="social-flex">
|
||||
<img src={facebook} alt="" />
|
||||
<span>schopefoodpantry</span>
|
||||
</span>
|
||||
</a>
|
||||
<a href="https://www.instagram.com/hopefoodpantrysc" target="_blank" rel="noopener noreferrer">
|
||||
<span class="social-flex">
|
||||
<img src={instagram} alt="" />
|
||||
<span>hopefoodpantrysc</span>
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Address</h2>
|
||||
<address>
|
||||
<p>
|
||||
4155 US 75 Ave
|
||||
<br />
|
||||
Sioux Center, IA 51250
|
||||
<br />
|
||||
(Rear of Property)
|
||||
</p>
|
||||
<p>Mail to: PO Box 21</p>
|
||||
</address>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Navigation</h2>
|
||||
<ul class="footer-links">
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/`}>Home</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/about.html`}>About</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/faq.html`}>FAQ</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Volunteering
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/#contact`}>Contact</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://donorbox.org/hope-food-pantry-1">Donate</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={privacy} aria-current={props.path === privacy ? 'page' : undefined}>
|
||||
Privacy
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<p class="copyright-text">Hope Food Pantry, Sioux Center, Iowa</p>
|
||||
</footer>
|
||||
{props.turnstile ? <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer /> : null}
|
||||
<script src={appPath(props.config, '/js/enhance.js')} defer />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptySchedulePage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Weekly pantry</h1>
|
||||
<p class="empty">No upcoming shifts are posted.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function EventPage(props: { config: AppConfig; event: PublicEvent; now: string; month?: string; path?: string }) {
|
||||
const description = props.event.description.trim();
|
||||
return (
|
||||
<>
|
||||
<h1>{props.event.title}</h1>
|
||||
{props.event.location ? <p class="location">{props.event.location}</p> : null}
|
||||
{props.event.slug === 'weekly-pantry' ? null : <p class="zone">Times are shown in {props.event.timeZone}.</p>}
|
||||
{description ? <p class="description">{description}</p> : null}
|
||||
{props.event.shifts.length === 0 ? (
|
||||
<p class="empty">No upcoming shifts are posted for this event.</p>
|
||||
) : (
|
||||
<ShiftCalendar
|
||||
config={props.config}
|
||||
event={props.event}
|
||||
now={props.now}
|
||||
month={props.month}
|
||||
path={props.path ?? `/e/${encodeURIComponent(props.event.slug)}`}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export type SignupFormView = {
|
||||
token: string;
|
||||
siteKey: string;
|
||||
values: SignupValues;
|
||||
errors: SignupErrors;
|
||||
};
|
||||
|
||||
export function ShiftPage(props: {
|
||||
config: AppConfig;
|
||||
shift: PublicShift;
|
||||
signup?: SignupFormView | null;
|
||||
notice?: string;
|
||||
}) {
|
||||
const description = props.shift.event.description.trim();
|
||||
return (
|
||||
<>
|
||||
<h1>{props.shift.role}</h1>
|
||||
{props.shift.event.location ? <p class="location">{props.shift.event.location}</p> : null}
|
||||
<ShiftWhen shift={props.shift} />
|
||||
<StatusLine shift={props.shift} />
|
||||
{description ? <p class="description">{description}</p> : null}
|
||||
{props.notice ? (
|
||||
<p class="error" role="alert">
|
||||
{props.notice}
|
||||
</p>
|
||||
) : null}
|
||||
{props.signup ? <SignupForm config={props.config} shiftId={props.shift.id} form={props.signup} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfirmationPage(props: {
|
||||
config: AppConfig;
|
||||
shift: PublicShift;
|
||||
name: string | null;
|
||||
managePath: string | null;
|
||||
cancelled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<h1>{props.cancelled ? 'This signup is cancelled' : "You're signed up"}</h1>
|
||||
<p>
|
||||
{props.cancelled
|
||||
? `${props.name ? `${props.name} is no longer signed up for ` : 'This signup is no longer for '}${props.shift.role}.`
|
||||
: `${props.name ? `${props.name} is signed up for ` : 'This signup is for '}${props.shift.role}.`}
|
||||
</p>
|
||||
<ShiftWhen shift={props.shift} />
|
||||
{props.managePath ? (
|
||||
<>
|
||||
<p>
|
||||
{props.cancelled
|
||||
? 'A cancellation email is queued. This link still opens the cancelled signup.'
|
||||
: 'A confirmation email is queued. Save this link too, in case the email is delayed. It opens this signup, where you can cancel it or switch it to another open shift.'}
|
||||
</p>
|
||||
<p>
|
||||
<a href={props.managePath}>Open this signup</a>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>If you just signed up, the link stays in this browser for a few minutes. A confirmation email is queued.</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export type SwitchForm = {
|
||||
action: string;
|
||||
token: string;
|
||||
formToken: string;
|
||||
targets: MoveTarget[];
|
||||
};
|
||||
|
||||
export function ManagePage(props: {
|
||||
signup: ManageView;
|
||||
cancel: { action: string; token: string } | null;
|
||||
switches: SwitchForm | null;
|
||||
reminders?: { action: string; token: string } | 'off' | null;
|
||||
notice?: string;
|
||||
note?: string;
|
||||
}) {
|
||||
const signup = props.signup;
|
||||
return (
|
||||
<>
|
||||
<h1>Your signup</h1>
|
||||
<p class="status">{signup.status === 'confirmed' ? 'Confirmed' : 'Cancelled'}</p>
|
||||
<p>{signup.eventTitle}</p>
|
||||
<h2>{signup.role}</h2>
|
||||
<p class="when">
|
||||
<time dateTime={signup.when.date}>{signup.when.dateLabel}</time> {signup.when.timeLabel} {signup.when.abbreviation}
|
||||
</p>
|
||||
{signup.location ? <p class="location">{signup.location}</p> : null}
|
||||
<dl class="details">
|
||||
<div>
|
||||
<dt>Name</dt>
|
||||
<dd>{signup.name}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Email</dt>
|
||||
<dd>{signup.email}</dd>
|
||||
</div>
|
||||
{signup.phone ? (
|
||||
<div>
|
||||
<dt>Phone</dt>
|
||||
<dd>{signup.phone}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.isMinor ? (
|
||||
<div>
|
||||
<dt>Guardian</dt>
|
||||
<dd>
|
||||
{signup.guardianName}
|
||||
{signup.guardianEmail ? ` (${signup.guardianEmail})` : ''}
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.notes ? (
|
||||
<div>
|
||||
<dt>Notes</dt>
|
||||
<dd class="description">{signup.notes}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{props.note ? <p class="status">{props.note}</p> : null}
|
||||
{props.notice ? (
|
||||
<p class="error" role="alert">
|
||||
{props.notice}
|
||||
</p>
|
||||
) : null}
|
||||
{props.switches ? (
|
||||
props.switches.targets.length === 0 ? (
|
||||
<p>There is no other open shift you can switch to.</p>
|
||||
) : (
|
||||
<form class="move-form" method="post" action={props.switches.action}>
|
||||
<p>Switch to another shift in this event. This opens your spot here and queues a change email. This link stops working, and the next page has the new one.</p>
|
||||
<input type="hidden" name="switch_token" value={props.switches.token} />
|
||||
<input type="hidden" name="form_token" value={props.switches.formToken} />
|
||||
<label for="switch-to">
|
||||
Switch to
|
||||
<select id="switch-to" name="destination" required>
|
||||
<option value="">Choose a shift</option>
|
||||
{props.switches.targets.map((target) => (
|
||||
<option value={String(target.id)} key={target.id}>
|
||||
{target.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit">Switch</button>
|
||||
</form>
|
||||
)
|
||||
) : null}
|
||||
{props.reminders === 'off' ? (
|
||||
<p>Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
) : null}
|
||||
<div class="manage-actions">
|
||||
{props.reminders && props.reminders !== 'off' ? (
|
||||
<form class="cancel-form" method="post" action={props.reminders.action}>
|
||||
<p>Stop reminder emails for this signup. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<input type="hidden" name="reminder_token" value={props.reminders.token} />
|
||||
<button type="submit">Stop reminder emails</button>
|
||||
</form>
|
||||
) : null}
|
||||
{props.cancel ? (
|
||||
<form class="cancel-form" method="post" action={props.cancel.action}>
|
||||
<p>Cancel this signup to open the spot for someone else. A cancellation email is queued when you cancel.</p>
|
||||
<input type="hidden" name="cancel_token" value={props.cancel.token} />
|
||||
<button type="submit">Cancel this signup</button>
|
||||
</form>
|
||||
) : (
|
||||
<p>This signup is cancelled. The spot is open for someone else. A cancellation email is queued.</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO(D3): The pantry still has to approve this wording, including retention and copies.
|
||||
// A blank setting keeps the unapproved message. Saved wording is shown as written, escaped, and is not a policy by itself.
|
||||
export function PrivacyPage(props: { paragraphs: string[] }) {
|
||||
return (
|
||||
<>
|
||||
<h1>Privacy</h1>
|
||||
{props.paragraphs.length === 0 ? (
|
||||
<>
|
||||
<p>Hope Volunteer does not have an approved privacy notice yet.</p>
|
||||
<p>When the pantry approves the wording, it will appear on this page. This page is not a privacy policy.</p>
|
||||
</>
|
||||
) : (
|
||||
props.paragraphs.map((paragraph, index) => <p key={index}>{paragraph}</p>)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SwitchAlreadyPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Your signup</h1>
|
||||
<p>This signup was already switched. Use the link in the email.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReminderOffPage(props: { config: AppConfig; token: string; replyTo: string; off: boolean; error?: string }) {
|
||||
return (
|
||||
<>
|
||||
<h1>Reminder emails</h1>
|
||||
{props.error ? (
|
||||
<p class="error" role="alert">
|
||||
{props.error}
|
||||
</p>
|
||||
) : null}
|
||||
{props.off ? (
|
||||
<p>Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
) : (
|
||||
<form method="post" action={appPath(props.config, `/u/${props.token}`)} class="cancel-form">
|
||||
<p>This turns off reminder emails for this signup. It does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>The pantry reads mail sent to {props.replyTo}. This button turns reminders off immediately.</p>
|
||||
<button type="submit">Stop reminder emails</button>
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>That page is not available</h1>
|
||||
<p>The link may be out of date, or the shift is not posted.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProblemPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Something went wrong</h1>
|
||||
<p>The page could not be loaded. Try again in a little while.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function WaitPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Please wait</h1>
|
||||
<p>Too many attempts. Please wait and try again.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function monthHref(config: AppConfig, path: string, monthId: string): string {
|
||||
return `${appPath(config, path)}?month=${monthId}`;
|
||||
}
|
||||
|
||||
function MonthArrow(props: { config: AppConfig; path: string; monthId: string; direction: 'prev' | 'next' }) {
|
||||
const next = props.direction === 'next';
|
||||
return (
|
||||
<a class="month-arrow" rel={props.direction} href={monthHref(props.config, props.path, props.monthId)}>
|
||||
<span class="sr-only">{next ? 'Next month' : 'Previous month'}</span>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d={next ? 'M9.5 5.5 16 12l-6.5 6.5' : 'M14.5 5.5 8 12l6.5 6.5'} />
|
||||
</svg>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftCalendar(props: {
|
||||
config: AppConfig;
|
||||
event: PublicEvent;
|
||||
now: string;
|
||||
month?: string;
|
||||
path: string;
|
||||
}) {
|
||||
const today = calendarToday(props.event.timeZone, props.now);
|
||||
const dates = props.event.shifts.map((shift) => shift.when.date);
|
||||
const monthId = chooseCalendarMonth(props.month, dates, today);
|
||||
const month = calendarMonth(monthId);
|
||||
const step = monthStep(monthId, dates);
|
||||
const shiftsByDate = new Map<string, PublicShift[]>();
|
||||
for (const shift of props.event.shifts) {
|
||||
if (shift.when.date.slice(0, 7) !== month.id) continue;
|
||||
const listed = shiftsByDate.get(shift.when.date);
|
||||
if (listed) listed.push(shift);
|
||||
else shiftsByDate.set(shift.when.date, [shift]);
|
||||
}
|
||||
const titleId = `month-${props.event.id}-${month.id}`;
|
||||
const shiftsThisMonth = [...shiftsByDate.values()].some((listed) => listed.length > 0);
|
||||
return (
|
||||
<div class="shift-calendar">
|
||||
<section class="cal-month" aria-labelledby={titleId}>
|
||||
<div class="month-nav">
|
||||
{step.previous ? (
|
||||
<MonthArrow config={props.config} path={props.path} monthId={step.previous} direction="prev" />
|
||||
) : (
|
||||
<span class="month-nav-slot"></span>
|
||||
)}
|
||||
<h2 id={titleId} class="cal-title">
|
||||
{month.label}
|
||||
</h2>
|
||||
{step.next ? (
|
||||
<MonthArrow config={props.config} path={props.path} monthId={step.next} direction="next" />
|
||||
) : (
|
||||
<span class="month-nav-slot"></span>
|
||||
)}
|
||||
</div>
|
||||
<div class="cal-weekdays" aria-hidden="true">
|
||||
{WEEKDAY_SHORT.map((weekday) => (
|
||||
<span key={weekday}>{weekday}</span>
|
||||
))}
|
||||
</div>
|
||||
<ol class="cal-weeks">
|
||||
{month.weeks.map((week) => {
|
||||
const weekStart = week[0];
|
||||
if (!weekStart) return null;
|
||||
return (
|
||||
<li class="cal-week" key={weekStart.date}>
|
||||
<ol class="cal-week-days">
|
||||
{week.map((day) => (
|
||||
<CalendarDayCell
|
||||
key={day.date}
|
||||
config={props.config}
|
||||
day={day}
|
||||
today={today}
|
||||
weekName={`shifts-${weekStart.date}`}
|
||||
shifts={shiftsByDate.get(day.date) ?? []}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
<div class="week-tray"></div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{shiftsThisMonth ? null : <p class="empty">No shifts this month.</p>}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarDayCell(props: { config: AppConfig; day: CalendarDay; today: string; weekName: string; shifts: PublicShift[] }) {
|
||||
if (!props.day.inMonth) return <li class="cal-day is-outside" aria-hidden="true"></li>;
|
||||
const today = props.day.date === props.today;
|
||||
const className = ['cal-day', today ? 'is-today' : '', props.day.date < props.today ? 'is-past' : '', props.shifts.length > 0 ? 'has-shifts' : 'is-empty']
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
return (
|
||||
<li class={className} aria-current={today ? 'date' : undefined}>
|
||||
<div class="cal-day-face">
|
||||
<p class="day-label">
|
||||
<DayStamp day={props.day} today={today} />
|
||||
{today ? (
|
||||
<span class="today-flag" aria-hidden="true">
|
||||
Today
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
{props.shifts.length > 0 ? (
|
||||
<details class="day-reveal" name={props.weekName} data-date={props.day.date}>
|
||||
<summary class="day-summary">
|
||||
<DayStamp day={props.day} today={today} />
|
||||
<span class="day-markers">
|
||||
{today ? (
|
||||
<span class="today-flag" aria-hidden="true">
|
||||
Today
|
||||
</span>
|
||||
) : null}
|
||||
<span class="event-dot" aria-hidden="true"></span>
|
||||
<span class="expand-chevron" aria-hidden="true"></span>
|
||||
</span>
|
||||
<span class="sr-only">Show shifts</span>
|
||||
</summary>
|
||||
</details>
|
||||
) : null}
|
||||
{props.shifts.length > 0 ? (
|
||||
<div class="shift-drawer" data-date={props.day.date}>
|
||||
<p class="tray-label">
|
||||
{props.day.weekday} {props.day.day}
|
||||
</p>
|
||||
<ShiftList config={props.config} shifts={props.shifts} className="day-shifts" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function DayStamp(props: { day: CalendarDay; today: boolean }) {
|
||||
return (
|
||||
<time dateTime={props.day.date}>
|
||||
<span class="day-full sr-only">{props.today ? `Today, ${props.day.label}` : props.day.label}</span>
|
||||
<span class="day-weekday" aria-hidden="true">
|
||||
{props.day.weekday}
|
||||
</span>
|
||||
<span class="day-num" aria-hidden="true">
|
||||
{props.day.day}
|
||||
</span>
|
||||
</time>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftList(props: { config: AppConfig; shifts: PublicShift[]; className: string }) {
|
||||
return (
|
||||
<ul class={props.className}>
|
||||
{props.shifts.map((shift) => (
|
||||
<li key={shift.id}>
|
||||
<CalendarShift config={props.config} shift={shift} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarShift(props: { config: AppConfig; shift: PublicShift }) {
|
||||
const shift = props.shift;
|
||||
const closed = shift.full || shift.cancelled || shift.ended;
|
||||
const action = closed ? 'View shift' : 'Sign up';
|
||||
return (
|
||||
<a class="cal-shift" href={appPath(props.config, `/s/${shift.id}`)}>
|
||||
<span class="cal-line">
|
||||
{shift.when.startLabel} {shift.role}
|
||||
</span>
|
||||
<span class="sr-only">
|
||||
{'. '}
|
||||
{action} for {shift.role} on {shift.when.dateLabel}, {shift.when.startLabel} to {shift.when.endLabel}{' '}
|
||||
{shift.when.abbreviation}. {spotsSentence(shift)}
|
||||
{shift.inProgress ? ' In progress.' : ''}
|
||||
</span>
|
||||
<div class="cal-detail" aria-hidden="true">
|
||||
<span class="cal-hold" aria-hidden="true"></span>
|
||||
<span class="role">{shift.role}</span>
|
||||
<span class="when">
|
||||
<time dateTime={shift.startsAtUtc}>{shift.when.startLabel}</time>
|
||||
{' to '}
|
||||
{shift.when.sameDay ? null : <time dateTime={shift.endsAtUtc}>{shift.when.endDateLabel} </time>}
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endLabel}</time> {shift.when.abbreviation}
|
||||
</span>
|
||||
{shift.inProgress ? <span class="status">In progress</span> : null}
|
||||
<Spots shift={shift} />
|
||||
<span class="cal-action">{action}</span>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftWhen(props: { shift: PublicShift }) {
|
||||
const shift = props.shift;
|
||||
return (
|
||||
<p class="when">
|
||||
<time dateTime={shift.startsAtUtc}>{shift.when.startLabel}</time>
|
||||
{' to '}
|
||||
{shift.when.sameDay ? null : (
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endDateLabel} </time>
|
||||
)}
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endLabel}</time> {shift.when.abbreviation}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function Spots(props: { shift: PublicShift }) {
|
||||
return <p class={props.shift.full ? 'spots is-full' : 'spots is-open'}>{spotsSentence(props.shift)}</p>;
|
||||
}
|
||||
|
||||
function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFormView }) {
|
||||
const form = props.form;
|
||||
const errors = form.errors;
|
||||
const errorEntries = Object.entries(errors).filter((entry): entry is [string, string] => Boolean(entry[1]));
|
||||
return (
|
||||
<form class="signup-form" method="post" action={appPath(props.config, `/s/${props.shiftId}`)}>
|
||||
<h2>Sign up</h2>
|
||||
<p>Each signup is for one person and takes one spot. Another person can use the same email address. If you are under 18, add a parent or guardian.</p>
|
||||
<noscript>
|
||||
<p class="error">Signing up needs JavaScript for the abuse check. The pantry has not published a contact method for help with signup.</p>
|
||||
</noscript>
|
||||
{errorEntries.length > 0 ? (
|
||||
<div class="error" role="alert">
|
||||
<p>Check these fields:</p>
|
||||
<ul>
|
||||
{errorEntries.map(([field, message]) => (
|
||||
<li key={field}>
|
||||
<a href={`#signup-${field}`}>{message}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
<input type="hidden" name="form_token" value={form.token} />
|
||||
<div class="hp" aria-hidden="true">
|
||||
<label>
|
||||
Company website
|
||||
<input name="company_website" type="text" tabindex={-1} autocomplete="off" value="" />
|
||||
</label>
|
||||
</div>
|
||||
<Field id="signup-name" label="Name" name="name" type="text" value={form.values.name} error={errors.name} autoComplete="name" />
|
||||
<Field id="signup-email" label="Email" name="email" type="email" value={form.values.email} error={errors.email} autoComplete="email" />
|
||||
<Field
|
||||
id="signup-phone"
|
||||
label="Phone (optional)"
|
||||
name="phone"
|
||||
type="tel"
|
||||
value={form.values.phone}
|
||||
error={errors.phone}
|
||||
autoComplete="tel"
|
||||
hint="We will not text you"
|
||||
/>
|
||||
<label for="signup-notes">
|
||||
Notes (optional)
|
||||
<textarea id="signup-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined} aria-describedby={errors.notes ? 'signup-notes-error' : undefined}>
|
||||
{form.values.notes}
|
||||
</textarea>
|
||||
{errors.notes ? (
|
||||
<span class="field-error" id="signup-notes-error">
|
||||
{errors.notes}
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label class="check" for="signup-under-18">
|
||||
<input id="signup-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={form.values.under18 ? true : undefined} />
|
||||
I am under 18
|
||||
</label>
|
||||
<fieldset data-guardian="">
|
||||
<legend>Parent or guardian</legend>
|
||||
<Field
|
||||
id="signup-guardianName"
|
||||
label="Guardian name"
|
||||
name="guardianName"
|
||||
type="text"
|
||||
value={form.values.guardianName}
|
||||
error={errors.guardianName}
|
||||
autoComplete="name"
|
||||
/>
|
||||
<Field
|
||||
id="signup-guardianEmail"
|
||||
label="Guardian email"
|
||||
name="guardianEmail"
|
||||
type="email"
|
||||
value={form.values.guardianEmail}
|
||||
error={errors.guardianEmail}
|
||||
autoComplete="email"
|
||||
/>
|
||||
</fieldset>
|
||||
<div class="cf-turnstile" data-sitekey={form.siteKey} data-action="signup" />
|
||||
<p id="signup-turnstile-hint">This check confirms the signup came from a browser.</p>
|
||||
<button type="submit">Sign up</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Field(props: {
|
||||
id: string;
|
||||
label: string;
|
||||
name: string;
|
||||
type: 'text' | 'email' | 'tel';
|
||||
value: string;
|
||||
error?: string;
|
||||
autoComplete: string;
|
||||
hint?: string;
|
||||
}) {
|
||||
const errorId = `${props.id}-error`;
|
||||
const hintId = `${props.id}-hint`;
|
||||
const describedBy = [props.hint ? hintId : '', props.error ? errorId : ''].filter(Boolean).join(' ') || undefined;
|
||||
return (
|
||||
<label for={props.id}>
|
||||
{props.label}
|
||||
<input
|
||||
id={props.id}
|
||||
name={props.name}
|
||||
type={props.type}
|
||||
value={props.value}
|
||||
autocomplete={props.autoComplete}
|
||||
aria-invalid={props.error ? 'true' : undefined}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
{props.hint ? (
|
||||
<span class="hint" id={hintId}>
|
||||
{props.hint}
|
||||
</span>
|
||||
) : null}
|
||||
{props.error ? (
|
||||
<span class="field-error" id={errorId}>
|
||||
{props.error}
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusLine(props: { shift: PublicShift }) {
|
||||
if (props.shift.cancelled) return <p class="status">Cancelled. This shift is closed.</p>;
|
||||
if (props.shift.ended) return <p class="status">Ended. This shift is closed.</p>;
|
||||
return (
|
||||
<>
|
||||
{props.shift.inProgress ? <p class="status">In progress</p> : null}
|
||||
<Spots shift={props.shift} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from './email.js';
|
||||
import { formatUtc } from './time.js';
|
||||
|
||||
/** Initial public limits from the October 14, 2026 specification. */
|
||||
export const SIGNUP_IP_LIMIT = 5;
|
||||
export const SIGNUP_IP_WINDOW_MS = 10 * 60 * 1000;
|
||||
export const SIGNUP_EMAIL_LIMIT = 3;
|
||||
/** A guardian can have several children signed up, so this allowance is a little wider. */
|
||||
export const SIGNUP_GUARDIAN_LIMIT = 5;
|
||||
export const SWITCH_IP_LIMIT = 10;
|
||||
export const SWITCH_RECIPIENT_LIMIT = 5;
|
||||
export const MANAGE_TOKEN_LIMIT = 20;
|
||||
export const LOGIN_EMAIL_LIMIT = 3;
|
||||
export const LOGIN_IP_LIMIT = 10;
|
||||
export const LOGIN_TOKEN_LIMIT = 20;
|
||||
const LOGIN_WINDOW_MS = 60 * 60 * 1000;
|
||||
/** Longer than a local signup day, which is the longest limit window. */
|
||||
const RATE_RETENTION_MS = 2 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Deletes limit counters older than the retention margin. The hourly cleanup uses this too. */
|
||||
export function purgeRateHits(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(Temporal.Instant.from(now).subtract({ milliseconds: RATE_RETENTION_MS }));
|
||||
return db.prepare('DELETE FROM rate_hits WHERE window_start < ?').run(cutoff).changes;
|
||||
}
|
||||
|
||||
export type RateDecision = { limited: false } | { limited: true; retryAfter: number };
|
||||
|
||||
/**
|
||||
* Counts validated public switch attempts, not the rotating signup id or token.
|
||||
* Both recipient roles share one daily allowance. Check and charge every bucket
|
||||
* atomically so a blocked recipient cannot consume another person's allowance.
|
||||
*/
|
||||
export function recordSwitchAttempt(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
ip: string,
|
||||
emails: string[],
|
||||
): RateDecision {
|
||||
const recipientWindow = dayWindow(now, timeZone);
|
||||
const buckets = [
|
||||
{ kind: 'switch-ip', id: ip, limit: SWITCH_IP_LIMIT, window: ipWindow(now) },
|
||||
...[...new Set(emails.map(normalizeEmail))].map((id) => ({
|
||||
kind: 'switch-recipient', id, limit: SWITCH_RECIPIENT_LIMIT, window: recipientWindow,
|
||||
})),
|
||||
].map((bucket) => ({
|
||||
...bucket,
|
||||
key: createHmac('sha256', secret).update(`${bucket.kind}\0${bucket.id}`).digest('hex'),
|
||||
}));
|
||||
return db.transaction((): RateDecision => {
|
||||
purgeRateHits(db, now);
|
||||
const read = db.prepare('SELECT count FROM rate_hits WHERE key = ? AND window_start = ?');
|
||||
let retryAfter = 0;
|
||||
for (const bucket of buckets) {
|
||||
const row = read.get(bucket.key, bucket.window.start) as { count: number } | undefined;
|
||||
if (row && row.count >= bucket.limit) retryAfter = Math.max(retryAfter, bucket.window.retryAfter);
|
||||
}
|
||||
if (retryAfter > 0) return { limited: true, retryAfter };
|
||||
const increment = db.prepare(
|
||||
`INSERT INTO rate_hits (key, window_start, count) VALUES (?, ?, 1)
|
||||
ON CONFLICT (key, window_start) DO UPDATE SET count = count + 1`,
|
||||
);
|
||||
for (const bucket of buckets) increment.run(bucket.key, bucket.window.start);
|
||||
return { limited: false };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts signup attempts. Keys are HMAC digests, so the table does not store
|
||||
* raw email addresses or IP addresses. The email allowance counts only after
|
||||
* Turnstile and field checks pass, so a failed widget cannot lock someone out
|
||||
* for the day. The IP allowance counts every signup POST.
|
||||
*/
|
||||
export function recordSignupIp(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, { kind: 'signup-ip', id: ip, limit: SIGNUP_IP_LIMIT, window: ipWindow(now) });
|
||||
}
|
||||
|
||||
/** Counts unknown or expired manage links. A valid link does not use this allowance. */
|
||||
export function recordInvalidManageToken(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'manage-token',
|
||||
id: ip,
|
||||
limit: MANAGE_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts sign-in requests from one network. A failed check still uses this allowance. */
|
||||
export function recordLoginIp(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-ip',
|
||||
id: ip,
|
||||
limit: LOGIN_IP_LIMIT,
|
||||
window: fixedWindow(now, LOGIN_WINDOW_MS),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts sign-in requests for one address after the check succeeds, whether or not a coordinator uses it. */
|
||||
export function recordLoginEmail(db: Database.Database, secret: string, now: string, emailNorm: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-email',
|
||||
id: emailNorm,
|
||||
limit: LOGIN_EMAIL_LIMIT,
|
||||
window: fixedWindow(now, LOGIN_WINDOW_MS),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts invalid reminder opt-out links. A valid link does not use this allowance. */
|
||||
export function recordInvalidUnsubscribe(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'reminder-off',
|
||||
id: ip,
|
||||
limit: MANAGE_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts invalid sign-in links. A valid link does not use this allowance. */
|
||||
export function recordInvalidLoginToken(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-token',
|
||||
id: ip,
|
||||
limit: LOGIN_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
export function recordSignupEmail(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
emailNorm: string,
|
||||
): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'signup-email',
|
||||
id: emailNorm,
|
||||
limit: SIGNUP_EMAIL_LIMIT,
|
||||
window: dayWindow(now, timeZone),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts signups that mail a guardian address. Without it, someone could rotate
|
||||
* volunteer addresses and keep sending mail to one guardian.
|
||||
*/
|
||||
export function recordSignupGuardian(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
guardianEmailNorm: string,
|
||||
): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'signup-guardian',
|
||||
id: guardianEmailNorm,
|
||||
limit: SIGNUP_GUARDIAN_LIMIT,
|
||||
window: dayWindow(now, timeZone),
|
||||
});
|
||||
}
|
||||
|
||||
function record(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
input: { kind: string; id: string; limit: number; window: { start: string; retryAfter: number } },
|
||||
): RateDecision {
|
||||
const key = createHmac('sha256', secret).update(`${input.kind}\0${input.id}`).digest('hex');
|
||||
const count = db.transaction(() => {
|
||||
purgeRateHits(db, now);
|
||||
const row = db
|
||||
.prepare(
|
||||
`INSERT INTO rate_hits (key, window_start, count) VALUES (?, ?, 1)
|
||||
ON CONFLICT (key, window_start) DO UPDATE SET count = count + 1
|
||||
RETURNING count`,
|
||||
)
|
||||
.get(key, input.window.start) as { count: number };
|
||||
return row.count;
|
||||
}).immediate();
|
||||
if (count > input.limit) return { limited: true, retryAfter: input.window.retryAfter };
|
||||
return { limited: false };
|
||||
}
|
||||
|
||||
function ipWindow(now: string): { start: string; retryAfter: number } {
|
||||
return fixedWindow(now, SIGNUP_IP_WINDOW_MS);
|
||||
}
|
||||
|
||||
function fixedWindow(now: string, windowMs: number): { start: string; retryAfter: number } {
|
||||
const epoch = Temporal.Instant.from(now).epochMilliseconds;
|
||||
const startMs = Math.floor(epoch / windowMs) * windowMs;
|
||||
const retryAfter = Math.max(1, Math.ceil((startMs + windowMs - epoch) / 1000));
|
||||
return { start: formatUtc(Temporal.Instant.fromEpochMilliseconds(startMs)), retryAfter };
|
||||
}
|
||||
|
||||
function dayWindow(now: string, timeZone: string): { start: string; retryAfter: number } {
|
||||
const zoned = Temporal.Instant.from(now).toZonedDateTimeISO(timeZone);
|
||||
const start = zoned.startOfDay();
|
||||
const next = start.add({ days: 1 });
|
||||
const retryAfter = Math.max(
|
||||
1,
|
||||
Math.ceil((next.toInstant().epochMilliseconds - zoned.epochMilliseconds) / 1000),
|
||||
);
|
||||
return { start: formatUtc(start.toInstant()), retryAfter };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { recoverCoordinator } from './auth/recover.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { openAppDatabase } from './db.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
/**
|
||||
* Host recovery command. In the container:
|
||||
* docker compose exec hope-volunteer node dist/recover-coordinator.js <current-email> [--replace <new-email>]
|
||||
* The container already has its configuration, so no --env-file is needed there.
|
||||
*/
|
||||
|
||||
// Same as the server: the database is owner-only.
|
||||
process.umask(0o077);
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const email = args[0] ?? '';
|
||||
const replaceFlag = args.indexOf('--replace');
|
||||
const replaceWith = replaceFlag === -1 ? undefined : args[replaceFlag + 1];
|
||||
|
||||
if (!email || email.startsWith('--') || (replaceFlag !== -1 && (!replaceWith || replaceWith.startsWith('--')))) {
|
||||
console.error('Usage: node dist/recover-coordinator.js <current-email> [--replace <new-email>]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const config = loadConfig(process.env);
|
||||
const db = await openAppDatabase(config);
|
||||
try {
|
||||
const result = recoverCoordinator(db, { email, replaceWith, now: nowUtc() });
|
||||
const verb = replaceWith ? 'Updated the sign-in address and revoked old sessions' : 'Revoked sessions and unused sign-in links';
|
||||
console.log(`${verb} for coordinator ${result.coordinatorId}.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from './auth/audit.js';
|
||||
import { LocalTimeError, addLocalDays, localShiftToUtc, todayInZone } from './time.js';
|
||||
|
||||
/** How far ahead an active template fills the schedule, counted in local days. */
|
||||
export const TEMPLATE_HORIZON_DAYS = 56;
|
||||
|
||||
export type ExpandResult = {
|
||||
created: number;
|
||||
templates: number;
|
||||
skipped: string[];
|
||||
};
|
||||
|
||||
type TemplateRow = {
|
||||
id: number;
|
||||
event_id: number;
|
||||
role: string;
|
||||
weekday: number;
|
||||
start_local: string;
|
||||
end_local: string;
|
||||
capacity: number;
|
||||
starts_on: string;
|
||||
ends_on: string | null;
|
||||
revision: number;
|
||||
tz: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add missing shifts from active weekly templates. A date that already has a
|
||||
* row for that template is left alone, including a cancelled row, so generation
|
||||
* cannot recreate or overwrite it. A local time that does not exist, or that
|
||||
* happens twice, is skipped instead of moved.
|
||||
*/
|
||||
export function expandTemplates(
|
||||
db: Database.Database,
|
||||
now: string,
|
||||
options?: { eventId?: number; timeZone?: string; coordinatorId?: number | null },
|
||||
): ExpandResult {
|
||||
const coordinatorId = options?.coordinatorId ?? null;
|
||||
const eventId = options?.eventId;
|
||||
const timeZone = options?.timeZone;
|
||||
const run = db.transaction((): ExpandResult => {
|
||||
const templates = listTemplates(db, eventId, timeZone);
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const template of templates) {
|
||||
const outcome = expandOne(db, template, now, coordinatorId);
|
||||
created += outcome.created;
|
||||
skipped.push(...outcome.skipped);
|
||||
}
|
||||
return { created, templates: templates.length, skipped };
|
||||
});
|
||||
return run.immediate();
|
||||
}
|
||||
|
||||
function listTemplates(db: Database.Database, eventId: number | undefined, timeZone: string | undefined): TemplateRow[] {
|
||||
const filters = ['t.active = 1'];
|
||||
const params: Array<number | string> = [];
|
||||
if (eventId !== undefined) {
|
||||
filters.push('t.event_id = ?');
|
||||
params.push(eventId);
|
||||
}
|
||||
if (timeZone !== undefined) {
|
||||
filters.push('e.tz = ?');
|
||||
params.push(timeZone);
|
||||
}
|
||||
const sql = `SELECT t.id AS id, t.event_id AS event_id, t.role AS role, t.weekday AS weekday,
|
||||
t.start_local AS start_local, t.end_local AS end_local, t.capacity AS capacity,
|
||||
t.starts_on AS starts_on, t.ends_on AS ends_on, t.revision AS revision, e.tz AS tz
|
||||
FROM shift_templates t
|
||||
JOIN events e ON e.id = t.event_id
|
||||
WHERE ${filters.join(' AND ')}
|
||||
ORDER BY t.id`;
|
||||
return db.prepare(sql).all(...params) as TemplateRow[];
|
||||
}
|
||||
|
||||
function expandOne(
|
||||
db: Database.Database,
|
||||
template: TemplateRow,
|
||||
now: string,
|
||||
coordinatorId: number | null,
|
||||
): { created: number; skipped: string[] } {
|
||||
let today: string;
|
||||
try {
|
||||
today = todayInZone(template.tz, Temporal.Instant.from(now));
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) return { created: 0, skipped: [err.message] };
|
||||
throw err;
|
||||
}
|
||||
const windowEnd = addLocalDays(today, TEMPLATE_HORIZON_DAYS);
|
||||
const dates = occurrenceDates(template, today, windowEnd);
|
||||
const insert = db.prepare(
|
||||
`INSERT OR IGNORE INTO shifts (
|
||||
event_id, template_id, occurrence_date, template_revision, role,
|
||||
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '', 0, 0, 1)`,
|
||||
);
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const date of dates) {
|
||||
let times: { startsAtUtc: string; endsAtUtc: string };
|
||||
try {
|
||||
times = localShiftToUtc(date, template.start_local, template.end_local, template.tz);
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) {
|
||||
skipped.push(err.message);
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const saved = insert.run(
|
||||
template.event_id,
|
||||
template.id,
|
||||
date,
|
||||
template.revision,
|
||||
template.role,
|
||||
times.startsAtUtc,
|
||||
times.endsAtUtc,
|
||||
template.capacity,
|
||||
);
|
||||
if (saved.changes === 1) created += 1;
|
||||
}
|
||||
if (created > 0) {
|
||||
writeAudit(db, coordinatorId, 'template.expand', { templateId: template.id, created }, now);
|
||||
}
|
||||
return { created, skipped };
|
||||
}
|
||||
|
||||
function occurrenceDates(template: TemplateRow, today: string, windowEnd: string): string[] {
|
||||
let start = today > template.starts_on ? today : template.starts_on;
|
||||
let end = windowEnd;
|
||||
if (template.ends_on && template.ends_on < end) end = template.ends_on;
|
||||
if (start > end) return [];
|
||||
let date = Temporal.PlainDate.from(start);
|
||||
const last = Temporal.PlainDate.from(end);
|
||||
const weekday = date.dayOfWeek % 7;
|
||||
date = date.add({ days: (template.weekday - weekday + 7) % 7 });
|
||||
const dates: string[] = [];
|
||||
while (Temporal.PlainDate.compare(date, last) <= 0) {
|
||||
dates.push(date.toString());
|
||||
date = date.add({ days: 7 });
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type { Context, Hono } from 'hono';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { readSession } from './auth/session.js';
|
||||
import { clientAddress } from './client-ip.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { Layout, NotFoundPage, ReminderOffPage, WaitPage } from './pages.js';
|
||||
import { recordInvalidUnsubscribe } from './rate-limit.js';
|
||||
import { disableReminders, readReminderOffToken } from './reminders.js';
|
||||
import { readReplyTo } from './settings.js';
|
||||
import { isBusy } from './sqlite-error.js';
|
||||
import { appPath } from './url.js';
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
export function registerReminderOff(
|
||||
app: Hono,
|
||||
services: {
|
||||
config: AppConfig;
|
||||
db: Database.Database;
|
||||
now: () => string;
|
||||
clientIp?: (c: Context) => string | null;
|
||||
},
|
||||
): void {
|
||||
app.get(appPath(services.config, '/u/:token'), (c) => showReminderOff(c, services));
|
||||
app.post(appPath(services.config, '/u/:token'), (c) => submitReminderOff(c, services));
|
||||
}
|
||||
|
||||
function showReminderOff(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
) {
|
||||
const signupId = readReminderOffToken(services.config.sessionSecret, c.req.param('token') ?? '');
|
||||
if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services);
|
||||
const off = remindersOff(services.db, signupId);
|
||||
return page(c, services, <ReminderOffPage config={services.config} token={c.req.param('token') ?? ''} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={off} />);
|
||||
}
|
||||
|
||||
async function submitReminderOff(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signupId = readReminderOffToken(services.config.sessionSecret, token);
|
||||
if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services);
|
||||
try {
|
||||
const result = disableReminders(services.db, signupId, services.now());
|
||||
if (!result.ok) return unavailable(c, services);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Reminder opt-out could not lock the database.');
|
||||
return page(c, services, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={false} error="This could not be saved. Please try again." />, 503);
|
||||
}
|
||||
return page(c, services, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off />);
|
||||
}
|
||||
|
||||
function reminderSignup(db: Database.Database, signupId: number): boolean {
|
||||
const row = db.prepare('SELECT id FROM signups WHERE id = ? AND anonymized_at IS NULL').get(signupId);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
function remindersOff(db: Database.Database, signupId: number): boolean {
|
||||
const row = db.prepare('SELECT reminders_off AS reminders_off FROM signups WHERE id = ?').get(signupId) as { reminders_off: number } | undefined;
|
||||
return row?.reminders_off === 1;
|
||||
}
|
||||
|
||||
function unavailable(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
) {
|
||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
const limit = recordInvalidUnsubscribe(services.db, services.config.sessionSecret, services.now(), ip);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
return page(c, services, <WaitPage />, 429);
|
||||
}
|
||||
return page(c, services, <NotFoundPage />, 404);
|
||||
}
|
||||
|
||||
function peerAddress(c: Context, override?: (c: Context) => string | null): string | null {
|
||||
if (override) return override(c);
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function page(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string },
|
||||
body: Child,
|
||||
status: 200 | 404 | 429 | 503 = 200,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const account = readSession(services.db, c.req.header('cookie'), services.now());
|
||||
return c.html(
|
||||
<Layout config={services.config} title="Reminder emails · Hope Volunteer" path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { queueDueReminders } from './reminders.js';
|
||||
|
||||
const INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
/** One reminder pass every five minutes. A pass that is still running is not started again. */
|
||||
export function startReminderRunner(
|
||||
db: Database.Database,
|
||||
mail: MailIdentity,
|
||||
secret: string,
|
||||
now: () => string,
|
||||
): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
queueDueReminders(db, mail, secret, now());
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Reminder queue failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { cancelPendingReminders } from './mail/queue.js';
|
||||
import { renderReminder } from './mail/templates.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { readReminderOffsets, readReplyTo } from './settings.js';
|
||||
import { formatInstantInZone } from './time.js';
|
||||
import { absoluteUrl } from './url.js';
|
||||
|
||||
export type ReminderPass = { queued: number; suppressed: number };
|
||||
|
||||
type DueSignup = {
|
||||
id: number;
|
||||
name: string;
|
||||
email_norm: string;
|
||||
guardian_email: string | null;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
shift_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues reminders that are due and still before the shift starts.
|
||||
* When more than one offset is already due, only the closest one is sent.
|
||||
* Older offsets are recorded as not sent, so a late signup does not get every missed reminder.
|
||||
* The same signup, offset, and shift version is not queued twice.
|
||||
* Offset hours and the reply-to address come from coordinator settings, or the defaults when none are saved.
|
||||
*/
|
||||
export function queueDueReminders(db: Database.Database, mail: MailIdentity, secret: string, now: string): ReminderPass {
|
||||
return db.transaction((): ReminderPass => {
|
||||
const offsets = readReminderOffsets(db);
|
||||
const activeMail = { ...mail, replyTo: readReplyTo(db, mail.replyTo) };
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email,
|
||||
su.shift_id AS shift_id, s.version AS version, s.starts_at_utc AS starts_at_utc,
|
||||
s.ends_at_utc AS ends_at_utc, s.role AS role,
|
||||
e.title AS title, e.location AS location, e.tz AS tz
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE su.status = 'confirmed'
|
||||
AND su.reminders_off = 0
|
||||
AND su.anonymized_at IS NULL
|
||||
AND su.name IS NOT NULL
|
||||
AND su.email_norm IS NOT NULL
|
||||
AND s.cancelled = 0
|
||||
AND s.starts_at_utc > ?`,
|
||||
)
|
||||
.all(now) as DueSignup[];
|
||||
let queued = 0;
|
||||
let suppressed = 0;
|
||||
const nowInstant = Temporal.Instant.from(now);
|
||||
for (const row of rows) {
|
||||
const start = Temporal.Instant.from(row.starts_at_utc);
|
||||
const due = offsets.filter((offset) => {
|
||||
const dueAt = start.subtract({ hours: offset.hours });
|
||||
return Temporal.Instant.compare(nowInstant, dueAt) >= 0 && !alreadyQueued(db, row.id, offset.kind, row.version);
|
||||
});
|
||||
if (due.length === 0) continue;
|
||||
const nearest = due.reduce((closest, offset) => (offset.hours < closest.hours ? offset : closest));
|
||||
if (insertReminder(db, row, nearest.kind, activeMail, secret, now, 'pending')) queued += 1;
|
||||
for (const offset of due) {
|
||||
if (offset.kind === nearest.kind) continue;
|
||||
if (insertReminder(db, row, offset.kind, activeMail, secret, now, 'suppressed')) suppressed += 1;
|
||||
}
|
||||
}
|
||||
return { queued, suppressed };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/** Turns reminders off for one signup. Confirmation, change, and cancellation mail still queue. */
|
||||
export function disableReminders(
|
||||
db: Database.Database,
|
||||
signupId: number,
|
||||
now: string,
|
||||
): { ok: true; already: boolean } | { ok: false } {
|
||||
return db.transaction((): { ok: true; already: boolean } | { ok: false } => {
|
||||
const row = db
|
||||
.prepare('SELECT reminders_off AS reminders_off FROM signups WHERE id = ? AND anonymized_at IS NULL')
|
||||
.get(signupId) as { reminders_off: number } | undefined;
|
||||
if (!row) return { ok: false };
|
||||
if (row.reminders_off !== 1) {
|
||||
db.prepare('UPDATE signups SET reminders_off = 1, updated_at = ? WHERE id = ? AND anonymized_at IS NULL').run(now, signupId);
|
||||
}
|
||||
cancelPendingReminders(db, signupId, 'Reminders were turned off before this message was sent.');
|
||||
return { ok: true, already: row.reminders_off === 1 };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
export function issueReminderOffToken(secret: string, signupId: number): string {
|
||||
const id = String(signupId);
|
||||
const mac = createHmac('sha256', secret).update(`hope-reminder-off-v1\0${id}`).digest('base64url');
|
||||
return `${id}.${mac}`;
|
||||
}
|
||||
|
||||
export function readReminderOffToken(secret: string, token: string): number | null {
|
||||
if (!/^([1-9][0-9]{0,15})\.([A-Za-z0-9_-]{20,128})$/.test(token)) return null;
|
||||
const id = Number(token.slice(0, token.indexOf('.')));
|
||||
if (!Number.isSafeInteger(id) || id <= 0) return null;
|
||||
const expected = issueReminderOffToken(secret, id);
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(token);
|
||||
if (left.length !== right.length || !timingSafeEqual(left, right)) return null;
|
||||
return id;
|
||||
}
|
||||
|
||||
function alreadyQueued(db: Database.Database, signupId: number, kind: string, version: number): boolean {
|
||||
const row = db
|
||||
.prepare('SELECT signup_id FROM reminders_sent WHERE signup_id = ? AND kind = ? AND shift_version = ?')
|
||||
.get(signupId, kind, version);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
function insertReminder(
|
||||
db: Database.Database,
|
||||
row: DueSignup,
|
||||
kind: string,
|
||||
mail: MailIdentity,
|
||||
secret: string,
|
||||
now: string,
|
||||
mode: 'pending' | 'suppressed',
|
||||
): boolean {
|
||||
const unsubscribeUrl = absoluteUrl(mail, `/u/${issueReminderOffToken(secret, row.id)}`);
|
||||
const headers = reminderHeaders(mail, unsubscribeUrl);
|
||||
const volunteerId = insertOutbox(db, row, kind, row.email_norm, 'volunteer', mail, headers, unsubscribeUrl, now, mode);
|
||||
if (volunteerId === null) return false;
|
||||
const saved = db
|
||||
.prepare(
|
||||
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (signup_id, kind, shift_version) DO NOTHING`,
|
||||
)
|
||||
.run(row.id, kind, row.version, volunteerId, now);
|
||||
if (saved.changes !== 1) return false;
|
||||
if (mode === 'pending' && row.guardian_email && row.guardian_email !== row.email_norm) {
|
||||
insertOutbox(db, row, kind, row.guardian_email, 'guardian', mail, headers, unsubscribeUrl, now, 'pending');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function insertOutbox(
|
||||
db: Database.Database,
|
||||
row: DueSignup,
|
||||
kind: string,
|
||||
recipient: string,
|
||||
audience: 'volunteer' | 'guardian',
|
||||
mail: MailIdentity,
|
||||
headers: Record<string, string>,
|
||||
unsubscribeUrl: string,
|
||||
now: string,
|
||||
mode: 'pending' | 'suppressed',
|
||||
): number | null {
|
||||
const rendered = mode === 'pending'
|
||||
? renderReminder({
|
||||
audience,
|
||||
volunteerName: row.name,
|
||||
shift: shiftFacts(row),
|
||||
unsubscribeUrl,
|
||||
replyTo: mail.replyTo,
|
||||
})
|
||||
: { subject: 'Reminder not sent', text: 'This reminder was not sent.', html: '<p>This reminder was not sent.</p>' };
|
||||
const saved = db
|
||||
.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at, last_error
|
||||
) VALUES (?, ?, ?, 'reminder', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
)
|
||||
.run(
|
||||
`reminder:v${row.version}:${row.id}:${kind}:${recipient}`,
|
||||
row.id,
|
||||
row.shift_id,
|
||||
recipient,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: mail.from, 'Reply-To': mail.replyTo, ...headers }),
|
||||
now,
|
||||
mode === 'pending' ? 'pending' : 'cancelled',
|
||||
now,
|
||||
mode === 'pending' ? null : 'A closer reminder was already due, so this one was not sent.',
|
||||
);
|
||||
if (saved.changes !== 1) return null;
|
||||
return Number(saved.lastInsertRowid);
|
||||
}
|
||||
|
||||
function reminderHeaders(mail: MailIdentity, unsubscribeUrl: string): Record<string, string> {
|
||||
const subject = encodeURIComponent('Stop reminder emails');
|
||||
return {
|
||||
'List-Unsubscribe': `<mailto:${mail.replyTo}?subject=${subject}>, <${unsubscribeUrl}>`,
|
||||
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
||||
};
|
||||
}
|
||||
|
||||
function shiftFacts(row: DueSignup): { role: string; eventTitle: string; location: string; whenLabel: string } {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
return {
|
||||
role: row.role,
|
||||
eventTitle: row.title,
|
||||
location: row.location,
|
||||
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatInstantInZone } from './time.js';
|
||||
|
||||
export type PublicShift = {
|
||||
id: number;
|
||||
role: string;
|
||||
startsAtUtc: string;
|
||||
endsAtUtc: string;
|
||||
capacity: number;
|
||||
occupied: number;
|
||||
remaining: number;
|
||||
full: boolean;
|
||||
cancelled: boolean;
|
||||
ended: boolean;
|
||||
inProgress: boolean;
|
||||
event: {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
timeZone: string;
|
||||
};
|
||||
when: {
|
||||
date: string;
|
||||
dateLabel: string;
|
||||
endDateLabel: string;
|
||||
sameDay: boolean;
|
||||
startLabel: string;
|
||||
endLabel: string;
|
||||
abbreviation: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type PublicEvent = {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
timeZone: string;
|
||||
shifts: PublicShift[];
|
||||
};
|
||||
|
||||
type ShiftRow = {
|
||||
id: number;
|
||||
role: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
capacity: number;
|
||||
cancelled: number;
|
||||
event_id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
occupied: number;
|
||||
};
|
||||
|
||||
const SHIFT_COLUMNS = `
|
||||
s.id AS id,
|
||||
s.role AS role,
|
||||
s.starts_at_utc AS starts_at_utc,
|
||||
s.ends_at_utc AS ends_at_utc,
|
||||
s.capacity AS capacity,
|
||||
s.cancelled AS cancelled,
|
||||
e.id AS event_id,
|
||||
e.slug AS slug,
|
||||
e.title AS title,
|
||||
e.description AS description,
|
||||
e.location AS location,
|
||||
e.tz AS tz,
|
||||
COALESCE(SUM(CASE WHEN su.status = 'confirmed' THEN su.group_size ELSE 0 END), 0) AS occupied
|
||||
`;
|
||||
|
||||
const SHIFT_FROM = `
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
LEFT JOIN signups su ON su.shift_id = s.id
|
||||
`;
|
||||
|
||||
export function getPublishedEvent(db: Database.Database, slug: string, now: string): PublicEvent | null {
|
||||
const event = db
|
||||
.prepare(
|
||||
`SELECT id, slug, title, description, location, tz, published
|
||||
FROM events WHERE slug = ?`,
|
||||
)
|
||||
.get(slug) as
|
||||
| {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: number;
|
||||
}
|
||||
| undefined;
|
||||
if (!event || event.published !== 1) return null;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT ${SHIFT_COLUMNS}
|
||||
${SHIFT_FROM}
|
||||
WHERE e.id = ? AND s.cancelled = 0 AND s.ends_at_utc > ?
|
||||
GROUP BY s.id
|
||||
ORDER BY s.starts_at_utc, s.role, s.id`,
|
||||
)
|
||||
.all(event.id, now) as ShiftRow[];
|
||||
return {
|
||||
id: event.id,
|
||||
slug: event.slug,
|
||||
title: event.title,
|
||||
description: event.description,
|
||||
location: event.location,
|
||||
timeZone: event.tz,
|
||||
shifts: rows.map((row) => presentShift(row, now)),
|
||||
};
|
||||
}
|
||||
|
||||
export function getPublicShift(db: Database.Database, id: number, now: string): PublicShift | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT ${SHIFT_COLUMNS}
|
||||
${SHIFT_FROM}
|
||||
WHERE s.id = ? AND e.published = 1
|
||||
GROUP BY s.id`,
|
||||
)
|
||||
.get(id) as ShiftRow | undefined;
|
||||
return row ? presentShift(row, now) : null;
|
||||
}
|
||||
|
||||
export function spotsSentence(shift: Pick<PublicShift, 'occupied' | 'capacity'>): string {
|
||||
const filled = Math.min(shift.capacity, Math.max(0, shift.occupied));
|
||||
return `${filled}/${shift.capacity} spots filled`;
|
||||
}
|
||||
|
||||
function presentShift(row: ShiftRow, now: string): PublicShift {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
const occupied = Number(row.occupied);
|
||||
const capacity = Number(row.capacity);
|
||||
const remaining = Math.max(0, capacity - occupied);
|
||||
const cancelled = row.cancelled === 1;
|
||||
const ended = row.ends_at_utc <= now;
|
||||
const inProgress = !cancelled && !ended && row.starts_at_utc <= now;
|
||||
return {
|
||||
id: row.id,
|
||||
role: row.role,
|
||||
startsAtUtc: row.starts_at_utc,
|
||||
endsAtUtc: row.ends_at_utc,
|
||||
capacity,
|
||||
occupied,
|
||||
remaining,
|
||||
full: !cancelled && !ended && remaining === 0,
|
||||
cancelled,
|
||||
ended,
|
||||
inProgress,
|
||||
event: {
|
||||
id: row.event_id,
|
||||
slug: row.slug,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
location: row.location,
|
||||
timeZone: row.tz,
|
||||
},
|
||||
when: {
|
||||
date: start.date,
|
||||
dateLabel: start.dateLabel,
|
||||
endDateLabel: end.dateLabel,
|
||||
sameDay: start.date === end.date,
|
||||
startLabel: start.timeLabel,
|
||||
endLabel: end.timeLabel,
|
||||
abbreviation: start.abbreviation,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
|
||||
/**
|
||||
* Baseline from the October 14, 2026 specification.
|
||||
* Signup pages load the Turnstile script in a frame. The widget also connects
|
||||
* to that same host. Do not widen this to a wildcard or unsafe-inline.
|
||||
*/
|
||||
export const CONTENT_SECURITY_POLICY = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' https://challenges.cloudflare.com",
|
||||
'frame-src https://challenges.cloudflare.com',
|
||||
"connect-src 'self' https://challenges.cloudflare.com",
|
||||
"img-src 'self' data:",
|
||||
"style-src 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'none'",
|
||||
].join('; ');
|
||||
|
||||
/** The app uses no device features. */
|
||||
export const PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=()';
|
||||
|
||||
/** One year, this host only. Other pantry subdomains are not covered. */
|
||||
export const STRICT_TRANSPORT_SECURITY = 'max-age=31536000';
|
||||
|
||||
/** HSTS is sent only when BASE_URL is https. A browser ignores it over http. */
|
||||
export function securityHeaders(options: { https: boolean }): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
await next();
|
||||
c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);
|
||||
c.header('Referrer-Policy', 'no-referrer');
|
||||
c.header('X-Content-Type-Options', 'nosniff');
|
||||
c.header('Permissions-Policy', PERMISSIONS_POLICY);
|
||||
if (options.https) c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from './auth/audit.js';
|
||||
import { normalizeEmail } from './email.js';
|
||||
|
||||
/** Earlier reminder, then the closer one. Used when the coordinator has not saved a pair. */
|
||||
export const DEFAULT_REMINDER_HOURS = [48, 2] as const;
|
||||
export const DEFAULT_RETENTION_MONTHS = 24;
|
||||
export const MAX_REMINDER_HOURS = 336;
|
||||
export const MAX_RETENTION_MONTHS = 120;
|
||||
export const MAX_PRIVACY_TEXT = 8000;
|
||||
|
||||
const HOUR_KEY = 'reminder_hours';
|
||||
const REPLY_KEY = 'reply_to';
|
||||
const PRIVACY_KEY = 'privacy_text';
|
||||
const RETENTION_KEY = 'retention_months';
|
||||
|
||||
export type PantrySettings = {
|
||||
/** Larger hour count first, so the first reminder is the earlier one. */
|
||||
reminderHours: readonly [number, number];
|
||||
replyTo: string;
|
||||
privacyText: string;
|
||||
retentionMonths: number;
|
||||
};
|
||||
|
||||
export type SettingsForm = {
|
||||
reminderFar: string;
|
||||
reminderNear: string;
|
||||
replyTo: string;
|
||||
retentionMonths: string;
|
||||
privacyText: string;
|
||||
};
|
||||
|
||||
export type SettingsErrors = Partial<Record<keyof SettingsForm, string>>;
|
||||
|
||||
export function readRetentionMonths(db: Database.Database): number {
|
||||
return storedRetention(db);
|
||||
}
|
||||
|
||||
export function readPantrySettings(db: Database.Database, fallbackReplyTo: string): PantrySettings {
|
||||
return {
|
||||
reminderHours: storedHours(db),
|
||||
replyTo: storedReplyTo(db) ?? fallbackReplyTo,
|
||||
privacyText: storedPrivacy(db),
|
||||
retentionMonths: storedRetention(db),
|
||||
};
|
||||
}
|
||||
|
||||
/** Closest offset is first, so a late catch-up keeps the reminder nearest the shift. */
|
||||
export function readReminderOffsets(db: Database.Database): { kind: string; hours: number }[] {
|
||||
const [earlier, closer] = storedHours(db);
|
||||
return [
|
||||
{ kind: `${closer}h`, hours: closer },
|
||||
{ kind: `${earlier}h`, hours: earlier },
|
||||
];
|
||||
}
|
||||
|
||||
export function readReplyTo(db: Database.Database, fallback: string): string {
|
||||
return storedReplyTo(db) ?? fallback;
|
||||
}
|
||||
|
||||
export function privacyParagraphs(text: string): string[] {
|
||||
return text
|
||||
.split(/\n+/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
export function settingsFormFrom(settings: PantrySettings): SettingsForm {
|
||||
return {
|
||||
reminderFar: String(settings.reminderHours[0]),
|
||||
reminderNear: String(settings.reminderHours[1]),
|
||||
replyTo: settings.replyTo,
|
||||
retentionMonths: String(settings.retentionMonths),
|
||||
privacyText: settings.privacyText,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSettingsForm(input: SettingsForm): { ok: true; value: PantrySettings } | { ok: false; errors: SettingsErrors } {
|
||||
const errors: SettingsErrors = {};
|
||||
const earlier = parseHour(input.reminderFar);
|
||||
const closer = parseHour(input.reminderNear);
|
||||
if (earlier === null) errors.reminderFar = `Enter a whole number of hours from 1 to ${MAX_REMINDER_HOURS}.`;
|
||||
if (closer === null) errors.reminderNear = `Enter a whole number of hours from 1 to ${MAX_REMINDER_HOURS}.`;
|
||||
if (earlier !== null && closer !== null && earlier === closer) {
|
||||
errors.reminderNear = 'The two reminder times have to be different.';
|
||||
}
|
||||
const reply = parseReply(input.replyTo);
|
||||
if (!reply.ok) errors.replyTo = reply.error;
|
||||
const months = parseMonths(input.retentionMonths);
|
||||
if (months === null) errors.retentionMonths = `Enter a whole number of months from 1 to ${MAX_RETENTION_MONTHS}.`;
|
||||
const privacy = parsePrivacy(input.privacyText);
|
||||
if (!privacy.ok) errors.privacyText = privacy.error;
|
||||
if (earlier === null || closer === null || earlier === closer || !reply.ok || months === null || !privacy.ok) {
|
||||
return { ok: false, errors };
|
||||
}
|
||||
const reminderHours: [number, number] = earlier > closer ? [earlier, closer] : [closer, earlier];
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
reminderHours,
|
||||
replyTo: reply.value,
|
||||
privacyText: privacy.value,
|
||||
retentionMonths: months,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the four coordinator settings. Retention is stored only.
|
||||
* This does not anonymize signups, and it does not change mail that is already queued.
|
||||
*/
|
||||
export function savePantrySettings(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
next: PantrySettings,
|
||||
fallbackReplyTo: string,
|
||||
now: string,
|
||||
): { changed: boolean } {
|
||||
const current = readPantrySettings(db, fallbackReplyTo);
|
||||
const replyChanged = current.replyTo !== next.replyTo;
|
||||
const privacyChanged = current.privacyText !== next.privacyText;
|
||||
const hoursChanged = current.reminderHours[0] !== next.reminderHours[0] || current.reminderHours[1] !== next.reminderHours[1];
|
||||
const retentionChanged = current.retentionMonths !== next.retentionMonths;
|
||||
if (!replyChanged && !privacyChanged && !hoursChanged && !retentionChanged) return { changed: false };
|
||||
db.transaction(() => {
|
||||
writeValue(db, HOUR_KEY, [next.reminderHours[0], next.reminderHours[1]], now);
|
||||
writeValue(db, REPLY_KEY, next.replyTo, now);
|
||||
writeValue(db, PRIVACY_KEY, next.privacyText, now);
|
||||
writeValue(db, RETENTION_KEY, next.retentionMonths, now);
|
||||
writeAudit(
|
||||
db,
|
||||
coordinatorId,
|
||||
'settings.update',
|
||||
{
|
||||
reminderEarlier: next.reminderHours[0],
|
||||
reminderCloser: next.reminderHours[1],
|
||||
retentionMonths: next.retentionMonths,
|
||||
replyChanged: replyChanged ? 1 : 0,
|
||||
privacyChanged: privacyChanged ? 1 : 0,
|
||||
},
|
||||
now,
|
||||
);
|
||||
}).immediate();
|
||||
return { changed: true };
|
||||
}
|
||||
|
||||
function storedHours(db: Database.Database): readonly [number, number] {
|
||||
const value = readValue(db, HOUR_KEY);
|
||||
if (!Array.isArray(value) || value.length !== 2) return DEFAULT_REMINDER_HOURS;
|
||||
const first = value[0];
|
||||
const second = value[1];
|
||||
if (!isHour(first) || !isHour(second) || first === second) return DEFAULT_REMINDER_HOURS;
|
||||
return first > second ? [first, second] : [second, first];
|
||||
}
|
||||
|
||||
function storedReplyTo(db: Database.Database): string | null {
|
||||
const value = readValue(db, REPLY_KEY);
|
||||
if (typeof value !== 'string') return null;
|
||||
try {
|
||||
return normalizeEmail(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function storedPrivacy(db: Database.Database): string {
|
||||
const value = readValue(db, PRIVACY_KEY);
|
||||
if (typeof value !== 'string') return '';
|
||||
const parsed = parsePrivacy(value);
|
||||
return parsed.ok ? parsed.value : '';
|
||||
}
|
||||
|
||||
function storedRetention(db: Database.Database): number {
|
||||
const value = readValue(db, RETENTION_KEY);
|
||||
return isMonth(value) ? value : DEFAULT_RETENTION_MONTHS;
|
||||
}
|
||||
|
||||
function readValue(db: Database.Database, key: string): unknown {
|
||||
const row = db.prepare('SELECT value_json AS value_json FROM settings WHERE key = ?').get(key) as { value_json: string } | undefined;
|
||||
if (!row) return undefined;
|
||||
try {
|
||||
return JSON.parse(row.value_json) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeValue(db: Database.Database, key: string, value: unknown, now: string): void {
|
||||
db.prepare(
|
||||
`INSERT INTO settings (key, value_json, updated_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT (key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at`,
|
||||
).run(key, JSON.stringify(value), now);
|
||||
}
|
||||
|
||||
function parseHour(value: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!/^[1-9][0-9]{0,2}$/.test(trimmed)) return null;
|
||||
const hours = Number(trimmed);
|
||||
return isHour(hours) ? hours : null;
|
||||
}
|
||||
|
||||
function parseMonths(value: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!/^[1-9][0-9]{0,2}$/.test(trimmed)) return null;
|
||||
const months = Number(trimmed);
|
||||
return isMonth(months) ? months : null;
|
||||
}
|
||||
|
||||
function parseReply(value: string): { ok: true; value: string } | { ok: false; error: string } {
|
||||
if (value.includes('<') || value.includes('>')) {
|
||||
return { ok: false, error: 'Enter an email address without a display name.' };
|
||||
}
|
||||
try {
|
||||
return { ok: true, value: normalizeEmail(value) };
|
||||
} catch {
|
||||
return { ok: false, error: 'Enter an email address.' };
|
||||
}
|
||||
}
|
||||
|
||||
function parsePrivacy(value: string): { ok: true; value: string } | { ok: false; error: string } {
|
||||
const cleaned = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\t/g, ' ').trim();
|
||||
if (cleaned.length > MAX_PRIVACY_TEXT) return { ok: false, error: 'Keep the privacy wording under 8,000 characters.' };
|
||||
if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(cleaned)) {
|
||||
return { ok: false, error: 'Remove the unusual character in the privacy wording.' };
|
||||
}
|
||||
return { ok: true, value: cleaned };
|
||||
}
|
||||
|
||||
function isHour(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_REMINDER_HOURS;
|
||||
}
|
||||
|
||||
function isMonth(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_RETENTION_MONTHS;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { z } from 'zod';
|
||||
import { EmailAddressError, normalizeEmail } from './email.js';
|
||||
|
||||
const NAME_MAX = 80;
|
||||
const PHONE_MAX = 40;
|
||||
const NOTES_MAX = 500;
|
||||
|
||||
export type SignupValues = {
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
notes: string;
|
||||
under18: boolean;
|
||||
guardianName: string;
|
||||
guardianEmail: string;
|
||||
};
|
||||
|
||||
export type SignupErrors = Partial<Record<'name' | 'email' | 'phone' | 'notes' | 'guardianName' | 'guardianEmail' | 'form', string>>;
|
||||
|
||||
export type SignupDraft = {
|
||||
name: string;
|
||||
email: string;
|
||||
emailNorm: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
guardianEmailNorm: string | null;
|
||||
};
|
||||
|
||||
export const EMPTY_SIGNUP: SignupValues = {
|
||||
name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
notes: '',
|
||||
under18: false,
|
||||
guardianName: '',
|
||||
guardianEmail: '',
|
||||
};
|
||||
|
||||
const controlChars = /[\u0000-\u001F\u007F]/;
|
||||
|
||||
export function parseSignupForm(
|
||||
input: SignupValues,
|
||||
voice: 'volunteer' | 'coordinator' = 'volunteer',
|
||||
): { ok: true; draft: SignupDraft } | { ok: false; errors: SignupErrors } {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
phone: z.string(),
|
||||
notes: z.string(),
|
||||
under18: z.boolean(),
|
||||
guardianName: z.string(),
|
||||
guardianEmail: z.string(),
|
||||
})
|
||||
.safeParse(input);
|
||||
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
|
||||
const errors: SignupErrors = {};
|
||||
const name = parsed.data.name.normalize('NFC').trim();
|
||||
const nameLabel = voice === 'coordinator' ? 'their name' : 'your name';
|
||||
if (name.length === 0) errors.name = `Enter ${nameLabel}.`;
|
||||
else if (name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(name)) errors.name = `Enter ${nameLabel} without line breaks.`;
|
||||
|
||||
let emailNorm = '';
|
||||
try {
|
||||
emailNorm = normalizeEmail(parsed.data.email);
|
||||
} catch (err) {
|
||||
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
|
||||
}
|
||||
|
||||
const phone = parsed.data.phone.normalize('NFC').trim();
|
||||
if (phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(phone)) errors.phone = 'Enter a phone number without line breaks.';
|
||||
|
||||
const notes = parsed.data.notes.normalize('NFC').trim();
|
||||
if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(notes)) errors.notes = 'Enter notes without control characters.';
|
||||
|
||||
let guardianName: string | null = null;
|
||||
let guardianEmail: string | null = null;
|
||||
let guardianEmailNorm: string | null = null;
|
||||
if (parsed.data.under18) {
|
||||
guardianName = parsed.data.guardianName.normalize('NFC').trim();
|
||||
if (guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
|
||||
else if (guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(guardianName)) errors.guardianName = 'Enter the guardian name without line breaks.';
|
||||
if (parsed.data.guardianEmail.trim() === '') {
|
||||
errors.guardianEmail = 'Enter the guardian email.';
|
||||
} else {
|
||||
try {
|
||||
guardianEmailNorm = normalizeEmail(parsed.data.guardianEmail);
|
||||
guardianEmail = guardianEmailNorm;
|
||||
} catch (err) {
|
||||
errors.guardianEmail = err instanceof EmailAddressError ? err.message : 'Enter the guardian email.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0 || emailNorm.length === 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
draft: {
|
||||
name,
|
||||
email: emailNorm,
|
||||
emailNorm,
|
||||
phone: phone.length === 0 ? null : phone,
|
||||
notes: notes.length === 0 ? null : notes,
|
||||
isMinor: parsed.data.under18,
|
||||
guardianName: parsed.data.under18 ? guardianName : null,
|
||||
guardianEmail: parsed.data.under18 ? guardianEmail : null,
|
||||
guardianEmailNorm: parsed.data.under18 ? guardianEmailNorm : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Context } from 'hono';
|
||||
import type { Hono } from 'hono';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { listMoveTargets, switchSignup } from './admin/store.js';
|
||||
import { cancelTokenMatches, issueCancelToken, issueReminderPageToken, issueSwitchToken, reminderPageTokenMatches, switchTokenMatches } from './cancel-token.js';
|
||||
import { clientAddress } from './client-ip.js';
|
||||
import { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { issueFormToken, newOperationId, openFormToken, readFormToken } from './form-token.js';
|
||||
import { originAllowed } from './origin.js';
|
||||
import { readReplyTo } from './settings.js';
|
||||
import {
|
||||
ConfirmationPage,
|
||||
Layout,
|
||||
ManagePage,
|
||||
NotFoundPage,
|
||||
ShiftPage,
|
||||
SwitchAlreadyPage,
|
||||
WaitPage,
|
||||
type SignupFormView,
|
||||
type SwitchForm,
|
||||
} from './pages.js';
|
||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupGuardian, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
||||
import { getPublicShift, type PublicShift } from './schedule.js';
|
||||
import { EMPTY_SIGNUP, parseSignupForm, type SignupErrors, type SignupValues } from './signup-form.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { disableReminders } from './reminders.js';
|
||||
import { cancelSignup, confirmedOperationShift, findSignupByOperation, readManageSignup, reserveSignup } from './signup.js';
|
||||
import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js';
|
||||
import { appPath, cookiePath } from './url.js';
|
||||
|
||||
const COULD_NOT_SAVE =
|
||||
'This signup could not be saved. If this shift is already in your confirmation, use that link.';
|
||||
const ALREADY_SIGNED_UP = 'That person is already signed up for this shift.';
|
||||
const TOO_FAST = 'Please wait a few seconds and submit the form again.';
|
||||
const CHECK_AGAIN = 'The check did not finish. Please try again.';
|
||||
const CHECK_UNAVAILABLE = 'The check could not be reached. Please try again in a little while.';
|
||||
const TOO_MANY = 'Too many signup attempts. Please wait and try again.';
|
||||
const FULL = 'This shift is full.';
|
||||
const CLOSED = 'This shift is closed.';
|
||||
const ORIGIN = 'The signup could not be sent from this page.';
|
||||
const CANCEL_ORIGIN = 'The cancellation could not be sent from this page.';
|
||||
const CANCEL_REJECTED = 'The cancellation could not be confirmed. Please try again.';
|
||||
const CANCEL_UNAVAILABLE = 'The cancellation could not be saved. Please try again in a little while.';
|
||||
const SWITCH_ORIGIN = 'The switch could not be sent from this page.';
|
||||
const SWITCH_REJECTED = 'The switch could not be confirmed. Please try again.';
|
||||
const SWITCH_UNAVAILABLE = 'The switch could not be saved. Please try again in a little while.';
|
||||
const SWITCH_STALE = 'This form is out of date. Submit it again.';
|
||||
const SWITCHED_NOTE = 'You are on this shift. This link replaces the earlier one. A change email is queued.';
|
||||
const EXPIRED = 'This form expired. Please submit it again.';
|
||||
|
||||
export type SignupServices = {
|
||||
config: AppConfig;
|
||||
db: Database.Database;
|
||||
now: () => string;
|
||||
clientIp?: (c: Context) => string | null;
|
||||
verifyTurnstile?: (input: TurnstileCheck) => Promise<TurnstileVerdict>;
|
||||
};
|
||||
|
||||
export function registerPublicSignup(app: Hono, services: SignupServices): void {
|
||||
const { config } = services;
|
||||
|
||||
app.get(appPath(config, '/s/:id'), (c) => {
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
return shiftResponse(c, services, shift, 200, blankForm(services, shift));
|
||||
});
|
||||
|
||||
app.post(appPath(config, '/s/:id'), (c) => submitSignup(c, services));
|
||||
|
||||
app.get(appPath(config, '/s/:id/confirmed'), (c) => {
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
const seal = openConfirmation(config.sessionSecret, c.req.header('cookie'), epochMs(services.now()));
|
||||
const manage = seal && seal.shiftId === shift.id ? readManageSignup(services.db, seal.token, services.now()) : null;
|
||||
const matches = Boolean(manage && seal && manage.signupId === seal.signupId);
|
||||
const cancelled = matches && manage?.status === 'cancelled';
|
||||
return html(
|
||||
c,
|
||||
config,
|
||||
cancelled ? 'This signup is cancelled · Hope Volunteer' : "You're signed up · Hope Volunteer",
|
||||
<ConfirmationPage
|
||||
config={config}
|
||||
shift={shift}
|
||||
name={matches && manage ? manage.name : null}
|
||||
managePath={matches && seal ? appPath(config, `/m/${seal.token}`) : null}
|
||||
cancelled={cancelled}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/m/:token'), (c) => showManage(c, services, c.req.param('token') ?? ''));
|
||||
|
||||
app.post(appPath(config, '/m/:token/switch'), (c) => submitSwitch(c, services));
|
||||
app.post(appPath(config, '/m/:token/reminders'), (c) => submitRemindersOff(c, services));
|
||||
app.post(appPath(config, '/m/:token'), (c) => submitCancel(c, services));
|
||||
}
|
||||
|
||||
async function submitSignup(c: Context, services: SignupServices): Promise<Response> {
|
||||
const { config, db } = services;
|
||||
const now = services.now();
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
const ip = clientAddress(config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
if (!originAllowed(c, config.baseUrl)) {
|
||||
return shiftResponse(c, services, shift, 403, formFor(services, shift, EMPTY_SIGNUP, {}, null), ORIGIN);
|
||||
}
|
||||
const ipLimit = recordSignupIp(db, config.sessionSecret, now, ip);
|
||||
if (ipLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, blankForm(services, shift), TOO_MANY, ipLimit.retryAfter);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
const values = valuesFrom(body);
|
||||
if (textField(body, 'company_website').trim() !== '') {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
}
|
||||
const tokenResult = readFormToken(config.sessionSecret, textField(body, 'form_token'), shift.id, epochMs(now));
|
||||
if (!tokenResult.ok) {
|
||||
const notice = tokenResult.reason === 'too_fast' ? TOO_FAST : EXPIRED;
|
||||
const token = tokenResult.reason === 'too_fast' ? textField(body, 'form_token') : null;
|
||||
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, {}, token), notice);
|
||||
}
|
||||
const parsed = parseSignupForm(values);
|
||||
if (!parsed.ok) {
|
||||
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, parsed.errors, textField(body, 'form_token')), undefined);
|
||||
}
|
||||
const existing = findSignupByOperation(db, tokenResult.claims.operationId);
|
||||
if (existing && existing.shiftId === shift.id && existing.emailNorm === parsed.draft.emailNorm) {
|
||||
return redirectConfirmed(c, services, shift.id, null);
|
||||
}
|
||||
if (existing) {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
}
|
||||
const turnstileToken = textField(body, 'cf-turnstile-response').trim();
|
||||
const verdict = turnstileToken === ''
|
||||
? ({ ok: false, reason: 'rejected' } as const)
|
||||
: await checkTurnstile(services, turnstileToken, ip);
|
||||
if (!verdict.ok) {
|
||||
if (verdict.reason === 'duplicate') {
|
||||
const again = findSignupByOperation(db, tokenResult.claims.operationId);
|
||||
if (again && again.shiftId === shift.id && again.emailNorm === parsed.draft.emailNorm) {
|
||||
return redirectConfirmed(c, services, shift.id, null);
|
||||
}
|
||||
}
|
||||
const notice = verdict.reason === 'unavailable' ? CHECK_UNAVAILABLE : CHECK_AGAIN;
|
||||
return shiftResponse(c, services, shift, verdict.reason === 'unavailable' ? 503 : 400, formFor(services, shift, values, {}, textField(body, 'form_token')), notice);
|
||||
}
|
||||
const emailLimit = recordSignupEmail(db, config.sessionSecret, now, config.defaultTimeZone, parsed.draft.emailNorm);
|
||||
if (emailLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, emailLimit.retryAfter);
|
||||
}
|
||||
const guardianEmail = parsed.draft.guardianEmailNorm;
|
||||
if (guardianEmail && guardianEmail !== parsed.draft.emailNorm) {
|
||||
const guardianLimit = recordSignupGuardian(db, config.sessionSecret, now, config.defaultTimeZone, guardianEmail);
|
||||
if (guardianLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, guardianLimit.retryAfter);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const reserved = reserveSignup(db, {
|
||||
shiftId: shift.id,
|
||||
name: parsed.draft.name,
|
||||
email: parsed.draft.emailNorm,
|
||||
phone: parsed.draft.phone,
|
||||
notes: parsed.draft.notes,
|
||||
isMinor: parsed.draft.isMinor,
|
||||
guardianName: parsed.draft.guardianName,
|
||||
guardianEmail: parsed.draft.guardianEmail,
|
||||
operationId: tokenResult.claims.operationId,
|
||||
now,
|
||||
mail: mailIdentity(db, config),
|
||||
});
|
||||
if (reserved.ok) return redirectConfirmed(c, services, shift.id, reserved.manageToken ? { signupId: reserved.signupId, token: reserved.manageToken } : null);
|
||||
if (reserved.reason === 'not_found') return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
if (reserved.reason === 'closed') return shiftResponse(c, services, loadShift(services, String(shift.id)) ?? shift, 400, null, CLOSED);
|
||||
if (reserved.reason === 'full') return shiftResponse(c, services, loadShift(services, String(shift.id)) ?? shift, 409, null, FULL);
|
||||
if (reserved.reason === 'duplicate') {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), ALREADY_SIGNED_UP);
|
||||
}
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Signup could not lock the database.');
|
||||
return shiftResponse(c, services, shift, 503, formFor(services, shift, values, {}, textField(body, 'form_token')), CHECK_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
function redirectConfirmed(
|
||||
c: Context,
|
||||
services: SignupServices,
|
||||
shiftId: number,
|
||||
issued: { signupId: number; token: string } | null,
|
||||
): Response {
|
||||
if (issued) {
|
||||
const sealed = sealConfirmation(services.config.sessionSecret, {
|
||||
signupId: issued.signupId,
|
||||
shiftId,
|
||||
token: issued.token,
|
||||
expiresAtMs: epochMs(services.now()) + 900 * 1000,
|
||||
});
|
||||
c.header('Set-Cookie', confirmationCookie(sealed, cookiePath(services.config), services.config.secureCookies));
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/s/${shiftId}/confirmed`), 303);
|
||||
}
|
||||
|
||||
function shiftResponse(
|
||||
c: Context,
|
||||
services: SignupServices,
|
||||
shift: PublicShift,
|
||||
status: 200 | 400 | 403 | 409 | 429 | 503,
|
||||
signup: SignupFormView | null,
|
||||
notice?: string,
|
||||
retryAfter?: number,
|
||||
) {
|
||||
if (retryAfter !== undefined) c.header('Retry-After', String(retryAfter));
|
||||
const current = loadShift(services, String(shift.id)) ?? shift;
|
||||
const showForm = signup !== null && !current.cancelled && !current.ended && !current.full;
|
||||
return html(
|
||||
c,
|
||||
services.config,
|
||||
`${current.role} · Hope Volunteer`,
|
||||
<ShiftPage config={services.config} shift={current} signup={showForm ? signup : null} notice={notice} />,
|
||||
status,
|
||||
showForm,
|
||||
);
|
||||
}
|
||||
|
||||
function blankForm(services: SignupServices, shift: PublicShift): SignupFormView | null {
|
||||
if (shift.cancelled || shift.ended || shift.full) return null;
|
||||
return formFor(services, shift, EMPTY_SIGNUP, {}, null);
|
||||
}
|
||||
|
||||
function formFor(
|
||||
services: SignupServices,
|
||||
shift: PublicShift,
|
||||
values: SignupValues,
|
||||
errors: SignupErrors,
|
||||
token: string | null,
|
||||
): SignupFormView {
|
||||
return {
|
||||
token: token && token.length > 0 ? token : issueFormToken(services.config.sessionSecret, {
|
||||
shiftId: shift.id,
|
||||
issuedAt: epochMs(services.now()),
|
||||
operationId: newOperationId(),
|
||||
}),
|
||||
siteKey: services.config.turnstile.siteKey,
|
||||
values,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
async function checkTurnstile(services: SignupServices, token: string, remoteIp: string): Promise<TurnstileVerdict> {
|
||||
const verify = services.verifyTurnstile ?? verifyTurnstile;
|
||||
try {
|
||||
return await verify({
|
||||
secret: services.config.turnstile.secretKey,
|
||||
token,
|
||||
remoteIp,
|
||||
expectedHostname: new URL(services.config.baseUrl).hostname,
|
||||
expectedAction: 'signup',
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
}
|
||||
|
||||
function loadShift(services: SignupServices, rawId: string): PublicShift | null {
|
||||
const id = parseShiftId(rawId);
|
||||
if (id === null) return null;
|
||||
return getPublicShift(services.db, id, services.now());
|
||||
}
|
||||
|
||||
function valuesFrom(body: Record<string, unknown>): SignupValues {
|
||||
return {
|
||||
name: textField(body, 'name'),
|
||||
email: textField(body, 'email'),
|
||||
phone: textField(body, 'phone'),
|
||||
notes: textField(body, 'notes'),
|
||||
under18: textField(body, 'under18') === 'yes',
|
||||
guardianName: textField(body, 'guardianName'),
|
||||
guardianEmail: textField(body, 'guardianEmail'),
|
||||
};
|
||||
}
|
||||
|
||||
function textField(body: Record<string, unknown>, name: string): string {
|
||||
const value = body[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function peerAddress(c: Context, override: SignupServices['clientIp']): string | null {
|
||||
if (override) return override(c);
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function showManage(c: Context, services: SignupServices, token: string, status: 200 | 400 | 403 | 429 | 503 = 200, notice?: string) {
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
const note = manageNote(c.req.query('notice'));
|
||||
return html(
|
||||
c,
|
||||
services.config,
|
||||
'Your signup · Hope Volunteer',
|
||||
<ManagePage
|
||||
signup={signup}
|
||||
cancel={cancelForm(services, token, signup.status)}
|
||||
switches={switchForm(services, token, signup)}
|
||||
reminders={reminderForm(services, token, signup)}
|
||||
notice={notice}
|
||||
note={note}
|
||||
/>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function manageNote(notice: string | undefined): string | undefined {
|
||||
if (notice === 'switched') return SWITCHED_NOTE;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function missingManage(c: Context, services: SignupServices) {
|
||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
const limit = recordInvalidManageToken(services.db, services.config.sessionSecret, services.now(), ip);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
return html(c, services.config, 'Please wait · Hope Volunteer', <WaitPage />, 429);
|
||||
}
|
||||
return html(c, services.config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
}
|
||||
|
||||
async function submitCancel(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
return showManage(c, services, token, 403, CANCEL_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!cancelTokenMatches(services.config.sessionSecret, token, textField(body, 'cancel_token'))) {
|
||||
return showManage(c, services, token, 400, CANCEL_REJECTED);
|
||||
}
|
||||
try {
|
||||
const result = cancelSignup(services.db, token, services.now(), mailIdentity(services.db, services.config));
|
||||
if (!result.ok) return missingManage(c, services);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Cancellation could not lock the database.');
|
||||
return showManage(c, services, token, 503, CANCEL_UNAVAILABLE);
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${token}`), 303);
|
||||
}
|
||||
|
||||
async function submitSwitch(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
if (!signup) return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />, 403);
|
||||
return showManage(c, services, token, 403, SWITCH_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!signup) return switchedAlready(c, services, token, body);
|
||||
if (!switchTokenMatches(services.config.sessionSecret, token, textField(body, 'switch_token'))) {
|
||||
return showManage(c, services, token, 400, SWITCH_REJECTED);
|
||||
}
|
||||
if (signup.status !== 'confirmed') return showManage(c, services, token, 400, 'This signup is cancelled.');
|
||||
const destination = Number(textField(body, 'destination'));
|
||||
if (!Number.isSafeInteger(destination) || destination <= 0) return showManage(c, services, token, 400, 'Choose a shift.');
|
||||
const formToken = readFormToken(services.config.sessionSecret, textField(body, 'form_token'), signup.shiftId, epochMs(services.now()), 0);
|
||||
if (!formToken.ok) return showManage(c, services, token, 400, SWITCH_STALE);
|
||||
try {
|
||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
const recipients = [signup.emailNorm];
|
||||
if (signup.isMinor && signup.guardianEmail) recipients.push(signup.guardianEmail);
|
||||
const limit = recordSwitchAttempt(
|
||||
services.db, services.config.sessionSecret, services.now(), services.config.defaultTimeZone, ip, recipients,
|
||||
);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
return showManage(c, services, token, 429, 'Too many switch attempts. Please try again later. You are still signed up for this shift.');
|
||||
}
|
||||
const result = switchSignup(services.db, signup.signupId, destination, formToken.claims.operationId, services.now(), mailIdentity(services.db, services.config));
|
||||
if (!result.ok) return showManage(c, services, token, 400, result.error);
|
||||
if (!result.manageToken) return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />);
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${result.manageToken}?notice=switched`), 303);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Switch could not lock the database.');
|
||||
return showManage(c, services, token, 503, SWITCH_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
function switchedAlready(c: Context, services: SignupServices, token: string, body: Record<string, unknown>) {
|
||||
if (!switchTokenMatches(services.config.sessionSecret, token, textField(body, 'switch_token'))) return missingManage(c, services);
|
||||
const formToken = openFormToken(services.config.sessionSecret, textField(body, 'form_token'), epochMs(services.now()), 0);
|
||||
if (!formToken.ok) return missingManage(c, services);
|
||||
const shiftId = confirmedOperationShift(services.db, formToken.claims.operationId);
|
||||
if (shiftId === null) return missingManage(c, services);
|
||||
return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />);
|
||||
}
|
||||
|
||||
function switchForm(services: SignupServices, token: string, signup: { status: 'confirmed' | 'cancelled'; shiftId: number; eventId: number; name: string; email: string }): SwitchForm | null {
|
||||
if (signup.status !== 'confirmed') return null;
|
||||
const targets = listMoveTargets(services.db, signup.eventId, signup.shiftId, services.now(), {
|
||||
publishedOnly: true,
|
||||
});
|
||||
if (targets.length === 0) return { action: '', token: '', formToken: '', targets };
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}/switch`),
|
||||
token: issueSwitchToken(services.config.sessionSecret, token),
|
||||
formToken: issueFormToken(services.config.sessionSecret, {
|
||||
shiftId: signup.shiftId,
|
||||
issuedAt: epochMs(services.now()),
|
||||
operationId: newOperationId(),
|
||||
}),
|
||||
targets,
|
||||
};
|
||||
}
|
||||
|
||||
function reminderForm(
|
||||
services: SignupServices,
|
||||
token: string,
|
||||
signup: { status: 'confirmed' | 'cancelled'; remindersOff: boolean },
|
||||
): { action: string; token: string } | 'off' | null {
|
||||
if (signup.status !== 'confirmed') return null;
|
||||
if (signup.remindersOff) return 'off';
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}/reminders`),
|
||||
token: issueReminderPageToken(services.config.sessionSecret, token),
|
||||
};
|
||||
}
|
||||
|
||||
async function submitRemindersOff(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
return showManage(c, services, token, 403, CANCEL_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!reminderPageTokenMatches(services.config.sessionSecret, token, textField(body, 'reminder_token'))) {
|
||||
return showManage(c, services, token, 400, CANCEL_REJECTED);
|
||||
}
|
||||
try {
|
||||
const result = disableReminders(services.db, signup.signupId, services.now());
|
||||
if (!result.ok) return missingManage(c, services);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Reminder opt-out could not lock the database.');
|
||||
return showManage(c, services, token, 503, CANCEL_UNAVAILABLE);
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${token}`), 303);
|
||||
}
|
||||
|
||||
function cancelForm(services: SignupServices, token: string, status: 'confirmed' | 'cancelled'): { action: string; token: string } | null {
|
||||
if (status !== 'confirmed') return null;
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}`),
|
||||
token: issueCancelToken(services.config.sessionSecret, token),
|
||||
};
|
||||
}
|
||||
|
||||
function html(
|
||||
c: Context,
|
||||
config: AppConfig,
|
||||
title: string,
|
||||
body: Child,
|
||||
status: 200 | 400 | 403 | 404 | 409 | 429 | 503 = 200,
|
||||
turnstile = false,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.html(
|
||||
<Layout config={config} title={title} path={c.req.path} turnstile={turnstile}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function mailIdentity(db: Database.Database, config: AppConfig): MailIdentity {
|
||||
return {
|
||||
baseUrl: config.baseUrl,
|
||||
basePath: config.basePath,
|
||||
from: config.mail.from,
|
||||
replyTo: readReplyTo(db, config.mail.replyTo),
|
||||
};
|
||||
}
|
||||
|
||||
function epochMs(utc: string): number {
|
||||
return Temporal.Instant.from(utc).epochMilliseconds;
|
||||
}
|
||||
|
||||
function parseShiftId(value: string): number | null {
|
||||
return parsePositiveId(value);
|
||||
}
|
||||
|
||||
function parsePositiveId(value: string): number | null {
|
||||
if (!/^[1-9][0-9]*$/.test(value)) return null;
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) ? id : null;
|
||||
}
|
||||
|
||||
function isBusy(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: unknown }).code).includes('SQLITE_BUSY');
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from './email.js';
|
||||
import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { formatInstantInZone, formatUtc, type ZonedClock } from './time.js';
|
||||
|
||||
const MANAGE_TOKEN_TTL_HOURS = 24 * 7;
|
||||
|
||||
export type ReserveInput = {
|
||||
shiftId: number;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
operationId: string;
|
||||
now: string;
|
||||
mail: MailIdentity;
|
||||
/** Public signup stays on published shifts. A coordinator can record a walk-in before the event is public. */
|
||||
audience?: 'public' | 'coordinator';
|
||||
onReserved?: (signupId: number) => void;
|
||||
};
|
||||
|
||||
export type ReserveResult =
|
||||
| { ok: true; signupId: number; manageToken: string | null; replay: boolean }
|
||||
| { ok: false; reason: 'not_found' | 'closed' | 'full' | 'duplicate' | 'conflict' };
|
||||
|
||||
export type ManageView = {
|
||||
signupId: number;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
status: 'confirmed' | 'cancelled';
|
||||
remindersOff: boolean;
|
||||
emailNorm: string;
|
||||
shiftId: number;
|
||||
eventId: number;
|
||||
role: string;
|
||||
location: string;
|
||||
eventTitle: string;
|
||||
when: ZonedClock;
|
||||
};
|
||||
|
||||
/**
|
||||
* Takes one spot only when the published shift still has room.
|
||||
* The immediate transaction is the capacity lock and also queues confirmation mail.
|
||||
* A later send failure does not undo the reservation.
|
||||
*/
|
||||
export function reserveSignup(db: Database.Database, input: ReserveInput): ReserveResult {
|
||||
const emailNorm = normalizeEmail(input.email);
|
||||
const operationKey = sha256(input.operationId);
|
||||
const attempt = db.transaction(() => placeReservation(db, input, emailNorm, operationKey));
|
||||
try {
|
||||
return attempt.immediate();
|
||||
} catch (err) {
|
||||
if (!isUniqueConstraint(err)) throw err;
|
||||
const existing = findOperation(db, operationKey);
|
||||
if (existing && existing.shiftId === input.shiftId && existing.emailNorm === emailNorm) {
|
||||
return { ok: true, signupId: existing.id, manageToken: null, replay: true };
|
||||
}
|
||||
if (confirmedPersonOnShift(db, input.shiftId, emailNorm, input.name)) return { ok: false, reason: 'duplicate' };
|
||||
return { ok: false, reason: 'conflict' };
|
||||
}
|
||||
}
|
||||
|
||||
export function findSignupByOperation(
|
||||
db: Database.Database,
|
||||
operationId: string,
|
||||
): { id: number; shiftId: number; emailNorm: string } | null {
|
||||
return findOperation(db, sha256(operationId));
|
||||
}
|
||||
|
||||
export function confirmedOperationShift(db: Database.Database, operationId: string): number | null {
|
||||
const found = findOperation(db, sha256(operationId));
|
||||
if (!found) return null;
|
||||
const row = db.prepare('SELECT status AS status FROM signups WHERE id = ?').get(found.id) as { status: string } | undefined;
|
||||
return row?.status === 'confirmed' ? found.shiftId : null;
|
||||
}
|
||||
|
||||
export type CancelResult = { ok: true; already: boolean } | { ok: false; reason: 'invalid' };
|
||||
|
||||
/**
|
||||
* Marks this signup cancelled, frees its spot, and queues cancellation mail.
|
||||
* Cancelling the same link again is the same result and does not queue a second letter.
|
||||
* A pending confirmation is cancelled in this transaction. Mail already accepted cannot be recalled.
|
||||
*/
|
||||
export function cancelSignup(db: Database.Database, token: string, now: string, mail: MailIdentity): CancelResult {
|
||||
if (!manageTokenShape(token)) return { ok: false, reason: 'invalid' };
|
||||
const hash = sha256(token);
|
||||
return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate();
|
||||
}
|
||||
|
||||
export function readManageSignup(db: Database.Database, token: string, now: string): ManageView | null {
|
||||
if (!manageTokenShape(token)) return null;
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
su.id AS signup_id,
|
||||
su.name AS name,
|
||||
su.email AS email,
|
||||
su.phone AS phone,
|
||||
su.notes AS notes,
|
||||
su.is_minor AS is_minor,
|
||||
su.guardian_name AS guardian_name,
|
||||
su.guardian_email AS guardian_email,
|
||||
su.status AS status,
|
||||
su.reminders_off AS reminders_off,
|
||||
su.email_norm AS email_norm,
|
||||
su.token_expires_at AS token_expires_at,
|
||||
su.shift_id AS shift_id,
|
||||
s.event_id AS event_id,
|
||||
s.role AS role,
|
||||
e.title AS title,
|
||||
e.location AS location,
|
||||
e.tz AS tz,
|
||||
s.starts_at_utc AS starts_at_utc
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE su.manage_token_hash = ? AND su.anonymized_at IS NULL`,
|
||||
)
|
||||
.get(sha256(token)) as ManageRow | undefined;
|
||||
if (!row || !row.token_expires_at || row.token_expires_at <= now) return null;
|
||||
if (row.status !== 'confirmed' && row.status !== 'cancelled') return null;
|
||||
if (!row.name || !row.email || !row.email_norm) return null;
|
||||
return {
|
||||
signupId: row.signup_id,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
notes: row.notes,
|
||||
isMinor: row.is_minor === 1,
|
||||
guardianName: row.guardian_name,
|
||||
guardianEmail: row.guardian_email,
|
||||
status: row.status,
|
||||
remindersOff: row.reminders_off === 1,
|
||||
emailNorm: row.email_norm,
|
||||
shiftId: row.shift_id,
|
||||
eventId: row.event_id,
|
||||
role: row.role,
|
||||
location: row.location,
|
||||
eventTitle: row.title,
|
||||
when: formatInstantInZone(row.starts_at_utc, row.tz),
|
||||
};
|
||||
}
|
||||
|
||||
function placeReservation(db: Database.Database, input: ReserveInput, emailNorm: string, operationKey: string): ReserveResult {
|
||||
const shift = db
|
||||
.prepare(
|
||||
`SELECT s.capacity AS capacity, s.cancelled AS cancelled, s.ends_at_utc AS ends_at_utc, s.starts_at_utc AS starts_at_utc,
|
||||
s.version AS version, s.role AS role, e.published AS published, e.title AS title, e.location AS location, e.tz AS tz
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE s.id = ?`,
|
||||
)
|
||||
.get(input.shiftId) as
|
||||
| {
|
||||
capacity: number;
|
||||
cancelled: number;
|
||||
ends_at_utc: string;
|
||||
starts_at_utc: string;
|
||||
version: number;
|
||||
role: string;
|
||||
published: number;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
}
|
||||
| undefined;
|
||||
const coordinator = input.audience === 'coordinator';
|
||||
if (!shift || (!coordinator && shift.published !== 1)) return { ok: false, reason: 'not_found' };
|
||||
if (shift.cancelled === 1 || shift.ends_at_utc <= input.now) return { ok: false, reason: 'closed' };
|
||||
|
||||
const existing = findOperation(db, operationKey);
|
||||
if (existing) {
|
||||
if (existing.shiftId === input.shiftId && existing.emailNorm === emailNorm) {
|
||||
return { ok: true, signupId: existing.id, manageToken: null, replay: true };
|
||||
}
|
||||
return { ok: false, reason: 'conflict' };
|
||||
}
|
||||
if (confirmedPersonOnShift(db, input.shiftId, emailNorm, input.name)) return { ok: false, reason: 'duplicate' };
|
||||
|
||||
const occupied = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(group_size), 0) AS occupied
|
||||
FROM signups
|
||||
WHERE shift_id = ? AND status = 'confirmed'`,
|
||||
)
|
||||
.get(input.shiftId) as { occupied: number };
|
||||
if (Number(occupied.occupied) + 1 > shift.capacity) return { ok: false, reason: 'full' };
|
||||
|
||||
const manageToken = randomBytes(32).toString('base64url');
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(shift.ends_at_utc).add({ hours: MANAGE_TOKEN_TTL_HOURS }));
|
||||
const inserted = db
|
||||
.prepare(
|
||||
`INSERT INTO signups (
|
||||
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
||||
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
||||
created_at, updated_at, operation_key
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 'confirmed', ?, ?, 0, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
input.shiftId,
|
||||
input.name,
|
||||
emailNorm,
|
||||
emailNorm,
|
||||
input.phone,
|
||||
input.isMinor ? 1 : 0,
|
||||
input.isMinor ? input.guardianName : null,
|
||||
input.isMinor ? input.guardianEmail : null,
|
||||
input.notes,
|
||||
sha256(manageToken),
|
||||
expiresAt,
|
||||
input.now,
|
||||
input.now,
|
||||
operationKey,
|
||||
);
|
||||
const signupId = Number(inserted.lastInsertRowid);
|
||||
queueConfirmation(db, {
|
||||
signupId,
|
||||
shiftId: input.shiftId,
|
||||
shiftVersion: shift.version,
|
||||
token: manageToken,
|
||||
volunteerName: input.name,
|
||||
volunteerEmail: emailNorm,
|
||||
guardianEmail: input.isMinor ? input.guardianEmail : null,
|
||||
shift: shiftFacts(shift).facts,
|
||||
mail: input.mail,
|
||||
now: input.now,
|
||||
});
|
||||
input.onReserved?.(signupId);
|
||||
return { ok: true, signupId, manageToken, replay: false };
|
||||
}
|
||||
|
||||
type OperationRow = { id: number; shiftId: number; emailNorm: string };
|
||||
|
||||
function findOperation(db: Database.Database, operationKey: string): OperationRow | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id AS id, shift_id AS shiftId, email_norm AS emailNorm
|
||||
FROM signups
|
||||
WHERE operation_key = ? AND email_norm IS NOT NULL`,
|
||||
)
|
||||
.get(operationKey) as OperationRow | undefined;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** True when this name and email already have a confirmed spot on the shift. */
|
||||
export function confirmedPersonOnShift(db: Database.Database, shiftId: number, emailNorm: string, name: string): boolean {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id FROM signups
|
||||
WHERE shift_id = ? AND email_norm = ? AND name = ? COLLATE NOCASE AND status = 'confirmed'
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(shiftId, emailNorm, name);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
/** Shifts where this name and email are already confirmed. */
|
||||
export function confirmedPersonShiftIds(db: Database.Database, emailNorm: string, name: string): number[] {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT shift_id AS shift_id FROM signups
|
||||
WHERE email_norm = ? AND name = ? COLLATE NOCASE AND status = 'confirmed'`,
|
||||
)
|
||||
.all(emailNorm, name) as Array<{ shift_id: number }>;
|
||||
return rows.map((row) => row.shift_id);
|
||||
}
|
||||
|
||||
function cancelConfirmed(db: Database.Database, hash: string, token: string, now: string, mail: MailIdentity): CancelResult {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
||||
su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email, su.shift_id AS shift_id
|
||||
FROM signups su
|
||||
WHERE su.manage_token_hash = ?`,
|
||||
)
|
||||
.get(hash) as
|
||||
| {
|
||||
id: number;
|
||||
status: string;
|
||||
token_expires_at: string | null;
|
||||
anonymized_at: string | null;
|
||||
name: string | null;
|
||||
email_norm: string | null;
|
||||
guardian_email: string | null;
|
||||
shift_id: number;
|
||||
}
|
||||
| undefined;
|
||||
if (!row || row.anonymized_at || !row.token_expires_at || row.token_expires_at <= now) {
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
if (row.status === 'cancelled') return { ok: true, already: true };
|
||||
if (row.status !== 'confirmed' || !row.name || !row.email_norm) return { ok: false, reason: 'invalid' };
|
||||
const updated = db
|
||||
.prepare(
|
||||
`UPDATE signups
|
||||
SET status = 'cancelled', updated_at = ?
|
||||
WHERE manage_token_hash = ? AND status = 'confirmed' AND anonymized_at IS NULL AND token_expires_at > ?`,
|
||||
)
|
||||
.run(now, hash, now);
|
||||
if (updated.changes === 1) {
|
||||
cancelPendingConfirmations(db, row.id);
|
||||
cancelPendingReminders(db, row.id, 'The signup was cancelled before this reminder was sent.');
|
||||
const shift = loadShiftFacts(db, row.shift_id);
|
||||
if (shift) {
|
||||
queueCancellation(db, {
|
||||
signupId: row.id,
|
||||
shiftId: row.shift_id,
|
||||
shiftVersion: shift.version,
|
||||
token,
|
||||
volunteerName: row.name,
|
||||
volunteerEmail: row.email_norm,
|
||||
guardianEmail: row.guardian_email,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
});
|
||||
}
|
||||
return { ok: true, already: false };
|
||||
}
|
||||
const again = db
|
||||
.prepare(`SELECT status AS status, token_expires_at AS token_expires_at FROM signups WHERE manage_token_hash = ?`)
|
||||
.get(hash) as { status: string; token_expires_at: string | null } | undefined;
|
||||
if (again?.status === 'cancelled' && again.token_expires_at && again.token_expires_at > now) {
|
||||
return { ok: true, already: true };
|
||||
}
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
|
||||
function shiftFacts(shift: {
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
version: number;
|
||||
}): { version: number; facts: { role: string; eventTitle: string; location: string; whenLabel: string } } {
|
||||
const start = formatInstantInZone(shift.starts_at_utc, shift.tz);
|
||||
const end = formatInstantInZone(shift.ends_at_utc, shift.tz);
|
||||
return {
|
||||
version: shift.version,
|
||||
facts: {
|
||||
role: shift.role,
|
||||
eventTitle: shift.title,
|
||||
location: shift.location,
|
||||
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function loadShiftFacts(db: Database.Database, shiftId: number) {
|
||||
const shift = db
|
||||
.prepare(
|
||||
`SELECT s.role AS role, s.version AS version, s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc,
|
||||
e.title AS title, e.location AS location, e.tz AS tz
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE s.id = ?`,
|
||||
)
|
||||
.get(shiftId) as
|
||||
| {
|
||||
role: string;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
}
|
||||
| undefined;
|
||||
return shift ? shiftFacts(shift) : null;
|
||||
}
|
||||
|
||||
function manageTokenShape(token: string): boolean {
|
||||
return /^[A-Za-z0-9_-]{20,128}$/.test(token);
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function isUniqueConstraint(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: string }).code).includes('SQLITE_CONSTRAINT');
|
||||
}
|
||||
|
||||
|
||||
|
||||
type ManageRow = {
|
||||
signup_id: number;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
email_norm: string | null;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
is_minor: number;
|
||||
guardian_name: string | null;
|
||||
guardian_email: string | null;
|
||||
status: string;
|
||||
reminders_off: number;
|
||||
token_expires_at: string | null;
|
||||
shift_id: number;
|
||||
event_id: number;
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
starts_at_utc: string;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
export function isUniqueConstraint(err: unknown): boolean {
|
||||
return (
|
||||
err instanceof Error &&
|
||||
'code' in err &&
|
||||
String((err as { code: unknown }).code).includes('SQLITE_CONSTRAINT') &&
|
||||
/unique/i.test(err.message)
|
||||
);
|
||||
}
|
||||
|
||||
export function isBusy(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: unknown }).code).includes('SQLITE_BUSY');
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
|
||||
/**
|
||||
* Node 22 does not ship a stable Temporal API. @js-temporal/polyfill is the
|
||||
* timezone library for this app. It can reject a local time that falls in a
|
||||
* daylight-saving gap or overlap instead of silently moving it.
|
||||
*
|
||||
* Database instants use formatUtc(): YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
* Local dates stay YYYY-MM-DD. Local times stay HH:MM.
|
||||
* Weekday 0 is Sunday and weekday 6 is Saturday.
|
||||
*/
|
||||
|
||||
const LOCAL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const LOCAL_TIME = /^([01][0-9]|2[0-3]):([0-5][0-9])$/;
|
||||
const UTC_INSTANT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/;
|
||||
|
||||
export class LocalTimeError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'LocalTimeError';
|
||||
}
|
||||
}
|
||||
|
||||
export type ZonedClock = {
|
||||
date: string;
|
||||
time24: string;
|
||||
timeLabel: string;
|
||||
weekday: number;
|
||||
abbreviation: string;
|
||||
timeZone: string;
|
||||
dateLabel: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export function isUtcInstant(value: string): boolean {
|
||||
return UTC_INSTANT.test(value);
|
||||
}
|
||||
|
||||
export function assertUtcInstant(value: string): string {
|
||||
if (!isUtcInstant(value)) {
|
||||
throw new LocalTimeError('Expected a UTC instant like 2026-01-15T15:00:00.000Z.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function assertValidTimeZone(timeZone: string): string {
|
||||
try {
|
||||
Temporal.Instant.from('2020-01-01T00:00:00Z').toZonedDateTimeISO(timeZone);
|
||||
return timeZone;
|
||||
} catch {
|
||||
throw new LocalTimeError(`${timeZone} is not a recognized IANA time zone.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function formatUtc(instant: Temporal.Instant): string {
|
||||
const zoned = instant.toZonedDateTimeISO('UTC');
|
||||
return `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}T${pad(zoned.hour)}:${pad(zoned.minute)}:${pad(zoned.second)}.${pad(zoned.millisecond, 3)}Z`;
|
||||
}
|
||||
|
||||
export function nowUtc(now: Temporal.Instant = Temporal.Now.instant()): string {
|
||||
return formatUtc(now);
|
||||
}
|
||||
|
||||
export function localToUtc(date: string, time: string, timeZone: string): string {
|
||||
assertValidTimeZone(timeZone);
|
||||
assertCalendarDate(date);
|
||||
if (!LOCAL_TIME.test(time)) {
|
||||
throw new LocalTimeError(`${time} is not a local time. Use 24-hour HH:MM, such as 09:00 or 17:30.`);
|
||||
}
|
||||
const parts = parseDateTime(date, time);
|
||||
try {
|
||||
const zoned = Temporal.ZonedDateTime.from(
|
||||
{
|
||||
timeZone,
|
||||
year: parts.year,
|
||||
month: parts.month,
|
||||
day: parts.day,
|
||||
hour: parts.hour,
|
||||
minute: parts.minute,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
},
|
||||
{ disambiguation: 'reject' },
|
||||
);
|
||||
return assertUtcInstant(formatUtc(zoned.toInstant()));
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) throw err;
|
||||
const kind = classifyLocalTime(parts, timeZone);
|
||||
const shown = `${date} ${time} (${clockLabel(time)})`;
|
||||
if (kind === 'gap') {
|
||||
throw new LocalTimeError(
|
||||
`${shown} does not exist in ${timeZone}. Daylight saving time skips that clock time. Choose a different local time.`,
|
||||
);
|
||||
}
|
||||
if (kind === 'overlap') {
|
||||
throw new LocalTimeError(
|
||||
`${shown} happens twice in ${timeZone} because daylight saving time repeats that hour. Choose a local time outside the repeated hour.`,
|
||||
);
|
||||
}
|
||||
throw new LocalTimeError(`${shown} is not a valid local time in ${timeZone}.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSameDayShift(startLocal: string, endLocal: string): void {
|
||||
if (!LOCAL_TIME.test(startLocal) || !LOCAL_TIME.test(endLocal)) {
|
||||
throw new LocalTimeError('Use local times in 24-hour HH:MM form, such as 09:00 or 17:30.');
|
||||
}
|
||||
if (endLocal <= startLocal) {
|
||||
throw new LocalTimeError(
|
||||
'Shifts must start and end on the same day, with the end time after the start. Overnight shifts are not available yet.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function localShiftToUtc(
|
||||
date: string,
|
||||
startLocal: string,
|
||||
endLocal: string,
|
||||
timeZone: string,
|
||||
): { startsAtUtc: string; endsAtUtc: string } {
|
||||
assertSameDayShift(startLocal, endLocal);
|
||||
const startsAtUtc = localToUtc(date, startLocal, timeZone);
|
||||
const endsAtUtc = localToUtc(date, endLocal, timeZone);
|
||||
if (endsAtUtc <= startsAtUtc) {
|
||||
throw new LocalTimeError('The shift end must be after the start.');
|
||||
}
|
||||
return { startsAtUtc, endsAtUtc };
|
||||
}
|
||||
|
||||
export function formatInstantInZone(utc: string, timeZone: string): ZonedClock {
|
||||
assertUtcInstant(utc);
|
||||
assertValidTimeZone(timeZone);
|
||||
const instant = Temporal.Instant.from(utc);
|
||||
const zoned = instant.toZonedDateTimeISO(timeZone);
|
||||
const date = `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}`;
|
||||
const time24 = `${pad(zoned.hour)}:${pad(zoned.minute)}`;
|
||||
const timeLabel = clockLabel(time24);
|
||||
const weekday = zoned.dayOfWeek % 7;
|
||||
const dateLabel = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
weekday: 'long',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
}).format(new Date(instant.epochMilliseconds));
|
||||
const abbreviation = timeZoneAbbreviation(instant, timeZone);
|
||||
return {
|
||||
date,
|
||||
time24,
|
||||
timeLabel,
|
||||
weekday,
|
||||
abbreviation,
|
||||
timeZone,
|
||||
dateLabel,
|
||||
label: `${dateLabel}, ${timeLabel} ${abbreviation}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function addLocalDays(date: string, days: number): string {
|
||||
assertCalendarDate(date);
|
||||
return Temporal.PlainDate.from(date).add({ days }).toString();
|
||||
}
|
||||
|
||||
export function weekdayIndex(date: string, timeZone: string): number {
|
||||
return formatInstantInZone(localToUtc(date, '12:00', timeZone), timeZone).weekday;
|
||||
}
|
||||
|
||||
export function todayInZone(timeZone: string, now: Temporal.Instant = Temporal.Now.instant()): string {
|
||||
assertValidTimeZone(timeZone);
|
||||
const zoned = now.toZonedDateTimeISO(timeZone);
|
||||
return `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}`;
|
||||
}
|
||||
|
||||
function assertCalendarDate(date: string): void {
|
||||
if (!LOCAL_DATE.test(date)) {
|
||||
throw new LocalTimeError(`${date} is not a real calendar date. Use YYYY-MM-DD.`);
|
||||
}
|
||||
try {
|
||||
Temporal.PlainDate.from(date);
|
||||
} catch {
|
||||
throw new LocalTimeError(`${date} is not a real calendar date.`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseDateTime(date: string, time: string): {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
} {
|
||||
const dateMatch = LOCAL_DATE.exec(date);
|
||||
const timeMatch = LOCAL_TIME.exec(time);
|
||||
if (!dateMatch || !timeMatch) {
|
||||
throw new LocalTimeError(`${date} ${time} is not a valid local date and time.`);
|
||||
}
|
||||
return {
|
||||
year: Number(dateMatch[1]),
|
||||
month: Number(dateMatch[2]),
|
||||
day: Number(dateMatch[3]),
|
||||
hour: Number(timeMatch[1]),
|
||||
minute: Number(timeMatch[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyLocalTime(
|
||||
parts: { year: number; month: number; day: number; hour: number; minute: number },
|
||||
timeZone: string,
|
||||
): 'gap' | 'overlap' | 'unique' {
|
||||
const earlier = zonedAt(parts, timeZone, 'earlier');
|
||||
const later = zonedAt(parts, timeZone, 'later');
|
||||
const earlierMatches = sameClock(earlier, parts);
|
||||
const laterMatches = sameClock(later, parts);
|
||||
if (earlierMatches && laterMatches && earlier.offset !== later.offset) return 'overlap';
|
||||
if (!earlierMatches && !laterMatches) return 'gap';
|
||||
return 'unique';
|
||||
}
|
||||
|
||||
function zonedAt(
|
||||
parts: { year: number; month: number; day: number; hour: number; minute: number },
|
||||
timeZone: string,
|
||||
disambiguation: 'earlier' | 'later',
|
||||
): Temporal.ZonedDateTime {
|
||||
return Temporal.ZonedDateTime.from(
|
||||
{
|
||||
timeZone,
|
||||
year: parts.year,
|
||||
month: parts.month,
|
||||
day: parts.day,
|
||||
hour: parts.hour,
|
||||
minute: parts.minute,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
},
|
||||
{ disambiguation },
|
||||
);
|
||||
}
|
||||
|
||||
function sameClock(
|
||||
zoned: Temporal.ZonedDateTime,
|
||||
parts: { hour: number; minute: number },
|
||||
): boolean {
|
||||
return zoned.hour === parts.hour && zoned.minute === parts.minute;
|
||||
}
|
||||
|
||||
function clockLabel(time: string): string {
|
||||
const match = LOCAL_TIME.exec(time);
|
||||
if (!match) return time;
|
||||
const hour = Number(match[1]);
|
||||
const minute = Number(match[2]);
|
||||
const suffix = hour < 12 ? 'AM' : 'PM';
|
||||
const hour12 = hour % 12 === 0 ? 12 : hour % 12;
|
||||
return `${hour12}:${pad(minute)} ${suffix}`;
|
||||
}
|
||||
|
||||
function timeZoneAbbreviation(instant: Temporal.Instant, timeZone: string): string {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
timeZoneName: 'short',
|
||||
hour: 'numeric',
|
||||
}).formatToParts(new Date(instant.epochMilliseconds));
|
||||
const name = parts.find((part) => part.type === 'timeZoneName')?.value;
|
||||
return name && name.length > 0 ? name : timeZone;
|
||||
}
|
||||
|
||||
function pad(value: number, width = 2): string {
|
||||
return String(value).padStart(width, '0');
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { isTurnstileTestKey } from './config.js';
|
||||
|
||||
export type TurnstileVerdict = { ok: true } | { ok: false; reason: 'rejected' | 'duplicate' | 'unavailable' };
|
||||
|
||||
export type TurnstileCheck = {
|
||||
secret: string;
|
||||
token: string;
|
||||
remoteIp: string;
|
||||
expectedHostname: string;
|
||||
expectedAction: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
};
|
||||
|
||||
/**
|
||||
* Server-side Turnstile check. A spent token is not sent again.
|
||||
* Network failure and an unexpected hostname or action fail closed.
|
||||
*/
|
||||
export async function verifyTurnstile(input: TurnstileCheck): Promise<TurnstileVerdict> {
|
||||
const body = new URLSearchParams({
|
||||
secret: input.secret,
|
||||
response: input.token,
|
||||
remoteip: input.remoteIp,
|
||||
});
|
||||
let response: Response;
|
||||
try {
|
||||
response = await (input.fetchImpl ?? fetch)('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
if (!response.ok) return { ok: false, reason: 'unavailable' };
|
||||
let payload: SiteverifyResponse;
|
||||
try {
|
||||
payload = (await response.json()) as SiteverifyResponse;
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
if (payload.success !== true) {
|
||||
const codes = payload['error-codes'] ?? [];
|
||||
if (codes.includes('timeout-or-duplicate')) return { ok: false, reason: 'duplicate' };
|
||||
return { ok: false, reason: 'rejected' };
|
||||
}
|
||||
// Cloudflare's documented test keys succeed with hostname example.com and no action.
|
||||
if (payload.metadata?.result_with_testing_key === true && isTurnstileTestKey(input.secret)) {
|
||||
return { ok: true };
|
||||
}
|
||||
if (payload.hostname !== input.expectedHostname) return { ok: false, reason: 'rejected' };
|
||||
if (payload.action !== input.expectedAction) return { ok: false, reason: 'rejected' };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
type SiteverifyResponse = {
|
||||
success?: boolean;
|
||||
hostname?: string;
|
||||
action?: string;
|
||||
'error-codes'?: string[];
|
||||
metadata?: { result_with_testing_key?: boolean };
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { AppConfig } from './config.js';
|
||||
|
||||
/** Prefix an app path with BASE_PATH. The path must start with /. */
|
||||
export function appPath(config: Pick<AppConfig, 'basePath'>, pathname: string): string {
|
||||
if (!pathname.startsWith('/')) {
|
||||
throw new Error(`App paths must start with /. Received ${pathname}.`);
|
||||
}
|
||||
if (pathname === '/') return config.basePath === '' ? '/' : config.basePath;
|
||||
return `${config.basePath}${pathname}`;
|
||||
}
|
||||
|
||||
/** Absolute public URL for redirects, assets, cookies' companion links, and mail. */
|
||||
export function absoluteUrl(config: Pick<AppConfig, 'baseUrl' | 'basePath'>, pathname: string): string {
|
||||
return `${config.baseUrl}${appPath(config, pathname)}`;
|
||||
}
|
||||
|
||||
/** Cookie Path attribute. An empty mount prefix uses the site root. */
|
||||
export function cookiePath(config: Pick<AppConfig, 'basePath'>): string {
|
||||
return config.basePath === '' ? '/' : config.basePath;
|
||||
}
|
||||
@@ -0,0 +1,982 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { ACCEPTED } from '../src/admin-pages.js';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { bootstrapAdmin } from '../src/auth/bootstrap.js';
|
||||
import { recoverCoordinator } from '../src/auth/recover.js';
|
||||
import { sessionClearCookie, sessionSetCookie } from '../src/auth/session.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { openAppDatabase } from '../src/db.js';
|
||||
import { deliverDueMail } from '../src/mail/deliver.js';
|
||||
import { renderMagicLink } from '../src/mail/templates.js';
|
||||
import type { Mailer, OutboundMail } from '../src/mail/types.js';
|
||||
import { LOGIN_IP_LIMIT } from '../src/rate-limit.js';
|
||||
import { readManageSignup, reserveSignup } from '../src/signup.js';
|
||||
import { devEnv } from './env.js';
|
||||
|
||||
const NOW = '2026-10-14T18:00:00.000Z';
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
const MAIL = {
|
||||
baseUrl: ORIGIN,
|
||||
basePath: '',
|
||||
from: 'Hope Food Pantry <volunteer@example.invalid>',
|
||||
replyTo: 'volunteer@example.invalid',
|
||||
};
|
||||
const dirs: string[] = [];
|
||||
const databases: { close: () => void }[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of databases.splice(0)) database.close();
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('coordinator sign-in', () => {
|
||||
it('uses the same response for an active coordinator and anyone else', async () => {
|
||||
const active = await buildApp();
|
||||
const inactive = await buildApp();
|
||||
inactive.db.prepare('UPDATE coordinators SET active = 0').run();
|
||||
const known = await postLogin(active.app, 'coordinator@example.invalid');
|
||||
const stranger = await postLogin(active.app, 'missing@example.invalid');
|
||||
const closed = await postLogin(inactive.app, 'coordinator@example.invalid');
|
||||
const knownHtml = await known.text();
|
||||
const strangerHtml = await stranger.text();
|
||||
const closedHtml = await closed.text();
|
||||
expect(known.status).toBe(200);
|
||||
expect(stranger.status).toBe(200);
|
||||
expect(closed.status).toBe(200);
|
||||
expect(knownHtml).toBe(strangerHtml);
|
||||
expect(knownHtml).toBe(closedHtml);
|
||||
expect(knownHtml).toContain(ACCEPTED);
|
||||
expect(knownHtml).not.toContain('not found');
|
||||
expect(knownHtml).not.toContain('/login/link/');
|
||||
expect(known.headers.get('set-cookie')).toBeNull();
|
||||
expect(count(active.db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link'")).toBe(1);
|
||||
expect(count(inactive.db, "SELECT COUNT(*) AS n FROM outbox")).toBe(0);
|
||||
});
|
||||
|
||||
it('does not sign in when the link is only opened', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
await postLogin(app, 'coordinator@example.invalid');
|
||||
const token = magicToken(db);
|
||||
const opened = await app.request(`/login/link/${token}`);
|
||||
const html = await opened.text();
|
||||
expect(opened.status).toBe(200);
|
||||
expect(html).toContain('The link works once');
|
||||
expect(html).not.toContain(LINK_GONE);
|
||||
expect(opened.headers.get('set-cookie')).toBeNull();
|
||||
expect(usedAt(db, token)).toBeNull();
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(0);
|
||||
|
||||
const ignored = await postLink(app, token, 'not-the-proof-value-000000000000');
|
||||
expect(ignored.status).toBe(404);
|
||||
expect(usedAt(db, token)).toBeNull();
|
||||
|
||||
const proof = field(html, 'proof');
|
||||
const signedIn = await postLink(app, token, proof);
|
||||
expect(signedIn.status).toBe(303);
|
||||
expect(signedIn.headers.get('location')).toBe('/admin');
|
||||
const setCookie = signedIn.headers.get('set-cookie') ?? '';
|
||||
expect(setCookie).toContain('HttpOnly');
|
||||
expect(setCookie).toContain('SameSite=Lax');
|
||||
expect(setCookie).not.toContain('Secure');
|
||||
expect(setCookie).not.toContain('@');
|
||||
expect(usedAt(db, token)).toBe(NOW);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
|
||||
|
||||
const again = await postLink(app, token, proof);
|
||||
expect(again.status).toBe(404);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
|
||||
const home = await app.request('/admin', { headers: { cookie: cookieHeader(signedIn) } });
|
||||
expect(home.status).toBe(200);
|
||||
const homeHtml = await home.text();
|
||||
expect(homeHtml).toContain('Signed in as <strong>Administrator</strong>');
|
||||
expect(homeHtml).toContain('No database backup has been saved yet.');
|
||||
expect(homeHtml).not.toContain('coordinator@example.invalid');
|
||||
});
|
||||
|
||||
it('still accepts a valid link after other guesses from the same network', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
await postLogin(app, 'coordinator@example.invalid');
|
||||
const token = magicToken(db);
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
const guess = await postLink(app, `not-a-real-token-value-${index}xxxx`, 'also-not-a-real-proof-value-0001');
|
||||
expect(guess.status).toBe(404);
|
||||
}
|
||||
const page = await app.request(`/login/link/${token}`);
|
||||
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
|
||||
expect(signedIn.status).toBe(303);
|
||||
const blocked = await postLink(app, 'not-a-real-token-value-finalxxx', 'also-not-a-real-proof-value-0001');
|
||||
expect(blocked.status).toBe(429);
|
||||
expect(blocked.headers.get('retry-after')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('limits sign-in requests for one address', async () => {
|
||||
const { app } = await buildApp();
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const response = await postLogin(app, 'coordinator@example.invalid');
|
||||
expect(response.status).toBe(200);
|
||||
}
|
||||
const limited = await postLogin(app, 'coordinator@example.invalid');
|
||||
expect(limited.status).toBe(429);
|
||||
expect(await limited.text()).toContain('Too many sign-in attempts');
|
||||
expect(limited.headers.get('retry-after')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not let a cross-site sign-in post use up the network allowance', async () => {
|
||||
const { app } = await buildApp();
|
||||
for (let index = 0; index < LOGIN_IP_LIMIT; index += 1) {
|
||||
const rejected = await app.request('/login', {
|
||||
method: 'POST',
|
||||
headers: { origin: 'https://evil.example', 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ email: 'coordinator@example.invalid', 'cf-turnstile-response': 'token' }),
|
||||
});
|
||||
expect(rejected.status).toBe(403);
|
||||
}
|
||||
const allowed = await postLogin(app, 'coordinator@example.invalid');
|
||||
expect(allowed.status).toBe(200);
|
||||
expect(await allowed.text()).toContain(ACCEPTED);
|
||||
});
|
||||
|
||||
it('creates the first administrator once and does not replace that account', async () => {
|
||||
const { db, created } = await buildApp();
|
||||
expect(created).toEqual({ created: true });
|
||||
expect(bootstrapAdmin(db, 'other@example.invalid', NOW)).toEqual({ created: false });
|
||||
expect(db.prepare('SELECT email, name, role, password_hash, active FROM coordinators').get()).toEqual({
|
||||
email: 'coordinator@example.invalid',
|
||||
name: 'Administrator',
|
||||
role: 'admin',
|
||||
password_hash: null,
|
||||
active: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('revokes sessions from the host recovery command and can replace the address', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(200);
|
||||
const result = recoverCoordinator(db, {
|
||||
email: 'coordinator@example.invalid',
|
||||
replaceWith: 'next@example.invalid',
|
||||
now: NOW,
|
||||
});
|
||||
expect(result).toEqual({ coordinatorId: 1 });
|
||||
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
|
||||
await postLogin(app, 'coordinator@example.invalid');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link' AND status = 'pending' AND to_email = 'coordinator@example.invalid'")).toBe(0);
|
||||
await postLogin(app, 'next@example.invalid');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link' AND status = 'pending' AND to_email = 'next@example.invalid'")).toBe(1);
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
});
|
||||
|
||||
it('sends a sign-in link without using it, and drops an expired one', async () => {
|
||||
const sent: OutboundMail[] = [];
|
||||
const mailer: Mailer = { send: async (message) => { sent.push(message); return { result: 'sent', providerId: 'local' }; } };
|
||||
const fresh = await buildApp();
|
||||
await postLogin(fresh.app, 'coordinator@example.invalid');
|
||||
const token = magicToken(fresh.db);
|
||||
expect(await deliverDueMail(fresh.db, mailer, NOW, () => 0.5)).toBe(1);
|
||||
expect(sent[0]?.text).toContain(`/login/link/${token}`);
|
||||
expect(sent[0]?.text).toContain('expires in 15 minutes');
|
||||
expect(sent[0]?.text).toContain('Opening the link does not sign you in');
|
||||
expect(usedAt(fresh.db, token)).toBeNull();
|
||||
|
||||
const stale = await buildApp();
|
||||
await postLogin(stale.app, 'coordinator@example.invalid');
|
||||
stale.db.prepare('UPDATE login_tokens SET expires_at = ?').run(NOW);
|
||||
const calls: OutboundMail[] = [];
|
||||
expect(await deliverDueMail(stale.db, { send: async (message) => { calls.push(message); return { result: 'sent', providerId: null }; } }, NOW, () => 0.5)).toBe(0);
|
||||
expect(calls).toHaveLength(0);
|
||||
expect(stale.db.prepare("SELECT status AS status FROM outbox WHERE kind = 'magic_link'").get()).toEqual({ status: 'cancelled' });
|
||||
});
|
||||
|
||||
it('escapes the sign-in letter', () => {
|
||||
const rendered = renderMagicLink({ signInUrl: 'http://127.0.0.1:3000/login/link/abc', replyTo: 'a<b@example.invalid' });
|
||||
expect(rendered.html).toContain('a<b@example.invalid');
|
||||
expect(rendered.html).not.toContain('a<b@example.invalid');
|
||||
expect(rendered.subject).not.toContain('\n');
|
||||
});
|
||||
|
||||
it('sets the session cookie for https and for a mounted path', () => {
|
||||
const secure = sessionSetCookie({ basePath: '/volunteer', secureCookies: true }, 'abc');
|
||||
expect(secure).toContain('Path=/volunteer');
|
||||
expect(secure).toContain('Secure');
|
||||
expect(secure).toContain('HttpOnly');
|
||||
expect(secure).toContain('SameSite=Lax');
|
||||
expect(sessionSetCookie({ basePath: '', secureCookies: false }, 'abc')).not.toContain('Secure');
|
||||
expect(sessionClearCookie({ basePath: '', secureCookies: false })).toContain('Max-Age=0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('coordinator screens', () => {
|
||||
it('keeps unpublished events and the roster off the public site', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
expect((await app.request('/admin')).status).toBe(303);
|
||||
|
||||
const created = await postForm(app, '/admin/events', cookie, {
|
||||
title: 'Soup Night',
|
||||
slug: '',
|
||||
description: 'Bring a spoon.',
|
||||
location: 'Sioux Center, Iowa',
|
||||
tz: 'America/Chicago',
|
||||
}, { origin: 'null', 'sec-fetch-site': 'same-origin' });
|
||||
expect(created.status).toBe(303);
|
||||
const eventId = Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
|
||||
expect((await app.request('/e/soup-night')).status).toBe(404);
|
||||
expect(await (await app.request('/')).text()).not.toContain('Soup Night');
|
||||
|
||||
const published = await postForm(app, `/admin/events/${eventId}`, cookie, {
|
||||
title: 'Soup Night',
|
||||
slug: 'soup-night',
|
||||
description: 'Bring a spoon.',
|
||||
location: 'Sioux Center, Iowa',
|
||||
tz: 'America/Chicago',
|
||||
published: 'yes',
|
||||
});
|
||||
expect(published.status).toBe(303);
|
||||
expect((await app.request('/e/soup-night')).status).toBe(200);
|
||||
|
||||
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
|
||||
role: 'Ladle',
|
||||
date: '2026-10-15',
|
||||
start: '09:00',
|
||||
end: '12:00',
|
||||
capacity: '2',
|
||||
});
|
||||
expect(shift.status).toBe(303);
|
||||
const shiftId = Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
|
||||
const backwards = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
|
||||
role: 'Overnight',
|
||||
date: '2026-10-15',
|
||||
start: '12:00',
|
||||
end: '09:00',
|
||||
capacity: '1',
|
||||
});
|
||||
expect(backwards.status).toBe(400);
|
||||
expect(await backwards.text()).toContain('same day');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(1);
|
||||
|
||||
const pat = reserve(db, shiftId, 'Pat Example', 'pat@example.invalid', 'pat-operation');
|
||||
const sam = reserve(db, shiftId, 'Sam Example', 'sam@example.invalid', 'sam-operation');
|
||||
expect(pat.manageToken).toBeTruthy();
|
||||
const roster = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||
const rosterHtml = await roster.text();
|
||||
expect(rosterHtml).toContain('pat@example.invalid');
|
||||
expect(rosterHtml).toContain('Sam Example');
|
||||
const publicShift = await (await app.request(`/s/${shiftId}`)).text();
|
||||
expect(publicShift).not.toContain('pat@example.invalid');
|
||||
expect(publicShift).not.toContain('Sam Example');
|
||||
expect(await (await app.request('/')).text()).not.toContain('pat@example.invalid');
|
||||
|
||||
const tooSmall = await postForm(app, `/admin/shifts/${shiftId}`, cookie, {
|
||||
role: 'Ladle',
|
||||
date: '2026-10-15',
|
||||
start: '09:00',
|
||||
end: '12:00',
|
||||
capacity: '1',
|
||||
});
|
||||
expect(tooSmall.status).toBe(400);
|
||||
expect(await tooSmall.text()).toContain('cannot be lower');
|
||||
expect(db.prepare('SELECT capacity AS capacity FROM shifts WHERE id = ?').get(shiftId)).toEqual({ capacity: 2 });
|
||||
|
||||
const moved = await postForm(app, `/admin/shifts/${shiftId}`, cookie, {
|
||||
role: 'Ladle',
|
||||
date: '2026-10-15',
|
||||
start: '10:00',
|
||||
end: '12:00',
|
||||
capacity: '2',
|
||||
});
|
||||
expect(moved.status).toBe(303);
|
||||
expect(readManageSignup(db, pat.manageToken ?? '', NOW)).toBeNull();
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(2);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(0);
|
||||
const changed = db.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'changed' AND to_email = 'pat@example.invalid'").get() as { body_text: string };
|
||||
const nextToken = /\/m\/([A-Za-z0-9_-]+)/.exec(changed.body_text)?.[1] ?? '';
|
||||
expect(readManageSignup(db, nextToken, NOW)?.status).toBe('confirmed');
|
||||
expect(await (await app.request(`/s/${shiftId}`)).text()).toContain('10:00 AM');
|
||||
|
||||
const patId = db.prepare("SELECT id AS id FROM signups WHERE email_norm = 'pat@example.invalid'").get() as { id: number };
|
||||
const cancelled = await postForm(app, `/admin/signups/${patId.id}/cancel`, cookie, {});
|
||||
expect(cancelled.status).toBe(303);
|
||||
expect(cancelled.headers.get('location')).toContain('signup-cancelled');
|
||||
expect(db.prepare("SELECT status AS status FROM signups WHERE id = ?").get(patId.id)).toEqual({ status: 'cancelled' });
|
||||
expect(await (await app.request(`/s/${shiftId}`)).text()).not.toContain('pat@example.invalid');
|
||||
expect(await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text()).toContain('Pat Example');
|
||||
|
||||
const closed = await postForm(app, `/admin/shifts/${shiftId}/cancel`, cookie, {});
|
||||
expect(closed.status).toBe(303);
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(shiftId)).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare("SELECT status AS status FROM signups WHERE email_norm = 'sam@example.invalid'").get()).toEqual({ status: 'cancelled' });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(2);
|
||||
expect(await (await app.request('/')).text()).not.toContain('Ladle');
|
||||
const closedPage = await (await app.request(`/s/${shiftId}`)).text();
|
||||
expect(closedPage).toContain('This shift is closed');
|
||||
expect(closedPage).not.toContain('<form');
|
||||
expect(closedPage).not.toContain('sam@example.invalid');
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
expect(sam.manageToken).not.toBe(nextToken);
|
||||
});
|
||||
|
||||
it('adds a walk-in without putting their name on the public list', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const shiftId = await openShift(app, cookie, { published: false, capacity: '2', role: 'Bagging', date: '2026-10-21' });
|
||||
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('Add a walk-in');
|
||||
expect(html).toContain('src="/js/enhance.js"');
|
||||
expect(html).toContain('data-under-18');
|
||||
expect(html).toContain('data-guardian');
|
||||
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
||||
expect(html).not.toContain('cf-turnstile');
|
||||
const body = walkInBody(html, {
|
||||
name: 'Dee Example',
|
||||
email: 'Dee@Example.invalid',
|
||||
phone: '712-555-0199',
|
||||
notes: 'Arrived at the door',
|
||||
});
|
||||
const added = await postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, body);
|
||||
const replay = await postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, body);
|
||||
expect(added.status).toBe(303);
|
||||
expect(added.headers.get('location')).toContain('notice=walk-in');
|
||||
expect(replay.status).toBe(303);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed' AND group_size = 1")).toBe(1);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending' AND to_email = 'dee@example.invalid'")).toBe(1);
|
||||
expect(db.prepare("SELECT action AS action FROM audit WHERE action = 'signup.walkin'").get()).toEqual({ action: 'signup.walkin' });
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
const roster = await (await app.request(added.headers.get('location') ?? '', { headers: { cookie } })).text();
|
||||
expect(roster).toContain('They are on this shift');
|
||||
expect(roster).toContain('Dee Example');
|
||||
expect(await (await app.request('/')).text()).not.toContain('Dee Example');
|
||||
expect(await (await app.request('/')).text()).not.toContain('dee@example.invalid');
|
||||
expect((await app.request(`/s/${shiftId}`)).status).toBe(404);
|
||||
|
||||
const again = await postWalkIn(app, cookie, shiftId, { name: 'Dee Example', email: 'dee@example.invalid' });
|
||||
expect(again.status).toBe(400);
|
||||
expect(await again.text()).toContain('already signed up');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
|
||||
|
||||
const other = await postWalkIn(app, cookie, shiftId, { name: 'Sam Example', email: 'dee@example.invalid' });
|
||||
expect(other.status).toBe(303);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed'")).toBe(2);
|
||||
});
|
||||
|
||||
it('keeps a walk-in off a full, closed, or ended shift and asks for a guardian', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const shiftId = await openShift(app, cookie, { published: true, capacity: '1', role: 'Sorting', date: '2026-10-21' });
|
||||
const minor = await postWalkIn(app, cookie, shiftId, { name: 'Kim Example', email: 'kim@example.invalid', under18: 'yes' });
|
||||
expect(minor.status).toBe(400);
|
||||
const minorHtml = await minor.text();
|
||||
expect(minorHtml).toContain('Enter the guardian name.');
|
||||
expect(minorHtml).toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
|
||||
|
||||
const added = await postWalkIn(app, cookie, shiftId, {
|
||||
name: 'Kim Example',
|
||||
email: 'kim@example.invalid',
|
||||
under18: 'yes',
|
||||
guardianName: 'Pat Example',
|
||||
guardianEmail: 'pat@example.invalid',
|
||||
});
|
||||
expect(added.status).toBe(303);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(2);
|
||||
const full = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
||||
expect(full).toContain('This shift is full.');
|
||||
expect(full).not.toContain('Add a walk-in');
|
||||
expect(await (await app.request(`/s/${shiftId}`)).text()).not.toContain('kim@example.invalid');
|
||||
const overflow = await postWalkIn(app, cookie, shiftId, { name: 'More Example', email: 'more@example.invalid' });
|
||||
expect(overflow.status).toBe(400);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
|
||||
|
||||
const endedId = await openShift(app, cookie, { published: true, capacity: '2', role: 'Morning', date: '2026-10-14', start: '09:00', end: '12:00' });
|
||||
const ended = await (await app.request(`/admin/shifts/${endedId}`, { headers: { cookie } })).text();
|
||||
expect(ended).toContain('This shift has ended.');
|
||||
expect(ended).not.toContain('Add a walk-in');
|
||||
|
||||
await postForm(app, `/admin/shifts/${shiftId}/cancel`, cookie, {});
|
||||
const closed = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
||||
expect(closed).not.toContain('Add a walk-in');
|
||||
const rejected = await app.request(`/admin/shifts/${shiftId}/walk-in`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ name: 'Late Example', email: 'late@example.invalid' }),
|
||||
});
|
||||
expect(rejected.status).toBe(403);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'late@example.invalid'")).toBe(0);
|
||||
});
|
||||
|
||||
it('marks attendance without emailing or showing it publicly', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const shiftId = await openShift(app, cookie, { published: true, capacity: '2', role: 'Greeting', date: '2026-10-22' });
|
||||
const added = await postWalkIn(app, cookie, shiftId, { name: 'Ria Example', email: 'ria.fake@example.invalid' });
|
||||
expect(added.status).toBe(303);
|
||||
const signupId = (db.prepare("SELECT id AS id FROM signups WHERE email_norm = 'ria.fake@example.invalid'").get() as { id: number }).id;
|
||||
const mailBefore = count(db, 'SELECT COUNT(*) AS n FROM outbox');
|
||||
const attended = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
|
||||
expect(attended.status).toBe(303);
|
||||
expect(attended.headers.get('location')).toContain('notice=attended');
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 1 });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(mailBefore);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend'")).toBe(1);
|
||||
const repeat = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
|
||||
expect(repeat.status).toBe(303);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend'")).toBe(1);
|
||||
const roster = await (await app.request(attended.headers.get('location') ?? '', { headers: { cookie } })).text();
|
||||
expect(roster).toContain('Marked attended.');
|
||||
expect(roster).toContain('Attended.');
|
||||
expect(roster).toContain('aria-pressed="true"');
|
||||
|
||||
const missed = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'no-show' });
|
||||
expect(missed.status).toBe(303);
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
|
||||
const missedPage = await (await app.request(missed.headers.get('location') ?? '', { headers: { cookie } })).text();
|
||||
expect(missedPage).toContain('No-show.');
|
||||
const cleared = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'clear' });
|
||||
expect(cleared.status).toBe(303);
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: null });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend.clear'")).toBe(1);
|
||||
|
||||
const marked = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
|
||||
expect(marked.status).toBe(303);
|
||||
const publicShift = await (await app.request(`/s/${shiftId}`)).text();
|
||||
expect(publicShift).not.toContain('ria.fake@example.invalid');
|
||||
expect(publicShift).not.toContain('No-show');
|
||||
expect(publicShift).not.toContain('Attended.');
|
||||
expect(await (await app.request('/')).text()).not.toContain('ria.fake@example.invalid');
|
||||
|
||||
db.prepare("UPDATE shifts SET starts_at_utc = '2026-10-14T14:00:00.000Z', ends_at_utc = '2026-10-14T17:00:00.000Z' WHERE id = ?").run(shiftId);
|
||||
const afterEnd = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'no-show' });
|
||||
expect(afterEnd.status).toBe(303);
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
|
||||
|
||||
await postForm(app, `/admin/signups/${signupId}/cancel`, cookie, {});
|
||||
const blocked = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
|
||||
expect(blocked.status).toBe(400);
|
||||
expect(await blocked.text()).toContain('That signup is cancelled.');
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
|
||||
const closedRoster = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
||||
expect(closedRoster).not.toContain(`/admin/signups/${signupId}/attendance`);
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
|
||||
const bare = await app.request(`/admin/signups/${signupId}/attendance`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ mark: 'attended' }),
|
||||
});
|
||||
expect(bare.status).toBe(403);
|
||||
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
|
||||
});
|
||||
|
||||
it('rejects a coordinator form without its matching token', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const rejected = await app.request('/admin/events', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ title: 'Nope', slug: 'nope', tz: 'America/Chicago' }),
|
||||
});
|
||||
expect(rejected.status).toBe(403);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM events')).toBe(0);
|
||||
const home = await app.request('/admin', { headers: { cookie } });
|
||||
const logout = await app.request('/logout', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf: field(await home.text(), 'csrf') }),
|
||||
});
|
||||
expect(logout.status).toBe(303);
|
||||
expect(logout.headers.get('set-cookie')).toContain('Max-Age=0');
|
||||
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
|
||||
});
|
||||
|
||||
it('moves a confirmed signup onto another shift in the same event', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
|
||||
const destinationId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-23', capacity: '2' });
|
||||
const added = await postWalkIn(app, cookie, sourceId, {
|
||||
name: 'Kim Example',
|
||||
email: 'kim@example.invalid',
|
||||
under18: 'yes',
|
||||
guardianName: 'Pat Example',
|
||||
guardianEmail: 'pat@example.invalid',
|
||||
});
|
||||
expect(added.status).toBe(303);
|
||||
const signupId = signupIdFor(db, 'kim@example.invalid');
|
||||
db.prepare('UPDATE signups SET phone = ?, notes = ?, reminders_off = 1, attended = 1 WHERE id = ?').run('712-555-0199', 'Blue shirt', signupId);
|
||||
const oldToken = manageToken(db, signupId, 'confirmation');
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at
|
||||
) VALUES (?, ?, ?, 'reminder', ?, 'Reminder', 'Soon', '<p>Soon</p>', '{}', ?, 0, 'pending', ?)`,
|
||||
).run(`reminder:${signupId}`, signupId, sourceId, 'kim@example.invalid', NOW, NOW);
|
||||
const versions = shiftVersions(db);
|
||||
const page = await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(optionValues(html, 'destination')).toEqual([String(destinationId)]);
|
||||
const moved = await postMove(app, cookie, signupId, html, String(destinationId));
|
||||
expect(moved.status).toBe(303);
|
||||
expect(moved.headers.get('location')).toBe(`/admin/shifts/${destinationId}?notice=moved`);
|
||||
|
||||
const source = db.prepare('SELECT status, attended, shift_id FROM signups WHERE id = ?').get(signupId) as {
|
||||
status: string;
|
||||
attended: number;
|
||||
shift_id: number;
|
||||
};
|
||||
expect(source).toEqual({ status: 'cancelled', attended: 1, shift_id: sourceId });
|
||||
expect(readManageSignup(db, oldToken, NOW)).toBeNull();
|
||||
const created = db.prepare(
|
||||
`SELECT id, status, attended, phone, notes, reminders_off, is_minor, guardian_name, guardian_email, shift_id
|
||||
FROM signups WHERE shift_id = ? AND status = 'confirmed'`,
|
||||
).get(destinationId) as {
|
||||
id: number;
|
||||
status: string;
|
||||
attended: number | null;
|
||||
phone: string;
|
||||
notes: string;
|
||||
reminders_off: number;
|
||||
is_minor: number;
|
||||
guardian_name: string;
|
||||
guardian_email: string;
|
||||
shift_id: number;
|
||||
};
|
||||
expect(created).toMatchObject({
|
||||
status: 'confirmed',
|
||||
attended: null,
|
||||
phone: '712-555-0199',
|
||||
notes: 'Blue shirt',
|
||||
reminders_off: 1,
|
||||
is_minor: 1,
|
||||
guardian_name: 'Pat Example',
|
||||
guardian_email: 'pat@example.invalid',
|
||||
shift_id: destinationId,
|
||||
});
|
||||
expect(shiftVersions(db)).toEqual(versions);
|
||||
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(2);
|
||||
expect(db.prepare("SELECT status AS status FROM outbox WHERE kind = 'reminder'").get()).toEqual({ status: 'cancelled' });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(2);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'")).toBe(0);
|
||||
const letter = db.prepare("SELECT subject, body_text FROM outbox WHERE kind = 'changed' AND to_email = 'kim@example.invalid'").get() as {
|
||||
subject: string;
|
||||
body_text: string;
|
||||
};
|
||||
expect(letter.subject).toBe('Your signup was moved to Distribution');
|
||||
expect(letter.body_text).toContain('A coordinator moved your signup to a different shift.');
|
||||
expect(letter.body_text).not.toContain(oldToken);
|
||||
const nextToken = manageToken(db, created.id, 'changed');
|
||||
expect(readManageSignup(db, nextToken, NOW)?.role).toBe('Distribution');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(1);
|
||||
|
||||
const again = await postMove(app, cookie, signupId, html, String(destinationId));
|
||||
expect(again.status).toBe(303);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'")).toBe(1);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(1);
|
||||
const roster = await (await app.request(moved.headers.get('location') ?? '', { headers: { cookie } })).text();
|
||||
expect(roster).toContain('They are on this shift. A change email is queued.');
|
||||
expect(roster).toContain('Kim Example');
|
||||
expect(roster).toContain('Attendance is not marked.');
|
||||
const sourceRoster = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
|
||||
expect(sourceRoster).not.toContain(`/admin/signups/${signupId}/move`);
|
||||
expect(sourceRoster).toContain('0/2 spots filled');
|
||||
expect(sourceRoster).toContain('event-pill is-open');
|
||||
const home = await (await app.request('/')).text();
|
||||
const shiftPage = await (await app.request(`/s/${destinationId}`)).text();
|
||||
expect(home).not.toContain('kim@example.invalid');
|
||||
expect(home).not.toContain('Kim Example');
|
||||
expect(shiftPage).not.toContain('kim@example.invalid');
|
||||
expect(shiftPage).not.toContain('Attended.');
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
});
|
||||
|
||||
it('keeps the original signup when the move cannot be saved', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
|
||||
const fullId = await addShift(app, cookie, eventId, { role: 'Full shift', date: '2026-10-23', capacity: '1' });
|
||||
const openId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-24', capacity: '2' });
|
||||
const endedId = await addShift(app, cookie, eventId, { role: 'Morning', date: '2026-10-14', capacity: '2', start: '09:00', end: '12:00' });
|
||||
const otherEvent = await createEvent(app, cookie, 'Other', true);
|
||||
const otherShift = await addShift(app, cookie, otherEvent, { role: 'Elsewhere', date: '2026-10-25', capacity: '2' });
|
||||
await postWalkIn(app, cookie, sourceId, { name: 'Ria Example', email: 'ria@example.invalid' });
|
||||
await postWalkIn(app, cookie, fullId, { name: 'Dee Example', email: 'dee@example.invalid' });
|
||||
const signupId = signupIdFor(db, 'ria@example.invalid');
|
||||
const page = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
|
||||
expect(optionValues(page, 'destination')).toEqual([String(openId)]);
|
||||
expect(page).not.toContain('Full shift,');
|
||||
expect(page).not.toContain('Morning,');
|
||||
const mailBefore = count(db, 'SELECT COUNT(*) AS n FROM outbox');
|
||||
|
||||
const full = await postMove(app, cookie, signupId, page, String(fullId));
|
||||
expect(full.status).toBe(400);
|
||||
expect(await full.text()).toContain('That shift is full.');
|
||||
const ended = await postMove(app, cookie, signupId, page, String(endedId));
|
||||
expect(ended.status).toBe(400);
|
||||
expect(await ended.text()).toContain('That shift is closed.');
|
||||
const elsewhere = await postMove(app, cookie, signupId, page, String(otherShift));
|
||||
expect(elsewhere.status).toBe(400);
|
||||
expect(await elsewhere.text()).toContain('Choose a shift in this event.');
|
||||
await postWalkIn(app, cookie, openId, { name: 'Ria Example', email: 'ria@example.invalid' });
|
||||
const duplicate = await postMove(app, cookie, signupId, page, String(openId));
|
||||
expect(duplicate.status).toBe(400);
|
||||
expect(await duplicate.text()).toContain('That person is already signed up for this shift.');
|
||||
expect(db.prepare('SELECT status, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'confirmed', shift_id: sourceId });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(0);
|
||||
expect(counted(db, signupId, 'confirmation', 'pending')).toBe(1);
|
||||
|
||||
const bare = await app.request(`/admin/signups/${signupId}/move`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ destination: String(openId) }),
|
||||
});
|
||||
expect(bare.status).toBe(403);
|
||||
expect(db.prepare('SELECT status FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'confirmed' });
|
||||
|
||||
const stale = await postMove(app, cookie, signupId, page.replace(/name="move_token" value="[^"]*"/, 'name="move_token" value="nope"'), String(openId));
|
||||
expect(stale.status).toBe(400);
|
||||
expect(await stale.text()).toContain('This form is out of date');
|
||||
await postForm(app, `/admin/signups/${signupId}/cancel`, cookie, {});
|
||||
const cancelled = await postMove(app, cookie, signupId, page, String(openId));
|
||||
expect(cancelled.status).toBe(400);
|
||||
expect(await cancelled.text()).toContain('That signup is cancelled.');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ria@example.invalid' AND status = 'confirmed'")).toBe(1);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBeGreaterThan(mailBefore);
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
});
|
||||
|
||||
it('moves someone onto a shift that already has their email for a different person', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
|
||||
const openId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-24', capacity: '2' });
|
||||
await postWalkIn(app, cookie, sourceId, { name: 'Ria Example', email: 'ria@example.invalid' });
|
||||
await postWalkIn(app, cookie, openId, { name: 'Sam Example', email: 'ria@example.invalid' });
|
||||
const signupId = signupIdFor(db, 'ria@example.invalid');
|
||||
const page = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
|
||||
const moved = await postMove(app, cookie, signupId, page, String(openId));
|
||||
expect(moved.status).toBe(303);
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ria@example.invalid' AND shift_id = ${openId} AND status = 'confirmed'`)).toBe(2);
|
||||
expect(db.prepare('SELECT status, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'cancelled', shift_id: sourceId });
|
||||
});
|
||||
|
||||
it('keeps the next two weeks of shifts in view and tucks later ones under see more', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
await addShift(app, cookie, eventId, { role: 'Morning', date: '2026-10-13', capacity: '2' });
|
||||
await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-15', capacity: '2' });
|
||||
await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-28', capacity: '2' });
|
||||
await addShift(app, cookie, eventId, { role: 'Intake', date: '2026-11-04', capacity: '2' });
|
||||
await addShift(app, cookie, eventId, { role: 'Packing', date: '2026-11-11', capacity: '2' });
|
||||
const eveningId = await addShift(app, cookie, eventId, { role: 'Evening', date: '2026-11-18', capacity: '2' });
|
||||
expect((await postForm(app, `/admin/shifts/${eveningId}/cancel`, cookie, {})).status).toBe(303);
|
||||
|
||||
const html = await (await app.request(`/admin/events/${eventId}`, { headers: { cookie } })).text();
|
||||
const moreAt = html.indexOf('See 2 more shifts');
|
||||
expect(moreAt).toBeGreaterThan(0);
|
||||
const before = html.slice(0, moreAt);
|
||||
const after = html.slice(moreAt);
|
||||
expect(before).toContain('Morning');
|
||||
expect(before).toContain('Sorting');
|
||||
expect(before).toContain('Distribution');
|
||||
expect(before).not.toContain('Intake');
|
||||
expect(before).not.toContain('Packing');
|
||||
expect(before).not.toContain('Evening');
|
||||
expect(after.indexOf('Intake')).toBeGreaterThan(-1);
|
||||
expect(after.indexOf('Packing')).toBeGreaterThan(after.indexOf('Intake'));
|
||||
expect(after.indexOf('Evening')).toBeGreaterThan(after.indexOf('Packing'));
|
||||
expect(after).toContain('Show fewer');
|
||||
expect(html).not.toContain('<details class="shift-more" open');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(6);
|
||||
|
||||
const soon = await createEvent(app, cookie, 'Soup', true);
|
||||
await addShift(app, cookie, soon, { role: 'Ladle', date: '2026-10-16', capacity: '2' });
|
||||
const short = await (await app.request(`/admin/events/${soon}`, { headers: { cookie } })).text();
|
||||
expect(short).toContain('Ladle');
|
||||
expect(short).not.toContain('See 1 more shift');
|
||||
expect(short).not.toContain('shift-more');
|
||||
|
||||
const distant = await createEvent(app, cookie, 'Holiday', true);
|
||||
await addShift(app, cookie, distant, { role: 'Early', date: '2026-11-04', capacity: '2' });
|
||||
await addShift(app, cookie, distant, { role: 'Later', date: '2026-11-18', capacity: '2' });
|
||||
const far = await (await app.request(`/admin/events/${distant}`, { headers: { cookie } })).text();
|
||||
const farMore = far.indexOf('See 1 more shift');
|
||||
expect(farMore).toBeGreaterThan(0);
|
||||
expect(far.slice(0, farMore)).toContain('Early');
|
||||
expect(far.slice(farMore)).toContain('Later');
|
||||
});
|
||||
|
||||
it('treats an expired session as signed out', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
db.prepare('UPDATE sessions SET expires_at = ?').run(NOW);
|
||||
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
|
||||
});
|
||||
});
|
||||
|
||||
const LINK_GONE = 'This sign-in link is not available.';
|
||||
|
||||
async function buildApp() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'hope-admin-'));
|
||||
dirs.push(root);
|
||||
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
|
||||
const db = await openAppDatabase(config);
|
||||
databases.push(db);
|
||||
const created = bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
|
||||
const app = createApp(config, db, {
|
||||
now: NOW,
|
||||
clientIp: () => '203.0.113.10',
|
||||
verifyTurnstile: async () => ({ ok: true }),
|
||||
});
|
||||
return { app, db, config, created };
|
||||
}
|
||||
|
||||
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof buildApp>>['db']) {
|
||||
await postLogin(app, 'coordinator@example.invalid');
|
||||
const token = magicToken(db);
|
||||
const page = await app.request(`/login/link/${token}`);
|
||||
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
|
||||
return cookieHeader(signedIn);
|
||||
}
|
||||
|
||||
function postLogin(app: Awaited<ReturnType<typeof buildApp>>['app'], email: string) {
|
||||
return app.request('/login', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ email, company_website: '', 'cf-turnstile-response': 'token' }),
|
||||
});
|
||||
}
|
||||
|
||||
function postLink(app: Awaited<ReturnType<typeof buildApp>>['app'], token: string, proof: string) {
|
||||
return app.request(`/login/link/${token}`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ proof }),
|
||||
});
|
||||
}
|
||||
|
||||
async function postForm(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
pathname: string,
|
||||
cookie: string,
|
||||
fields: Record<string, string>,
|
||||
extraHeaders: Record<string, string> = {},
|
||||
) {
|
||||
const current = await app.request('/admin', { headers: { cookie } });
|
||||
const csrf = field(await current.text(), 'csrf');
|
||||
return app.request(pathname, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: extraHeaders.origin ?? ORIGIN,
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
cookie,
|
||||
...extraHeaders,
|
||||
},
|
||||
body: new URLSearchParams({ csrf, ...fields }),
|
||||
});
|
||||
}
|
||||
|
||||
function reserve(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: number, name: string, email: string, operationId: string) {
|
||||
const result = reserveSignup(db, {
|
||||
shiftId,
|
||||
name,
|
||||
email,
|
||||
phone: '712-555-0100',
|
||||
notes: 'Bring gloves',
|
||||
isMinor: false,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
operationId,
|
||||
now: NOW,
|
||||
mail: MAIL,
|
||||
});
|
||||
if (!result.ok || !result.manageToken) throw new Error('Reservation did not save.');
|
||||
return result;
|
||||
}
|
||||
|
||||
function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
|
||||
const row = db
|
||||
.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link' AND status = 'pending' ORDER BY id DESC LIMIT 1")
|
||||
.get() as { body_text: string } | undefined;
|
||||
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(row?.body_text ?? '')?.[1];
|
||||
if (!token) throw new Error('The sign-in link was not queued.');
|
||||
return token;
|
||||
}
|
||||
|
||||
function usedAt(db: Awaited<ReturnType<typeof buildApp>>['db'], token: string): string | null {
|
||||
const row = db.prepare('SELECT used_at AS used_at FROM login_tokens WHERE token_hash = ?').get(sha256(token)) as { used_at: string | null };
|
||||
return row.used_at;
|
||||
}
|
||||
|
||||
function cookieHeader(response: Response): string {
|
||||
const match = /hope_session=([^;]+)/.exec(response.headers.get('set-cookie') ?? '');
|
||||
if (!match?.[1]) throw new Error('The session cookie was not set.');
|
||||
return `hope_session=${match[1]}`;
|
||||
}
|
||||
|
||||
async function createEvent(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
title: string,
|
||||
published: boolean,
|
||||
) {
|
||||
const created = await postForm(app, '/admin/events', cookie, {
|
||||
title,
|
||||
slug: '',
|
||||
description: '',
|
||||
location: 'Sioux Center, Iowa',
|
||||
tz: 'America/Chicago',
|
||||
...(published ? { published: 'yes' } : {}),
|
||||
});
|
||||
return Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
|
||||
}
|
||||
|
||||
async function addShift(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
eventId: number,
|
||||
input: { role: string; date: string; capacity: string; start?: string; end?: string },
|
||||
) {
|
||||
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
|
||||
role: input.role,
|
||||
date: input.date,
|
||||
start: input.start ?? '09:00',
|
||||
end: input.end ?? '12:00',
|
||||
capacity: input.capacity,
|
||||
});
|
||||
return Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
|
||||
}
|
||||
|
||||
function postMove(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
signupId: number,
|
||||
html: string,
|
||||
destination: string,
|
||||
) {
|
||||
return postBody(
|
||||
app,
|
||||
`/admin/signups/${signupId}/move`,
|
||||
cookie,
|
||||
new URLSearchParams({
|
||||
csrf: field(html, 'csrf'),
|
||||
move_token: field(html, 'move_token'),
|
||||
destination,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function optionValues(html: string, name: string): string[] {
|
||||
const select = new RegExp(`<select\\b[^>]*\\bname="${name}"[^>]*>([\\s\\S]*?)</select>`).exec(html)?.[1] ?? '';
|
||||
return [...select.matchAll(/value="(\d+)"/g)].map((match) => match[1] ?? '');
|
||||
}
|
||||
|
||||
function signupIdFor(db: Awaited<ReturnType<typeof buildApp>>['db'], email: string): number {
|
||||
return Number((db.prepare('SELECT id AS id FROM signups WHERE email_norm = ? ORDER BY id LIMIT 1').get(email) as { id: number }).id);
|
||||
}
|
||||
|
||||
function manageToken(db: Awaited<ReturnType<typeof buildApp>>['db'], signupId: number, kind: string): string {
|
||||
const row = db.prepare('SELECT body_text AS body_text FROM outbox WHERE signup_id = ? AND kind = ? LIMIT 1').get(signupId, kind) as {
|
||||
body_text: string;
|
||||
};
|
||||
const token = /\/m\/([A-Za-z0-9_-]+)/.exec(row.body_text)?.[1];
|
||||
if (!token) throw new Error('The manage link was not queued.');
|
||||
return token;
|
||||
}
|
||||
|
||||
function shiftVersions(db: Awaited<ReturnType<typeof buildApp>>['db']): Array<{ id: number; version: number }> {
|
||||
return db.prepare('SELECT id AS id, version AS version FROM shifts ORDER BY id').all() as Array<{ id: number; version: number }>;
|
||||
}
|
||||
|
||||
function counted(db: Awaited<ReturnType<typeof buildApp>>['db'], signupId: number, kind: string, status: string): number {
|
||||
return Number(
|
||||
(db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE signup_id = ? AND kind = ? AND status = ?').get(signupId, kind, status) as { n: number }).n,
|
||||
);
|
||||
}
|
||||
|
||||
async function openShift(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
input: { published: boolean; capacity: string; role: string; date: string; start?: string; end?: string },
|
||||
) {
|
||||
const created = await postForm(app, '/admin/events', cookie, {
|
||||
title: input.role,
|
||||
slug: '',
|
||||
description: '',
|
||||
location: 'Sioux Center, Iowa',
|
||||
tz: 'America/Chicago',
|
||||
...(input.published ? { published: 'yes' } : {}),
|
||||
});
|
||||
const eventId = Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
|
||||
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
|
||||
role: input.role,
|
||||
date: input.date,
|
||||
start: input.start ?? '09:00',
|
||||
end: input.end ?? '12:00',
|
||||
capacity: input.capacity,
|
||||
});
|
||||
return Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
|
||||
}
|
||||
|
||||
async function postWalkIn(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
shiftId: number,
|
||||
fields: Record<string, string>,
|
||||
) {
|
||||
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||
return postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, walkInBody(await page.text(), fields));
|
||||
}
|
||||
|
||||
function walkInBody(html: string, fields: Record<string, string>) {
|
||||
return new URLSearchParams({
|
||||
csrf: field(html, 'csrf'),
|
||||
form_token: field(html, 'form_token'),
|
||||
name: fields.name ?? '',
|
||||
email: fields.email ?? '',
|
||||
phone: fields.phone ?? '',
|
||||
notes: fields.notes ?? '',
|
||||
guardianName: fields.guardianName ?? '',
|
||||
guardianEmail: fields.guardianEmail ?? '',
|
||||
...(fields.under18 ? { under18: fields.under18 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function postBody(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
pathname: string,
|
||||
cookie: string,
|
||||
body: URLSearchParams,
|
||||
) {
|
||||
return app.request(pathname, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
function field(html: string, name: string): string {
|
||||
const tag = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
|
||||
return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
|
||||
}
|
||||
|
||||
function count(db: Awaited<ReturnType<typeof buildApp>>['db'], sql: string): number {
|
||||
return Number((db.prepare(sql).get() as { n: number }).n);
|
||||
}
|
||||
|
||||
function auditJson(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
|
||||
return (db.prepare('SELECT detail_json AS detail_json FROM audit').all() as Array<{ detail_json: string }>)
|
||||
.map((row) => row.detail_json)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import Database from 'better-sqlite3';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { openAppDatabase } from '../src/db.js';
|
||||
import { describeBackup, runDueBackup, startBackupRunner } from '../src/jobs/backup.js';
|
||||
import { formatUtc } from '../src/time.js';
|
||||
import { devEnv } from './env.js';
|
||||
|
||||
const dirs: string[] = [];
|
||||
const databases: { close: () => void }[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of databases.splice(0)) database.close();
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('daily database backup', () => {
|
||||
it('saves one consistent copy after 2:30 and does not rewrite it later the same day', async () => {
|
||||
const { db, backups } = await openDb();
|
||||
const at = localUtc('2026-06-15', 2, 30);
|
||||
const before = localUtc('2026-06-15', 2, 0);
|
||||
db.prepare(`INSERT INTO settings (key, value_json, updated_at) VALUES ('probe', '"first"', ?)`).run(at);
|
||||
|
||||
expect((await runDueBackup(db, backups, before)).ran).toBe(false);
|
||||
expect(existsSync(path.join(backups, 'daily-2026-06-15.db'))).toBe(false);
|
||||
|
||||
const saved = await runDueBackup(db, backups, at);
|
||||
expect(saved).toMatchObject({ ran: true, date: '2026-06-15', weekly: false, prunedDaily: 0, prunedWeekly: 0 });
|
||||
const copy = new Database(path.join(backups, 'daily-2026-06-15.db'), { readonly: true, fileMustExist: true });
|
||||
try {
|
||||
expect(copy.pragma('journal_mode', { simple: true })).toBe('delete');
|
||||
expect(copy.pragma('integrity_check', { simple: true })).toBe('ok');
|
||||
expect(copy.prepare(`SELECT value_json FROM settings WHERE key = 'probe'`).get()).toEqual({ value_json: '"first"' });
|
||||
} finally {
|
||||
copy.close();
|
||||
}
|
||||
expect(readdirSync(backups).filter((name) => name.includes('wal') || name.includes('shm') || name.endsWith('.partial'))).toEqual([]);
|
||||
expect(existsSync(path.join(backups, 'weekly-2026-06-15.db'))).toBe(false);
|
||||
|
||||
db.prepare(`UPDATE settings SET value_json = '"later"' WHERE key = 'probe'`).run();
|
||||
expect((await runDueBackup(db, backups, localUtc('2026-06-15', 3, 0))).ran).toBe(false);
|
||||
const again = new Database(path.join(backups, 'daily-2026-06-15.db'), { readonly: true, fileMustExist: true });
|
||||
try {
|
||||
expect(again.prepare(`SELECT value_json FROM settings WHERE key = 'probe'`).get()).toEqual({ value_json: '"first"' });
|
||||
} finally {
|
||||
again.close();
|
||||
}
|
||||
expect(db.prepare(`SELECT detail_json FROM audit WHERE action = 'backup.save'`).get()).toEqual({
|
||||
detail_json: '{"prunedDaily":0,"prunedWeekly":0}',
|
||||
});
|
||||
expect(JSON.stringify(db.prepare('SELECT detail_json FROM audit').all())).not.toContain('@');
|
||||
});
|
||||
|
||||
it('keeps 14 daily copies, 8 Sunday copies, and files that are not snapshots', async () => {
|
||||
const { db, backups } = await openDb();
|
||||
mkdirSync(backups, { recursive: true });
|
||||
for (let day = 1; day <= 20; day += 1) {
|
||||
writeFileSync(path.join(backups, `daily-2026-05-${String(day).padStart(2, '0')}.db`), '');
|
||||
}
|
||||
for (let day = 1; day <= 10; day += 1) {
|
||||
writeFileSync(path.join(backups, `weekly-2026-01-${String(day).padStart(2, '0')}.db`), '');
|
||||
}
|
||||
writeFileSync(path.join(backups, 'pre-migrate-20260601T000000000Z.db'), 'keep');
|
||||
writeFileSync(path.join(backups, 'notes.txt'), 'keep');
|
||||
|
||||
const sunday = localUtc('2026-06-14', 2, 30);
|
||||
const saved = await runDueBackup(db, backups, sunday);
|
||||
expect(saved).toMatchObject({ ran: true, date: '2026-06-14', weekly: true, prunedDaily: 7, prunedWeekly: 3 });
|
||||
const names = readdirSync(backups).sort();
|
||||
expect(names).toContain('pre-migrate-20260601T000000000Z.db');
|
||||
expect(names).toContain('notes.txt');
|
||||
expect(names).toContain('daily-2026-06-14.db');
|
||||
expect(names).toContain('weekly-2026-06-14.db');
|
||||
expect(names).not.toContain('daily-2026-05-01.db');
|
||||
expect(names).not.toContain('daily-2026-05-07.db');
|
||||
expect(names).toContain('daily-2026-05-08.db');
|
||||
expect(names).not.toContain('weekly-2026-01-01.db');
|
||||
expect(names).toContain('weekly-2026-01-04.db');
|
||||
expect(names.filter((name) => name.includes('wal') || name.includes('shm') || name.endsWith('.partial'))).toEqual([]);
|
||||
const weekly = new Database(path.join(backups, 'weekly-2026-06-14.db'), { readonly: true, fileMustExist: true });
|
||||
try {
|
||||
expect(weekly.pragma('integrity_check', { simple: true })).toBe('ok');
|
||||
} finally {
|
||||
weekly.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves older copies in place when the new backup fails', async () => {
|
||||
const { db, backups } = await openDb();
|
||||
mkdirSync(backups, { recursive: true });
|
||||
writeFileSync(path.join(backups, 'daily-2026-06-01.db'), 'older');
|
||||
writeFileSync(path.join(backups, 'pre-migrate-20260601T000000000Z.db'), 'keep');
|
||||
const errors: string[] = [];
|
||||
const write = console.error;
|
||||
console.error = (message?: unknown) => {
|
||||
errors.push(String(message));
|
||||
};
|
||||
let result: Awaited<ReturnType<typeof runDueBackup>>;
|
||||
try {
|
||||
result = await runDueBackup(db, backups, localUtc('2026-06-15', 2, 30), async () => {
|
||||
throw new Error('disk full');
|
||||
});
|
||||
} finally {
|
||||
console.error = write;
|
||||
}
|
||||
expect(result.ran).toBe(false);
|
||||
expect(readdirSync(backups).sort()).toEqual(['daily-2026-06-01.db', 'pre-migrate-20260601T000000000Z.db']);
|
||||
expect(db.prepare(`SELECT COUNT(*) AS n FROM job_runs WHERE job = 'backup'`).get()).toEqual({ n: 0 });
|
||||
expect(errors.join(' ')).toContain('disk full');
|
||||
expect(errors.join(' ')).not.toContain('@');
|
||||
});
|
||||
|
||||
it('waits through the missing 2:30 and runs once when the hour repeats its earlier neighbor', async () => {
|
||||
const spring = await openDb();
|
||||
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 1, 30, 'reject'))).ran).toBe(false);
|
||||
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 3, 0, 'reject'))).ran).toBe(true);
|
||||
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 3, 30, 'reject'))).ran).toBe(false);
|
||||
|
||||
const fall = await openDb();
|
||||
const duringRepeat = localUtc('2026-11-01', 1, 30, 'later');
|
||||
const atHalf = localUtc('2026-11-01', 2, 30, 'reject');
|
||||
expect((await runDueBackup(fall.db, fall.backups, duringRepeat)).ran).toBe(false);
|
||||
expect((await runDueBackup(fall.db, fall.backups, atHalf)).ran).toBe(true);
|
||||
expect((await runDueBackup(fall.db, fall.backups, localUtc('2026-11-01', 2, 45, 'reject'))).ran).toBe(false);
|
||||
expect(fall.db.prepare(`SELECT COUNT(*) AS n FROM job_runs WHERE job = 'backup'`).get()).toEqual({ n: 1 });
|
||||
});
|
||||
|
||||
it('describes a missing, current, or old backup without naming a file path', () => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'hope-backup-status-'));
|
||||
dirs.push(root);
|
||||
const early = localUtc('2026-06-15', 2, 0);
|
||||
const due = localUtc('2026-06-15', 2, 30);
|
||||
expect(describeBackup(root, early)).toEqual({
|
||||
state: 'waiting',
|
||||
text: 'No database backup has been saved yet.',
|
||||
});
|
||||
expect(describeBackup(root, due)).toEqual({
|
||||
state: 'behind',
|
||||
text: 'No database backup has been saved yet.',
|
||||
});
|
||||
writeFileSync(path.join(root, 'daily-2026-06-14.db'), '');
|
||||
expect(describeBackup(root, early).text).toBe('Database backup saved June 14, 2026.');
|
||||
expect(describeBackup(root, due)).toEqual({
|
||||
state: 'behind',
|
||||
text: 'Database backup is behind. The newest saved copy is June 14, 2026.',
|
||||
});
|
||||
writeFileSync(path.join(root, 'daily-2026-06-15.db'), '');
|
||||
expect(describeBackup(root, due)).toEqual({
|
||||
state: 'saved',
|
||||
text: 'Database backup saved June 15, 2026.',
|
||||
});
|
||||
expect(JSON.stringify(describeBackup(root, due))).not.toContain('/');
|
||||
});
|
||||
|
||||
it('saves the backup on the first check after 2:30', async () => {
|
||||
const { db, backups } = await openDb();
|
||||
const runner = startBackupRunner(db, backups, () => localUtc('2026-06-15', 2, 30));
|
||||
const file = path.join(backups, 'daily-2026-06-15.db');
|
||||
for (let attempt = 0; attempt < 50 && !existsSync(file); attempt += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
runner.stop();
|
||||
expect(existsSync(file)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function localUtc(date: string, hour: number, minute: number, disambiguation: 'earlier' | 'later' | 'reject' = 'reject'): string {
|
||||
const [year, month, day] = date.split('-').map(Number);
|
||||
const zoned = Temporal.ZonedDateTime.from(
|
||||
{ timeZone: 'America/Chicago', year, month, day, hour, minute, second: 0, millisecond: 0 },
|
||||
{ disambiguation },
|
||||
);
|
||||
return formatUtc(zoned.toInstant());
|
||||
}
|
||||
|
||||
async function openDb() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'hope-backup-'));
|
||||
dirs.push(root);
|
||||
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
|
||||
const db = await openAppDatabase(config);
|
||||
databases.push(db);
|
||||
const backups = path.join(root, 'data', 'backups');
|
||||
return { db, backups };
|
||||
}
|
||||