create-acrylblends 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +8 -7
- package/dist/index.js.map +1 -1
- package/docs/framework/README.md +2 -1
- package/docs/framework/UPSTREAM.md +1 -1
- package/docs/framework/getting-started/deploy.md +5 -5
- package/docs/framework/getting-started/service-worker.md +5 -3
- package/docs/framework/guides/create-acrylblends.md +2 -2
- package/docs/framework/guides/data.md +202 -0
- package/docs/framework/guides/forms-and-sessions.md +34 -30
- package/docs/framework/upstream.json +3 -3
- package/package.json +2 -2
- package/templates/chat/gitignore +3 -2
- package/templates/chat/migrations/001-chat.sql +12 -0
- package/templates/chat/src/app.ts +4 -2
- package/templates/chat/src/chat-app.ts +22 -18
- package/templates/chat/src/db.ts +30 -36
- package/templates/chat/src/index.ts +9 -4
- package/templates/chat/test/chat.test.ts +21 -9
- package/templates/chat/test/server.test.ts +1 -1
- package/templates/notes/gitignore +3 -2
- package/templates/notes/migrations/001-notes.sql +18 -0
- package/templates/notes/src/app.ts +4 -3
- package/templates/notes/src/auth.ts +21 -19
- package/templates/notes/src/db.ts +40 -50
- package/templates/notes/src/index.ts +9 -4
- package/templates/notes/src/notes-app.ts +35 -29
- package/templates/notes/test/notes.test.ts +27 -20
- package/templates/notes/test/server.test.ts +1 -1
|
@@ -15,7 +15,7 @@ async function start(env: Record<string, string> = {}) {
|
|
|
15
15
|
env: {
|
|
16
16
|
...process.env,
|
|
17
17
|
PORT: '0',
|
|
18
|
-
CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.
|
|
18
|
+
CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.sqlite'),
|
|
19
19
|
...env,
|
|
20
20
|
},
|
|
21
21
|
stdio: ['ignore', 'pipe', 'inherit'],
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
CREATE TABLE users (
|
|
2
|
+
id INTEGER PRIMARY KEY,
|
|
3
|
+
email TEXT NOT NULL UNIQUE,
|
|
4
|
+
password_hash TEXT NOT NULL
|
|
5
|
+
);
|
|
6
|
+
|
|
7
|
+
CREATE TABLE sessions (
|
|
8
|
+
token TEXT PRIMARY KEY,
|
|
9
|
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
CREATE TABLE notes (
|
|
13
|
+
id INTEGER PRIMARY KEY,
|
|
14
|
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
15
|
+
title TEXT NOT NULL,
|
|
16
|
+
body TEXT NOT NULL,
|
|
17
|
+
updated_at TEXT NOT NULL
|
|
18
|
+
);
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { openNotesDb } from './db.ts'
|
|
2
2
|
import { createApp } from './notes-app.ts'
|
|
3
3
|
|
|
4
|
-
/** The
|
|
5
|
-
|
|
4
|
+
/** The composition root: opens the database (once) and builds the app. `index.ts` serves it; the desktop shell does too, and calls `close` when it stops. */
|
|
5
|
+
const { db, close } = await openNotesDb()
|
|
6
6
|
|
|
7
|
+
export { close }
|
|
7
8
|
export default createApp(db)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
1
2
|
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
|
2
|
-
import type { DatabaseSync } from 'node:sqlite'
|
|
3
3
|
import { promisify } from 'node:util'
|
|
4
4
|
|
|
5
5
|
const scryptAsync = promisify(scrypt) as (
|
|
@@ -22,34 +22,36 @@ export async function verifyPassword(password: string, stored: string): Promise<
|
|
|
22
22
|
return timingSafeEqual(actual, expected)
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
export function authStore(db:
|
|
25
|
+
export function authStore(db: Db) {
|
|
26
26
|
return {
|
|
27
27
|
findUser(email: string) {
|
|
28
|
-
return db.
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
return db.get<{ id: number; email: string; password_hash: string }>(
|
|
29
|
+
'SELECT id, email, password_hash FROM users WHERE email = ?',
|
|
30
|
+
email,
|
|
31
|
+
)
|
|
31
32
|
},
|
|
32
33
|
async createUser(email: string, password: string): Promise<number> {
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
const user = await db.get<{ id: number }>(
|
|
35
|
+
'INSERT INTO users (email, password_hash) VALUES (?, ?) RETURNING id',
|
|
36
|
+
email,
|
|
37
|
+
await hashPassword(password),
|
|
38
|
+
)
|
|
39
|
+
return user!.id
|
|
37
40
|
},
|
|
38
|
-
startSession(userId: number): string {
|
|
41
|
+
async startSession(userId: number): Promise<string> {
|
|
39
42
|
const token = randomBytes(32).toString('hex')
|
|
40
|
-
db.
|
|
43
|
+
await db.run('INSERT INTO sessions (token, user_id) VALUES (?, ?)', token, userId)
|
|
41
44
|
return token
|
|
42
45
|
},
|
|
43
|
-
userFor(token: string | undefined) {
|
|
46
|
+
async userFor(token: string | undefined) {
|
|
44
47
|
if (!token) return undefined
|
|
45
|
-
return db
|
|
46
|
-
.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
.get(token) as { id: number; email: string } | undefined
|
|
48
|
+
return db.get<{ id: number; email: string }>(
|
|
49
|
+
'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
|
|
50
|
+
token,
|
|
51
|
+
)
|
|
50
52
|
},
|
|
51
|
-
endSession(token: string) {
|
|
52
|
-
db.
|
|
53
|
+
async endSession(token: string): Promise<void> {
|
|
54
|
+
await db.run('DELETE FROM sessions WHERE token = ?', token)
|
|
53
55
|
},
|
|
54
56
|
}
|
|
55
57
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
2
|
+
import { openDb } from '__PACKAGE__/db/sqlite'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
2
4
|
|
|
3
5
|
export interface Note {
|
|
4
6
|
id: number
|
|
@@ -8,63 +10,51 @@ export interface Note {
|
|
|
8
10
|
updated_at: string
|
|
9
11
|
}
|
|
10
12
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
email TEXT NOT NULL UNIQUE,
|
|
18
|
-
password_hash TEXT NOT NULL
|
|
19
|
-
);
|
|
20
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
21
|
-
token TEXT PRIMARY KEY,
|
|
22
|
-
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
|
|
23
|
-
);
|
|
24
|
-
CREATE TABLE IF NOT EXISTS notes (
|
|
25
|
-
id INTEGER PRIMARY KEY,
|
|
26
|
-
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
27
|
-
title TEXT NOT NULL,
|
|
28
|
-
body TEXT NOT NULL,
|
|
29
|
-
updated_at TEXT NOT NULL
|
|
30
|
-
);
|
|
31
|
-
`)
|
|
32
|
-
return db
|
|
13
|
+
/** The folder of numbered SQL files (001-notes.sql, ...). Applied on start, each once, in one transaction. */
|
|
14
|
+
const MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))
|
|
15
|
+
|
|
16
|
+
/** Open the notes database and apply the migrations. Call `close` once, when the process stops. */
|
|
17
|
+
export function openNotesDb(path = process.env.NOTES_DB ?? 'data/notes.sqlite') {
|
|
18
|
+
return openDb({ path, migrations: MIGRATIONS })
|
|
33
19
|
}
|
|
34
20
|
|
|
35
|
-
export function notesStore(db:
|
|
21
|
+
export function notesStore(db: Db) {
|
|
36
22
|
return {
|
|
37
|
-
list(userId: number, q = ''): Note[] {
|
|
23
|
+
list(userId: number, q = ''): Promise<Note[]> {
|
|
38
24
|
const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`
|
|
39
|
-
return db
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
get(userId: number, id: number): Note | undefined {
|
|
46
|
-
return db
|
|
47
|
-
.prepare('SELECT * FROM notes WHERE id = ? AND user_id = ?')
|
|
48
|
-
.get(id, userId) as unknown as Note | undefined
|
|
25
|
+
return db.all<Note>(
|
|
26
|
+
`SELECT * FROM notes WHERE user_id = ? AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') ORDER BY updated_at DESC, id DESC`,
|
|
27
|
+
userId,
|
|
28
|
+
like,
|
|
29
|
+
like,
|
|
30
|
+
)
|
|
49
31
|
},
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
.prepare('INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?)')
|
|
53
|
-
.run(userId, title, body, new Date().toISOString())
|
|
54
|
-
return this.get(userId, Number(info.lastInsertRowid))!
|
|
32
|
+
get(userId: number, id: number): Promise<Note | undefined> {
|
|
33
|
+
return db.get<Note>('SELECT * FROM notes WHERE id = ? AND user_id = ?', id, userId)
|
|
55
34
|
},
|
|
56
|
-
|
|
57
|
-
db.
|
|
58
|
-
'
|
|
59
|
-
|
|
60
|
-
|
|
35
|
+
async create(userId: number, title: string, body: string): Promise<Note> {
|
|
36
|
+
const note = await db.get<Note>(
|
|
37
|
+
'INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?) RETURNING *',
|
|
38
|
+
userId,
|
|
39
|
+
title,
|
|
40
|
+
body,
|
|
41
|
+
new Date().toISOString(),
|
|
42
|
+
)
|
|
43
|
+
return note!
|
|
61
44
|
},
|
|
62
|
-
|
|
63
|
-
return (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
45
|
+
update(userId: number, id: number, title: string, body: string): Promise<Note | undefined> {
|
|
46
|
+
return db.get<Note>(
|
|
47
|
+
'UPDATE notes SET title = ?, body = ?, updated_at = ? WHERE id = ? AND user_id = ? RETURNING *',
|
|
48
|
+
title,
|
|
49
|
+
body,
|
|
50
|
+
new Date().toISOString(),
|
|
51
|
+
id,
|
|
52
|
+
userId,
|
|
67
53
|
)
|
|
68
54
|
},
|
|
55
|
+
async remove(userId: number, id: number): Promise<boolean> {
|
|
56
|
+
const { changes } = await db.run('DELETE FROM notes WHERE id = ? AND user_id = ?', id, userId)
|
|
57
|
+
return changes > 0
|
|
58
|
+
},
|
|
69
59
|
}
|
|
70
60
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { serve } from '__PACKAGE__/node-server'
|
|
2
|
-
import app, {
|
|
2
|
+
import app, { close } from './app.ts'
|
|
3
3
|
|
|
4
4
|
const port = Number(process.env.PORT || 3000)
|
|
5
5
|
// Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
|
|
@@ -9,11 +9,16 @@ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
|
|
|
9
9
|
console.log(`listening on http://${info.address}:${info.port}`)
|
|
10
10
|
})
|
|
11
11
|
|
|
12
|
-
// Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
|
|
12
|
+
// Stop taking requests, let the ones in flight finish, then close the database and exit. A connection that never ends cannot keep the process alive past 10 seconds.
|
|
13
13
|
function shutdown(): void {
|
|
14
14
|
server.close(() => {
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
close().then(
|
|
16
|
+
() => process.exit(0),
|
|
17
|
+
(error) => {
|
|
18
|
+
console.error(error)
|
|
19
|
+
process.exit(1)
|
|
20
|
+
},
|
|
21
|
+
)
|
|
17
22
|
})
|
|
18
23
|
server.closeIdleConnections()
|
|
19
24
|
setTimeout(() => process.exit(1), 10_000).unref()
|
|
@@ -2,13 +2,13 @@ import type { Context } from '__PACKAGE__'
|
|
|
2
2
|
import { __CLASS__ } from '__PACKAGE__'
|
|
3
3
|
import { deleteCookie, getCookie, setCookie } from '__PACKAGE__/cookie'
|
|
4
4
|
import { csrf } from '__PACKAGE__/csrf'
|
|
5
|
+
import type { Db } from '__PACKAGE__/db'
|
|
5
6
|
import { createMiddleware } from '__PACKAGE__/factory'
|
|
6
7
|
import { HTTPException } from '__PACKAGE__/http-exception'
|
|
7
8
|
import { clientModules } from '__PACKAGE__/node-server'
|
|
8
9
|
import { schemaValidator } from '__PACKAGE__/schema-validator'
|
|
9
|
-
import type { DatabaseSync } from 'node:sqlite'
|
|
10
10
|
import { authStore, verifyPassword } from './auth.ts'
|
|
11
|
-
import { notesStore
|
|
11
|
+
import { notesStore } from './db.ts'
|
|
12
12
|
import { checkCredentials, checkNote, NoteSchema } from './schema.ts'
|
|
13
13
|
import { authPage, formPage, listPage } from './views.tsx'
|
|
14
14
|
|
|
@@ -24,36 +24,42 @@ export interface AppOptions {
|
|
|
24
24
|
publicOrigin?: string
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
export function createApi(db:
|
|
27
|
+
export function createApi(db: Db) {
|
|
28
28
|
const auth = authStore(db)
|
|
29
29
|
const notes = notesStore(db)
|
|
30
30
|
return new __CLASS__<Env>()
|
|
31
31
|
.use(async (c, next) => {
|
|
32
|
-
const user = auth.userFor(getCookie(c, COOKIE))
|
|
32
|
+
const user = await auth.userFor(getCookie(c, COOKIE))
|
|
33
33
|
if (!user) return c.json({ error: 'Log in first.' }, 401)
|
|
34
34
|
c.set('user', user)
|
|
35
35
|
await next()
|
|
36
36
|
})
|
|
37
|
-
.get('/', (c) =>
|
|
38
|
-
|
|
37
|
+
.get('/', async (c) =>
|
|
38
|
+
c.json({ notes: await notes.list(c.get('user').id, c.req.query('q') ?? '') }, 200),
|
|
39
|
+
)
|
|
40
|
+
.post('/', schemaValidator('json', NoteSchema), async (c) =>
|
|
39
41
|
c.json(
|
|
40
42
|
{
|
|
41
|
-
note: notes.create(
|
|
43
|
+
note: await notes.create(
|
|
44
|
+
c.get('user').id,
|
|
45
|
+
c.req.valid('json').title,
|
|
46
|
+
c.req.valid('json').body,
|
|
47
|
+
),
|
|
42
48
|
},
|
|
43
49
|
201,
|
|
44
50
|
),
|
|
45
51
|
)
|
|
46
|
-
.get('/:id', (c) => {
|
|
47
|
-
const note = notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
52
|
+
.get('/:id', async (c) => {
|
|
53
|
+
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
48
54
|
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
49
55
|
})
|
|
50
|
-
.put('/:id', schemaValidator('json', NoteSchema), (c) => {
|
|
56
|
+
.put('/:id', schemaValidator('json', NoteSchema), async (c) => {
|
|
51
57
|
const { title, body } = c.req.valid('json')
|
|
52
|
-
const note = notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
|
|
58
|
+
const note = await notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
|
|
53
59
|
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
54
60
|
})
|
|
55
|
-
.delete('/:id', (c) =>
|
|
56
|
-
notes.remove(c.get('user').id, Number(c.req.param('id')))
|
|
61
|
+
.delete('/:id', async (c) =>
|
|
62
|
+
(await notes.remove(c.get('user').id, Number(c.req.param('id'))))
|
|
57
63
|
? c.json({ ok: true }, 200)
|
|
58
64
|
: c.json({ error: 'No such note.' }, 404),
|
|
59
65
|
)
|
|
@@ -62,7 +68,7 @@ export function createApi(db: DatabaseSync) {
|
|
|
62
68
|
export type Api = ReturnType<typeof createApi>
|
|
63
69
|
|
|
64
70
|
export function createApp(
|
|
65
|
-
db:
|
|
71
|
+
db: Db,
|
|
66
72
|
{
|
|
67
73
|
trustProxy = process.env.TRUST_PROXY === '1',
|
|
68
74
|
publicOrigin = process.env.PUBLIC_ORIGIN,
|
|
@@ -91,7 +97,7 @@ export function createApp(
|
|
|
91
97
|
})
|
|
92
98
|
|
|
93
99
|
const requireUser = createMiddleware<Env>(async (c, next) => {
|
|
94
|
-
const user = auth.userFor(getCookie(c, COOKIE))
|
|
100
|
+
const user = await auth.userFor(getCookie(c, COOKIE))
|
|
95
101
|
if (!user) return c.redirect('/login')
|
|
96
102
|
c.set('user', user)
|
|
97
103
|
await next()
|
|
@@ -107,11 +113,11 @@ export function createApp(
|
|
|
107
113
|
.trim()
|
|
108
114
|
.toLowerCase()
|
|
109
115
|
const errors = checkCredentials(email, form.password, true)
|
|
110
|
-
if (errors.length === 0 && auth.findUser(email))
|
|
116
|
+
if (errors.length === 0 && (await auth.findUser(email)))
|
|
111
117
|
errors.push('That email already has an account. Log in instead.')
|
|
112
118
|
if (errors.length > 0) return c.html(authPage('signup', errors, email), 400)
|
|
113
119
|
const id = await auth.createUser(email, String(form.password))
|
|
114
|
-
setCookie(c, COOKIE, auth.startSession(id), session(c))
|
|
120
|
+
setCookie(c, COOKIE, await auth.startSession(id), session(c))
|
|
115
121
|
return c.redirect('/notes', 303)
|
|
116
122
|
})
|
|
117
123
|
|
|
@@ -122,16 +128,16 @@ export function createApp(
|
|
|
122
128
|
.toLowerCase()
|
|
123
129
|
const errors = checkCredentials(email, form.password, false)
|
|
124
130
|
if (errors.length > 0) return c.html(authPage('login', errors, email), 400)
|
|
125
|
-
const user = auth.findUser(email)
|
|
131
|
+
const user = await auth.findUser(email)
|
|
126
132
|
if (!user || !(await verifyPassword(String(form.password), user.password_hash)))
|
|
127
133
|
return c.html(authPage('login', ['Wrong email or password.'], email), 401)
|
|
128
|
-
setCookie(c, COOKIE, auth.startSession(user.id), session(c))
|
|
134
|
+
setCookie(c, COOKIE, await auth.startSession(user.id), session(c))
|
|
129
135
|
return c.redirect('/notes', 303)
|
|
130
136
|
})
|
|
131
137
|
|
|
132
|
-
app.post('/logout', (c) => {
|
|
138
|
+
app.post('/logout', async (c) => {
|
|
133
139
|
const token = getCookie(c, COOKIE)
|
|
134
|
-
if (token) auth.endSession(token)
|
|
140
|
+
if (token) await auth.endSession(token)
|
|
135
141
|
deleteCookie(c, COOKIE, { path: '/' })
|
|
136
142
|
return c.redirect('/login', 303)
|
|
137
143
|
})
|
|
@@ -139,9 +145,9 @@ export function createApp(
|
|
|
139
145
|
app.use('/notes/*', requireUser)
|
|
140
146
|
app.use('/notes', requireUser)
|
|
141
147
|
|
|
142
|
-
app.get('/notes', (c) => {
|
|
148
|
+
app.get('/notes', async (c) => {
|
|
143
149
|
const q = (c.req.query('q') ?? '').trim()
|
|
144
|
-
return c.html(listPage(c.get('user').email, notes.list(c.get('user').id, q), q))
|
|
150
|
+
return c.html(listPage(c.get('user').email, await notes.list(c.get('user').id, q), q))
|
|
145
151
|
})
|
|
146
152
|
app.get('/notes/new', (c) =>
|
|
147
153
|
c.html(formPage(c.get('user').email, '/notes', { title: '', body: '' })),
|
|
@@ -159,11 +165,11 @@ export function createApp(
|
|
|
159
165
|
),
|
|
160
166
|
400,
|
|
161
167
|
)
|
|
162
|
-
notes.create(c.get('user').id, checked.value.title, checked.value.body)
|
|
168
|
+
await notes.create(c.get('user').id, checked.value.title, checked.value.body)
|
|
163
169
|
return c.redirect('/notes', 303)
|
|
164
170
|
})
|
|
165
|
-
app.get('/notes/:id/edit', (c) => {
|
|
166
|
-
const note = notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
171
|
+
app.get('/notes/:id/edit', async (c) => {
|
|
172
|
+
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
167
173
|
return note
|
|
168
174
|
? c.html(formPage(c.get('user').email, `/notes/${note.id}`, note))
|
|
169
175
|
: c.html(listPage(c.get('user').email, [], ''), 404)
|
|
@@ -182,12 +188,12 @@ export function createApp(
|
|
|
182
188
|
),
|
|
183
189
|
400,
|
|
184
190
|
)
|
|
185
|
-
if (!notes.update(c.get('user').id, id, checked.value.title, checked.value.body))
|
|
191
|
+
if (!(await notes.update(c.get('user').id, id, checked.value.title, checked.value.body)))
|
|
186
192
|
return c.text('No such note.', 404)
|
|
187
193
|
return c.redirect('/notes', 303)
|
|
188
194
|
})
|
|
189
|
-
app.post('/notes/:id/delete', (c) => {
|
|
190
|
-
if (!notes.remove(c.get('user').id, Number(c.req.param('id'))))
|
|
195
|
+
app.post('/notes/:id/delete', async (c) => {
|
|
196
|
+
if (!(await notes.remove(c.get('user').id, Number(c.req.param('id')))))
|
|
191
197
|
return c.text('No such note.', 404)
|
|
192
198
|
return c.redirect('/notes', 303)
|
|
193
199
|
})
|
|
@@ -1,10 +1,19 @@
|
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
1
2
|
import { testClient } from '__PACKAGE__/testing'
|
|
2
3
|
import assert from 'node:assert/strict'
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import { openDb } from '../src/db.ts'
|
|
4
|
+
import { after, test } from 'node:test'
|
|
5
|
+
import { openNotesDb } from '../src/db.ts'
|
|
6
6
|
import { createApi, createApp } from '../src/notes-app.ts'
|
|
7
7
|
|
|
8
|
+
/** A fresh database in memory with the real migrations; every one is closed when the tests end. */
|
|
9
|
+
const closers: (() => Promise<void>)[] = []
|
|
10
|
+
after(() => Promise.all(closers.map((close) => close())))
|
|
11
|
+
async function memoryDb(): Promise<Db> {
|
|
12
|
+
const { db, close } = await openNotesDb(':memory:')
|
|
13
|
+
closers.push(close)
|
|
14
|
+
return db
|
|
15
|
+
}
|
|
16
|
+
|
|
8
17
|
const form = (data: Record<string, string>, cookie = ''): RequestInit => ({
|
|
9
18
|
method: 'POST',
|
|
10
19
|
body: new URLSearchParams(data),
|
|
@@ -18,7 +27,7 @@ async function signedUp(app: ReturnType<typeof createApp>, email = 'a@example.co
|
|
|
18
27
|
}
|
|
19
28
|
|
|
20
29
|
test('the home page sends a visitor to the notes, which send them to log in', async () => {
|
|
21
|
-
const app = createApp(
|
|
30
|
+
const app = createApp(await memoryDb())
|
|
22
31
|
assert.equal((await app.request('/')).headers.get('location'), '/notes')
|
|
23
32
|
const res = await app.request('/notes')
|
|
24
33
|
assert.equal(res.status, 302)
|
|
@@ -26,7 +35,7 @@ test('the home page sends a visitor to the notes, which send them to log in', as
|
|
|
26
35
|
})
|
|
27
36
|
|
|
28
37
|
test('sign up validates, refuses a duplicate, and starts a session', async () => {
|
|
29
|
-
const app = createApp(
|
|
38
|
+
const app = createApp(await memoryDb())
|
|
30
39
|
assert.match(await (await app.request('/signup')).text(), /Create account/)
|
|
31
40
|
const bad = await app.request('/signup', form({ email: 'nope', password: 'short' }))
|
|
32
41
|
assert.equal(bad.status, 400)
|
|
@@ -44,7 +53,7 @@ test('sign up validates, refuses a duplicate, and starts a session', async () =>
|
|
|
44
53
|
})
|
|
45
54
|
|
|
46
55
|
test('log in checks the password; log out ends the session', async () => {
|
|
47
|
-
const app = createApp(
|
|
56
|
+
const app = createApp(await memoryDb())
|
|
48
57
|
const first = await signedUp(app)
|
|
49
58
|
assert.match(await (await app.request('/login')).text(), /Log in/)
|
|
50
59
|
const wrong = await app.request(
|
|
@@ -69,7 +78,7 @@ test('log in checks the password; log out ends the session', async () => {
|
|
|
69
78
|
})
|
|
70
79
|
|
|
71
80
|
test('create, search, edit and delete a note through the forms', async () => {
|
|
72
|
-
const app = createApp(
|
|
81
|
+
const app = createApp(await memoryDb())
|
|
73
82
|
const cookie = await signedUp(app)
|
|
74
83
|
assert.match(
|
|
75
84
|
await (await app.request('/notes/new', { headers: { cookie } })).text(),
|
|
@@ -123,7 +132,7 @@ test('create, search, edit and delete a note through the forms', async () => {
|
|
|
123
132
|
})
|
|
124
133
|
|
|
125
134
|
test("one user cannot read or change another user's notes", async () => {
|
|
126
|
-
const app = createApp(
|
|
135
|
+
const app = createApp(await memoryDb())
|
|
127
136
|
const alice = await signedUp(app, 'alice@example.com')
|
|
128
137
|
const bob = await signedUp(app, 'bob@example.com')
|
|
129
138
|
await app.request('/notes', form({ title: 'Secret', body: 'alice only' }, alice))
|
|
@@ -133,7 +142,7 @@ test("one user cannot read or change another user's notes", async () => {
|
|
|
133
142
|
})
|
|
134
143
|
|
|
135
144
|
test('the JSON API needs a session and validates input', async () => {
|
|
136
|
-
const db =
|
|
145
|
+
const db = await memoryDb()
|
|
137
146
|
const app = createApp(db)
|
|
138
147
|
const cookie = await signedUp(app)
|
|
139
148
|
const res = await app.request('/api/notes')
|
|
@@ -149,7 +158,7 @@ test('the JSON API needs a session and validates input', async () => {
|
|
|
149
158
|
})
|
|
150
159
|
|
|
151
160
|
test('the typed client covers every API route', async () => {
|
|
152
|
-
const db =
|
|
161
|
+
const db = await memoryDb()
|
|
153
162
|
const app = createApp(db)
|
|
154
163
|
const cookie = await signedUp(app)
|
|
155
164
|
const client = testClient(createApi(db))
|
|
@@ -180,7 +189,7 @@ test('the typed client covers every API route', async () => {
|
|
|
180
189
|
})
|
|
181
190
|
|
|
182
191
|
test('csrf refuses a form POST from another site', async () => {
|
|
183
|
-
const app = createApp(
|
|
192
|
+
const app = createApp(await memoryDb())
|
|
184
193
|
const res = await app.request('/signup', {
|
|
185
194
|
method: 'POST',
|
|
186
195
|
body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
|
|
@@ -192,7 +201,7 @@ test('csrf refuses a form POST from another site', async () => {
|
|
|
192
201
|
test('the session cookie is Secure over HTTPS, and behind a proxy only when the proxy is trusted', async () => {
|
|
193
202
|
const body = new URLSearchParams({ email: 'a@example.com', password: 'correct horse' })
|
|
194
203
|
const flags = async (url: string, headers: Record<string, string>, trustProxy: boolean) => {
|
|
195
|
-
const app = createApp(
|
|
204
|
+
const app = createApp(await memoryDb(), { trustProxy })
|
|
196
205
|
const origin = new URL(url).origin
|
|
197
206
|
const res = await app.request(url, { method: 'POST', body, headers: { origin, ...headers } })
|
|
198
207
|
assert.equal(res.status, 303)
|
|
@@ -206,7 +215,7 @@ test('the session cookie is Secure over HTTPS, and behind a proxy only when the
|
|
|
206
215
|
})
|
|
207
216
|
|
|
208
217
|
test('behind a proxy csrf accepts the public origin and still refuses others', async () => {
|
|
209
|
-
const app = createApp(
|
|
218
|
+
const app = createApp(await memoryDb(), { publicOrigin: 'https://notes.example.com' })
|
|
210
219
|
const post = (origin: string) =>
|
|
211
220
|
app.request('/signup', {
|
|
212
221
|
method: 'POST',
|
|
@@ -218,12 +227,10 @@ test('behind a proxy csrf accepts the public origin and still refuses others', a
|
|
|
218
227
|
})
|
|
219
228
|
|
|
220
229
|
test('an error answers a plain 500 with no stack and no detail', async () => {
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
exec() {},
|
|
226
|
-
} as unknown as DatabaseSync
|
|
230
|
+
const fail = async (): Promise<never> => {
|
|
231
|
+
throw new Error('secret detail at /srv/app/db.ts:1')
|
|
232
|
+
}
|
|
233
|
+
const broken: Db = { exec: fail, run: fail, get: fail, all: fail, transaction: fail }
|
|
227
234
|
const app = createApp(broken)
|
|
228
235
|
const res = await app.request('/notes', { headers: { cookie: 'sid=anything' } })
|
|
229
236
|
assert.equal(res.status, 500)
|
|
@@ -231,7 +238,7 @@ test('an error answers a plain 500 with no stack and no detail', async () => {
|
|
|
231
238
|
})
|
|
232
239
|
|
|
233
240
|
test('the note form loads the character counter, a client component compiled for the browser', async () => {
|
|
234
|
-
const app = createApp(
|
|
241
|
+
const app = createApp(await memoryDb())
|
|
235
242
|
const cookie = await signedUp(app)
|
|
236
243
|
assert.match(
|
|
237
244
|
await (await app.request('/notes/new', { headers: { cookie } })).text(),
|
|
@@ -15,7 +15,7 @@ async function start(env: Record<string, string> = {}) {
|
|
|
15
15
|
env: {
|
|
16
16
|
...process.env,
|
|
17
17
|
PORT: '0',
|
|
18
|
-
NOTES_DB: join(mkdtempSync(join(tmpdir(), 'notes-')), 'notes.
|
|
18
|
+
NOTES_DB: join(mkdtempSync(join(tmpdir(), 'notes-')), 'notes.sqlite'),
|
|
19
19
|
...env,
|
|
20
20
|
},
|
|
21
21
|
stdio: ['ignore', 'pipe', 'inherit'],
|