@cookiemunch/sdk 0.32.0 → 0.34.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.
@@ -0,0 +1,86 @@
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/express.ts
21
+ var express_exports = {};
22
+ __export(express_exports, {
23
+ RAW_BODY_REQUIRED: () => RAW_BODY_REQUIRED,
24
+ expressRights: () => expressRights
25
+ });
26
+ module.exports = __toCommonJS(express_exports);
27
+ var OWNED = /\/(lookup|requests)(?:\/[^/]+(?:\/(cancel|run))?)?\/*$/;
28
+ 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
+ async function bodyOf(req) {
30
+ if (req.rawBody !== void 0) return req.rawBody;
31
+ if (req.body instanceof Uint8Array || typeof req.body === "string") return req.body;
32
+ const consumed = req._body === true || req.readableEnded === true;
33
+ if (!consumed) {
34
+ const parts = [];
35
+ for await (const c of req) parts.push(typeof c === "string" ? new TextEncoder().encode(c) : c);
36
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
37
+ let at = 0;
38
+ for (const p of parts) out.set(p, at), at += p.length;
39
+ return out;
40
+ }
41
+ if (req.body !== void 0 && req.body !== null) throw new Error(RAW_BODY_REQUIRED);
42
+ return void 0;
43
+ }
44
+ function expressRights(handlers) {
45
+ return async (req, res, next) => {
46
+ const host = req.get?.("host") ?? (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? "localhost";
47
+ const proto = req.protocol ?? (req.socket?.encrypted ? "https" : "http");
48
+ let url;
49
+ try {
50
+ url = new URL(req.originalUrl ?? req.url ?? "/", `${proto}://${host}`);
51
+ } catch {
52
+ return next();
53
+ }
54
+ if (!OWNED.test(url.pathname)) return next();
55
+ let response;
56
+ try {
57
+ const headers = new 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
+ }
65
+ const method = (req.method ?? "GET").toUpperCase();
66
+ const body = method === "GET" || method === "HEAD" ? void 0 : await bodyOf(req);
67
+ response = await handlers.fetch(new Request(url, { method, headers, ...body !== void 0 ? { body } : {} }));
68
+ } catch (err) {
69
+ return next(err);
70
+ }
71
+ if (response.status === 404 && !response.headers.has("x-version")) return next();
72
+ res.statusCode = response.status;
73
+ const cookies = response.headers.getSetCookie?.() ?? [];
74
+ response.headers.forEach((v, k) => {
75
+ if (k !== "set-cookie") res.setHeader(k, v);
76
+ });
77
+ if (cookies.length) res.setHeader("set-cookie", cookies);
78
+ res.end(new Uint8Array(await response.arrayBuffer()));
79
+ };
80
+ }
81
+ // Annotate the CommonJS export names for ESM import in node:
82
+ 0 && (module.exports = {
83
+ RAW_BODY_REQUIRED,
84
+ expressRights
85
+ });
86
+ //# sourceMappingURL=express.cjs.map
@@ -0,0 +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\n// The same tail createRightsHandlers routes on; anything else is not ours and is never read.\nconst OWNED = /\\/(lookup|requests)(?:\\/[^/]+(?:\\/(cancel|run))?)?\\/*$/;\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 = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\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 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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwDA,IAAM,QAAQ;AAEP,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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AQ,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,56 @@
1
+ /**
2
+ * `@cookiemunch/sdk/rights/express` — mount `createRightsHandlers` in Express, Connect or NestJS.
3
+ *
4
+ * import express from 'express';
5
+ * import { createRightsHandlers } from '@cookiemunch/sdk/rights';
6
+ * import { expressRights } from '@cookiemunch/sdk/rights/express';
7
+ * const rights = createRightsHandlers({ key, idSecret, lookup, access, erase });
8
+ * // Before any express.json(), or with express.raw() on this route: the handlers need the bytes as sent.
9
+ * app.use('/privacy', express.raw({ type: 'application/json' }), expressRights(rights));
10
+ *
11
+ * NestJS (`NestFactory.create(AppModule, { rawBody: true })`, so `req.rawBody` holds the bytes):
12
+ *
13
+ * @Controller()
14
+ * export class PrivacyController {
15
+ * private readonly rights = expressRights(createRightsHandlers({ ... }));
16
+ * @All('privacy/*')
17
+ * handle(@Req() req: Request, @Res() res: Response) {
18
+ * return this.rights(req, res, (err) => { if (err) throw err; res.status(404).end(); });
19
+ * }
20
+ * }
21
+ *
22
+ * The body passed on is the raw request bytes: `req.rawBody`, a Buffer `req.body` (express.raw), or the
23
+ * stream read here when nothing consumed it. A `req.body` already parsed into an object is refused
24
+ * (passed to `next(err)`), never re-serialised: signatures verify over the bytes received, and
25
+ * `JSON.stringify` of a parsed body is not those bytes.
26
+ *
27
+ * A path the handlers do not own (anything not ending in `/lookup` or `/requests[/{id}[/cancel|/run]]`),
28
+ * and the bare 404 answered to a caller without the key, go to `next()`, so the rest of the app answers
29
+ * them as it answers any unknown path.
30
+ */
31
+ import type { RightsHandlers } from '../rights.js';
32
+ /** The parts of an Express / Connect / Node request this reads. */
33
+ export interface ExpressLikeRequest extends AsyncIterable<Uint8Array | string> {
34
+ method?: string;
35
+ url?: string;
36
+ originalUrl?: string;
37
+ protocol?: string;
38
+ headers: Record<string, string | string[] | undefined>;
39
+ get?(name: string): string | undefined;
40
+ rawBody?: Uint8Array | string;
41
+ body?: unknown;
42
+ readableEnded?: boolean;
43
+ socket?: {
44
+ encrypted?: boolean;
45
+ };
46
+ }
47
+ /** The parts of an Express / Node response this writes. */
48
+ export interface ExpressLikeResponse {
49
+ statusCode: number;
50
+ setHeader(name: string, value: string | string[]): unknown;
51
+ end(body?: Uint8Array): unknown;
52
+ }
53
+ export type ExpressNext = (err?: unknown) => void;
54
+ export declare const RAW_BODY_REQUIRED: string;
55
+ /** An Express / Connect middleware serving the handlers; resolves once the answer is written. */
56
+ export declare function expressRights(handlers: Pick<RightsHandlers, 'fetch'>): (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNext) => Promise<void>;
@@ -0,0 +1,60 @@
1
+ // src/rights/express.ts
2
+ var OWNED = /\/(lookup|requests)(?:\/[^/]+(?:\/(cancel|run))?)?\/*$/;
3
+ 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
+ async function bodyOf(req) {
5
+ if (req.rawBody !== void 0) return req.rawBody;
6
+ if (req.body instanceof Uint8Array || typeof req.body === "string") return req.body;
7
+ const consumed = req._body === true || req.readableEnded === true;
8
+ if (!consumed) {
9
+ const parts = [];
10
+ for await (const c of req) parts.push(typeof c === "string" ? new TextEncoder().encode(c) : c);
11
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
12
+ let at = 0;
13
+ for (const p of parts) out.set(p, at), at += p.length;
14
+ return out;
15
+ }
16
+ if (req.body !== void 0 && req.body !== null) throw new Error(RAW_BODY_REQUIRED);
17
+ return void 0;
18
+ }
19
+ function expressRights(handlers) {
20
+ return async (req, res, next) => {
21
+ const host = req.get?.("host") ?? (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) ?? "localhost";
22
+ const proto = req.protocol ?? (req.socket?.encrypted ? "https" : "http");
23
+ let url;
24
+ try {
25
+ url = new URL(req.originalUrl ?? req.url ?? "/", `${proto}://${host}`);
26
+ } catch {
27
+ return next();
28
+ }
29
+ if (!OWNED.test(url.pathname)) return next();
30
+ let response;
31
+ try {
32
+ const headers = new 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
+ }
40
+ const method = (req.method ?? "GET").toUpperCase();
41
+ const body = method === "GET" || method === "HEAD" ? void 0 : await bodyOf(req);
42
+ response = await handlers.fetch(new Request(url, { method, headers, ...body !== void 0 ? { body } : {} }));
43
+ } catch (err) {
44
+ return next(err);
45
+ }
46
+ if (response.status === 404 && !response.headers.has("x-version")) return next();
47
+ res.statusCode = response.status;
48
+ const cookies = response.headers.getSetCookie?.() ?? [];
49
+ response.headers.forEach((v, k) => {
50
+ if (k !== "set-cookie") res.setHeader(k, v);
51
+ });
52
+ if (cookies.length) res.setHeader("set-cookie", cookies);
53
+ res.end(new Uint8Array(await response.arrayBuffer()));
54
+ };
55
+ }
56
+ export {
57
+ RAW_BODY_REQUIRED,
58
+ expressRights
59
+ };
60
+ //# sourceMappingURL=express.js.map
@@ -0,0 +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\n// The same tail createRightsHandlers routes on; anything else is not ours and is never read.\nconst OWNED = /\\/(lookup|requests)(?:\\/[^/]+(?:\\/(cancel|run))?)?\\/*$/;\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 = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\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 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":";AAwDA,IAAM,QAAQ;AAEP,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,I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,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.cjs CHANGED
@@ -35,6 +35,7 @@ __export(rights_exports, {
35
35
  RIGHTS_STORE_TABLE_SQLITE: () => RIGHTS_STORE_TABLE_SQLITE,
36
36
  createRightsHandlers: () => createRightsHandlers,
37
37
  fileStore: () => fileStore,
38
+ ioredisStore: () => ioredisStore,
38
39
  redisStore: () => redisStore,
39
40
  sqlStore: () => sqlStore
40
41
  });
@@ -107,6 +108,7 @@ function isObject(v) {
107
108
  }
108
109
  function createRightsHandlers(o) {
109
110
  if (typeof o.key !== "string" || !o.key) throw new Error("createRightsHandlers: key is required");
111
+ if (o.key.length < 24) console.warn("createRightsHandlers: key is shorter than 24 characters; rotate it to a longer one (PATCH /v1/dsar/executors/{id} {secretKey}) so it cannot be guessed");
110
112
  if (typeof o.idSecret !== "string" || o.idSecret.length < 32) throw new Error("createRightsHandlers: idSecret must be at least 32 characters");
111
113
  if (typeof o.lookup !== "function") throw new Error("createRightsHandlers: lookup is required");
112
114
  const subtle = globalThis.crypto?.subtle;
@@ -446,6 +448,18 @@ function redisStore(client) {
446
448
  }
447
449
  };
448
450
  }
451
+ function ioredisStore(client) {
452
+ const k = (key) => `cookiemunch:rights:${key}`;
453
+ return {
454
+ get: (key) => client.get(k(key)),
455
+ async set(key, value, opts) {
456
+ await (opts?.ttlSeconds ? client.set(k(key), value, "EX", opts.ttlSeconds) : client.set(k(key), value));
457
+ },
458
+ async delete(key) {
459
+ await client.del(k(key));
460
+ }
461
+ };
462
+ }
449
463
  // Annotate the CommonJS export names for ESM import in node:
450
464
  0 && (module.exports = {
451
465
  IDEMPOTENCY_TTL_SECONDS,
@@ -453,6 +467,7 @@ function redisStore(client) {
453
467
  RIGHTS_STORE_TABLE_SQLITE,
454
468
  createRightsHandlers,
455
469
  fileStore,
470
+ ioredisStore,
456
471
  redisStore,
457
472
  sqlStore
458
473
  });