Compare commits

...

2 Commits

Author SHA1 Message Date
219257fef2 switch to more deno functions and do other optimizations 2026-03-30 18:15:27 -06:00
fedb9ca0c5 start with phase 1 2026-03-30 17:50:54 -06:00
18 changed files with 1228 additions and 0 deletions

16
.env.example Normal file
View File

@@ -0,0 +1,16 @@
# Server
PORT=3100
# Twilio
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=+1234567890
# Endorser API (for JWT validation)
ENDORSER_API_URL=http://localhost:3000
# Database
SMS_DB_PATH=./sms-service.sqlite3
# Logging
LOG_LEVEL=info

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
.env
.DS_Store
*.sqlite3
*.sqlite3-shm
*.sqlite3-wal
.idea

View File

@@ -0,0 +1,44 @@
# SMS Notification Service
An SMS notification service for [Time Safari](https://timesafari.app) that handles phone number verification and scheduled SMS notifications (daily reminders, activity digests). It authenticates users by forwarding JWTs to an [endorser-ch](https://github.com/trentlarson/endorser-ch) server, stores verified phone numbers and notification preferences in SQLite, and sends messages via Twilio.
## Prerequisites
- [Deno](https://deno.land/) v2+
- A Twilio account (optional for development — falls back to console logging)
## Setup
```bash
cp .env.example .env
# Edit .env with your configuration
```
## Run
```bash
# Development (auto-reload)
deno task dev
# Production
deno task start
```
## Test
```bash
deno task check # Type-check
deno task test # Run tests
```
## Deploy
The service is a single Deno process with a SQLite database file. To deploy:
1. Copy the project to your server
2. Set environment variables (see `.env.example`)
3. Run `deno task start`
For process management, use systemd, Docker, or [Deno Deploy](https://deno.com/deploy).
The SQLite database is created automatically on first run and migrations are applied on startup.

19
deno.json Normal file
View File

@@ -0,0 +1,19 @@
{
"tasks": {
"start": "deno run -A --env-file src/index.ts",
"dev": "deno run -A --watch --env-file src/index.ts",
"test": "deno test -A test/",
"check": "deno check src/**/*.ts"
},
"imports": {
"hono": "jsr:@hono/hono",
"pino": "npm:pino@9",
"twilio": "npm:twilio@5",
"node-cron": "npm:node-cron@3",
"@db/sqlite": "jsr:@db/sqlite@0.12",
"@std/encoding": "jsr:@std/encoding"
},
"compilerOptions": {
"strict": true
}
}

446
deno.lock generated Normal file
View File

@@ -0,0 +1,446 @@
{
"version": "5",
"specifiers": {
"jsr:@db/sqlite@0.12": "0.12.0",
"jsr:@denosaurs/plug@1": "1.1.0",
"jsr:@hono/hono@*": "4.12.9",
"jsr:@std/assert@0.217": "0.217.0",
"jsr:@std/encoding@*": "1.0.10",
"jsr:@std/encoding@1": "1.0.10",
"jsr:@std/fmt@1": "1.0.9",
"jsr:@std/fs@1": "1.0.20",
"jsr:@std/internal@^1.0.12": "1.0.12",
"jsr:@std/path@0.217": "0.217.0",
"jsr:@std/path@1": "1.1.3",
"jsr:@std/path@^1.1.3": "1.1.3",
"npm:node-cron@3": "3.0.3",
"npm:pino@9": "9.14.0",
"npm:twilio@5": "5.13.1"
},
"jsr": {
"@db/sqlite@0.12.0": {
"integrity": "dd1ef7f621ad50fc1e073a1c3609c4470bd51edc0994139c5bf9851de7a6d85f",
"dependencies": [
"jsr:@denosaurs/plug",
"jsr:@std/path@0.217"
]
},
"@denosaurs/plug@1.1.0": {
"integrity": "eb2f0b7546c7bca2000d8b0282c54d50d91cf6d75cb26a80df25a6de8c4bc044",
"dependencies": [
"jsr:@std/encoding@1",
"jsr:@std/fmt",
"jsr:@std/fs",
"jsr:@std/path@1"
]
},
"@hono/hono@4.12.9": {
"integrity": "53c2b0a721c1d782e6a347ad5bf15a3235ff624b98859c21f779b7ee2f5e040e"
},
"@std/assert@0.217.0": {
"integrity": "c98e279362ca6982d5285c3b89517b757c1e3477ee9f14eb2fdf80a45aaa9642"
},
"@std/encoding@1.0.10": {
"integrity": "8783c6384a2d13abd5e9e87a7ae0520a30e9f56aeeaa3bdf910a3eaaf5c811a1"
},
"@std/fmt@1.0.9": {
"integrity": "2487343e8899fb2be5d0e3d35013e54477ada198854e52dd05ed0422eddcabe0"
},
"@std/fs@1.0.20": {
"integrity": "e953206aae48d46ee65e8783ded459f23bec7dd1f3879512911c35e5484ea187",
"dependencies": [
"jsr:@std/internal",
"jsr:@std/path@^1.1.3"
]
},
"@std/internal@1.0.12": {
"integrity": "972a634fd5bc34b242024402972cd5143eac68d8dffaca5eaa4dba30ce17b027"
},
"@std/path@0.217.0": {
"integrity": "1217cc25534bca9a2f672d7fe7c6f356e4027df400c0e85c0ef3e4343bc67d11",
"dependencies": [
"jsr:@std/assert"
]
},
"@std/path@1.1.3": {
"integrity": "b015962d82a5e6daea980c32b82d2c40142149639968549c649031a230b1afb3",
"dependencies": [
"jsr:@std/internal"
]
}
},
"npm": {
"@pinojs/redact@0.4.0": {
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="
},
"agent-base@6.0.2": {
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"dependencies": [
"debug"
]
},
"asynckit@0.4.0": {
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"atomic-sleep@1.0.0": {
"integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="
},
"axios@1.14.0": {
"integrity": "sha512-3Y8yrqLSwjuzpXuZ0oIYZ/XGgLwUIBU3uLvbcpb0pidD9ctpShJd43KSlEEkVQg6DS0G9NKyzOvBfUtDKEyHvQ==",
"dependencies": [
"follow-redirects",
"form-data",
"proxy-from-env"
]
},
"buffer-equal-constant-time@1.0.1": {
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
},
"call-bind-apply-helpers@1.0.2": {
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dependencies": [
"es-errors",
"function-bind"
]
},
"call-bound@1.0.4": {
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"dependencies": [
"call-bind-apply-helpers",
"get-intrinsic"
]
},
"combined-stream@1.0.8": {
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": [
"delayed-stream"
]
},
"dayjs@1.11.20": {
"integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ=="
},
"debug@4.4.3": {
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dependencies": [
"ms"
]
},
"delayed-stream@1.0.0": {
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="
},
"dunder-proto@1.0.1": {
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dependencies": [
"call-bind-apply-helpers",
"es-errors",
"gopd"
]
},
"ecdsa-sig-formatter@1.0.11": {
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"dependencies": [
"safe-buffer"
]
},
"es-define-property@1.0.1": {
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="
},
"es-errors@1.3.0": {
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="
},
"es-object-atoms@1.1.1": {
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dependencies": [
"es-errors"
]
},
"es-set-tostringtag@2.1.0": {
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dependencies": [
"es-errors",
"get-intrinsic",
"has-tostringtag",
"hasown"
]
},
"follow-redirects@1.15.11": {
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="
},
"form-data@4.0.5": {
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
"dependencies": [
"asynckit",
"combined-stream",
"es-set-tostringtag",
"hasown",
"mime-types"
]
},
"function-bind@1.1.2": {
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="
},
"get-intrinsic@1.3.0": {
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dependencies": [
"call-bind-apply-helpers",
"es-define-property",
"es-errors",
"es-object-atoms",
"function-bind",
"get-proto",
"gopd",
"has-symbols",
"hasown",
"math-intrinsics"
]
},
"get-proto@1.0.1": {
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"dependencies": [
"dunder-proto",
"es-object-atoms"
]
},
"gopd@1.2.0": {
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="
},
"has-symbols@1.1.0": {
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="
},
"has-tostringtag@1.0.2": {
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"dependencies": [
"has-symbols"
]
},
"hasown@2.0.2": {
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dependencies": [
"function-bind"
]
},
"https-proxy-agent@5.0.1": {
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"dependencies": [
"agent-base",
"debug"
]
},
"jsonwebtoken@9.0.3": {
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
"dependencies": [
"jws",
"lodash.includes",
"lodash.isboolean",
"lodash.isinteger",
"lodash.isnumber",
"lodash.isplainobject",
"lodash.isstring",
"lodash.once",
"ms",
"semver"
]
},
"jwa@2.0.1": {
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"dependencies": [
"buffer-equal-constant-time",
"ecdsa-sig-formatter",
"safe-buffer"
]
},
"jws@4.0.1": {
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
"dependencies": [
"jwa",
"safe-buffer"
]
},
"lodash.includes@4.3.0": {
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="
},
"lodash.isboolean@3.0.3": {
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="
},
"lodash.isinteger@4.0.4": {
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="
},
"lodash.isnumber@3.0.3": {
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="
},
"lodash.isplainobject@4.0.6": {
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="
},
"lodash.isstring@4.0.1": {
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="
},
"lodash.once@4.1.1": {
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
},
"math-intrinsics@1.1.0": {
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="
},
"mime-db@1.52.0": {
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="
},
"mime-types@2.1.35": {
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": [
"mime-db"
]
},
"ms@2.1.3": {
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node-cron@3.0.3": {
"integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
"dependencies": [
"uuid"
]
},
"object-inspect@1.13.4": {
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="
},
"on-exit-leak-free@2.1.2": {
"integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="
},
"pino-abstract-transport@2.0.0": {
"integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==",
"dependencies": [
"split2"
]
},
"pino-std-serializers@7.1.0": {
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="
},
"pino@9.14.0": {
"integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==",
"dependencies": [
"@pinojs/redact",
"atomic-sleep",
"on-exit-leak-free",
"pino-abstract-transport",
"pino-std-serializers",
"process-warning",
"quick-format-unescaped",
"real-require",
"safe-stable-stringify",
"sonic-boom",
"thread-stream"
],
"bin": true
},
"process-warning@5.0.0": {
"integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="
},
"proxy-from-env@2.1.0": {
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA=="
},
"qs@6.14.2": {
"integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==",
"dependencies": [
"side-channel"
]
},
"quick-format-unescaped@4.0.4": {
"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="
},
"real-require@0.2.0": {
"integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="
},
"safe-buffer@5.2.1": {
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
},
"safe-stable-stringify@2.5.0": {
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="
},
"scmp@2.1.0": {
"integrity": "sha512-o/mRQGk9Rcer/jEEw/yw4mwo3EU/NvYvp577/Btqrym9Qy5/MdWGBqipbALgd2lrdWTJ5/gqDusxfnQBxOxT2Q==",
"deprecated": true
},
"semver@7.7.4": {
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"bin": true
},
"side-channel-list@1.0.0": {
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"dependencies": [
"es-errors",
"object-inspect"
]
},
"side-channel-map@1.0.1": {
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"dependencies": [
"call-bound",
"es-errors",
"get-intrinsic",
"object-inspect"
]
},
"side-channel-weakmap@1.0.2": {
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"dependencies": [
"call-bound",
"es-errors",
"get-intrinsic",
"object-inspect",
"side-channel-map"
]
},
"side-channel@1.1.0": {
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"dependencies": [
"es-errors",
"object-inspect",
"side-channel-list",
"side-channel-map",
"side-channel-weakmap"
]
},
"sonic-boom@4.2.1": {
"integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",
"dependencies": [
"atomic-sleep"
]
},
"split2@4.2.0": {
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="
},
"thread-stream@3.1.0": {
"integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==",
"dependencies": [
"real-require"
]
},
"twilio@5.13.1": {
"integrity": "sha512-sT+PkhptF4Mf7t8eXFFvPQx4w5VHnBIPXbltGPMFRe+R2GxfRdMuFbuNA/cEm0aQR6LFQOn33+fhClg+TjRVqQ==",
"dependencies": [
"axios",
"dayjs",
"https-proxy-agent",
"jsonwebtoken",
"qs",
"scmp",
"xmlbuilder"
]
},
"uuid@8.3.2": {
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": true
},
"xmlbuilder@13.0.2": {
"integrity": "sha512-Eux0i2QdDYKbdbA6AM6xE4m6ZTZr4G4xF9kahI2ukSEMCzwce2eX9WlTI5J3s+NU7hpasFsr8hWIONae7LluAQ=="
}
},
"workspace": {
"dependencies": [
"jsr:@db/sqlite@0.12",
"jsr:@hono/hono@*",
"jsr:@std/encoding@*",
"npm:node-cron@3",
"npm:pino@9",
"npm:twilio@5"
]
}
}

View File

@@ -0,0 +1,49 @@
-- SMS User table
CREATE TABLE sms_user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
phone_number TEXT NOT NULL UNIQUE,
issuer_did TEXT UNIQUE,
pending_did TEXT,
stored_jwt TEXT,
jwt_expires_at TEXT,
verified INTEGER NOT NULL DEFAULT 0,
verification_code TEXT,
verification_expiry TEXT,
verification_attempts INTEGER NOT NULL DEFAULT 0,
codes_requested_this_hour INTEGER NOT NULL DEFAULT 0,
codes_requested_hour_start TEXT,
cooldown_until TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- Notification preferences table
CREATE TABLE sms_notification_pref (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES sms_user(id) ON DELETE CASCADE,
notification_type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 0,
send_time_utc TEXT,
timezone_offset INTEGER,
reminder_message TEXT,
alert_search_params TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(user_id, notification_type)
);
-- Send log table
CREATE TABLE sms_send_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES sms_user(id) ON DELETE CASCADE,
notification_type TEXT NOT NULL,
sent_at TEXT NOT NULL DEFAULT (datetime('now')),
status TEXT NOT NULL,
provider_message_id TEXT,
error_message TEXT
);
CREATE INDEX idx_sms_user_did ON sms_user(issuer_did);
CREATE INDEX idx_sms_notification_pref_user ON sms_notification_pref(user_id);
CREATE INDEX idx_sms_send_log_user ON sms_send_log(user_id);
CREATE INDEX idx_sms_send_log_sent_at ON sms_send_log(sent_at);

View File

@@ -0,0 +1,63 @@
import { Hono } from "hono";
import type { AppEnv } from "../../common/types.ts";
import { getDb } from "../../db.ts";
import { config } from "../../common/config.ts";
import l from "../../common/logger.ts";
import { authMiddleware } from "../middleware/auth.ts";
import { decodeBase64Url } from "@std/encoding/base64url";
const router = new Hono<AppEnv>();
router.use("*", authMiddleware);
router.put("/jwt", async (c) => {
try {
const { jwt } = await c.req.json();
if (!jwt) {
return c.json({ error: { message: "jwt is required", code: "MISSING_FIELD" } }, 400);
}
const issuerDid = c.get("issuerDid");
const db = getDb();
const user = db.prepare("SELECT * FROM sms_user WHERE issuer_did = ?").get(issuerDid) as Record<string, unknown> | undefined;
if (!user) {
return c.json({ error: { message: "No phone registration found. Register first.", code: "NOT_REGISTERED" } }, 400);
}
if (!user.verified) {
return c.json({ error: { message: "Phone not verified", code: "NOT_VERIFIED" } }, 400);
}
const response = await fetch(`${config.endorserApiUrl}/api/v2/report/rateLimits`, {
headers: { Authorization: `Bearer ${jwt}` },
});
if (!response.ok) {
return c.json({ error: { message: "Provided JWT is not valid", code: "INVALID_JWT" } }, 400);
}
let jwtExpiresAt: string | null = null;
try {
const payloadBytes = decodeBase64Url(jwt.split(".")[1]);
const payload = JSON.parse(new TextDecoder().decode(payloadBytes));
if (payload.exp) {
jwtExpiresAt = new Date(payload.exp * 1000).toISOString();
}
} catch {
// If we can't parse expiry, store without it
}
const now = new Date().toISOString();
db.prepare(
"UPDATE sms_user SET stored_jwt = ?, jwt_expires_at = ?, updated_at = ? WHERE id = ?"
).run(jwt, jwtExpiresAt, now, user.id as number);
return c.json({ success: { message: "JWT stored", jwtExpiresAt } });
} catch (err) {
l.error("storeJwt error: %s", err);
return c.json({ error: { message: "Internal server error" } }, 500);
}
});
export default router;

View File

@@ -0,0 +1,78 @@
import { Hono } from "hono";
import type { AppEnv } from "../../common/types.ts";
import registrationService from "../services/registration.service.ts";
import { sendSms } from "../services/sms-provider.ts";
import { getDb } from "../../db.ts";
import l from "../../common/logger.ts";
import { authMiddleware } from "../middleware/auth.ts";
const router = new Hono<AppEnv>();
router.use("*", authMiddleware);
router.post("/register", async (c) => {
try {
const { phoneNumber } = await c.req.json();
if (!phoneNumber) {
return c.json({ error: { message: "phoneNumber is required", code: "MISSING_FIELD" } }, 400);
}
const issuerDid = c.get("issuerDid");
const { code } = await registrationService.register(phoneNumber, issuerDid);
const db = getDb();
const user = db.prepare("SELECT id FROM sms_user WHERE phone_number = ?").get(phoneNumber) as { id: number } | undefined;
await sendSms(
phoneNumber,
`Your Time Safari verification code is: ${code}. It expires in 15 minutes.`,
user?.id,
"verification"
);
return c.json({ success: { message: "Verification code sent" } });
} catch (err: unknown) {
const e = err as { clientError?: { message: string; code: string } };
if (e.clientError) {
return c.json({ error: e.clientError }, 400);
}
l.error("register error: %s", err);
return c.json({ error: { message: "Internal server error" } }, 500);
}
});
router.post("/verify", async (c) => {
try {
const { phoneNumber, code } = await c.req.json();
if (!phoneNumber || !code) {
return c.json({ error: { message: "phoneNumber and code are required", code: "MISSING_FIELD" } }, 400);
}
const result = await registrationService.verify(phoneNumber, code);
return c.json({ success: result });
} catch (err: unknown) {
const e = err as { clientError?: { message: string; code: string } };
if (e.clientError) {
return c.json({ error: e.clientError }, 400);
}
l.error("verify error: %s", err);
return c.json({ error: { message: "Internal server error" } }, 500);
}
});
router.delete("/register", (c) => {
try {
const issuerDid = c.get("issuerDid");
registrationService.unregister(issuerDid);
return c.json({ success: { message: "Registration removed" } });
} catch (err: unknown) {
const e = err as { clientError?: { message: string; code: string } };
if (e.clientError) {
return c.json({ error: e.clientError }, 400);
}
l.error("unregister error: %s", err);
return c.json({ error: { message: "Internal server error" } }, 500);
}
});
export default router;

View File

@@ -0,0 +1,63 @@
import type { Next } from "hono";
import type { Context } from "hono";
import type { AppEnv } from "../../common/types.ts";
import { config } from "../../common/config.ts";
import l from "../../common/logger.ts";
const BEARER_PREFIX = "Bearer ";
const didCache = new Map<string, { did: string; expiresAt: number }>();
const CACHE_TTL_MS = 60_000;
function simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0;
}
return hash.toString(36);
}
export async function authMiddleware(c: Context<AppEnv>, next: Next): Promise<Response | void> {
const authHeader = c.req.header("Authorization");
if (!authHeader || !authHeader.startsWith(BEARER_PREFIX)) {
return c.json({ error: { message: "Missing or invalid Authorization header" } }, 401);
}
const token = authHeader.substring(BEARER_PREFIX.length);
const tokenHash = simpleHash(token);
const cached = didCache.get(tokenHash);
if (cached && cached.expiresAt > Date.now()) {
c.set("issuerDid", cached.did);
return next();
}
try {
const response = await fetch(`${config.endorserApiUrl}/api/v2/report/rateLimits`, {
headers: { Authorization: authHeader },
});
if (!response.ok) {
l.info(`Auth rejected by endorser-ch: ${response.status}`);
return c.json({ error: { message: "Authentication failed" } }, 401);
}
const data = await response.json() as Record<string, unknown>;
const payload = data.payload as Record<string, unknown> | undefined;
const did = payload?.issuer || data.issuer;
if (!did) {
l.error("No DID found in endorser-ch response");
return c.json({ error: { message: "Could not extract DID from token" } }, 401);
}
didCache.set(tokenHash, { did: did as string, expiresAt: Date.now() + CACHE_TTL_MS });
c.set("issuerDid", did as string);
return next();
} catch (err) {
l.error("Error contacting endorser-ch for auth: %s", err);
return c.json({ error: { message: "Auth service unavailable" } }, 502);
}
}

View File

@@ -0,0 +1,231 @@
import { getDb } from "../../db.ts";
import l from "../../common/logger.ts";
import { encodeBase64 } from "@std/encoding/base64";
const E164_US_REGEX = /^\+1[2-9]\d{9}$/;
const CODE_LENGTH = 6;
const CODE_EXPIRY_MINUTES = 15;
const MAX_CODES_PER_HOUR = 3;
const MAX_VERIFY_ATTEMPTS = 5;
const COOLDOWN_MINUTES = 60;
const PBKDF2_ITERATIONS = 100_000;
const SALT_LENGTH = 16;
interface SmsUser {
id: number;
phone_number: string;
issuer_did: string | null;
pending_did: string | null;
stored_jwt: string | null;
jwt_expires_at: string | null;
verified: number;
verification_code: string | null;
verification_expiry: string | null;
verification_attempts: number;
codes_requested_this_hour: number;
codes_requested_hour_start: string | null;
cooldown_until: string | null;
}
export class RegistrationService {
async register(
phoneNumber: string,
issuerDid: string
): Promise<{ code: string }> {
if (!E164_US_REGEX.test(phoneNumber)) {
throw { clientError: { message: "Invalid phone number. Must be US E.164 format (+1XXXXXXXXXX).", code: "INVALID_PHONE" } };
}
const db = getDb();
const now = new Date().toISOString();
let user = db.prepare("SELECT * FROM sms_user WHERE phone_number = ?").get(phoneNumber) as SmsUser | undefined;
if (user) {
if (user.cooldown_until && new Date(user.cooldown_until) > new Date()) {
const remaining = Math.ceil(
(new Date(user.cooldown_until).getTime() - Date.now()) / 60000
);
throw { clientError: { message: `Rate limited. Try again in ${remaining} minutes.`, code: "RATE_LIMITED" } };
}
const hourStart = user.codes_requested_hour_start
? new Date(user.codes_requested_hour_start)
: null;
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
if (hourStart && hourStart > oneHourAgo) {
if (user.codes_requested_this_hour >= MAX_CODES_PER_HOUR) {
const cooldownUntil = new Date(
Date.now() + COOLDOWN_MINUTES * 60 * 1000
).toISOString();
db.prepare("UPDATE sms_user SET cooldown_until = ?, updated_at = ? WHERE id = ?").run(
cooldownUntil, now, user.id
);
throw { clientError: { message: `Too many codes requested. Try again in ${COOLDOWN_MINUTES} minutes.`, code: "RATE_LIMITED" } };
}
}
if (user.issuer_did && user.issuer_did !== issuerDid && user.verified) {
db.prepare(
"UPDATE sms_user SET pending_did = ?, verified = 0, updated_at = ? WHERE id = ?"
).run(issuerDid, now, user.id);
} else if (!user.issuer_did) {
db.prepare("UPDATE sms_user SET issuer_did = ?, updated_at = ? WHERE id = ?").run(
issuerDid, now, user.id
);
}
} else {
db.prepare(
"INSERT INTO sms_user (phone_number, issuer_did, created_at, updated_at) VALUES (?, ?, ?, ?)"
).run(phoneNumber, issuerDid, now, now);
user = db.prepare("SELECT * FROM sms_user WHERE phone_number = ?").get(phoneNumber) as SmsUser;
}
const code = generateCode();
const hashedCode = await hashCode(code);
const expiry = new Date(
Date.now() + CODE_EXPIRY_MINUTES * 60 * 1000
).toISOString();
const hourStart = user!.codes_requested_hour_start
? new Date(user!.codes_requested_hour_start)
: null;
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
const resetHour = !hourStart || hourStart <= oneHourAgo;
db.prepare(`
UPDATE sms_user SET
verification_code = ?,
verification_expiry = ?,
verification_attempts = 0,
codes_requested_this_hour = ?,
codes_requested_hour_start = ?,
updated_at = ?
WHERE id = ?
`).run(
hashedCode,
expiry,
resetHour ? 1 : user!.codes_requested_this_hour + 1,
resetHour ? now : user!.codes_requested_hour_start,
now,
user!.id
);
l.info(`Verification code generated for phone ${phoneNumber.slice(-4)}`);
return { code };
}
async verify(phoneNumber: string, code: string): Promise<{ success: boolean }> {
const db = getDb();
const now = new Date().toISOString();
const user = db.prepare("SELECT * FROM sms_user WHERE phone_number = ?").get(phoneNumber) as SmsUser | undefined;
if (!user) {
throw { clientError: { message: "Phone number not found", code: "NOT_FOUND" } };
}
if (user.verified && !user.pending_did) {
throw { clientError: { message: "Phone already verified", code: "ALREADY_VERIFIED" } };
}
if (!user.verification_code || !user.verification_expiry) {
throw { clientError: { message: "No verification pending", code: "NO_PENDING" } };
}
if (user.verification_attempts >= MAX_VERIFY_ATTEMPTS) {
throw { clientError: { message: "Too many attempts. Request a new code.", code: "TOO_MANY_ATTEMPTS" } };
}
if (new Date(user.verification_expiry) < new Date()) {
throw { clientError: { message: "Verification code expired", code: "CODE_EXPIRED" } };
}
db.prepare("UPDATE sms_user SET verification_attempts = verification_attempts + 1, updated_at = ? WHERE id = ?").run(now, user.id);
const match = await verifyCode(code, user.verification_code);
if (!match) {
throw { clientError: { message: "Invalid verification code", code: "INVALID_CODE" } };
}
// deno-lint-ignore no-explicit-any
const updateFields: Record<string, any> = {
verified: 1,
verification_code: null,
verification_expiry: null,
verification_attempts: 0,
updated_at: now,
};
if (user.pending_did) {
updateFields.issuer_did = user.pending_did;
updateFields.pending_did = null;
updateFields.stored_jwt = null;
updateFields.jwt_expires_at = null;
}
const setClauses = Object.keys(updateFields).map((k) => `${k} = ?`).join(", ");
db.prepare(`UPDATE sms_user SET ${setClauses} WHERE id = ?`).run(
...Object.values(updateFields),
user.id
);
l.info(`Phone ${phoneNumber.slice(-4)} verified`);
return { success: true };
}
unregister(issuerDid: string): void {
const db = getDb();
const user = db.prepare("SELECT id FROM sms_user WHERE issuer_did = ?").get(issuerDid) as { id: number } | undefined;
if (!user) {
throw { clientError: { message: "No registration found", code: "NOT_FOUND" } };
}
db.prepare("DELETE FROM sms_user WHERE id = ?").run(user.id);
l.info(`Unregistered DID ${issuerDid.slice(-8)}`);
}
}
function generateCode(): string {
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return (arr[0] % 1_000_000).toString().padStart(CODE_LENGTH, "0");
}
async function hashCode(code: string): Promise<string> {
const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(code),
"PBKDF2",
false,
["deriveBits"]
);
const derived = await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
key,
256
);
const saltB64 = encodeBase64(salt);
const hashB64 = encodeBase64(new Uint8Array(derived));
return `${saltB64}:${hashB64}`;
}
async function verifyCode(code: string, stored: string): Promise<boolean> {
const [saltB64, hashB64] = stored.split(":");
const salt = Uint8Array.from(atob(saltB64), (c) => c.charCodeAt(0));
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(code),
"PBKDF2",
false,
["deriveBits"]
);
const derived = await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
key,
256
);
const derivedB64 = encodeBase64(new Uint8Array(derived));
return derivedB64 === hashB64;
}
export default new RegistrationService();

View File

@@ -0,0 +1,68 @@
import l from "../../common/logger.ts";
import { config } from "../../common/config.ts";
import { getDb } from "../../db.ts";
export interface SmsProvider {
sendSms(to: string, body: string): Promise<{ messageId: string }>;
}
class LogProvider implements SmsProvider {
async sendSms(to: string, body: string): Promise<{ messageId: string }> {
const messageId = `log-${Date.now()}`;
l.info(`[SMS LOG] To: ${to} | Body: ${body} | ID: ${messageId}`);
return { messageId };
}
}
function getProvider(): SmsProvider {
if (config.twilioAccountSid && config.twilioAuthToken && config.twilioPhoneNumber) {
// Lazy-loading Twilio provider: only imports the SDK on first call
// deno-lint-ignore no-explicit-any
let client: any = null;
return {
async sendSms(to: string, body: string) {
if (!client) {
l.info("Initializing Twilio SMS provider");
const twilio = (await import("twilio")).default;
client = twilio(config.twilioAccountSid, config.twilioAuthToken);
}
const message = await client.messages.create({
to,
from: config.twilioPhoneNumber,
body,
});
return { messageId: message.sid };
},
};
}
l.info("Using Log SMS provider (no Twilio credentials configured)");
return new LogProvider();
}
const provider = getProvider();
export async function sendSms(
to: string,
body: string,
userId?: number,
notificationType?: string
): Promise<{ messageId: string }> {
const db = getDb();
try {
const result = await provider.sendSms(to, body);
if (userId) {
db.prepare(
"INSERT INTO sms_send_log (user_id, notification_type, status, provider_message_id) VALUES (?, ?, 'sent', ?)"
).run(userId, notificationType || "verification", result.messageId);
}
return result;
} catch (err: unknown) {
if (userId) {
const msg = err instanceof Error ? err.message : String(err);
db.prepare(
"INSERT INTO sms_send_log (user_id, notification_type, status, error_message) VALUES (?, ?, 'failed', ?)"
).run(userId, notificationType || "verification", msg);
}
throw err;
}
}

8
src/common/config.ts Normal file
View File

@@ -0,0 +1,8 @@
export const config = {
port: parseInt(Deno.env.get("PORT") || "3100", 10),
twilioAccountSid: Deno.env.get("TWILIO_ACCOUNT_SID") || "",
twilioAuthToken: Deno.env.get("TWILIO_AUTH_TOKEN") || "",
twilioPhoneNumber: Deno.env.get("TWILIO_PHONE_NUMBER") || "",
endorserApiUrl: Deno.env.get("ENDORSER_API_URL") || "http://localhost:3000",
smsDbPath: Deno.env.get("SMS_DB_PATH") || "./sms-service.sqlite3",
};

8
src/common/logger.ts Normal file
View File

@@ -0,0 +1,8 @@
import pino from "pino";
const l = pino({
name: "sms-service",
level: Deno.env.get("LOG_LEVEL") || "error",
});
export default l;

12
src/common/routes.ts Normal file
View File

@@ -0,0 +1,12 @@
import type { Hono } from "hono";
import registrationRouter from "../api/controllers/registration-router.ts";
import jwtRouter from "../api/controllers/jwt-router.ts";
export default function routes(app: Hono): void {
app.get("/api/sms/health", (c) => c.json({ status: "ok" }));
app.route("/api/sms", registrationRouter);
app.route("/api/sms", jwtRouter);
app.notFound((c) => c.json({ error: { message: "Route not found" } }, 404));
}

28
src/common/server.ts Normal file
View File

@@ -0,0 +1,28 @@
import { Hono } from "hono";
import { cors } from "hono/cors";
import { secureHeaders } from "hono/secure-headers";
import l from "./logger.ts";
export function createApp(): Hono {
const app = new Hono();
// Request logging
app.use("*", async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
l.info({ method: c.req.method, path: c.req.path, status: c.res.status, ms }, "request");
});
app.use("*", secureHeaders());
app.use("*", cors({
origin: "*",
allowHeaders: ["Authorization", "Content-Type"],
}));
return app;
}
export function listen(app: Hono, port: number): Deno.HttpServer {
l.info(`Server running on port ${port}`);
return Deno.serve({ port }, app.fetch);
}

5
src/common/types.ts Normal file
View File

@@ -0,0 +1,5 @@
export type AppEnv = {
Variables: {
issuerDid: string;
};
};

62
src/db.ts Normal file
View File

@@ -0,0 +1,62 @@
import { Database } from "@db/sqlite";
import { config } from "./common/config.ts";
import l from "./common/logger.ts";
let db: Database;
export function getDb(): Database {
if (!db) {
throw new Error("Database not initialized. Call initDb() first.");
}
return db;
}
export function initDb(): void {
db = new Database(config.smsDbPath);
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA foreign_keys = ON");
db.exec("PRAGMA busy_timeout = 5000");
runMigrations();
}
function runMigrations(): void {
const sqlDir = new URL("../sql", import.meta.url);
let entries: Deno.DirEntry[];
try {
entries = [...Deno.readDirSync(sqlDir)];
} catch {
l.warn("No sql/ directory found, skipping migrations");
return;
}
db.exec(`
CREATE TABLE IF NOT EXISTS _migrations (
name TEXT PRIMARY KEY,
applied_at TEXT DEFAULT (datetime('now'))
)
`);
const applied = new Set(
db.prepare("SELECT name FROM _migrations").all().map((r) => (r as Record<string, string>).name)
);
const files = entries
.filter((e) => e.isFile && e.name.endsWith(".sql"))
.map((e) => e.name)
.sort();
for (const file of files) {
if (applied.has(file)) continue;
const filePath = new URL(file, sqlDir.href + "/");
const sql = Deno.readTextFileSync(filePath);
l.info(`Applying migration: ${file}`);
db.exec(sql);
db.prepare("INSERT INTO _migrations (name) VALUES (?)").run(file);
}
}
export function closeDb(): void {
if (db) {
db.close();
}
}

22
src/index.ts Normal file
View File

@@ -0,0 +1,22 @@
import { createApp, listen } from "./common/server.ts";
import routes from "./common/routes.ts";
import { config } from "./common/config.ts";
import { initDb, closeDb } from "./db.ts";
import l from "./common/logger.ts";
initDb();
l.info("Database initialized");
const app = createApp();
routes(app);
const server = listen(app, config.port);
const shutdown = () => {
l.info("Shutting down...");
server.shutdown();
closeDb();
Deno.exit(0);
};
Deno.addSignalListener("SIGTERM", shutdown);
Deno.addSignalListener("SIGINT", shutdown);