create-acrylblends 0.2.8 → 0.3.0

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.
Files changed (58) hide show
  1. package/README.md +5 -4
  2. package/dist/index.d.ts +1 -3
  3. package/dist/index.js +20 -198
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +2 -2
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/getting-started/basic.md +1 -2
  8. package/docs/framework/getting-started/desktop.md +1 -1
  9. package/docs/framework/guides/bring-your-own-tool.md +216 -0
  10. package/docs/framework/guides/create-acrylblends.md +5 -4
  11. package/docs/framework/guides/data.md +2 -1
  12. package/docs/framework/upstream.json +3 -3
  13. package/package.json +2 -3
  14. package/templates/bun/gitignore +0 -2
  15. package/templates/bun/package.json +0 -19
  16. package/templates/bun/src/index.ts +0 -7
  17. package/templates/bun/test/app.test.ts +0 -8
  18. package/templates/bun/tsconfig.json +0 -15
  19. package/templates/chat/gitignore +0 -7
  20. package/templates/chat/migrations/001-chat.sql +0 -12
  21. package/templates/chat/package.json +0 -26
  22. package/templates/chat/src/app.ts +0 -8
  23. package/templates/chat/src/chat-app.ts +0 -100
  24. package/templates/chat/src/client/chat.tsx +0 -115
  25. package/templates/chat/src/client/tsconfig.json +0 -15
  26. package/templates/chat/src/db.ts +0 -53
  27. package/templates/chat/src/index.ts +0 -27
  28. package/templates/chat/src/llm.ts +0 -42
  29. package/templates/chat/src/page.tsx +0 -38
  30. package/templates/chat/test/chat.test.ts +0 -165
  31. package/templates/chat/test/server.test.ts +0 -59
  32. package/templates/chat/tsconfig.json +0 -19
  33. package/templates/nodejs/gitignore +0 -3
  34. package/templates/nodejs/package.json +0 -23
  35. package/templates/nodejs/src/app.ts +0 -10
  36. package/templates/nodejs/src/client/counter.tsx +0 -12
  37. package/templates/nodejs/src/client/tsconfig.json +0 -15
  38. package/templates/nodejs/src/index.ts +0 -21
  39. package/templates/nodejs/src/page.tsx +0 -26
  40. package/templates/nodejs/src/routes.ts +0 -10
  41. package/templates/nodejs/test/app.test.ts +0 -40
  42. package/templates/nodejs/test/server.test.ts +0 -48
  43. package/templates/nodejs/tsconfig.json +0 -19
  44. package/templates/notes/gitignore +0 -7
  45. package/templates/notes/migrations/001-notes.sql +0 -18
  46. package/templates/notes/package.json +0 -26
  47. package/templates/notes/src/app.ts +0 -8
  48. package/templates/notes/src/auth.ts +0 -57
  49. package/templates/notes/src/client/counter.tsx +0 -21
  50. package/templates/notes/src/client/tsconfig.json +0 -15
  51. package/templates/notes/src/db.ts +0 -60
  52. package/templates/notes/src/index.ts +0 -27
  53. package/templates/notes/src/notes-app.ts +0 -205
  54. package/templates/notes/src/schema.ts +0 -38
  55. package/templates/notes/src/views.tsx +0 -134
  56. package/templates/notes/test/notes.test.ts +0 -252
  57. package/templates/notes/test/server.test.ts +0 -59
  58. package/templates/notes/tsconfig.json +0 -19
@@ -1,205 +0,0 @@
1
- import type { Context } from '__PACKAGE__'
2
- import { __CLASS__ } from '__PACKAGE__'
3
- import { deleteCookie, getCookie, setCookie } from '__PACKAGE__/cookie'
4
- import { csrf } from '__PACKAGE__/csrf'
5
- import type { Db } from '__PACKAGE__/db'
6
- import { createMiddleware } from '__PACKAGE__/factory'
7
- import { HTTPException } from '__PACKAGE__/http-exception'
8
- import { clientModules } from '__PACKAGE__/node-server'
9
- import { schemaValidator } from '__PACKAGE__/schema-validator'
10
- import { authStore, verifyPassword } from './auth.ts'
11
- import { notesStore } from './db.ts'
12
- import { checkCredentials, checkNote, NoteSchema } from './schema.ts'
13
- import { authPage, formPage, listPage } from './views.tsx'
14
-
15
- type Env = { Variables: { user: { id: number; email: string } } }
16
-
17
- const COOKIE = 'sid'
18
- const MONTH = 60 * 60 * 24 * 30
19
-
20
- export interface AppOptions {
21
- /** Believe `X-Forwarded-Proto` (set it when a reverse proxy you run terminates HTTPS in front of the app). Default: the TRUST_PROXY=1 environment variable. */
22
- trustProxy?: boolean
23
- /** The address people use in the browser, for example `https://notes.example.com`. Behind a proxy the app sees `http://127.0.0.1:3000`, so csrf needs it. Default: PUBLIC_ORIGIN. */
24
- publicOrigin?: string
25
- }
26
-
27
- export function createApi(db: Db) {
28
- const auth = authStore(db)
29
- const notes = notesStore(db)
30
- return new __CLASS__<Env>()
31
- .use(async (c, next) => {
32
- const user = await auth.userFor(getCookie(c, COOKIE))
33
- if (!user) return c.json({ error: 'Log in first.' }, 401)
34
- c.set('user', user)
35
- await next()
36
- })
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) =>
41
- c.json(
42
- {
43
- note: await notes.create(
44
- c.get('user').id,
45
- c.req.valid('json').title,
46
- c.req.valid('json').body,
47
- ),
48
- },
49
- 201,
50
- ),
51
- )
52
- .get('/:id', async (c) => {
53
- const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
54
- return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
55
- })
56
- .put('/:id', schemaValidator('json', NoteSchema), async (c) => {
57
- const { title, body } = c.req.valid('json')
58
- const note = await notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
59
- return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
60
- })
61
- .delete('/:id', async (c) =>
62
- (await notes.remove(c.get('user').id, Number(c.req.param('id'))))
63
- ? c.json({ ok: true }, 200)
64
- : c.json({ error: 'No such note.' }, 404),
65
- )
66
- }
67
-
68
- export type Api = ReturnType<typeof createApi>
69
-
70
- export function createApp(
71
- db: Db,
72
- {
73
- trustProxy = process.env.TRUST_PROXY === '1',
74
- publicOrigin = process.env.PUBLIC_ORIGIN,
75
- }: AppOptions = {},
76
- ) {
77
- const auth = authStore(db)
78
- const notes = notesStore(db)
79
- const app = new __CLASS__<Env>()
80
- // Refuses a form POST that does not come from this site (checks Origin and Sec-Fetch-Site); JSON requests are not form-shaped and pass.
81
- app.use(csrf(publicOrigin ? { origin: [publicOrigin] } : undefined))
82
- // A secure cookie is only sent over HTTPS: set when the request is HTTPS, or a proxy we trust says it was.
83
- const session = (c: Context<Env>) => ({
84
- path: '/',
85
- httpOnly: true,
86
- sameSite: 'Lax' as const,
87
- maxAge: MONTH,
88
- secure:
89
- new URL(c.req.url).protocol === 'https:' ||
90
- (trustProxy && c.req.header('x-forwarded-proto') === 'https'),
91
- })
92
- // The log has the stack; the page never does.
93
- app.onError((error, c) => {
94
- if (error instanceof HTTPException) return error.getResponse()
95
- console.error(error)
96
- return c.text('Internal Server Error', 500)
97
- })
98
-
99
- const requireUser = createMiddleware<Env>(async (c, next) => {
100
- const user = await auth.userFor(getCookie(c, COOKIE))
101
- if (!user) return c.redirect('/login')
102
- c.set('user', user)
103
- await next()
104
- })
105
-
106
- app.get('/', (c) => c.redirect('/notes'))
107
- app.get('/signup', (c) => c.html(authPage('signup')))
108
- app.get('/login', (c) => c.html(authPage('login')))
109
-
110
- app.post('/signup', async (c) => {
111
- const form = await c.req.parseBody()
112
- const email = String(form.email ?? '')
113
- .trim()
114
- .toLowerCase()
115
- const errors = checkCredentials(email, form.password, true)
116
- if (errors.length === 0 && (await auth.findUser(email)))
117
- errors.push('That email already has an account. Log in instead.')
118
- if (errors.length > 0) return c.html(authPage('signup', errors, email), 400)
119
- const id = await auth.createUser(email, String(form.password))
120
- setCookie(c, COOKIE, await auth.startSession(id), session(c))
121
- return c.redirect('/notes', 303)
122
- })
123
-
124
- app.post('/login', async (c) => {
125
- const form = await c.req.parseBody()
126
- const email = String(form.email ?? '')
127
- .trim()
128
- .toLowerCase()
129
- const errors = checkCredentials(email, form.password, false)
130
- if (errors.length > 0) return c.html(authPage('login', errors, email), 400)
131
- const user = await auth.findUser(email)
132
- if (!user || !(await verifyPassword(String(form.password), user.password_hash)))
133
- return c.html(authPage('login', ['Wrong email or password.'], email), 401)
134
- setCookie(c, COOKIE, await auth.startSession(user.id), session(c))
135
- return c.redirect('/notes', 303)
136
- })
137
-
138
- app.post('/logout', async (c) => {
139
- const token = getCookie(c, COOKIE)
140
- if (token) await auth.endSession(token)
141
- deleteCookie(c, COOKIE, { path: '/' })
142
- return c.redirect('/login', 303)
143
- })
144
-
145
- app.use('/notes/*', requireUser)
146
- app.use('/notes', requireUser)
147
-
148
- app.get('/notes', async (c) => {
149
- const q = (c.req.query('q') ?? '').trim()
150
- return c.html(listPage(c.get('user').email, await notes.list(c.get('user').id, q), q))
151
- })
152
- app.get('/notes/new', (c) =>
153
- c.html(formPage(c.get('user').email, '/notes', { title: '', body: '' })),
154
- )
155
- app.post('/notes', async (c) => {
156
- const form = await c.req.parseBody()
157
- const checked = checkNote(form)
158
- if ('issues' in checked)
159
- return c.html(
160
- formPage(
161
- c.get('user').email,
162
- '/notes',
163
- { title: String(form.title ?? ''), body: String(form.body ?? '') },
164
- checked.issues.map((i) => i.message),
165
- ),
166
- 400,
167
- )
168
- await notes.create(c.get('user').id, checked.value.title, checked.value.body)
169
- return c.redirect('/notes', 303)
170
- })
171
- app.get('/notes/:id/edit', async (c) => {
172
- const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
173
- return note
174
- ? c.html(formPage(c.get('user').email, `/notes/${note.id}`, note))
175
- : c.html(listPage(c.get('user').email, [], ''), 404)
176
- })
177
- app.post('/notes/:id', async (c) => {
178
- const id = Number(c.req.param('id'))
179
- const form = await c.req.parseBody()
180
- const checked = checkNote(form)
181
- if ('issues' in checked)
182
- return c.html(
183
- formPage(
184
- c.get('user').email,
185
- `/notes/${id}`,
186
- { title: String(form.title ?? ''), body: String(form.body ?? '') },
187
- checked.issues.map((i) => i.message),
188
- ),
189
- 400,
190
- )
191
- if (!(await notes.update(c.get('user').id, id, checked.value.title, checked.value.body)))
192
- return c.text('No such note.', 404)
193
- return c.redirect('/notes', 303)
194
- })
195
- app.post('/notes/:id/delete', async (c) => {
196
- if (!(await notes.remove(c.get('user').id, Number(c.req.param('id')))))
197
- return c.text('No such note.', 404)
198
- return c.redirect('/notes', 303)
199
- })
200
-
201
- app.route('/api/notes', createApi(db))
202
- // Client components without a bundler: src/client is compiled when the browser asks; `npm run build` compiles it once for production.
203
- app.route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
204
- return app
205
- }
@@ -1,38 +0,0 @@
1
- import type { StandardSchema } from '__PACKAGE__/schema-validator'
2
-
3
- export interface NoteInput {
4
- title: string
5
- body: string
6
- }
7
-
8
- export const TITLE_MAX = 80
9
- export const BODY_MAX = 2000
10
-
11
- /** The one place a note's rules live: the HTML forms and the JSON API both use it. */
12
- export function checkNote(
13
- value: unknown,
14
- ): { value: NoteInput } | { issues: { message: string; path: string[] }[] } {
15
- const input = (value ?? {}) as Record<string, unknown>
16
- const title = typeof input.title === 'string' ? input.title.trim() : ''
17
- const body = typeof input.body === 'string' ? input.body : ''
18
- const issues: { message: string; path: string[] }[] = []
19
- if (title === '') issues.push({ message: 'Give the note a title.', path: ['title'] })
20
- else if (title.length > TITLE_MAX)
21
- issues.push({ message: `The title is at most ${TITLE_MAX} characters.`, path: ['title'] })
22
- if (body.length > BODY_MAX)
23
- issues.push({ message: `The note is at most ${BODY_MAX} characters.`, path: ['body'] })
24
- return issues.length > 0 ? { issues } : { value: { title, body } }
25
- }
26
-
27
- export const NoteSchema: StandardSchema<NoteInput> = {
28
- '~standard': { validate: (value) => checkNote(value) },
29
- }
30
-
31
- export function checkCredentials(email: unknown, password: unknown, signup: boolean): string[] {
32
- const errors: string[] = []
33
- if (typeof email !== 'string' || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))
34
- errors.push('Enter a valid email address.')
35
- if (typeof password !== 'string' || password === '') errors.push('Enter a password.')
36
- else if (signup && password.length < 8) errors.push('The password needs at least 8 characters.')
37
- return errors
38
- }
@@ -1,134 +0,0 @@
1
- import type { Note } from './db.ts'
2
- import { BODY_MAX, TITLE_MAX } from './schema.ts'
3
-
4
- const counterScript = `
5
- const filter = document.getElementById('filter')
6
- if (filter) filter.addEventListener('input', () => {
7
- const q = filter.value.toLowerCase()
8
- for (const li of document.querySelectorAll('[data-note]'))
9
- li.hidden = !li.textContent.toLowerCase().includes(q)
10
- })
11
- `
12
-
13
- const Layout = ({
14
- title,
15
- user,
16
- children,
17
- }: {
18
- title: string
19
- user?: string
20
- children?: unknown
21
- }) => (
22
- <html lang="en">
23
- <head>
24
- <meta charset="utf-8" />
25
- <meta name="viewport" content="width=device-width, initial-scale=1" />
26
- <title>{title}</title>
27
- <style
28
- dangerouslySetInnerHTML={{
29
- __html:
30
- 'body{font:16px system-ui;max-width:42rem;margin:2rem auto;padding:0 1rem}label{display:block;margin:.75rem 0 .25rem}input,textarea{width:100%;box-sizing:border-box;padding:.5rem}.error{color:#b00020}nav{display:flex;gap:1rem;align-items:center}nav form{margin-left:auto}li{margin:.5rem 0}',
31
- }}
32
- />
33
- </head>
34
- <body>
35
- <nav>
36
- <strong>Notes</strong>
37
- {user ? (
38
- <>
39
- <a href="/notes">All notes</a>
40
- <a href="/notes/new">New note</a>
41
- <form method="post" action="/logout">
42
- <span>{user} </span>
43
- <button type="submit">Log out</button>
44
- </form>
45
- </>
46
- ) : (
47
- <>
48
- <a href="/login">Log in</a>
49
- <a href="/signup">Sign up</a>
50
- </>
51
- )}
52
- </nav>
53
- {children}
54
- <script dangerouslySetInnerHTML={{ __html: counterScript }} />
55
- <script type="module" src="/client/counter.tsx" />
56
- </body>
57
- </html>
58
- )
59
-
60
- const Errors = ({ errors }: { errors: string[] }) =>
61
- errors.length > 0 ? (
62
- <ul class="error" role="alert">
63
- {errors.map((e) => (
64
- <li>{e}</li>
65
- ))}
66
- </ul>
67
- ) : null
68
-
69
- export const authPage = (mode: 'login' | 'signup', errors: string[] = [], email = ''): string =>
70
- (
71
- <Layout title={mode === 'login' ? 'Log in' : 'Sign up'}>
72
- <h1>{mode === 'login' ? 'Log in' : 'Sign up'}</h1>
73
- <Errors errors={errors} />
74
- <form method="post" action={`/${mode}`}>
75
- <label for="email">Email</label>
76
- <input id="email" name="email" type="email" value={email} />
77
- <label for="password">Password</label>
78
- <input id="password" name="password" type="password" />
79
- <p>
80
- <button type="submit">{mode === 'login' ? 'Log in' : 'Create account'}</button>
81
- </p>
82
- </form>
83
- </Layout>
84
- ).toString()
85
-
86
- export const listPage = (user: string, notes: Note[], q: string): string =>
87
- (
88
- <Layout title="Notes" user={user}>
89
- <h1>Your notes</h1>
90
- <form method="get" action="/notes">
91
- <label for="filter">Search</label>
92
- <input id="filter" name="q" type="search" value={q} />
93
- <button type="submit">Search</button>
94
- </form>
95
- {notes.length === 0 ? <p>{q ? `No note matches "${q}".` : 'No notes yet.'}</p> : null}
96
- <ul>
97
- {notes.map((n) => (
98
- <li data-note>
99
- <a href={`/notes/${n.id}/edit`}>{n.title}</a>
100
- <form method="post" action={`/notes/${n.id}/delete`} style="display:inline">
101
- <button type="submit">Delete</button>
102
- </form>
103
- </li>
104
- ))}
105
- </ul>
106
- </Layout>
107
- ).toString()
108
-
109
- export const formPage = (
110
- user: string,
111
- action: string,
112
- note: { title: string; body: string },
113
- errors: string[] = [],
114
- ): string =>
115
- (
116
- <Layout title="Note" user={user}>
117
- <h1>{action === '/notes' ? 'New note' : 'Edit note'}</h1>
118
- <Errors errors={errors} />
119
- <form method="post" action={action}>
120
- <label for="title">Title</label>
121
- <input id="title" name="title" value={note.title} />
122
- <label for="body">Note</label>
123
- <textarea id="body" name="body" rows={8} maxlength={BODY_MAX}>
124
- {note.body}
125
- </textarea>
126
- <small id="count" aria-live="polite" data-island="counter" />
127
- <p>
128
- <button type="submit">Save</button> <a href="/notes">Cancel</a>
129
- </p>
130
- </form>
131
- </Layout>
132
- ).toString()
133
-
134
- export { TITLE_MAX }
@@ -1,252 +0,0 @@
1
- import type { Db } from '__PACKAGE__/db'
2
- import { testClient } from '__PACKAGE__/testing'
3
- import assert from 'node:assert/strict'
4
- import { after, test } from 'node:test'
5
- import { openNotesDb } from '../src/db.ts'
6
- import { createApi, createApp } from '../src/notes-app.ts'
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
-
17
- const form = (data: Record<string, string>, cookie = ''): RequestInit => ({
18
- method: 'POST',
19
- body: new URLSearchParams(data),
20
- headers: { origin: 'http://localhost', ...(cookie ? { cookie } : {}) },
21
- })
22
-
23
- async function signedUp(app: ReturnType<typeof createApp>, email = 'a@example.com') {
24
- const res = await app.request('/signup', form({ email, password: 'correct horse' }))
25
- assert.equal(res.status, 303)
26
- return (res.headers.get('set-cookie') ?? '').split(';')[0] ?? ''
27
- }
28
-
29
- test('the home page sends a visitor to the notes, which send them to log in', async () => {
30
- const app = createApp(await memoryDb())
31
- assert.equal((await app.request('/')).headers.get('location'), '/notes')
32
- const res = await app.request('/notes')
33
- assert.equal(res.status, 302)
34
- assert.equal(res.headers.get('location'), '/login')
35
- })
36
-
37
- test('sign up validates, refuses a duplicate, and starts a session', async () => {
38
- const app = createApp(await memoryDb())
39
- assert.match(await (await app.request('/signup')).text(), /Create account/)
40
- const bad = await app.request('/signup', form({ email: 'nope', password: 'short' }))
41
- assert.equal(bad.status, 400)
42
- const text = await bad.text()
43
- assert.match(text, /valid email/)
44
- assert.match(text, /at least 8 characters/)
45
- const cookie = await signedUp(app)
46
- assert.match(cookie, /^sid=/)
47
- const again = await app.request(
48
- '/signup',
49
- form({ email: 'a@example.com', password: 'correct horse' }),
50
- )
51
- assert.equal(again.status, 400)
52
- assert.match(await again.text(), /already has an account/)
53
- })
54
-
55
- test('log in checks the password; log out ends the session', async () => {
56
- const app = createApp(await memoryDb())
57
- const first = await signedUp(app)
58
- assert.match(await (await app.request('/login')).text(), /Log in/)
59
- const wrong = await app.request(
60
- '/login',
61
- form({ email: 'a@example.com', password: 'nope nope nope' }),
62
- )
63
- assert.equal(wrong.status, 401)
64
- assert.match(await wrong.text(), /Wrong email or password/)
65
- const empty = await app.request('/login', form({ email: '', password: '' }))
66
- assert.equal(empty.status, 400)
67
- const ok = await app.request(
68
- '/login',
69
- form({ email: 'a@example.com', password: 'correct horse' }),
70
- )
71
- assert.equal(ok.status, 303)
72
- const cookie = (ok.headers.get('set-cookie') ?? '').split(';')[0] ?? ''
73
- assert.equal((await app.request('/notes', { headers: { cookie } })).status, 200)
74
- const out = await app.request('/logout', form({}, cookie))
75
- assert.equal(out.headers.get('location'), '/login')
76
- assert.equal((await app.request('/notes', { headers: { cookie } })).status, 302)
77
- assert.equal((await app.request('/notes', { headers: { cookie: first } })).status, 200)
78
- })
79
-
80
- test('create, search, edit and delete a note through the forms', async () => {
81
- const app = createApp(await memoryDb())
82
- const cookie = await signedUp(app)
83
- assert.match(
84
- await (await app.request('/notes/new', { headers: { cookie } })).text(),
85
- /data-island="counter"/,
86
- )
87
-
88
- const invalid = await app.request('/notes', form({ title: ' ', body: 'x' }, cookie))
89
- assert.equal(invalid.status, 400)
90
- assert.match(await invalid.text(), /Give the note a title/)
91
-
92
- assert.equal(
93
- (await app.request('/notes', form({ title: 'Groceries', body: 'milk and eggs' }, cookie)))
94
- .status,
95
- 303,
96
- )
97
- assert.equal(
98
- (await app.request('/notes', form({ title: 'Ideas', body: 'a framework' }, cookie))).status,
99
- 303,
100
- )
101
-
102
- const list = await (await app.request('/notes', { headers: { cookie } })).text()
103
- assert.match(list, /Groceries/)
104
- assert.match(list, /Ideas/)
105
- const found = await (await app.request('/notes?q=eggs', { headers: { cookie } })).text()
106
- assert.match(found, /Groceries/)
107
- assert.doesNotMatch(found, /Ideas/)
108
- assert.match(
109
- await (await app.request('/notes?q=zzz', { headers: { cookie } })).text(),
110
- /No note matches/,
111
- )
112
-
113
- const edit = await app.request('/notes/1/edit', { headers: { cookie } })
114
- assert.match(await edit.text(), /milk and eggs/)
115
- const toolong = await app.request('/notes/1', form({ title: 'x'.repeat(81), body: '' }, cookie))
116
- assert.equal(toolong.status, 400)
117
- assert.match(await toolong.text(), /at most 80/)
118
- assert.equal(
119
- (await app.request('/notes/1', form({ title: 'Shopping', body: 'oat milk' }, cookie))).status,
120
- 303,
121
- )
122
- assert.match(await (await app.request('/notes', { headers: { cookie } })).text(), /Shopping/)
123
- assert.equal((await app.request('/notes/99', form({ title: 'x', body: '' }, cookie))).status, 404)
124
- assert.equal((await app.request('/notes/99/edit', { headers: { cookie } })).status, 404)
125
-
126
- assert.equal((await app.request('/notes/1/delete', form({}, cookie))).status, 303)
127
- assert.equal((await app.request('/notes/1/delete', form({}, cookie))).status, 404)
128
- assert.doesNotMatch(
129
- await (await app.request('/notes', { headers: { cookie } })).text(),
130
- /Shopping/,
131
- )
132
- })
133
-
134
- test("one user cannot read or change another user's notes", async () => {
135
- const app = createApp(await memoryDb())
136
- const alice = await signedUp(app, 'alice@example.com')
137
- const bob = await signedUp(app, 'bob@example.com')
138
- await app.request('/notes', form({ title: 'Secret', body: 'alice only' }, alice))
139
- assert.equal((await app.request('/notes/1/edit', { headers: { cookie: bob } })).status, 404)
140
- assert.equal((await app.request('/notes/1/delete', form({}, bob))).status, 404)
141
- assert.match(await (await app.request('/notes', { headers: { cookie: alice } })).text(), /Secret/)
142
- })
143
-
144
- test('the JSON API needs a session and validates input', async () => {
145
- const db = await memoryDb()
146
- const app = createApp(db)
147
- const cookie = await signedUp(app)
148
- const res = await app.request('/api/notes')
149
- assert.equal(res.status, 401)
150
- const bad = await app.request('/api/notes', {
151
- method: 'POST',
152
- headers: { cookie, 'content-type': 'application/json' },
153
- body: JSON.stringify({ title: '' }),
154
- })
155
- assert.equal(bad.status, 400)
156
- const body = (await bad.json()) as { issues: { message: string }[] }
157
- assert.match(body.issues[0]?.message ?? '', /title/)
158
- })
159
-
160
- test('the typed client covers every API route', async () => {
161
- const db = await memoryDb()
162
- const app = createApp(db)
163
- const cookie = await signedUp(app)
164
- const client = testClient(createApi(db))
165
- const as = { headers: { cookie } }
166
-
167
- const created = await client.index.$post({ json: { title: 'First', body: 'hello' } }, as)
168
- assert.equal(created.status, 201)
169
- const { note } = await created.json()
170
- assert.equal(note.title, 'First')
171
-
172
- const listed = await client.index.$get({ query: { q: 'hel' } }, as)
173
- assert.equal((await listed.json()).notes.length, 1)
174
-
175
- const got = await client[':id'].$get({ param: { id: String(note.id) } }, as)
176
- assert.equal(got.status, 200)
177
- const missing = await client[':id'].$get({ param: { id: '99' } }, as)
178
- assert.equal(missing.status, 404)
179
-
180
- const updated = await client[':id'].$put(
181
- { param: { id: String(note.id) }, json: { title: 'Renamed', body: '' } },
182
- as,
183
- )
184
- assert.equal(updated.status, 200)
185
-
186
- const gone = await client[':id'].$delete({ param: { id: String(note.id) } }, as)
187
- assert.equal(gone.status, 200)
188
- assert.equal((await client[':id'].$delete({ param: { id: String(note.id) } }, as)).status, 404)
189
- })
190
-
191
- test('csrf refuses a form POST from another site', async () => {
192
- const app = createApp(await memoryDb())
193
- const res = await app.request('/signup', {
194
- method: 'POST',
195
- body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
196
- headers: { origin: 'https://evil.example' },
197
- })
198
- assert.equal(res.status, 403)
199
- })
200
-
201
- test('the session cookie is Secure over HTTPS, and behind a proxy only when the proxy is trusted', async () => {
202
- const body = new URLSearchParams({ email: 'a@example.com', password: 'correct horse' })
203
- const flags = async (url: string, headers: Record<string, string>, trustProxy: boolean) => {
204
- const app = createApp(await memoryDb(), { trustProxy })
205
- const origin = new URL(url).origin
206
- const res = await app.request(url, { method: 'POST', body, headers: { origin, ...headers } })
207
- assert.equal(res.status, 303)
208
- return res.headers.get('set-cookie') ?? ''
209
- }
210
- assert.doesNotMatch(await flags('http://localhost/signup', {}, false), /Secure/i)
211
- assert.match(await flags('https://localhost/signup', {}, false), /Secure/i)
212
- const forwarded = { 'x-forwarded-proto': 'https' }
213
- assert.doesNotMatch(await flags('http://localhost/signup', forwarded, false), /Secure/i)
214
- assert.match(await flags('http://localhost/signup', forwarded, true), /Secure/i)
215
- })
216
-
217
- test('behind a proxy csrf accepts the public origin and still refuses others', async () => {
218
- const app = createApp(await memoryDb(), { publicOrigin: 'https://notes.example.com' })
219
- const post = (origin: string) =>
220
- app.request('/signup', {
221
- method: 'POST',
222
- body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
223
- headers: { origin },
224
- })
225
- assert.equal((await post('https://notes.example.com')).status, 303)
226
- assert.equal((await post('https://evil.example')).status, 403)
227
- })
228
-
229
- test('an error answers a plain 500 with no stack and no detail', async () => {
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 }
234
- const app = createApp(broken)
235
- const res = await app.request('/notes', { headers: { cookie: 'sid=anything' } })
236
- assert.equal(res.status, 500)
237
- assert.equal(await res.text(), 'Internal Server Error')
238
- })
239
-
240
- test('the note form loads the character counter, a client component compiled for the browser', async () => {
241
- const app = createApp(await memoryDb())
242
- const cookie = await signedUp(app)
243
- assert.match(
244
- await (await app.request('/notes/new', { headers: { cookie } })).text(),
245
- /src="\/client\/counter\.tsx"/,
246
- )
247
- const module = await app.request('/client/counter.tsx')
248
- assert.equal(module.status, 200)
249
- assert.match(module.headers.get('content-type') ?? '', /javascript/)
250
- assert.doesNotMatch(await module.text(), /<Count/)
251
- assert.equal((await app.request('/client/../src/db.ts')).status, 404)
252
- })