@ultimabase/auth 0.0.0-stage → 0.1.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.
package/src/token.ts ADDED
@@ -0,0 +1,47 @@
1
+ // Where a request carries its session token (D-112): the Bearer header, then
2
+ // the cookie, which auth sets and clears through a function's client (D-113).
3
+ import type { CookieOptions } from 'ultimabase'
4
+
5
+ /** The longest a browser keeps a cookie: 400 days. */
6
+ export const cookieAge: number = 400 * 24 * 60 * 60
7
+
8
+ /** The cookie's name and attributes, read once when the application starts. */
9
+ export interface Cookie {
10
+ readonly name: string
11
+ /** Its attributes but `maxAge`, the same to set and to clear it. */
12
+ readonly options: CookieOptions
13
+ }
14
+
15
+ /** Secure and `__Host-` in production, so it works on `http://localhost`. */
16
+ export function cookieOf(): Cookie {
17
+ const secure = process.env['NODE_ENV'] === 'production'
18
+ const name = secure ? '__Host-ultimabase_session' : 'ultimabase_session'
19
+ return {
20
+ name,
21
+ options: { httpOnly: true, sameSite: 'Lax', path: '/', secure },
22
+ }
23
+ }
24
+
25
+ /**
26
+ * The token the `Authorization` header sends, `''` for a Bearer without one,
27
+ * `undefined` without a Bearer header, which another plugin may read.
28
+ */
29
+ export function bearerOf(request: Request): string | undefined {
30
+ const header = request.headers.get('authorization')
31
+ const match = header === null ? null : /^bearer(?: +(.*))?$/i.exec(header)
32
+ if (match === null) return undefined
33
+ return match[1]?.trim() ?? ''
34
+ }
35
+
36
+ /** The token the cookie sends, if any. */
37
+ export function cookieTokenOf(
38
+ request: Request,
39
+ cookie: Cookie,
40
+ ): string | undefined {
41
+ const header = request.headers.get('cookie') ?? ''
42
+ for (const pair of header.split(';')) {
43
+ const [name, ...value] = pair.split('=')
44
+ if (name?.trim() === cookie.name) return value.join('=').trim()
45
+ }
46
+ return undefined
47
+ }