@cookiemunch/sdk 0.35.0 → 0.36.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/CHANGELOG.md +24 -0
- package/dist/chunk-UALQAYRN.js +19 -0
- package/dist/chunk-UALQAYRN.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rights/express.cjs +16 -8
- package/dist/rights/express.cjs.map +1 -1
- package/dist/rights/express.js +6 -9
- package/dist/rights/express.js.map +1 -1
- package/dist/rights/fastify.cjs +85 -0
- package/dist/rights/fastify.cjs.map +1 -0
- package/dist/rights/fastify.d.ts +47 -0
- package/dist/rights/fastify.js +48 -0
- package/dist/rights/fastify.js.map +1 -0
- package/dist/rights/shared.d.ts +3 -0
- package/dist/rights.cjs.map +1 -1
- package/dist/rights.d.ts +2 -1
- package/dist/rights.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/package.json +9 -1
package/dist/rights/express.cjs
CHANGED
|
@@ -24,7 +24,22 @@ __export(express_exports, {
|
|
|
24
24
|
expressRights: () => expressRights
|
|
25
25
|
});
|
|
26
26
|
module.exports = __toCommonJS(express_exports);
|
|
27
|
+
|
|
28
|
+
// src/rights/shared.ts
|
|
27
29
|
var OWNED = /\/(lookup|requests)(?:\/[^/]+(?:\/(cancel|run))?)?\/*$/;
|
|
30
|
+
function headersOf(raw) {
|
|
31
|
+
const headers = new Headers();
|
|
32
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
33
|
+
if (v === void 0) continue;
|
|
34
|
+
if (Array.isArray(v)) {
|
|
35
|
+
if (k.toLowerCase() === "set-cookie") for (const one of v) headers.append(k, one);
|
|
36
|
+
else headers.set(k, v.join(", "));
|
|
37
|
+
} else headers.set(k, v);
|
|
38
|
+
}
|
|
39
|
+
return headers;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/rights/express.ts
|
|
28
43
|
var RAW_BODY_REQUIRED = "@cookiemunch/sdk/rights/express: req.body was already parsed into an object and no raw bytes are available. Signatures verify over the bytes received, so the parsed body cannot be re-serialised. Keep the raw body on this route: express.raw({ type: 'application/json' }) before expressRights (and before any express.json() that covers it), a verify hook that sets req.rawBody, or in NestJS NestFactory.create(AppModule, { rawBody: true }).";
|
|
29
44
|
async function bodyOf(req) {
|
|
30
45
|
if (req.rawBody !== void 0) return req.rawBody;
|
|
@@ -54,14 +69,7 @@ function expressRights(handlers) {
|
|
|
54
69
|
if (!OWNED.test(url.pathname)) return next();
|
|
55
70
|
let response;
|
|
56
71
|
try {
|
|
57
|
-
const headers =
|
|
58
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
59
|
-
if (v === void 0) continue;
|
|
60
|
-
if (Array.isArray(v)) {
|
|
61
|
-
if (k.toLowerCase() === "set-cookie") for (const one of v) headers.append(k, one);
|
|
62
|
-
else headers.set(k, v.join(", "));
|
|
63
|
-
} else headers.set(k, v);
|
|
64
|
-
}
|
|
72
|
+
const headers = headersOf(req.headers);
|
|
65
73
|
const method = (req.method ?? "GET").toUpperCase();
|
|
66
74
|
const body = method === "GET" || method === "HEAD" ? void 0 : await bodyOf(req);
|
|
67
75
|
response = await handlers.fetch(new Request(url, { method, headers, ...body !== void 0 ? { body } : {} }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rights/express.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/express` — mount `createRightsHandlers` in Express, Connect or NestJS.\n *\n * import express from 'express';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { expressRights } from '@cookiemunch/sdk/rights/express';\n * const rights = createRightsHandlers({ key, idSecret, lookup, access, erase });\n * // Before any express.json(), or with express.raw() on this route: the handlers need the bytes as sent.\n * app.use('/privacy', express.raw({ type: 'application/json' }), expressRights(rights));\n *\n * NestJS (`NestFactory.create(AppModule, { rawBody: true })`, so `req.rawBody` holds the bytes):\n *\n * @Controller()\n * export class PrivacyController {\n * private readonly rights = expressRights(createRightsHandlers({ ... }));\n * @All('privacy/*')\n * handle(@Req() req: Request, @Res() res: Response) {\n * return this.rights(req, res, (err) => { if (err) throw err; res.status(404).end(); });\n * }\n * }\n *\n * The body passed on is the raw request bytes: `req.rawBody`, a Buffer `req.body` (express.raw), or the\n * stream read here when nothing consumed it. A `req.body` already parsed into an object is refused\n * (passed to `next(err)`), never re-serialised: signatures verify over the bytes received, and\n * `JSON.stringify` of a parsed body is not those bytes.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to `next()`, so the rest of the app answers\n * them as it answers any unknown path.\n */\nimport type { RightsHandlers } from '../rights.js';\n\n/** The parts of an Express / Connect / Node request this reads. */\nexport interface ExpressLikeRequest extends AsyncIterable<Uint8Array | string> {\n method?: string;\n url?: string;\n originalUrl?: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n get?(name: string): string | undefined;\n rawBody?: Uint8Array | string;\n body?: unknown;\n readableEnded?: boolean;\n socket?: { encrypted?: boolean };\n}\n\n/** The parts of an Express / Node response this writes. */\nexport interface ExpressLikeResponse {\n statusCode: number;\n setHeader(name: string, value: string | string[]): unknown;\n end(body?: Uint8Array): unknown;\n}\n\nexport type ExpressNext = (err?: unknown) => void;\n\
|
|
1
|
+
{"version":3,"sources":["../../src/rights/express.ts","../../src/rights/shared.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/express` — mount `createRightsHandlers` in Express, Connect or NestJS.\n *\n * import express from 'express';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { expressRights } from '@cookiemunch/sdk/rights/express';\n * const rights = createRightsHandlers({ key, idSecret, lookup, access, erase });\n * // Before any express.json(), or with express.raw() on this route: the handlers need the bytes as sent.\n * app.use('/privacy', express.raw({ type: 'application/json' }), expressRights(rights));\n *\n * NestJS (`NestFactory.create(AppModule, { rawBody: true })`, so `req.rawBody` holds the bytes):\n *\n * @Controller()\n * export class PrivacyController {\n * private readonly rights = expressRights(createRightsHandlers({ ... }));\n * @All('privacy/*')\n * handle(@Req() req: Request, @Res() res: Response) {\n * return this.rights(req, res, (err) => { if (err) throw err; res.status(404).end(); });\n * }\n * }\n *\n * The body passed on is the raw request bytes: `req.rawBody`, a Buffer `req.body` (express.raw), or the\n * stream read here when nothing consumed it. A `req.body` already parsed into an object is refused\n * (passed to `next(err)`), never re-serialised: signatures verify over the bytes received, and\n * `JSON.stringify` of a parsed body is not those bytes.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to `next()`, so the rest of the app answers\n * them as it answers any unknown path.\n */\nimport type { RightsHandlers } from '../rights.js';\nimport { OWNED, headersOf } from './shared.js';\n\n/** The parts of an Express / Connect / Node request this reads. */\nexport interface ExpressLikeRequest extends AsyncIterable<Uint8Array | string> {\n method?: string;\n url?: string;\n originalUrl?: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n get?(name: string): string | undefined;\n rawBody?: Uint8Array | string;\n body?: unknown;\n readableEnded?: boolean;\n socket?: { encrypted?: boolean };\n}\n\n/** The parts of an Express / Node response this writes. */\nexport interface ExpressLikeResponse {\n statusCode: number;\n setHeader(name: string, value: string | string[]): unknown;\n end(body?: Uint8Array): unknown;\n}\n\nexport type ExpressNext = (err?: unknown) => void;\n\nexport const RAW_BODY_REQUIRED =\n '@cookiemunch/sdk/rights/express: req.body was already parsed into an object and no raw bytes are available. '\n + 'Signatures verify over the bytes received, so the parsed body cannot be re-serialised. '\n + \"Keep the raw body on this route: express.raw({ type: 'application/json' }) before expressRights (and before any express.json() that covers it), \"\n + 'a verify hook that sets req.rawBody, or in NestJS NestFactory.create(AppModule, { rawBody: true }).';\n\nasync function bodyOf(req: ExpressLikeRequest): Promise<Uint8Array | string | undefined> {\n if (req.rawBody !== undefined) return req.rawBody;\n if (req.body instanceof Uint8Array || typeof req.body === 'string') return req.body;\n // body-parser sets `_body` once it has consumed the stream; `{}` on a request it skipped is not a parse.\n const consumed = (req as { _body?: boolean })._body === true || req.readableEnded === true;\n if (!consumed) {\n const parts: Uint8Array[] = [];\n for await (const c of req) parts.push(typeof c === 'string' ? new TextEncoder().encode(c) : c);\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let at = 0;\n for (const p of parts) (out.set(p, at), (at += p.length));\n return out;\n }\n if (req.body !== undefined && req.body !== null) throw new Error(RAW_BODY_REQUIRED);\n return undefined;\n}\n\n/** An Express / Connect middleware serving the handlers; resolves once the answer is written. */\nexport function expressRights(handlers: Pick<RightsHandlers, 'fetch'>) {\n return async (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNext): Promise<void> => {\n const host = req.get?.('host') ?? (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? 'localhost';\n const proto = req.protocol ?? (req.socket?.encrypted ? 'https' : 'http');\n let url: URL;\n try {\n url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`);\n } catch {\n return next();\n }\n if (!OWNED.test(url.pathname)) return next();\n\n let response: Response;\n try {\n const headers = headersOf(req.headers);\n const method = (req.method ?? 'GET').toUpperCase();\n const body = method === 'GET' || method === 'HEAD' ? undefined : await bodyOf(req);\n response = await handlers.fetch(new Request(url, { method, headers, ...(body !== undefined ? { body: body as BodyInit } : {}) }));\n } catch (err) {\n return next(err);\n }\n // No X-Version: the bare 404 a caller without the key gets. Let the app answer it like any other unknown path.\n if (response.status === 404 && !response.headers.has('x-version')) return next();\n\n res.statusCode = response.status;\n const cookies = response.headers.getSetCookie?.() ?? [];\n response.headers.forEach((v, k) => {\n if (k !== 'set-cookie') res.setHeader(k, v);\n });\n if (cookies.length) res.setHeader('set-cookie', cookies);\n res.end(new Uint8Array(await response.arrayBuffer()));\n };\n}\n","/** What the Node framework adapters share: which paths the handlers own, and Node headers as fetch Headers. */\n\n// The same tail createRightsHandlers routes on; anything else is not ours and is never read.\nexport const OWNED = /\\/(lookup|requests)(?:\\/[^/]+(?:\\/(cancel|run))?)?\\/*$/;\n\nexport function headersOf(raw: Record<string, string | string[] | undefined>): Headers {\n const headers = new Headers();\n for (const [k, v] of Object.entries(raw)) {\n if (v === undefined) continue;\n if (Array.isArray(v)) {\n if (k.toLowerCase() === 'set-cookie') for (const one of v) headers.append(k, one);\n else headers.set(k, v.join(', '));\n } else headers.set(k, v);\n }\n return headers;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,QAAQ;AAEd,SAAS,UAAU,KAA6D;AACrF,QAAM,UAAU,IAAI,QAAQ;AAC5B,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,GAAG,GAAG;AACxC,QAAI,MAAM,OAAW;AACrB,QAAI,MAAM,QAAQ,CAAC,GAAG;AACpB,UAAI,EAAE,YAAY,MAAM,aAAc,YAAW,OAAO,EAAG,SAAQ,OAAO,GAAG,GAAG;AAAA,UAC3E,SAAQ,IAAI,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,IAClC,MAAO,SAAQ,IAAI,GAAG,CAAC;AAAA,EACzB;AACA,SAAO;AACT;;;ADyCO,IAAM,oBACX;AAKF,eAAe,OAAO,KAAmE;AACvF,MAAI,IAAI,YAAY,OAAW,QAAO,IAAI;AAC1C,MAAI,IAAI,gBAAgB,cAAc,OAAO,IAAI,SAAS,SAAU,QAAO,IAAI;AAE/E,QAAM,WAAY,IAA4B,UAAU,QAAQ,IAAI,kBAAkB;AACtF,MAAI,CAAC,UAAU;AACb,UAAM,QAAsB,CAAC;AAC7B,qBAAiB,KAAK,IAAK,OAAM,KAAK,OAAO,MAAM,WAAW,IAAI,YAAY,EAAE,OAAO,CAAC,IAAI,CAAC;AAC7F,UAAM,MAAM,IAAI,WAAW,MAAM,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC,CAAC;AAClE,QAAI,KAAK;AACT,eAAW,KAAK,MAAO,CAAC,IAAI,IAAI,GAAG,EAAE,GAAI,MAAM,EAAE;AACjD,WAAO;AAAA,EACT;AACA,MAAI,IAAI,SAAS,UAAa,IAAI,SAAS,KAAM,OAAM,IAAI,MAAM,iBAAiB;AAClF,SAAO;AACT;AAGO,SAAS,cAAc,UAAyC;AACrE,SAAO,OAAO,KAAyB,KAA0B,SAAqC;AACpG,UAAM,OAAO,IAAI,MAAM,MAAM,MAAM,MAAM,QAAQ,IAAI,QAAQ,IAAI,IAAI,IAAI,QAAQ,KAAK,CAAC,IAAI,IAAI,QAAQ,SAAS;AAChH,UAAM,QAAQ,IAAI,aAAa,IAAI,QAAQ,YAAY,UAAU;AACjE,QAAI;AACJ,QAAI;AACF,YAAM,IAAI,IAAI,IAAI,eAAe,IAAI,OAAO,KAAK,GAAG,KAAK,MAAM,IAAI,EAAE;AAAA,IACvE,QAAQ;AACN,aAAO,KAAK;AAAA,IACd;AACA,QAAI,CAAC,MAAM,KAAK,IAAI,QAAQ,EAAG,QAAO,KAAK;AAE3C,QAAI;AACJ,QAAI;AACF,YAAM,UAAU,UAAU,IAAI,OAAO;AACrC,YAAM,UAAU,IAAI,UAAU,OAAO,YAAY;AACjD,YAAM,OAAO,WAAW,SAAS,WAAW,SAAS,SAAY,MAAM,OAAO,GAAG;AACjF,iBAAW,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK,EAAE,QAAQ,SAAS,GAAI,SAAS,SAAY,EAAE,KAAuB,IAAI,CAAC,EAAG,CAAC,CAAC;AAAA,IAClI,SAAS,KAAK;AACZ,aAAO,KAAK,GAAG;AAAA,IACjB;AAEA,QAAI,SAAS,WAAW,OAAO,CAAC,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAO,KAAK;AAE/E,QAAI,aAAa,SAAS;AAC1B,UAAM,UAAU,SAAS,QAAQ,eAAe,KAAK,CAAC;AACtD,aAAS,QAAQ,QAAQ,CAAC,GAAG,MAAM;AACjC,UAAI,MAAM,aAAc,KAAI,UAAU,GAAG,CAAC;AAAA,IAC5C,CAAC;AACD,QAAI,QAAQ,OAAQ,KAAI,UAAU,cAAc,OAAO;AACvD,QAAI,IAAI,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;AAAA,EACtD;AACF;","names":[]}
|
package/dist/rights/express.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OWNED,
|
|
3
|
+
headersOf
|
|
4
|
+
} from "../chunk-UALQAYRN.js";
|
|
5
|
+
|
|
1
6
|
// src/rights/express.ts
|
|
2
|
-
var OWNED = /\/(lookup|requests)(?:\/[^/]+(?:\/(cancel|run))?)?\/*$/;
|
|
3
7
|
var RAW_BODY_REQUIRED = "@cookiemunch/sdk/rights/express: req.body was already parsed into an object and no raw bytes are available. Signatures verify over the bytes received, so the parsed body cannot be re-serialised. Keep the raw body on this route: express.raw({ type: 'application/json' }) before expressRights (and before any express.json() that covers it), a verify hook that sets req.rawBody, or in NestJS NestFactory.create(AppModule, { rawBody: true }).";
|
|
4
8
|
async function bodyOf(req) {
|
|
5
9
|
if (req.rawBody !== void 0) return req.rawBody;
|
|
@@ -29,14 +33,7 @@ function expressRights(handlers) {
|
|
|
29
33
|
if (!OWNED.test(url.pathname)) return next();
|
|
30
34
|
let response;
|
|
31
35
|
try {
|
|
32
|
-
const headers =
|
|
33
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
34
|
-
if (v === void 0) continue;
|
|
35
|
-
if (Array.isArray(v)) {
|
|
36
|
-
if (k.toLowerCase() === "set-cookie") for (const one of v) headers.append(k, one);
|
|
37
|
-
else headers.set(k, v.join(", "));
|
|
38
|
-
} else headers.set(k, v);
|
|
39
|
-
}
|
|
36
|
+
const headers = headersOf(req.headers);
|
|
40
37
|
const method = (req.method ?? "GET").toUpperCase();
|
|
41
38
|
const body = method === "GET" || method === "HEAD" ? void 0 : await bodyOf(req);
|
|
42
39
|
response = await handlers.fetch(new Request(url, { method, headers, ...body !== void 0 ? { body } : {} }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rights/express.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/express` — mount `createRightsHandlers` in Express, Connect or NestJS.\n *\n * import express from 'express';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { expressRights } from '@cookiemunch/sdk/rights/express';\n * const rights = createRightsHandlers({ key, idSecret, lookup, access, erase });\n * // Before any express.json(), or with express.raw() on this route: the handlers need the bytes as sent.\n * app.use('/privacy', express.raw({ type: 'application/json' }), expressRights(rights));\n *\n * NestJS (`NestFactory.create(AppModule, { rawBody: true })`, so `req.rawBody` holds the bytes):\n *\n * @Controller()\n * export class PrivacyController {\n * private readonly rights = expressRights(createRightsHandlers({ ... }));\n * @All('privacy/*')\n * handle(@Req() req: Request, @Res() res: Response) {\n * return this.rights(req, res, (err) => { if (err) throw err; res.status(404).end(); });\n * }\n * }\n *\n * The body passed on is the raw request bytes: `req.rawBody`, a Buffer `req.body` (express.raw), or the\n * stream read here when nothing consumed it. A `req.body` already parsed into an object is refused\n * (passed to `next(err)`), never re-serialised: signatures verify over the bytes received, and\n * `JSON.stringify` of a parsed body is not those bytes.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to `next()`, so the rest of the app answers\n * them as it answers any unknown path.\n */\nimport type { RightsHandlers } from '../rights.js';\n\n/** The parts of an Express / Connect / Node request this reads. */\nexport interface ExpressLikeRequest extends AsyncIterable<Uint8Array | string> {\n method?: string;\n url?: string;\n originalUrl?: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n get?(name: string): string | undefined;\n rawBody?: Uint8Array | string;\n body?: unknown;\n readableEnded?: boolean;\n socket?: { encrypted?: boolean };\n}\n\n/** The parts of an Express / Node response this writes. */\nexport interface ExpressLikeResponse {\n statusCode: number;\n setHeader(name: string, value: string | string[]): unknown;\n end(body?: Uint8Array): unknown;\n}\n\nexport type ExpressNext = (err?: unknown) => void;\n\
|
|
1
|
+
{"version":3,"sources":["../../src/rights/express.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/express` — mount `createRightsHandlers` in Express, Connect or NestJS.\n *\n * import express from 'express';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { expressRights } from '@cookiemunch/sdk/rights/express';\n * const rights = createRightsHandlers({ key, idSecret, lookup, access, erase });\n * // Before any express.json(), or with express.raw() on this route: the handlers need the bytes as sent.\n * app.use('/privacy', express.raw({ type: 'application/json' }), expressRights(rights));\n *\n * NestJS (`NestFactory.create(AppModule, { rawBody: true })`, so `req.rawBody` holds the bytes):\n *\n * @Controller()\n * export class PrivacyController {\n * private readonly rights = expressRights(createRightsHandlers({ ... }));\n * @All('privacy/*')\n * handle(@Req() req: Request, @Res() res: Response) {\n * return this.rights(req, res, (err) => { if (err) throw err; res.status(404).end(); });\n * }\n * }\n *\n * The body passed on is the raw request bytes: `req.rawBody`, a Buffer `req.body` (express.raw), or the\n * stream read here when nothing consumed it. A `req.body` already parsed into an object is refused\n * (passed to `next(err)`), never re-serialised: signatures verify over the bytes received, and\n * `JSON.stringify` of a parsed body is not those bytes.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to `next()`, so the rest of the app answers\n * them as it answers any unknown path.\n */\nimport type { RightsHandlers } from '../rights.js';\nimport { OWNED, headersOf } from './shared.js';\n\n/** The parts of an Express / Connect / Node request this reads. */\nexport interface ExpressLikeRequest extends AsyncIterable<Uint8Array | string> {\n method?: string;\n url?: string;\n originalUrl?: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n get?(name: string): string | undefined;\n rawBody?: Uint8Array | string;\n body?: unknown;\n readableEnded?: boolean;\n socket?: { encrypted?: boolean };\n}\n\n/** The parts of an Express / Node response this writes. */\nexport interface ExpressLikeResponse {\n statusCode: number;\n setHeader(name: string, value: string | string[]): unknown;\n end(body?: Uint8Array): unknown;\n}\n\nexport type ExpressNext = (err?: unknown) => void;\n\nexport const RAW_BODY_REQUIRED =\n '@cookiemunch/sdk/rights/express: req.body was already parsed into an object and no raw bytes are available. '\n + 'Signatures verify over the bytes received, so the parsed body cannot be re-serialised. '\n + \"Keep the raw body on this route: express.raw({ type: 'application/json' }) before expressRights (and before any express.json() that covers it), \"\n + 'a verify hook that sets req.rawBody, or in NestJS NestFactory.create(AppModule, { rawBody: true }).';\n\nasync function bodyOf(req: ExpressLikeRequest): Promise<Uint8Array | string | undefined> {\n if (req.rawBody !== undefined) return req.rawBody;\n if (req.body instanceof Uint8Array || typeof req.body === 'string') return req.body;\n // body-parser sets `_body` once it has consumed the stream; `{}` on a request it skipped is not a parse.\n const consumed = (req as { _body?: boolean })._body === true || req.readableEnded === true;\n if (!consumed) {\n const parts: Uint8Array[] = [];\n for await (const c of req) parts.push(typeof c === 'string' ? new TextEncoder().encode(c) : c);\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let at = 0;\n for (const p of parts) (out.set(p, at), (at += p.length));\n return out;\n }\n if (req.body !== undefined && req.body !== null) throw new Error(RAW_BODY_REQUIRED);\n return undefined;\n}\n\n/** An Express / Connect middleware serving the handlers; resolves once the answer is written. */\nexport function expressRights(handlers: Pick<RightsHandlers, 'fetch'>) {\n return async (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNext): Promise<void> => {\n const host = req.get?.('host') ?? (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? 'localhost';\n const proto = req.protocol ?? (req.socket?.encrypted ? 'https' : 'http');\n let url: URL;\n try {\n url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`);\n } catch {\n return next();\n }\n if (!OWNED.test(url.pathname)) return next();\n\n let response: Response;\n try {\n const headers = headersOf(req.headers);\n const method = (req.method ?? 'GET').toUpperCase();\n const body = method === 'GET' || method === 'HEAD' ? undefined : await bodyOf(req);\n response = await handlers.fetch(new Request(url, { method, headers, ...(body !== undefined ? { body: body as BodyInit } : {}) }));\n } catch (err) {\n return next(err);\n }\n // No X-Version: the bare 404 a caller without the key gets. Let the app answer it like any other unknown path.\n if (response.status === 404 && !response.headers.has('x-version')) return next();\n\n res.statusCode = response.status;\n const cookies = response.headers.getSetCookie?.() ?? [];\n response.headers.forEach((v, k) => {\n if (k !== 'set-cookie') res.setHeader(k, v);\n });\n if (cookies.length) res.setHeader('set-cookie', cookies);\n res.end(new Uint8Array(await response.arrayBuffer()));\n };\n}\n"],"mappings":";;;;;;AAwDO,IAAM,oBACX;AAKF,eAAe,OAAO,KAAmE;AACvF,MAAI,IAAI,YAAY,OAAW,QAAO,IAAI;AAC1C,MAAI,IAAI,gBAAgB,cAAc,OAAO,IAAI,SAAS,SAAU,QAAO,IAAI;AAE/E,QAAM,WAAY,IAA4B,UAAU,QAAQ,IAAI,kBAAkB;AACtF,MAAI,CAAC,UAAU;AACb,UAAM,QAAsB,CAAC;AAC7B,qBAAiB,KAAK,IAAK,OAAM,KAAK,OAAO,MAAM,WAAW,IAAI,YAAY,EAAE,OAAO,CAAC,IAAI,CAAC;AAC7F,UAAM,MAAM,IAAI,WAAW,MAAM,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC,CAAC;AAClE,QAAI,KAAK;AACT,eAAW,KAAK,MAAO,CAAC,IAAI,IAAI,GAAG,EAAE,GAAI,MAAM,EAAE;AACjD,WAAO;AAAA,EACT;AACA,MAAI,IAAI,SAAS,UAAa,IAAI,SAAS,KAAM,OAAM,IAAI,MAAM,iBAAiB;AAClF,SAAO;AACT;AAGO,SAAS,cAAc,UAAyC;AACrE,SAAO,OAAO,KAAyB,KAA0B,SAAqC;AACpG,UAAM,OAAO,IAAI,MAAM,MAAM,MAAM,MAAM,QAAQ,IAAI,QAAQ,IAAI,IAAI,IAAI,QAAQ,KAAK,CAAC,IAAI,IAAI,QAAQ,SAAS;AAChH,UAAM,QAAQ,IAAI,aAAa,IAAI,QAAQ,YAAY,UAAU;AACjE,QAAI;AACJ,QAAI;AACF,YAAM,IAAI,IAAI,IAAI,eAAe,IAAI,OAAO,KAAK,GAAG,KAAK,MAAM,IAAI,EAAE;AAAA,IACvE,QAAQ;AACN,aAAO,KAAK;AAAA,IACd;AACA,QAAI,CAAC,MAAM,KAAK,IAAI,QAAQ,EAAG,QAAO,KAAK;AAE3C,QAAI;AACJ,QAAI;AACF,YAAM,UAAU,UAAU,IAAI,OAAO;AACrC,YAAM,UAAU,IAAI,UAAU,OAAO,YAAY;AACjD,YAAM,OAAO,WAAW,SAAS,WAAW,SAAS,SAAY,MAAM,OAAO,GAAG;AACjF,iBAAW,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK,EAAE,QAAQ,SAAS,GAAI,SAAS,SAAY,EAAE,KAAuB,IAAI,CAAC,EAAG,CAAC,CAAC;AAAA,IAClI,SAAS,KAAK;AACZ,aAAO,KAAK,GAAG;AAAA,IACjB;AAEA,QAAI,SAAS,WAAW,OAAO,CAAC,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAO,KAAK;AAE/E,QAAI,aAAa,SAAS;AAC1B,UAAM,UAAU,SAAS,QAAQ,eAAe,KAAK,CAAC;AACtD,aAAS,QAAQ,QAAQ,CAAC,GAAG,MAAM;AACjC,UAAI,MAAM,aAAc,KAAI,UAAU,GAAG,CAAC;AAAA,IAC5C,CAAC;AACD,QAAI,QAAQ,OAAQ,KAAI,UAAU,cAAc,OAAO;AACvD,QAAI,IAAI,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;AAAA,EACtD;AACF;","names":[]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/rights/fastify.ts
|
|
21
|
+
var fastify_exports = {};
|
|
22
|
+
__export(fastify_exports, {
|
|
23
|
+
RAW_BODY_REQUIRED: () => RAW_BODY_REQUIRED,
|
|
24
|
+
fastifyRights: () => fastifyRights
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
27
|
+
|
|
28
|
+
// src/rights/shared.ts
|
|
29
|
+
var OWNED = /\/(lookup|requests)(?:\/[^/]+(?:\/(cancel|run))?)?\/*$/;
|
|
30
|
+
function headersOf(raw) {
|
|
31
|
+
const headers = new Headers();
|
|
32
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
33
|
+
if (v === void 0) continue;
|
|
34
|
+
if (Array.isArray(v)) {
|
|
35
|
+
if (k.toLowerCase() === "set-cookie") for (const one of v) headers.append(k, one);
|
|
36
|
+
else headers.set(k, v.join(", "));
|
|
37
|
+
} else headers.set(k, v);
|
|
38
|
+
}
|
|
39
|
+
return headers;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/rights/fastify.ts
|
|
43
|
+
var RAW_BODY_REQUIRED = "@cookiemunch/sdk/rights/fastify: the request body reached the handler already parsed. Signatures verify over the bytes received, so it cannot be re-serialised. Register fastifyRights(...) directly with app.register (not through fastify-plugin), so its raw-body parser applies.";
|
|
44
|
+
function fastifyRights(handlers) {
|
|
45
|
+
return async function cookieMunchRights(app) {
|
|
46
|
+
app.removeAllContentTypeParsers();
|
|
47
|
+
app.addContentTypeParser("*", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
|
|
48
|
+
app.route({
|
|
49
|
+
method: ["GET", "POST", "PUT", "PATCH", "DELETE"],
|
|
50
|
+
url: "/*",
|
|
51
|
+
handler: async (req, reply) => {
|
|
52
|
+
const host = (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? "localhost";
|
|
53
|
+
let url;
|
|
54
|
+
try {
|
|
55
|
+
url = new URL(req.url, `${req.protocol ?? "http"}://${host}`);
|
|
56
|
+
} catch {
|
|
57
|
+
return reply.callNotFound();
|
|
58
|
+
}
|
|
59
|
+
if (!OWNED.test(url.pathname)) return reply.callNotFound();
|
|
60
|
+
const body = req.body;
|
|
61
|
+
if (body !== void 0 && body !== null && !(body instanceof Uint8Array) && typeof body !== "string") throw new Error(RAW_BODY_REQUIRED);
|
|
62
|
+
const method = req.method.toUpperCase();
|
|
63
|
+
const response = await handlers.fetch(new Request(url, {
|
|
64
|
+
method,
|
|
65
|
+
headers: headersOf(req.headers),
|
|
66
|
+
...method !== "GET" && body != null ? { body } : {}
|
|
67
|
+
}));
|
|
68
|
+
if (response.status === 404 && !response.headers.has("x-version")) return reply.callNotFound();
|
|
69
|
+
reply.code(response.status);
|
|
70
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
71
|
+
response.headers.forEach((v, k) => {
|
|
72
|
+
if (k !== "set-cookie") reply.header(k, v);
|
|
73
|
+
});
|
|
74
|
+
if (cookies.length) reply.header("set-cookie", cookies);
|
|
75
|
+
return reply.send(new Uint8Array(await response.arrayBuffer()));
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
81
|
+
0 && (module.exports = {
|
|
82
|
+
RAW_BODY_REQUIRED,
|
|
83
|
+
fastifyRights
|
|
84
|
+
});
|
|
85
|
+
//# sourceMappingURL=fastify.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/rights/fastify.ts","../../src/rights/shared.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/fastify` — mount `createRightsHandlers` in Fastify (v4 or v5).\n *\n * import Fastify from 'fastify';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { fastifyRights } from '@cookiemunch/sdk/rights/fastify';\n * const app = Fastify();\n * app.register(fastifyRights(createRightsHandlers({ key, idSecret, lookup, access, erase })), { prefix: '/privacy' });\n *\n * The plugin is encapsulated (it is not wrapped in fastify-plugin, and must not be): inside it, every\n * content type is read as the raw bytes, because signatures verify over the bytes received and Fastify's\n * JSON parser would hand the handlers an object. The rest of the app keeps its own parsers.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to the app's not-found handler.\n */\nimport type { RightsHandlers } from '../rights.js';\nimport { OWNED, headersOf } from './shared.js';\n\n/** The parts of a Fastify request this reads. */\nexport interface FastifyLikeRequest {\n method: string;\n url: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n}\n\n/** The parts of a Fastify reply this writes. */\nexport interface FastifyLikeReply {\n code(status: number): FastifyLikeReply;\n header(name: string, value: string | string[]): FastifyLikeReply;\n send(body?: Uint8Array): unknown;\n callNotFound(): void;\n}\n\n/** The parts of a Fastify instance the plugin uses. */\nexport interface FastifyLikeInstance {\n removeAllContentTypeParsers(): void;\n addContentTypeParser(type: string, opts: { parseAs: 'buffer' }, parser: (req: unknown, body: Uint8Array, done: (err: Error | null, body?: Uint8Array) => void) => void): void;\n route(opts: { method: string[]; url: string; handler: (req: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<unknown> }): unknown;\n}\n\nexport const RAW_BODY_REQUIRED =\n '@cookiemunch/sdk/rights/fastify: the request body reached the handler already parsed. '\n + 'Signatures verify over the bytes received, so it cannot be re-serialised. '\n + 'Register fastifyRights(...) directly with app.register (not through fastify-plugin), so its raw-body parser applies.';\n\n/** A Fastify plugin serving the handlers. */\nexport function fastifyRights(handlers: Pick<RightsHandlers, 'fetch'>) {\n return async function cookieMunchRights(app: FastifyLikeInstance): Promise<void> {\n app.removeAllContentTypeParsers();\n app.addContentTypeParser('*', { parseAs: 'buffer' }, (_req, body, done) => done(null, body));\n app.route({\n method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],\n url: '/*',\n handler: async (req, reply) => {\n const host = (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? 'localhost';\n let url: URL;\n try {\n url = new URL(req.url, `${req.protocol ?? 'http'}://${host}`);\n } catch {\n return reply.callNotFound();\n }\n if (!OWNED.test(url.pathname)) return reply.callNotFound();\n const body = req.body;\n if (body !== undefined && body !== null && !(body instanceof Uint8Array) && typeof body !== 'string') throw new Error(RAW_BODY_REQUIRED);\n const method = req.method.toUpperCase();\n const response = await handlers.fetch(new Request(url, {\n method,\n headers: headersOf(req.headers),\n ...(method !== 'GET' && body != null ? { body: body as BodyInit } : {}),\n }));\n // No X-Version: the bare 404 a caller without the key gets. Let the app answer it like any other unknown path.\n if (response.status === 404 && !response.headers.has('x-version')) return reply.callNotFound();\n reply.code(response.status);\n const cookies = response.headers.getSetCookie?.() ?? [];\n response.headers.forEach((v, k) => {\n if (k !== 'set-cookie') reply.header(k, v);\n });\n if (cookies.length) reply.header('set-cookie', cookies);\n return reply.send(new Uint8Array(await response.arrayBuffer()));\n },\n });\n };\n}\n","/** What the Node framework adapters share: which paths the handlers own, and Node headers as fetch Headers. */\n\n// The same tail createRightsHandlers routes on; anything else is not ours and is never read.\nexport const OWNED = /\\/(lookup|requests)(?:\\/[^/]+(?:\\/(cancel|run))?)?\\/*$/;\n\nexport function headersOf(raw: Record<string, string | string[] | undefined>): Headers {\n const headers = new Headers();\n for (const [k, v] of Object.entries(raw)) {\n if (v === undefined) continue;\n if (Array.isArray(v)) {\n if (k.toLowerCase() === 'set-cookie') for (const one of v) headers.append(k, one);\n else headers.set(k, v.join(', '));\n } else headers.set(k, v);\n }\n return headers;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,QAAQ;AAEd,SAAS,UAAU,KAA6D;AACrF,QAAM,UAAU,IAAI,QAAQ;AAC5B,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,GAAG,GAAG;AACxC,QAAI,MAAM,OAAW;AACrB,QAAI,MAAM,QAAQ,CAAC,GAAG;AACpB,UAAI,EAAE,YAAY,MAAM,aAAc,YAAW,OAAO,EAAG,SAAQ,OAAO,GAAG,GAAG;AAAA,UAC3E,SAAQ,IAAI,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,IAClC,MAAO,SAAQ,IAAI,GAAG,CAAC;AAAA,EACzB;AACA,SAAO;AACT;;;AD4BO,IAAM,oBACX;AAKK,SAAS,cAAc,UAAyC;AACrE,SAAO,eAAe,kBAAkB,KAAyC;AAC/E,QAAI,4BAA4B;AAChC,QAAI,qBAAqB,KAAK,EAAE,SAAS,SAAS,GAAG,CAAC,MAAM,MAAM,SAAS,KAAK,MAAM,IAAI,CAAC;AAC3F,QAAI,MAAM;AAAA,MACR,QAAQ,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ;AAAA,MAChD,KAAK;AAAA,MACL,SAAS,OAAO,KAAK,UAAU;AAC7B,cAAM,QAAQ,MAAM,QAAQ,IAAI,QAAQ,IAAI,IAAI,IAAI,QAAQ,KAAK,CAAC,IAAI,IAAI,QAAQ,SAAS;AAC3F,YAAI;AACJ,YAAI;AACF,gBAAM,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI,YAAY,MAAM,MAAM,IAAI,EAAE;AAAA,QAC9D,QAAQ;AACN,iBAAO,MAAM,aAAa;AAAA,QAC5B;AACA,YAAI,CAAC,MAAM,KAAK,IAAI,QAAQ,EAAG,QAAO,MAAM,aAAa;AACzD,cAAM,OAAO,IAAI;AACjB,YAAI,SAAS,UAAa,SAAS,QAAQ,EAAE,gBAAgB,eAAe,OAAO,SAAS,SAAU,OAAM,IAAI,MAAM,iBAAiB;AACvI,cAAM,SAAS,IAAI,OAAO,YAAY;AACtC,cAAM,WAAW,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK;AAAA,UACrD;AAAA,UACA,SAAS,UAAU,IAAI,OAAO;AAAA,UAC9B,GAAI,WAAW,SAAS,QAAQ,OAAO,EAAE,KAAuB,IAAI,CAAC;AAAA,QACvE,CAAC,CAAC;AAEF,YAAI,SAAS,WAAW,OAAO,CAAC,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAO,MAAM,aAAa;AAC7F,cAAM,KAAK,SAAS,MAAM;AAC1B,cAAM,UAAU,SAAS,QAAQ,eAAe,KAAK,CAAC;AACtD,iBAAS,QAAQ,QAAQ,CAAC,GAAG,MAAM;AACjC,cAAI,MAAM,aAAc,OAAM,OAAO,GAAG,CAAC;AAAA,QAC3C,CAAC;AACD,YAAI,QAAQ,OAAQ,OAAM,OAAO,cAAc,OAAO;AACtD,eAAO,MAAM,KAAK,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;AAAA,MAChE;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@cookiemunch/sdk/rights/fastify` — mount `createRightsHandlers` in Fastify (v4 or v5).
|
|
3
|
+
*
|
|
4
|
+
* import Fastify from 'fastify';
|
|
5
|
+
* import { createRightsHandlers } from '@cookiemunch/sdk/rights';
|
|
6
|
+
* import { fastifyRights } from '@cookiemunch/sdk/rights/fastify';
|
|
7
|
+
* const app = Fastify();
|
|
8
|
+
* app.register(fastifyRights(createRightsHandlers({ key, idSecret, lookup, access, erase })), { prefix: '/privacy' });
|
|
9
|
+
*
|
|
10
|
+
* The plugin is encapsulated (it is not wrapped in fastify-plugin, and must not be): inside it, every
|
|
11
|
+
* content type is read as the raw bytes, because signatures verify over the bytes received and Fastify's
|
|
12
|
+
* JSON parser would hand the handlers an object. The rest of the app keeps its own parsers.
|
|
13
|
+
*
|
|
14
|
+
* A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),
|
|
15
|
+
* and the bare 404 answered to a caller without the key, go to the app's not-found handler.
|
|
16
|
+
*/
|
|
17
|
+
import type { RightsHandlers } from '../rights.js';
|
|
18
|
+
/** The parts of a Fastify request this reads. */
|
|
19
|
+
export interface FastifyLikeRequest {
|
|
20
|
+
method: string;
|
|
21
|
+
url: string;
|
|
22
|
+
protocol?: string;
|
|
23
|
+
headers: Record<string, string | string[] | undefined>;
|
|
24
|
+
body?: unknown;
|
|
25
|
+
}
|
|
26
|
+
/** The parts of a Fastify reply this writes. */
|
|
27
|
+
export interface FastifyLikeReply {
|
|
28
|
+
code(status: number): FastifyLikeReply;
|
|
29
|
+
header(name: string, value: string | string[]): FastifyLikeReply;
|
|
30
|
+
send(body?: Uint8Array): unknown;
|
|
31
|
+
callNotFound(): void;
|
|
32
|
+
}
|
|
33
|
+
/** The parts of a Fastify instance the plugin uses. */
|
|
34
|
+
export interface FastifyLikeInstance {
|
|
35
|
+
removeAllContentTypeParsers(): void;
|
|
36
|
+
addContentTypeParser(type: string, opts: {
|
|
37
|
+
parseAs: 'buffer';
|
|
38
|
+
}, parser: (req: unknown, body: Uint8Array, done: (err: Error | null, body?: Uint8Array) => void) => void): void;
|
|
39
|
+
route(opts: {
|
|
40
|
+
method: string[];
|
|
41
|
+
url: string;
|
|
42
|
+
handler: (req: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<unknown>;
|
|
43
|
+
}): unknown;
|
|
44
|
+
}
|
|
45
|
+
export declare const RAW_BODY_REQUIRED: string;
|
|
46
|
+
/** A Fastify plugin serving the handlers. */
|
|
47
|
+
export declare function fastifyRights(handlers: Pick<RightsHandlers, 'fetch'>): (app: FastifyLikeInstance) => Promise<void>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OWNED,
|
|
3
|
+
headersOf
|
|
4
|
+
} from "../chunk-UALQAYRN.js";
|
|
5
|
+
|
|
6
|
+
// src/rights/fastify.ts
|
|
7
|
+
var RAW_BODY_REQUIRED = "@cookiemunch/sdk/rights/fastify: the request body reached the handler already parsed. Signatures verify over the bytes received, so it cannot be re-serialised. Register fastifyRights(...) directly with app.register (not through fastify-plugin), so its raw-body parser applies.";
|
|
8
|
+
function fastifyRights(handlers) {
|
|
9
|
+
return async function cookieMunchRights(app) {
|
|
10
|
+
app.removeAllContentTypeParsers();
|
|
11
|
+
app.addContentTypeParser("*", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
|
|
12
|
+
app.route({
|
|
13
|
+
method: ["GET", "POST", "PUT", "PATCH", "DELETE"],
|
|
14
|
+
url: "/*",
|
|
15
|
+
handler: async (req, reply) => {
|
|
16
|
+
const host = (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? "localhost";
|
|
17
|
+
let url;
|
|
18
|
+
try {
|
|
19
|
+
url = new URL(req.url, `${req.protocol ?? "http"}://${host}`);
|
|
20
|
+
} catch {
|
|
21
|
+
return reply.callNotFound();
|
|
22
|
+
}
|
|
23
|
+
if (!OWNED.test(url.pathname)) return reply.callNotFound();
|
|
24
|
+
const body = req.body;
|
|
25
|
+
if (body !== void 0 && body !== null && !(body instanceof Uint8Array) && typeof body !== "string") throw new Error(RAW_BODY_REQUIRED);
|
|
26
|
+
const method = req.method.toUpperCase();
|
|
27
|
+
const response = await handlers.fetch(new Request(url, {
|
|
28
|
+
method,
|
|
29
|
+
headers: headersOf(req.headers),
|
|
30
|
+
...method !== "GET" && body != null ? { body } : {}
|
|
31
|
+
}));
|
|
32
|
+
if (response.status === 404 && !response.headers.has("x-version")) return reply.callNotFound();
|
|
33
|
+
reply.code(response.status);
|
|
34
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
35
|
+
response.headers.forEach((v, k) => {
|
|
36
|
+
if (k !== "set-cookie") reply.header(k, v);
|
|
37
|
+
});
|
|
38
|
+
if (cookies.length) reply.header("set-cookie", cookies);
|
|
39
|
+
return reply.send(new Uint8Array(await response.arrayBuffer()));
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
RAW_BODY_REQUIRED,
|
|
46
|
+
fastifyRights
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=fastify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/rights/fastify.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights/fastify` — mount `createRightsHandlers` in Fastify (v4 or v5).\n *\n * import Fastify from 'fastify';\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * import { fastifyRights } from '@cookiemunch/sdk/rights/fastify';\n * const app = Fastify();\n * app.register(fastifyRights(createRightsHandlers({ key, idSecret, lookup, access, erase })), { prefix: '/privacy' });\n *\n * The plugin is encapsulated (it is not wrapped in fastify-plugin, and must not be): inside it, every\n * content type is read as the raw bytes, because signatures verify over the bytes received and Fastify's\n * JSON parser would hand the handlers an object. The rest of the app keeps its own parsers.\n *\n * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),\n * and the bare 404 answered to a caller without the key, go to the app's not-found handler.\n */\nimport type { RightsHandlers } from '../rights.js';\nimport { OWNED, headersOf } from './shared.js';\n\n/** The parts of a Fastify request this reads. */\nexport interface FastifyLikeRequest {\n method: string;\n url: string;\n protocol?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n}\n\n/** The parts of a Fastify reply this writes. */\nexport interface FastifyLikeReply {\n code(status: number): FastifyLikeReply;\n header(name: string, value: string | string[]): FastifyLikeReply;\n send(body?: Uint8Array): unknown;\n callNotFound(): void;\n}\n\n/** The parts of a Fastify instance the plugin uses. */\nexport interface FastifyLikeInstance {\n removeAllContentTypeParsers(): void;\n addContentTypeParser(type: string, opts: { parseAs: 'buffer' }, parser: (req: unknown, body: Uint8Array, done: (err: Error | null, body?: Uint8Array) => void) => void): void;\n route(opts: { method: string[]; url: string; handler: (req: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<unknown> }): unknown;\n}\n\nexport const RAW_BODY_REQUIRED =\n '@cookiemunch/sdk/rights/fastify: the request body reached the handler already parsed. '\n + 'Signatures verify over the bytes received, so it cannot be re-serialised. '\n + 'Register fastifyRights(...) directly with app.register (not through fastify-plugin), so its raw-body parser applies.';\n\n/** A Fastify plugin serving the handlers. */\nexport function fastifyRights(handlers: Pick<RightsHandlers, 'fetch'>) {\n return async function cookieMunchRights(app: FastifyLikeInstance): Promise<void> {\n app.removeAllContentTypeParsers();\n app.addContentTypeParser('*', { parseAs: 'buffer' }, (_req, body, done) => done(null, body));\n app.route({\n method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],\n url: '/*',\n handler: async (req, reply) => {\n const host = (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? 'localhost';\n let url: URL;\n try {\n url = new URL(req.url, `${req.protocol ?? 'http'}://${host}`);\n } catch {\n return reply.callNotFound();\n }\n if (!OWNED.test(url.pathname)) return reply.callNotFound();\n const body = req.body;\n if (body !== undefined && body !== null && !(body instanceof Uint8Array) && typeof body !== 'string') throw new Error(RAW_BODY_REQUIRED);\n const method = req.method.toUpperCase();\n const response = await handlers.fetch(new Request(url, {\n method,\n headers: headersOf(req.headers),\n ...(method !== 'GET' && body != null ? { body: body as BodyInit } : {}),\n }));\n // No X-Version: the bare 404 a caller without the key gets. Let the app answer it like any other unknown path.\n if (response.status === 404 && !response.headers.has('x-version')) return reply.callNotFound();\n reply.code(response.status);\n const cookies = response.headers.getSetCookie?.() ?? [];\n response.headers.forEach((v, k) => {\n if (k !== 'set-cookie') reply.header(k, v);\n });\n if (cookies.length) reply.header('set-cookie', cookies);\n return reply.send(new Uint8Array(await response.arrayBuffer()));\n },\n });\n };\n}\n"],"mappings":";;;;;;AA2CO,IAAM,oBACX;AAKK,SAAS,cAAc,UAAyC;AACrE,SAAO,eAAe,kBAAkB,KAAyC;AAC/E,QAAI,4BAA4B;AAChC,QAAI,qBAAqB,KAAK,EAAE,SAAS,SAAS,GAAG,CAAC,MAAM,MAAM,SAAS,KAAK,MAAM,IAAI,CAAC;AAC3F,QAAI,MAAM;AAAA,MACR,QAAQ,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ;AAAA,MAChD,KAAK;AAAA,MACL,SAAS,OAAO,KAAK,UAAU;AAC7B,cAAM,QAAQ,MAAM,QAAQ,IAAI,QAAQ,IAAI,IAAI,IAAI,QAAQ,KAAK,CAAC,IAAI,IAAI,QAAQ,SAAS;AAC3F,YAAI;AACJ,YAAI;AACF,gBAAM,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI,YAAY,MAAM,MAAM,IAAI,EAAE;AAAA,QAC9D,QAAQ;AACN,iBAAO,MAAM,aAAa;AAAA,QAC5B;AACA,YAAI,CAAC,MAAM,KAAK,IAAI,QAAQ,EAAG,QAAO,MAAM,aAAa;AACzD,cAAM,OAAO,IAAI;AACjB,YAAI,SAAS,UAAa,SAAS,QAAQ,EAAE,gBAAgB,eAAe,OAAO,SAAS,SAAU,OAAM,IAAI,MAAM,iBAAiB;AACvI,cAAM,SAAS,IAAI,OAAO,YAAY;AACtC,cAAM,WAAW,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK;AAAA,UACrD;AAAA,UACA,SAAS,UAAU,IAAI,OAAO;AAAA,UAC9B,GAAI,WAAW,SAAS,QAAQ,OAAO,EAAE,KAAuB,IAAI,CAAC;AAAA,QACvE,CAAC,CAAC;AAEF,YAAI,SAAS,WAAW,OAAO,CAAC,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAO,MAAM,aAAa;AAC7F,cAAM,KAAK,SAAS,MAAM;AAC1B,cAAM,UAAU,SAAS,QAAQ,eAAe,KAAK,CAAC;AACtD,iBAAS,QAAQ,QAAQ,CAAC,GAAG,MAAM;AACjC,cAAI,MAAM,aAAc,OAAM,OAAO,GAAG,CAAC;AAAA,QAC3C,CAAC;AACD,YAAI,QAAQ,OAAQ,OAAM,OAAO,cAAc,OAAO;AACtD,eAAO,MAAM,KAAK,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;AAAA,MAChE;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
|