@yaks/workerd 0.0.0-stage → 0.2.36

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 (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +273 -2
  3. package/_dist/cache.d.ts +67 -0
  4. package/_dist/cache.d.ts.map +1 -0
  5. package/_dist/compose.d.ts +69 -0
  6. package/_dist/compose.d.ts.map +1 -0
  7. package/_dist/deferred.d.ts +10 -0
  8. package/_dist/deferred.d.ts.map +1 -0
  9. package/_dist/door.d.ts +36 -0
  10. package/_dist/door.d.ts.map +1 -0
  11. package/_dist/fetch.d.ts +27 -0
  12. package/_dist/fetch.d.ts.map +1 -0
  13. package/_dist/gen.d.ts +65 -0
  14. package/_dist/gen.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +53 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/plugin.d.ts +15 -0
  18. package/_dist/plugin.d.ts.map +1 -0
  19. package/_dist/purge.d.ts +104 -0
  20. package/_dist/purge.d.ts.map +1 -0
  21. package/_dist/rate.d.ts +65 -0
  22. package/_dist/rate.d.ts.map +1 -0
  23. package/_dist/stub.d.ts +20 -0
  24. package/_dist/stub.d.ts.map +1 -0
  25. package/_dist/upgrade.d.ts +25 -0
  26. package/_dist/upgrade.d.ts.map +1 -0
  27. package/_dist/version.d.ts +2 -0
  28. package/_dist/version.d.ts.map +1 -0
  29. package/_dist/worker.d.ts +40 -0
  30. package/_dist/worker.d.ts.map +1 -0
  31. package/cache.js +199 -0
  32. package/cache.js.map +1 -0
  33. package/cache.ts +254 -0
  34. package/compose.js +126 -0
  35. package/compose.js.map +1 -0
  36. package/compose.ts +236 -0
  37. package/deferred.js +39 -0
  38. package/deferred.js.map +1 -0
  39. package/deferred.ts +64 -0
  40. package/deno.json +1 -0
  41. package/door.js +64 -0
  42. package/door.js.map +1 -0
  43. package/door.ts +89 -0
  44. package/fetch.js +228 -0
  45. package/fetch.js.map +1 -0
  46. package/fetch.ts +231 -0
  47. package/gen.js +153 -0
  48. package/gen.js.map +1 -0
  49. package/gen.ts +189 -0
  50. package/mod.js +53 -0
  51. package/mod.js.map +1 -0
  52. package/mod.ts +69 -0
  53. package/package.json +52 -4
  54. package/plugin.js +16 -0
  55. package/plugin.js.map +1 -0
  56. package/plugin.ts +19 -0
  57. package/purge.js +200 -0
  58. package/purge.js.map +1 -0
  59. package/purge.ts +245 -0
  60. package/rate.js +84 -0
  61. package/rate.js.map +1 -0
  62. package/rate.ts +110 -0
  63. package/stub.js +23 -0
  64. package/stub.js.map +1 -0
  65. package/stub.ts +42 -0
  66. package/upgrade.js +82 -0
  67. package/upgrade.js.map +1 -0
  68. package/upgrade.ts +96 -0
  69. package/version.js +24 -0
  70. package/version.js.map +1 -0
  71. package/version.ts +30 -0
  72. package/worker.js +62 -0
  73. package/worker.js.map +1 -0
  74. package/worker.ts +87 -0
package/compose.ts ADDED
@@ -0,0 +1,236 @@
1
+ // A Worker made from a config: the plugins it names, each contributing a
2
+ // `./worker` facet, composed into the module's default export and the
3
+ // classes the runtime constructs by name. Exported as `@yaks/workerd/compose`
4
+ // as well, which imports nothing of @yaks/api but its route matching: a
5
+ // Worker's entry evaluates this module on every cold start.
6
+ //
7
+ // A Worker resolves no module at run time, so the facets arrive already
8
+ // imported, by plugin (gen.ts writes that module from the config). Each facet
9
+ // is small and eager; what it answers with loads on its first call, so a cold
10
+ // isolate evaluates only the code of whatever woke it.
11
+ //
12
+ // Bindings arrive with each call rather than at import, so every factory is
13
+ // handed the Worker's env, and a plugin's options are read from it the way a
14
+ // host reads them (@yaks/host/config `revealed`): `{"binding": "AI"}` is the
15
+ // binding, `{"secret": "KEY"}` the secret. What is built from one env is kept
16
+ // for as long as that env object is.
17
+ import { type Route, routed } from '@yaks/api/routed'
18
+ import { lazy } from '@yaks/fp'
19
+ import {
20
+ type Config,
21
+ given,
22
+ holding,
23
+ type Options,
24
+ revealed,
25
+ used,
26
+ } from '@yaks/host/config'
27
+ import { deferred, type Made } from './deferred.js'
28
+ import type { Context, Env } from './worker.ts'
29
+
30
+ /** The boundary every invocation enters: the Worker's own handlers, and each
31
+ * call of a class whose calls are {@link Deferred.entered}, given the state or
32
+ * context the runtime made it with, so a Durable Object's boundary can ask
33
+ * whether the runtime moved it. It runs `run` and answers what it answers; a
34
+ * tracker reports what escapes it. */
35
+ export type Entry = <T>(
36
+ env: Env,
37
+ name: string,
38
+ run: () => Promise<T>,
39
+ request?: Request,
40
+ state?: unknown,
41
+ ) => Promise<T>
42
+
43
+ /** A class the runtime constructs by its name (a Durable Object, an
44
+ * entrypoint), made at once and loaded on its first call. */
45
+ export type Deferred = {
46
+ /** the runtime's class it extends: `DurableObject` or `WorkerEntrypoint`
47
+ * from `cloudflare:workers`, or `Object` for one called only by `fetch`
48
+ * and the runtime's own callbacks */
49
+ base: abstract new (...args: never[]) => object
50
+ /** the methods it answers; each is the loaded object's own */
51
+ methods: readonly string[]
52
+ /** what makes the object, from the runtime's arguments: its state or
53
+ * context, and the env */
54
+ load: () => Promise<Made>
55
+ /** whether each call enters {@link Entry} as `<Name> <method>` */
56
+ entered?: boolean
57
+ }
58
+
59
+ /** A route a plugin adds to a Worker. Its answer may be `null`: the request
60
+ * is not its after all (a hostname it does not serve, a door it does not
61
+ * know), and the router asks the next route. */
62
+ export type WorkerRoute = Omit<Route, 'handle'> & {
63
+ handle: (request: Request) => Response | null | Promise<Response | null>
64
+ }
65
+
66
+ /** What a plugin puts around the routes from its own on: it is handed each
67
+ * request and `next`, which asks those routes, and answers what it decides.
68
+ * A wrap may hand `next` another request, or answer without asking it. */
69
+ export type Wrap = (
70
+ request: Request,
71
+ next: (request: Request) => Promise<Response>,
72
+ ) => Promise<Response>
73
+
74
+ /** A handler of the Worker's default export other than `fetch`: one letter
75
+ * Email Routing handed it, or one batch a queue delivered. */
76
+ export type Handling = (given: never, ctx: Context) => Promise<void>
77
+
78
+ /** `<plugin>/worker` — what a plugin adds to a Worker. Every field is
79
+ * optional. A factory is given the plugin's options, read from the env, and
80
+ * the env itself, for code that is not yet given its bindings as options. */
81
+ export type WorkerFacet = {
82
+ /** the classes it defines, by the name wrangler.toml binds */
83
+ classes?: Record<string, Deferred>
84
+ /** the paths it answers. The router asks each plugin in the config's
85
+ * order, and a request takes the first route that matches it and answers. */
86
+ routes?: (options: Options, env: Env) => WorkerRoute[]
87
+ /** what it puts around its own routes and every later plugin's */
88
+ wrap?: (options: Options, env: Env) => Wrap
89
+ /** the letters handed to the Worker; at most one plugin answers them */
90
+ email?: (options: Options, env: Env) => Handling
91
+ /** the batches a queue delivers; at most one plugin answers them */
92
+ queue?: (options: Options, env: Env) => Handling
93
+ /** the boundary every invocation enters; at most one plugin gives it */
94
+ entry?: () => Promise<Entry>
95
+ }
96
+
97
+ /** A Worker module: its default export, and its classes by name. */
98
+ export type Composed = {
99
+ default: {
100
+ fetch: (request: Request, env: Env, ctx?: Context) => Promise<Response>
101
+ email?: (message: unknown, env: Env, ctx: Context) => Promise<void>
102
+ queue?: (batch: unknown, env: Env, ctx: Context) => Promise<void>
103
+ }
104
+ classes: Record<string, new (...args: unknown[]) => object>
105
+ }
106
+
107
+ // Memoized per env object, retried after a failure.
108
+ let per = <T>(make: (env: Env) => T) => {
109
+ let held = new WeakMap<Env, T>()
110
+ return (env: Env) => {
111
+ if (!held.has(env)) held.set(env, make(env))
112
+ return held.get(env)!
113
+ }
114
+ }
115
+
116
+ // The one facet field at most one plugin may give.
117
+ let single = <K extends keyof WorkerFacet>(
118
+ named: [string, WorkerFacet][],
119
+ key: K,
120
+ ): [string, NonNullable<WorkerFacet[K]>] | undefined => {
121
+ let giving = named.filter(([, f]) => f[key])
122
+ if (giving.length > 1) {
123
+ throw new Error(
124
+ `${giving.map(([p]) => p).join(' and ')} both give a Worker its ${key}`,
125
+ )
126
+ }
127
+ let [one] = giving
128
+ return one && [one[0], one[1][key]!]
129
+ }
130
+
131
+ /**
132
+ * The Worker `config` names, from each plugin's `./worker` facet in `facets`.
133
+ *
134
+ * ```ts
135
+ * import { compose } from '@yaks/workerd'
136
+ * import { equal } from '@yaks/testing'
137
+ *
138
+ * let yak = compose({ plugins: ['hello'] }, {
139
+ * hello: {
140
+ * routes: () => [{
141
+ * method: 'GET',
142
+ * path: '/',
143
+ * handle: () => new Response('hello'),
144
+ * }],
145
+ * },
146
+ * })
147
+ * let res = await yak.default.fetch(new Request('https://x.test/'), {})
148
+ * equal(await res.text(), 'hello')
149
+ * ```
150
+ */
151
+ export let compose = (
152
+ config: Config,
153
+ facets: Record<string, WorkerFacet>,
154
+ ): Composed => {
155
+ let plugs = config.plugins ?? []
156
+ let named = plugs.map((plug): [string, WorkerFacet] => {
157
+ let facet = facets[used(plug)]
158
+ if (!facet) throw new Error(`no ./worker facet for ${used(plug)}`)
159
+ return [used(plug), facet]
160
+ })
161
+ let options = (plugin: string, env: Env) =>
162
+ revealed(
163
+ given(plugs.find((p) => used(p) == plugin)!),
164
+ holding(env),
165
+ ) as Options
166
+
167
+ let giving = single(named, 'entry')
168
+ let entering = giving && lazy(giving[1])
169
+ let entry: Entry = async (env, name, run, request, state) => {
170
+ if (!entering) return await run()
171
+ let enter = await entering()
172
+ return await enter(env, name, run, request, state)
173
+ }
174
+
175
+ let classes: Composed['classes'] = {}
176
+ for (let [plugin, facet] of named) {
177
+ for (let [name, c] of Object.entries(facet.classes ?? {})) {
178
+ if (classes[name]) throw new Error(`${plugin} defines ${name} again`)
179
+ classes[name] = deferred(
180
+ c.base,
181
+ c.load,
182
+ c.methods,
183
+ c.entered
184
+ ? (args, method, call, given) =>
185
+ entry(
186
+ args[1] as Env,
187
+ `${name} ${method}`,
188
+ call,
189
+ given.find((g): g is Request => g instanceof Request),
190
+ args[0],
191
+ )
192
+ : undefined,
193
+ )
194
+ }
195
+ }
196
+
197
+ // Each plugin's routes and wrap, from the last plugin's to the first, so
198
+ // that a request asks the plugins in the config's order and a wrap is
199
+ // around its own routes and every later plugin's.
200
+ let answer = per((env) =>
201
+ named.reduceRight<(request: Request) => Promise<Response>>(
202
+ (next, [plugin, f]) => {
203
+ let routes = f.routes?.(options(plugin, env), env) ?? []
204
+ let ask = async (request: Request) => {
205
+ let path = new URL(request.url).pathname
206
+ for (let route of routes) {
207
+ if (!routed(route as Route, request.method, path)) continue
208
+ let answered = await route.handle(request)
209
+ if (answered) return answered
210
+ }
211
+ return await next(request)
212
+ }
213
+ let wrap = f.wrap?.(options(plugin, env), env)
214
+ return wrap ? (request) => wrap(request, ask) : ask
215
+ },
216
+ () => Promise.resolve(new Response('Not found', { status: 404 })),
217
+ )
218
+ )
219
+ let fetch = (request: Request, env: Env) =>
220
+ entry(env, 'gateway fetch', () => answer(env)(request), request)
221
+
222
+ let handling = (key: 'email' | 'queue') => {
223
+ let one = single(named, key)
224
+ if (!one) return undefined
225
+ let [plugin, make] = one
226
+ let made = per((env) => make(options(plugin, env), env))
227
+ return (given: unknown, env: Env, ctx: Context) =>
228
+ entry(env, `gateway ${key}`, () => made(env)(given as never, ctx))
229
+ }
230
+ let email = handling('email'), queue = handling('queue')
231
+
232
+ return {
233
+ default: { fetch, ...email && { email }, ...queue && { queue } },
234
+ classes,
235
+ }
236
+ }
package/deferred.js ADDED
@@ -0,0 +1,39 @@
1
+ // A class the runtime constructs at once whose object is made on its first
2
+ // call, from a module loaded then. A module is evaluated when it is first
3
+ // imported, so an isolate that wakes one Durable Object evaluates that
4
+ // object's code and not the router's, and one that answers a page none of
5
+ // the object's own.
6
+ import { lazy } from "@yaks/fp";
7
+ /** `Base` with `methods`, each of which loads what `load` gives, makes one
8
+ * object with it from the constructor's arguments, and answers through it.
9
+ * A load that fails is tried again by the next call, and so is a factory
10
+ * that throws. `around`, when given, runs each call. */ export let deferred = (Base, load, methods, around)=>{
11
+ let loaded = lazy(load);
12
+ let args = new WeakMap();
13
+ let made = new WeakMap();
14
+ let Lazy = class extends Base {
15
+ constructor(...given){
16
+ super(...given);
17
+ args.set(this, given);
18
+ }
19
+ };
20
+ let object = (self)=>{
21
+ let held = made.get(self);
22
+ if (!held) {
23
+ held = loaded().then((make)=>make(...args.get(self)));
24
+ held.catch(()=>made.delete(self));
25
+ made.set(self, held);
26
+ }
27
+ return held;
28
+ };
29
+ for (let method of methods){
30
+ Object.defineProperty(Lazy.prototype, method, {
31
+ value (...given) {
32
+ let call = async ()=>(await object(this))[method](...given);
33
+ return around ? around(args.get(this), method, call, given) : call();
34
+ }
35
+ });
36
+ }
37
+ return Lazy;
38
+ };
39
+ //# sourceMappingURL=deferred.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferred.js","sources":["./deferred.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,0EAA0E;AAC1E,uEAAuE;AACvE,0EAA0E;AAC1E,oBAAoB;AAEpB,SAAS,IAAI,wBAA6B;AAkB1C;;;sDAGsD,GACtD,OAAO,IAAI,WAAW,CACpB,MACA,MACA,SACA;EAEA,IAAI,SAAS,KAAK;EAClB,IAAI,OAAO,IAAI;EACf,IAAI,OAAO,IAAI;EACf,IAAI,OAAO,cAAe;IACxB,YAAY,GAAG,KAAgB,CAAE;MAC/B,KAAK,IAAI;MACT,KAAK,GAAG,CAAC,IAAI,EAAE;IACjB;EACF;EACA,IAAI,SAAS,CAAC;IACZ,IAAI,OAAO,KAAK,GAAG,CAAC;IACpB,IAAI,CAAC,MAAM;MACT,OAAO,SAAS,IAAI,CAAC,CAAC,OACpB,AAAC,QAAwC,KAAK,GAAG,CAAC;MAEpD,KAAK,KAAK,CAAC,IAAM,KAAK,MAAM,CAAC;MAC7B,KAAK,GAAG,CAAC,MAAM;IACjB;IACA,OAAO;EACT;EACA,KAAK,IAAI,UAAU,QAAS;IAC1B,OAAO,cAAc,CAAC,KAAK,SAAS,EAAE,QAAQ;MAC5C,OAAoB,GAAG,KAAgB;QACrC,IAAI,OAAO,UAAY,CAAC,MAAM,OAAO,IAAI,CAAC,CAAC,CAAC,OAAO,IAAI;QACvD,OAAO,SAAS,OAAO,KAAK,GAAG,CAAC,IAAI,GAAI,QAAQ,MAAM,SAAS;MACjE;IACF;EACF;EACA,OAAO;AACT,EAAC"}
package/deferred.ts ADDED
@@ -0,0 +1,64 @@
1
+ // A class the runtime constructs at once whose object is made on its first
2
+ // call, from a module loaded then. A module is evaluated when it is first
3
+ // imported, so an isolate that wakes one Durable Object evaluates that
4
+ // object's code and not the router's, and one that answers a page none of
5
+ // the object's own.
6
+
7
+ import { lazy } from '@yaks/fp'
8
+
9
+ /** What makes the object a deferred class answers through, from the
10
+ * arguments the runtime constructed the class with (its state or context,
11
+ * and its bindings). A class is one: `(...args) => new C(...args)`. */
12
+ export type Made = (...args: never[]) => object
13
+
14
+ /** How each call is run: around the deferred object's own answer, given the
15
+ * constructor's arguments, the method's name and its arguments. */
16
+ export type Around = (
17
+ args: unknown[],
18
+ method: string,
19
+ call: () => Promise<unknown>,
20
+ given: unknown[],
21
+ ) => Promise<unknown>
22
+
23
+ type Answering = Record<string, (...args: unknown[]) => unknown>
24
+
25
+ /** `Base` with `methods`, each of which loads what `load` gives, makes one
26
+ * object with it from the constructor's arguments, and answers through it.
27
+ * A load that fails is tried again by the next call, and so is a factory
28
+ * that throws. `around`, when given, runs each call. */
29
+ export let deferred = (
30
+ Base: abstract new (...args: never[]) => object,
31
+ load: () => Promise<Made>,
32
+ methods: readonly string[],
33
+ around?: Around,
34
+ ): new (...args: unknown[]) => object => {
35
+ let loaded = lazy(load)
36
+ let args = new WeakMap<object, unknown[]>()
37
+ let made = new WeakMap<object, Promise<Answering>>()
38
+ let Lazy = class extends (Base as new (...args: unknown[]) => object) {
39
+ constructor(...given: unknown[]) {
40
+ super(...given)
41
+ args.set(this, given)
42
+ }
43
+ }
44
+ let object = (self: object) => {
45
+ let held = made.get(self)
46
+ if (!held) {
47
+ held = loaded().then((make) =>
48
+ (make as (...a: unknown[]) => object)(...args.get(self)!) as Answering
49
+ )
50
+ held.catch(() => made.delete(self))
51
+ made.set(self, held)
52
+ }
53
+ return held
54
+ }
55
+ for (let method of methods) {
56
+ Object.defineProperty(Lazy.prototype, method, {
57
+ value(this: object, ...given: unknown[]) {
58
+ let call = async () => (await object(this))[method](...given)
59
+ return around ? around(args.get(this)!, method, call, given) : call()
60
+ },
61
+ })
62
+ }
63
+ return Lazy
64
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"compilerOptions":{"lib":["dom","esnext"]},"publish":{"exclude":["**/*_test.ts","testing.ts","conform.ts","workers.json"]},"name":"@yaks/workerd","version":"0.2.36","license":"Apache-2.0","description":"Makes a Cloudflare Worker from a plugin config, and serves the graph API from one with WebSocket upgrades, request authentication, and forwarding to Durable Objects.","exports":{".":"./mod.ts","./compose":"./compose.ts","./worker":"./plugin.ts","./gen":"./gen.ts","./rate":"./rate.ts","./cache":"./cache.ts","./purge":"./purge.ts","./fetch":"./fetch.ts","./upgrade":"./upgrade.ts"},"imports":{"@yaks/workerd":"./mod.ts","@yaks/workerd/compose":"./compose.ts","@yaks/workerd/worker":"./plugin.ts","@yaks/workerd/gen":"./gen.ts","@yaks/workerd/rate":"./rate.ts","@yaks/workerd/cache":"./cache.ts","@yaks/workerd/purge":"./purge.ts","@yaks/workerd/fetch":"./fetch.ts","@yaks/workerd/upgrade":"./upgrade.ts"}}
package/door.js ADDED
@@ -0,0 +1,64 @@
1
+ // Who is making the request, on a Worker. @yaks/api asks the code serving it
2
+ // one question — which entity is making this request — and there are two ways
3
+ // a Worker carries the answer: a session cookie a browser sends on its own, and
4
+ // a bearer token a script sends deliberately.
5
+ //
6
+ // Reading the credential is all that belongs here. What a credential means
7
+ // depends on the application's own secret — a signed JWT, a KV lookup, a member
8
+ // row — so `verify` is supplied by the caller, and this package never sees a
9
+ // key.
10
+ import { Unauthorized } from "@yaks/api";
11
+ // A cookie value is usually percent-encoded, but nothing makes it so: a value
12
+ // that is not valid encoding is the value itself, not a thrown request.
13
+ let decoded = (value)=>{
14
+ try {
15
+ return decodeURIComponent(value);
16
+ } catch {
17
+ return value;
18
+ }
19
+ };
20
+ /** Every cookie on a request, by name. An absent or malformed header is an
21
+ * empty set, never a throw. */ export let cookies = (request)=>{
22
+ let out = {};
23
+ for (let part of (request.headers.get('cookie') ?? '').split(';')){
24
+ let at = part.indexOf('=');
25
+ let name = at < 0 ? '' : part.slice(0, at).trim();
26
+ if (!name) continue;
27
+ out[name] = decoded(part.slice(at + 1).trim());
28
+ }
29
+ return out;
30
+ };
31
+ /** The `authorization: Bearer …` token on a request, or null. The scheme is
32
+ * matched case-insensitively, as HTTP requires. */ export let bearer = (request)=>{
33
+ let header = request.headers.get('authorization') ?? '';
34
+ let [scheme, ...rest] = header.split(' ');
35
+ let token = rest.join(' ').trim();
36
+ return scheme.toLowerCase() == 'bearer' && token ? token : null;
37
+ };
38
+ /**
39
+ * Request authentication for a Worker: read the credential a request carries —
40
+ * the named cookie first, then a bearer token — and pass it to `verify`. The
41
+ * result is an
42
+ * {@link https://jsr.io/@yaks/api/doc/~/Authenticate | Authenticate} for
43
+ * `api()`, so it runs on reads, writes and socket upgrades alike.
44
+ *
45
+ * ```ts
46
+ * declare let memberFor: (token: string) => { by: string } | null
47
+ *
48
+ * let authenticate = door({
49
+ * cookie: 'shop_session',
50
+ * verify: (token) => memberFor(token),
51
+ * required: true,
52
+ * })
53
+ * ```
54
+ *
55
+ * With `required`, a request carrying no credential — or one `verify` rejects —
56
+ * gets a 401 response. Without it, the request is served and its writes are stored
57
+ * with no actor on them.
58
+ */ export let door = (o)=>async (request)=>{
59
+ let token = (o.cookie ? cookies(request)[o.cookie] : null) ?? bearer(request);
60
+ let who = token ? await o.verify(token, request) : null;
61
+ if (!who && o.required) throw new Unauthorized();
62
+ return who;
63
+ };
64
+ //# sourceMappingURL=door.js.map
package/door.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"door.js","sources":["./door.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,gFAAgF;AAChF,8CAA8C;AAC9C,EAAE;AACF,2EAA2E;AAC3E,gFAAgF;AAChF,6EAA6E;AAC7E,OAAO;AAGP,SAAS,YAAY,yBAA8B;AAGnD,8EAA8E;AAC9E,wEAAwE;AACxE,IAAI,UAAU,CAAC;EACb,IAAI;IACF,OAAO,mBAAmB;EAC5B,EAAE,OAAM;IACN,OAAO;EACT;AACF;AAEA;6BAC6B,GAC7B,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,MAA8B,CAAC;EACnC,KAAK,IAAI,QAAQ,CAAC,QAAQ,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,EAAE,KAAK,CAAC,KAAM;IACjE,IAAI,KAAK,KAAK,OAAO,CAAC;IACtB,IAAI,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC,GAAG,IAAI,IAAI;IAC/C,IAAI,CAAC,MAAM;IACX,GAAG,CAAC,KAAK,GAAG,QAAQ,KAAK,KAAK,CAAC,KAAK,GAAG,IAAI;EAC7C;EACA,OAAO;AACT,EAAC;AAED;iDACiD,GACjD,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,SAAS,QAAQ,OAAO,CAAC,GAAG,CAAC,oBAAoB;EACrD,IAAI,CAAC,QAAQ,GAAG,KAAK,GAAG,OAAO,KAAK,CAAC;EACrC,IAAI,QAAQ,KAAK,IAAI,CAAC,KAAK,IAAI;EAC/B,OAAO,OAAO,WAAW,MAAM,YAAY,QAAQ,QAAQ;AAC7D,EAAC;AAkBD;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,IAAI,OAAO,CAAC,IAA0B,OAAO;IAClD,IAAI,QAAQ,CAAC,EAAE,MAAM,GAAG,QAAQ,QAAQ,CAAC,EAAE,MAAM,CAAC,GAAG,IAAI,KAAK,OAAO;IACrE,IAAI,MAAM,QAAQ,MAAM,EAAE,MAAM,CAAC,OAAO,WAAW;IACnD,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI;IAClC,OAAO;EACT,EAAC"}
package/door.ts ADDED
@@ -0,0 +1,89 @@
1
+ // Who is making the request, on a Worker. @yaks/api asks the code serving it
2
+ // one question — which entity is making this request — and there are two ways
3
+ // a Worker carries the answer: a session cookie a browser sends on its own, and
4
+ // a bearer token a script sends deliberately.
5
+ //
6
+ // Reading the credential is all that belongs here. What a credential means
7
+ // depends on the application's own secret — a signed JWT, a KV lookup, a member
8
+ // row — so `verify` is supplied by the caller, and this package never sees a
9
+ // key.
10
+
11
+ import type { Authenticate } from '@yaks/api'
12
+ import { Unauthorized } from '@yaks/api'
13
+ import type { Actor } from 'jsr:@yaks/graph@0.2.36'
14
+
15
+ // A cookie value is usually percent-encoded, but nothing makes it so: a value
16
+ // that is not valid encoding is the value itself, not a thrown request.
17
+ let decoded = (value: string) => {
18
+ try {
19
+ return decodeURIComponent(value)
20
+ } catch {
21
+ return value
22
+ }
23
+ }
24
+
25
+ /** Every cookie on a request, by name. An absent or malformed header is an
26
+ * empty set, never a throw. */
27
+ export let cookies = (request: Request): Record<string, string> => {
28
+ let out: Record<string, string> = {}
29
+ for (let part of (request.headers.get('cookie') ?? '').split(';')) {
30
+ let at = part.indexOf('=')
31
+ let name = at < 0 ? '' : part.slice(0, at).trim()
32
+ if (!name) continue
33
+ out[name] = decoded(part.slice(at + 1).trim())
34
+ }
35
+ return out
36
+ }
37
+
38
+ /** The `authorization: Bearer …` token on a request, or null. The scheme is
39
+ * matched case-insensitively, as HTTP requires. */
40
+ export let bearer = (request: Request): string | null => {
41
+ let header = request.headers.get('authorization') ?? ''
42
+ let [scheme, ...rest] = header.split(' ')
43
+ let token = rest.join(' ').trim()
44
+ return scheme.toLowerCase() == 'bearer' && token ? token : null
45
+ }
46
+
47
+ /** How a Worker's authentication is configured. */
48
+ export type Door = {
49
+ /** turn a credential into the actor making the request — `by` whoever holds
50
+ * it, and `via` whatever it arrived through; `null` for a token this
51
+ * application does not accept */
52
+ verify: (
53
+ token: string,
54
+ request: Request,
55
+ ) => Actor | null | Promise<Actor | null>
56
+ /** the cookie a session token lives in (default: read only the bearer) */
57
+ cookie?: string
58
+ /** answer a request with no verified identity with a 401 (default: it is
59
+ * served, and its writes are stored unattributed) */
60
+ required?: boolean
61
+ }
62
+
63
+ /**
64
+ * Request authentication for a Worker: read the credential a request carries —
65
+ * the named cookie first, then a bearer token — and pass it to `verify`. The
66
+ * result is an
67
+ * {@link https://jsr.io/@yaks/api/doc/~/Authenticate | Authenticate} for
68
+ * `api()`, so it runs on reads, writes and socket upgrades alike.
69
+ *
70
+ * ```ts
71
+ * declare let memberFor: (token: string) => { by: string } | null
72
+ *
73
+ * let authenticate = door({
74
+ * cookie: 'shop_session',
75
+ * verify: (token) => memberFor(token),
76
+ * required: true,
77
+ * })
78
+ * ```
79
+ *
80
+ * With `required`, a request carrying no credential — or one `verify` rejects —
81
+ * gets a 401 response. Without it, the request is served and its writes are stored
82
+ * with no actor on them.
83
+ */
84
+ export let door = (o: Door): Authenticate => async (request) => {
85
+ let token = (o.cookie ? cookies(request)[o.cookie] : null) ?? bearer(request)
86
+ let who = token ? await o.verify(token, request) : null
87
+ if (!who && o.required) throw new Unauthorized()
88
+ return who
89
+ }