slotlock 0.5.1 → 0.5.3

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/types.d.ts CHANGED
@@ -30,8 +30,14 @@ export interface SlotlockResource {
30
30
  visibility?: 'shared' | 'private';
31
31
  /** When the tenant archived it: no longer listed or booked, its history kept. Absent in use. */
32
32
  archivedAt?: Date;
33
- /** What a booking on it must satisfy (`SlotlockBookingRules`). Absent when it has none. */
33
+ /** Its own booking rules (`SlotlockBookingRules`). Absent when it has none. */
34
34
  bookingRules?: SlotlockBookingRules;
35
+ /**
36
+ * What a booking on it must satisfy: the tenant's default rules, overlaid by its pool's, overlaid
37
+ * by its own (`setBookingRuleDefaults`), a field set at a narrower level winning. Absent when no
38
+ * rule applies.
39
+ */
40
+ effectiveBookingRules?: SlotlockBookingRules;
35
41
  /**
36
42
  * The pool it belongs to: interchangeable resources sharing a name, such as a vehicle class or a
37
43
  * room type, booked by the class (`slotlock_book_pool`). Absent when it is in none.
@@ -630,6 +636,13 @@ export interface CalendarEventRetentionResult {
630
636
  hasMore: boolean;
631
637
  }
632
638
  /** What erasing a tenant deleted. */
639
+ /** A tenant's default booking rules (`SlotlockStore.getBookingRuleDefaults`). */
640
+ export interface SlotlockBookingRuleDefaults {
641
+ /** The tenant's own defaults, under every pool's; null when it has none. */
642
+ tenant: SlotlockBookingRules | null;
643
+ /** Each pool's defaults, by pool name, for the pools that have them. */
644
+ pools: Record<string, SlotlockBookingRules>;
645
+ }
633
646
  export interface SlotlockTenantErasure {
634
647
  /** Rows deleted, by table (every table the tenant owns rows in is named, with 0 for none). */
635
648
  rows: Record<string, number>;
package/webhooks.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { SlotlockChange, SlotlockEventFeed } from './event-feed.js';
1
+ import { lookup as dnsLookup } from 'node:dns';
2
+ import type { SlotlockChange, SlotlockChangeOrigin, SlotlockEventFeed } from './event-feed.js';
2
3
  /** The CloudEvents envelope a change is delivered and listed as. */
3
4
  export interface SlotlockCloudEvent {
4
5
  specversion: '1.0';
@@ -8,9 +9,16 @@ export interface SlotlockCloudEvent {
8
9
  subject: string;
9
10
  time: string;
10
11
  datacontenttype: 'application/json';
12
+ /** Extension attribute: where the change came from (`mcp`, `rest`, `dashboard`, ...), when recorded. */
13
+ slotlockorigin?: SlotlockChangeOrigin;
14
+ /** Extension attribute: the id of the API key that made the change, when one did. */
15
+ slotlockkeyid?: string;
11
16
  data: Record<string, unknown>;
12
17
  }
13
- /** A change as CloudEvents 1.0 (structured mode): `type` is `io.pylota.slotlock.<change type>`. */
18
+ /**
19
+ * A change as CloudEvents 1.0 (structured mode): `type` is `io.pylota.slotlock.<change type>`, with
20
+ * the extension attributes `slotlockorigin` and `slotlockkeyid` when the change records them.
21
+ */
14
22
  export declare function slotlockCloudEvent(change: SlotlockChange): SlotlockCloudEvent;
15
23
  /**
16
24
  * The Standard Webhooks signature of one attempt: `v1,` and the base64 HMAC-SHA256, keyed by the
@@ -49,6 +57,29 @@ export declare function createSlotlockWebhookSender(options?: {
49
57
  timeoutMs?: number;
50
58
  allowPrivateNetworks?: boolean;
51
59
  }): SlotlockWebhookSender;
60
+ /**
61
+ * A `dns.lookup` that answers every address a name resolves to, and refuses (an error with `code`)
62
+ * a name with any private one unless `allowPrivateNetworks`. Given to a socket's connect, it checks
63
+ * the addresses the connection will use, so a name rebound to a private address after an earlier
64
+ * check is still refused. `resolve` stands in for `dns.lookup` (tests).
65
+ */
66
+ export declare function slotlockPrivateAddressLookup(options: {
67
+ allowPrivateNetworks: boolean;
68
+ code: string;
69
+ what: string;
70
+ resolve?: typeof dnsLookup;
71
+ }): typeof dnsLookup;
72
+ /**
73
+ * A `fetch` for a server reaching a URL a tenant chose (the dashboard assistant's model): Node's
74
+ * http client with the webhooks' address check. A URL naming a private address, or a host that
75
+ * resolves to one when the socket connects, is refused with an error whose `code` is
76
+ * `private_address`, unless `allowPrivateNetworks`. No redirect is followed (the answer is
77
+ * returned as is) and no proxy from the environment is used. Takes a string body only.
78
+ */
79
+ export declare function createSlotlockGuardedFetch(options?: {
80
+ allowPrivateNetworks?: boolean;
81
+ resolve?: typeof dnsLookup;
82
+ }): typeof fetch;
52
83
  export interface SlotlockWebhookPassResult {
53
84
  /** Changes an endpoint accepted. */
54
85
  delivered: number;
package/webhooks.js CHANGED
@@ -8,8 +8,12 @@ import { lookup as dnsLookup } from 'node:dns';
8
8
  import { Agent as HttpAgent, request as httpRequest } from 'node:http';
9
9
  import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
10
10
  import { BlockList, isIP } from 'node:net';
11
+ import { Readable } from 'node:stream';
11
12
  import { ignoreRejection } from './hooks.js';
12
- /** A change as CloudEvents 1.0 (structured mode): `type` is `io.pylota.slotlock.<change type>`. */
13
+ /**
14
+ * A change as CloudEvents 1.0 (structured mode): `type` is `io.pylota.slotlock.<change type>`, with
15
+ * the extension attributes `slotlockorigin` and `slotlockkeyid` when the change records them.
16
+ */
13
17
  export function slotlockCloudEvent(change) {
14
18
  return {
15
19
  specversion: '1.0',
@@ -19,6 +23,8 @@ export function slotlockCloudEvent(change) {
19
23
  subject: change.subject,
20
24
  time: change.occurredAt.toISOString(),
21
25
  datacontenttype: 'application/json',
26
+ ...(change.origin ? { slotlockorigin: change.origin } : {}),
27
+ ...(change.keyId ? { slotlockkeyid: change.keyId } : {}),
22
28
  data: change.data,
23
29
  };
24
30
  }
@@ -104,28 +110,16 @@ export function isPrivateAddress(address) {
104
110
  */
105
111
  export function createSlotlockWebhookSender(options = {}) {
106
112
  const timeoutMs = options.timeoutMs ?? 15_000;
107
- const lookup = ((hostname, lookupOptions, callback) => {
108
- dnsLookup(hostname, { ...lookupOptions, all: true }, (error, addresses) => {
109
- if (error)
110
- return callback(error);
111
- const list = addresses;
112
- if (!options.allowPrivateNetworks && list.some(({ address }) => isPrivateAddress(address))) {
113
- return callback(Object.assign(new Error(`webhook host ${hostname} resolves to a private address`), { code: 'webhook_private_address' }));
114
- }
115
- const all = lookupOptions.all;
116
- if (all)
117
- return callback(null, list);
118
- const first = list[0];
119
- return first ? callback(null, first.address, first.family) : callback(new Error('no address'));
120
- });
113
+ const lookup = slotlockPrivateAddressLookup({
114
+ allowPrivateNetworks: options.allowPrivateNetworks === true,
115
+ code: 'webhook_private_address',
116
+ what: 'webhook',
121
117
  });
122
118
  return (request) => new Promise((resolve, reject) => {
123
119
  const url = new URL(request.url);
124
- if (isIP(url.hostname.replace(/^\[|\]$/g, '')) && !options.allowPrivateNetworks) {
125
- if (isPrivateAddress(url.hostname.replace(/^\[|\]$/g, ''))) {
126
- reject(Object.assign(new Error('webhook URL names a private address'), { code: 'webhook_private_address' }));
127
- return;
128
- }
120
+ if (!options.allowPrivateNetworks && namesPrivateAddress(url)) {
121
+ reject(Object.assign(new Error('webhook URL names a private address'), { code: 'webhook_private_address' }));
122
+ return;
129
123
  }
130
124
  const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
131
125
  const outgoing = send(url, {
@@ -164,6 +158,94 @@ export function createSlotlockWebhookSender(options = {}) {
164
158
  outgoing.end(request.body);
165
159
  });
166
160
  }
161
+ /** Whether a URL's host is an IP address literal that isPrivateAddress refuses. */
162
+ function namesPrivateAddress(url) {
163
+ const host = url.hostname.replace(/^\[|\]$/g, '');
164
+ return isIP(host) !== 0 && isPrivateAddress(host);
165
+ }
166
+ /**
167
+ * A `dns.lookup` that answers every address a name resolves to, and refuses (an error with `code`)
168
+ * a name with any private one unless `allowPrivateNetworks`. Given to a socket's connect, it checks
169
+ * the addresses the connection will use, so a name rebound to a private address after an earlier
170
+ * check is still refused. `resolve` stands in for `dns.lookup` (tests).
171
+ */
172
+ export function slotlockPrivateAddressLookup(options) {
173
+ const resolve = options.resolve ?? dnsLookup;
174
+ return ((hostname, lookupOptions, callback) => {
175
+ resolve(hostname, { ...lookupOptions, all: true }, (error, addresses) => {
176
+ if (error)
177
+ return callback(error);
178
+ const list = addresses;
179
+ if (!options.allowPrivateNetworks && list.some(({ address }) => isPrivateAddress(address))) {
180
+ return callback(Object.assign(new Error(`${options.what} host ${hostname} resolves to a private address`), { code: options.code }));
181
+ }
182
+ const all = lookupOptions.all;
183
+ if (all)
184
+ return callback(null, list);
185
+ const first = list[0];
186
+ return first ? callback(null, first.address, first.family) : callback(new Error('no address'));
187
+ });
188
+ });
189
+ }
190
+ /**
191
+ * A `fetch` for a server reaching a URL a tenant chose (the dashboard assistant's model): Node's
192
+ * http client with the webhooks' address check. A URL naming a private address, or a host that
193
+ * resolves to one when the socket connects, is refused with an error whose `code` is
194
+ * `private_address`, unless `allowPrivateNetworks`. No redirect is followed (the answer is
195
+ * returned as is) and no proxy from the environment is used. Takes a string body only.
196
+ */
197
+ export function createSlotlockGuardedFetch(options = {}) {
198
+ const allow = options.allowPrivateNetworks === true;
199
+ const lookup = slotlockPrivateAddressLookup({
200
+ allowPrivateNetworks: allow,
201
+ code: 'private_address',
202
+ what: 'requested',
203
+ ...(options.resolve ? { resolve: options.resolve } : {}),
204
+ });
205
+ const refused = () => Object.assign(new Error('the URL names a private address'), { code: 'private_address' });
206
+ return (async (input, init = {}) => {
207
+ const url = new URL(input instanceof Request ? input.url : String(input));
208
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
209
+ throw new TypeError('unsupported URL');
210
+ if (!allow && namesPrivateAddress(url))
211
+ throw refused();
212
+ const body = init.body === undefined || init.body === null ? undefined : String(init.body);
213
+ const headers = {};
214
+ new Headers(init.headers).forEach((value, name) => {
215
+ headers[name] = value;
216
+ });
217
+ if (body !== undefined)
218
+ headers['content-length'] = String(Buffer.byteLength(body));
219
+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
220
+ return new Promise((resolve, reject) => {
221
+ const outgoing = send(url, {
222
+ method: init.method ?? 'GET',
223
+ headers,
224
+ // An agent of its own: a proxy from the environment would skip the address check.
225
+ agent: url.protocol === 'https:' ? new HttpsAgent({ lookup }) : new HttpAgent({ lookup }),
226
+ lookup,
227
+ ...(init.signal ? { signal: init.signal } : {}),
228
+ }, (response) => {
229
+ const status = response.statusCode ?? 0;
230
+ const answer = new Headers();
231
+ for (const [name, value] of Object.entries(response.headers)) {
232
+ for (const each of Array.isArray(value) ? value : value === undefined ? [] : [value]) {
233
+ answer.append(name, each);
234
+ }
235
+ }
236
+ if (status < 200 || status > 599) {
237
+ response.destroy();
238
+ reject(new Error(`unexpected HTTP status ${status}`));
239
+ return;
240
+ }
241
+ const stream = status === 204 || status === 304 ? null : Readable.toWeb(response);
242
+ resolve(new Response(stream, { status, headers: answer }));
243
+ });
244
+ outgoing.on('error', reject);
245
+ outgoing.end(body);
246
+ });
247
+ });
248
+ }
167
249
  /**
168
250
  * One delivery pass for a tenant: claim each endpoint with changes due, send them in order until
169
251
  * one fails, and record how far each got. A 2xx is delivered; 410 disables the endpoint; anything