@molecule/api-resource-version-history 1.0.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.
Files changed (62) hide show
  1. package/LICENSE +115 -0
  2. package/dist/authorizers/index.d.ts +24 -0
  3. package/dist/authorizers/index.d.ts.map +1 -0
  4. package/dist/authorizers/index.js +23 -0
  5. package/dist/authorizers/ownership.d.ts +77 -0
  6. package/dist/authorizers/ownership.d.ts.map +1 -0
  7. package/dist/authorizers/ownership.js +112 -0
  8. package/dist/browser-guard.d.ts +2 -0
  9. package/dist/browser-guard.d.ts.map +1 -0
  10. package/dist/browser-guard.js +18 -0
  11. package/dist/diff.d.ts +33 -0
  12. package/dist/diff.d.ts.map +1 -0
  13. package/dist/diff.js +110 -0
  14. package/dist/handlers/count.d.ts +17 -0
  15. package/dist/handlers/count.d.ts.map +1 -0
  16. package/dist/handlers/count.js +58 -0
  17. package/dist/handlers/create.d.ts +19 -0
  18. package/dist/handlers/create.d.ts.map +1 -0
  19. package/dist/handlers/create.js +73 -0
  20. package/dist/handlers/diff.d.ts +19 -0
  21. package/dist/handlers/diff.d.ts.map +1 -0
  22. package/dist/handlers/diff.js +70 -0
  23. package/dist/handlers/index.d.ts +8 -0
  24. package/dist/handlers/index.d.ts.map +1 -0
  25. package/dist/handlers/index.js +7 -0
  26. package/dist/handlers/list.d.ts +18 -0
  27. package/dist/handlers/list.d.ts.map +1 -0
  28. package/dist/handlers/list.js +61 -0
  29. package/dist/handlers/read.d.ts +20 -0
  30. package/dist/handlers/read.d.ts.map +1 -0
  31. package/dist/handlers/read.js +68 -0
  32. package/dist/handlers/readByNumber.d.ts +17 -0
  33. package/dist/handlers/readByNumber.d.ts.map +1 -0
  34. package/dist/handlers/readByNumber.js +80 -0
  35. package/dist/handlers/restore.d.ts +20 -0
  36. package/dist/handlers/restore.d.ts.map +1 -0
  37. package/dist/handlers/restore.js +84 -0
  38. package/dist/i18n.d.ts +10 -0
  39. package/dist/i18n.d.ts.map +1 -0
  40. package/dist/i18n.js +17 -0
  41. package/dist/index.d.ts +130 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +129 -0
  44. package/dist/registry.d.ts +79 -0
  45. package/dist/registry.d.ts.map +1 -0
  46. package/dist/registry.js +65 -0
  47. package/dist/requestHandlerMap.d.ts +25 -0
  48. package/dist/requestHandlerMap.d.ts.map +1 -0
  49. package/dist/requestHandlerMap.js +24 -0
  50. package/dist/routes.d.ts +67 -0
  51. package/dist/routes.d.ts.map +1 -0
  52. package/dist/routes.js +69 -0
  53. package/dist/service.d.ts +107 -0
  54. package/dist/service.d.ts.map +1 -0
  55. package/dist/service.js +193 -0
  56. package/dist/types.d.ts +106 -0
  57. package/dist/types.d.ts.map +1 -0
  58. package/dist/types.js +11 -0
  59. package/dist/validation.d.ts +21 -0
  60. package/dist/validation.d.ts.map +1 -0
  61. package/dist/validation.js +34 -0
  62. package/package.json +70 -0
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Append-only version history resource for molecule.dev.
3
+ *
4
+ * Polymorphic, append-only `versions` table that captures full snapshots of
5
+ * any resource type, plus a shallow diff against the prior version. Routes
6
+ * surface list / read / count / diff / restore — there is no UPDATE or
7
+ * DELETE for individual versions, by design. Restoring a prior version
8
+ * appends a new version whose snapshot equals the target's; the existing
9
+ * rows are never mutated.
10
+ *
11
+ * @remarks
12
+ * - **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
13
+ * bare array — read the rows off `result.data` (server). On the client, `unwrapList(res)`
14
+ * from `@molecule/app-http` normalizes this envelope (pass it the whole HttpResponse), so
15
+ * the rows come back; reading the response as a bare array — or `res.data` alone (which is
16
+ * the envelope) — yields an EMPTY list.
17
+ * **Security — the raw routes are NOT open.** Snapshots can contain any
18
+ * tenant's data, so every route requires an authenticated session AND each
19
+ * handler re-derives the caller from `res.locals.session.userId` and authorizes
20
+ * access to the *parent* resource via {@link isVersionAuthorized}. Access is
21
+ * **fail-closed and pluggable**: because the store is polymorphic it cannot
22
+ * know who owns an arbitrary `(resourceType, resourceId)`, so an app mounting
23
+ * these routes MUST register a {@link VersionOwnershipResolver} per resource
24
+ * type at startup via {@link registerOwnershipResolver} — until it does, every
25
+ * read/list/diff/restore returns 404 (no existence leak) rather than exposing
26
+ * another tenant's snapshots. Cross-tenant admin access is opt-in via the
27
+ * {@link versionHistoryAdmin} middleware. Do NOT mount the raw routes without
28
+ * either a registered resolver or your own resource-ownership gate.
29
+ *
30
+ * Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
31
+ * API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
32
+ * once — nothing at runtime creates them. Handler errors flow through `t()`
33
+ * with English defaults; install `@molecule/api-locales-resource-version-history`
34
+ * and register it with `registerLocaleModule` for translations.
35
+ *
36
+ * @e2e
37
+ * Versioning-correctness checklist — drive the real UI (live preview, no mocks)
38
+ * wherever this app surfaces revisions/history, adapt each item to the actual
39
+ * screens, and check every box. A box you can't check is a versioning bug to
40
+ * fix — not a skip. The point is to PROVE versions are recorded, ordered,
41
+ * diffable, restorable, and tamper-evident, not just that CRUD compiles:
42
+ * - [ ] Editing a versioned resource RECORDS a new version: after a save the
43
+ * history count grows by exactly one, the prior version is RETAINED (its
44
+ * snapshot unchanged — not overwritten), and the new row carries the next
45
+ * 1-based `version` number (previous + 1), the acting user as `userId`
46
+ * (author), and a fresh `createdAt`. The very first save has `changes: null`;
47
+ * later saves record a `changes` shallow diff (before/after per field)
48
+ * against the prior snapshot.
49
+ * - [ ] Listing history returns versions newest-first (by `version` descending)
50
+ * with `total` reflecting every version, each row showing its number, author
51
+ * (`userId`), `reason`, and `createdAt` — and the count only ever GROWS across
52
+ * saves (append-only: no save shrinks or rewrites history).
53
+ * - [ ] Viewing an old version shows that version's full `snapshot`; diffing two
54
+ * versions renders the per-field `changes` as a forward delta (the
55
+ * lower-numbered version is `from`, the higher is `to`), and a diff across two
56
+ * different resources is rejected (no cross-resource diff).
57
+ * - [ ] Reverting/restoring an old version makes it current AND itself APPENDS a
58
+ * new version whose snapshot equals the target's — the prior current version
59
+ * and the restored-from version both still exist afterward, the new version's
60
+ * number is the next in sequence, its author is the acting user, and its
61
+ * `reason` records the restore (default `Restored from version <n>`). History
62
+ * is never lost by a revert.
63
+ * - [ ] Retention is append-only and unbounded — nothing prunes: there is no UI
64
+ * or endpoint to edit or delete an individual version (no UPDATE/DELETE
65
+ * route), so a resource's history count never decreases. (If the app layers
66
+ * its own retention policy on top, verify it prunes oldest-first per that
67
+ * policy and never drops the current version.)
68
+ * - [ ] AUTHORIZATION — a resource's version history is reachable only by a user
69
+ * who can access that resource: a different user id-guessing the
70
+ * `(resourceType, resourceId)` or a `versionId` gets 404 (no existence leak),
71
+ * never another tenant's history, and with no ownership resolver registered
72
+ * every read/list/diff/restore fails closed. The version author is always the
73
+ * session user (`res.locals.session.userId`), never a body-supplied id — a
74
+ * caller cannot attribute a change to someone else. A user cannot fabricate or
75
+ * delete history to hide a change: versions are append-only and a revert
76
+ * appends rather than rewrites; only the opt-in `versionHistoryAdmin`
77
+ * middleware crosses tenants.
78
+ *
79
+ * @module
80
+ * @example
81
+ * ```typescript
82
+ * import {
83
+ * routes,
84
+ * requestHandlerMap,
85
+ * createVersion,
86
+ * registerOwnershipResolver,
87
+ * } from '@molecule/api-resource-version-history'
88
+ *
89
+ * // REQUIRED before mounting the routes: tell version-history how to check
90
+ * // parent-resource ownership for each resource type you version. Without this
91
+ * // every read/list/diff/restore fails closed (404) — the routes are never open.
92
+ * registerOwnershipResolver('document', async ({ resourceId, userId }) => {
93
+ * const doc = await findById('documents', resourceId)
94
+ * return doc?.userId === userId
95
+ * })
96
+ *
97
+ * // Wire routes via mlcl inject:
98
+ * // POST /:resourceType/:resourceId/versions
99
+ * // GET /:resourceType/:resourceId/versions
100
+ * // GET /:resourceType/:resourceId/versions/count
101
+ * // GET /:resourceType/:resourceId/versions/:version
102
+ * // GET /versions/:versionId
103
+ * // POST /versions/:versionId/restore
104
+ * // GET /versions/:fromVersionId/diff/:toVersionId
105
+ *
106
+ * // Or call the service directly from another resource's update handler.
107
+ * // The acting user ALWAYS comes from the session (res.locals.session) —
108
+ * // never from the request body:
109
+ * const userId = (res.locals.session as { userId?: string } | undefined)?.userId
110
+ * await createVersion({
111
+ * resourceType: 'document',
112
+ * resourceId: doc.id,
113
+ * userId: userId ?? null,
114
+ * snapshot: doc,
115
+ * reason: 'autosave',
116
+ * })
117
+ * ```
118
+ */
119
+ export * from './authorizers/index.js';
120
+ export * from './browser-guard.js';
121
+ export * from './diff.js';
122
+ export * from './handlers/index.js';
123
+ export * from './i18n.js';
124
+ export * from './registry.js';
125
+ export * from './requestHandlerMap.js';
126
+ export * from './routes.js';
127
+ export * from './service.js';
128
+ export * from './types.js';
129
+ export * from './validation.js';
130
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqHG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,WAAW,CAAA;AACzB,cAAc,qBAAqB,CAAA;AACnC,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Append-only version history resource for molecule.dev.
3
+ *
4
+ * Polymorphic, append-only `versions` table that captures full snapshots of
5
+ * any resource type, plus a shallow diff against the prior version. Routes
6
+ * surface list / read / count / diff / restore — there is no UPDATE or
7
+ * DELETE for individual versions, by design. Restoring a prior version
8
+ * appends a new version whose snapshot equals the target's; the existing
9
+ * rows are never mutated.
10
+ *
11
+ * @remarks
12
+ * - **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
13
+ * bare array — read the rows off `result.data` (server). On the client, `unwrapList(res)`
14
+ * from `@molecule/app-http` normalizes this envelope (pass it the whole HttpResponse), so
15
+ * the rows come back; reading the response as a bare array — or `res.data` alone (which is
16
+ * the envelope) — yields an EMPTY list.
17
+ * **Security — the raw routes are NOT open.** Snapshots can contain any
18
+ * tenant's data, so every route requires an authenticated session AND each
19
+ * handler re-derives the caller from `res.locals.session.userId` and authorizes
20
+ * access to the *parent* resource via {@link isVersionAuthorized}. Access is
21
+ * **fail-closed and pluggable**: because the store is polymorphic it cannot
22
+ * know who owns an arbitrary `(resourceType, resourceId)`, so an app mounting
23
+ * these routes MUST register a {@link VersionOwnershipResolver} per resource
24
+ * type at startup via {@link registerOwnershipResolver} — until it does, every
25
+ * read/list/diff/restore returns 404 (no existence leak) rather than exposing
26
+ * another tenant's snapshots. Cross-tenant admin access is opt-in via the
27
+ * {@link versionHistoryAdmin} middleware. Do NOT mount the raw routes without
28
+ * either a registered resolver or your own resource-ownership gate.
29
+ *
30
+ * Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
31
+ * API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
32
+ * once — nothing at runtime creates them. Handler errors flow through `t()`
33
+ * with English defaults; install `@molecule/api-locales-resource-version-history`
34
+ * and register it with `registerLocaleModule` for translations.
35
+ *
36
+ * @e2e
37
+ * Versioning-correctness checklist — drive the real UI (live preview, no mocks)
38
+ * wherever this app surfaces revisions/history, adapt each item to the actual
39
+ * screens, and check every box. A box you can't check is a versioning bug to
40
+ * fix — not a skip. The point is to PROVE versions are recorded, ordered,
41
+ * diffable, restorable, and tamper-evident, not just that CRUD compiles:
42
+ * - [ ] Editing a versioned resource RECORDS a new version: after a save the
43
+ * history count grows by exactly one, the prior version is RETAINED (its
44
+ * snapshot unchanged — not overwritten), and the new row carries the next
45
+ * 1-based `version` number (previous + 1), the acting user as `userId`
46
+ * (author), and a fresh `createdAt`. The very first save has `changes: null`;
47
+ * later saves record a `changes` shallow diff (before/after per field)
48
+ * against the prior snapshot.
49
+ * - [ ] Listing history returns versions newest-first (by `version` descending)
50
+ * with `total` reflecting every version, each row showing its number, author
51
+ * (`userId`), `reason`, and `createdAt` — and the count only ever GROWS across
52
+ * saves (append-only: no save shrinks or rewrites history).
53
+ * - [ ] Viewing an old version shows that version's full `snapshot`; diffing two
54
+ * versions renders the per-field `changes` as a forward delta (the
55
+ * lower-numbered version is `from`, the higher is `to`), and a diff across two
56
+ * different resources is rejected (no cross-resource diff).
57
+ * - [ ] Reverting/restoring an old version makes it current AND itself APPENDS a
58
+ * new version whose snapshot equals the target's — the prior current version
59
+ * and the restored-from version both still exist afterward, the new version's
60
+ * number is the next in sequence, its author is the acting user, and its
61
+ * `reason` records the restore (default `Restored from version <n>`). History
62
+ * is never lost by a revert.
63
+ * - [ ] Retention is append-only and unbounded — nothing prunes: there is no UI
64
+ * or endpoint to edit or delete an individual version (no UPDATE/DELETE
65
+ * route), so a resource's history count never decreases. (If the app layers
66
+ * its own retention policy on top, verify it prunes oldest-first per that
67
+ * policy and never drops the current version.)
68
+ * - [ ] AUTHORIZATION — a resource's version history is reachable only by a user
69
+ * who can access that resource: a different user id-guessing the
70
+ * `(resourceType, resourceId)` or a `versionId` gets 404 (no existence leak),
71
+ * never another tenant's history, and with no ownership resolver registered
72
+ * every read/list/diff/restore fails closed. The version author is always the
73
+ * session user (`res.locals.session.userId`), never a body-supplied id — a
74
+ * caller cannot attribute a change to someone else. A user cannot fabricate or
75
+ * delete history to hide a change: versions are append-only and a revert
76
+ * appends rather than rewrites; only the opt-in `versionHistoryAdmin`
77
+ * middleware crosses tenants.
78
+ *
79
+ * @module
80
+ * @example
81
+ * ```typescript
82
+ * import {
83
+ * routes,
84
+ * requestHandlerMap,
85
+ * createVersion,
86
+ * registerOwnershipResolver,
87
+ * } from '@molecule/api-resource-version-history'
88
+ *
89
+ * // REQUIRED before mounting the routes: tell version-history how to check
90
+ * // parent-resource ownership for each resource type you version. Without this
91
+ * // every read/list/diff/restore fails closed (404) — the routes are never open.
92
+ * registerOwnershipResolver('document', async ({ resourceId, userId }) => {
93
+ * const doc = await findById('documents', resourceId)
94
+ * return doc?.userId === userId
95
+ * })
96
+ *
97
+ * // Wire routes via mlcl inject:
98
+ * // POST /:resourceType/:resourceId/versions
99
+ * // GET /:resourceType/:resourceId/versions
100
+ * // GET /:resourceType/:resourceId/versions/count
101
+ * // GET /:resourceType/:resourceId/versions/:version
102
+ * // GET /versions/:versionId
103
+ * // POST /versions/:versionId/restore
104
+ * // GET /versions/:fromVersionId/diff/:toVersionId
105
+ *
106
+ * // Or call the service directly from another resource's update handler.
107
+ * // The acting user ALWAYS comes from the session (res.locals.session) —
108
+ * // never from the request body:
109
+ * const userId = (res.locals.session as { userId?: string } | undefined)?.userId
110
+ * await createVersion({
111
+ * resourceType: 'document',
112
+ * resourceId: doc.id,
113
+ * userId: userId ?? null,
114
+ * snapshot: doc,
115
+ * reason: 'autosave',
116
+ * })
117
+ * ```
118
+ */
119
+ export * from './authorizers/index.js';
120
+ export * from './browser-guard.js';
121
+ export * from './diff.js';
122
+ export * from './handlers/index.js';
123
+ export * from './i18n.js';
124
+ export * from './registry.js';
125
+ export * from './requestHandlerMap.js';
126
+ export * from './routes.js';
127
+ export * from './service.js';
128
+ export * from './types.js';
129
+ export * from './validation.js';
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Parent-resource ownership-resolver registry for HTTP-driven version access.
3
+ *
4
+ * The version-history store is polymorphic and append-only: it captures full
5
+ * snapshots of *any* resource type and has no permission model of its own. It
6
+ * therefore cannot, by itself, know whether the caller is allowed to read or
7
+ * restore a given version — that truth lives with whoever owns the **parent**
8
+ * resource (the document/project/etc. the snapshot belongs to), not with the
9
+ * version row's `userId` (which is merely who captured the snapshot and may be
10
+ * `null` for system-generated versions).
11
+ *
12
+ * This registry lets each parent resource register a
13
+ * {@link VersionOwnershipResolver} keyed by `resourceType` at startup, so the
14
+ * HTTP handlers can ask "may this caller access versions of
15
+ * `(resourceType, resourceId)`?" without baking concrete resource imports into
16
+ * the version-history package (mirrors the trash resource's restore-callback
17
+ * registry).
18
+ *
19
+ * **Fail-closed:** when no resolver is registered for a `resourceType`, the
20
+ * handlers deny access (404, no existence leak). Apps that mount the raw
21
+ * version-history routes MUST register a resolver for every resource type they
22
+ * version, or compose their own ownership gate — otherwise the routes are
23
+ * inert by design rather than open.
24
+ *
25
+ * @module
26
+ */
27
+ /**
28
+ * The context an ownership resolver receives to decide access. `userId` is the
29
+ * authenticated caller (re-derived from `res.locals.session.userId`, never
30
+ * client-supplied).
31
+ */
32
+ export interface VersionOwnershipContext {
33
+ /** The parent resource type (e.g. `'document'`, `'project'`). */
34
+ resourceType: string;
35
+ /** The parent resource id whose versions are being accessed. */
36
+ resourceId: string;
37
+ /** The authenticated caller's user id. */
38
+ userId: string;
39
+ }
40
+ /**
41
+ * Resolves whether the authenticated caller may read/restore versions of a
42
+ * given parent resource. Return `true` to allow, `false` to deny. May be
43
+ * async (e.g. it can look the parent resource up in the database).
44
+ *
45
+ * @param context - The {@link VersionOwnershipContext} to authorize.
46
+ * @returns `true` when the caller owns / may access the parent resource.
47
+ */
48
+ export type VersionOwnershipResolver = (context: VersionOwnershipContext) => boolean | Promise<boolean>;
49
+ /**
50
+ * Registers an ownership resolver for a parent resource type.
51
+ *
52
+ * Subsequent calls with the same `resourceType` overwrite the previous
53
+ * registration.
54
+ *
55
+ * @param resourceType - The parent resource type the resolver authorizes.
56
+ * @param resolver - The resolver to invoke when authorizing access to versions
57
+ * of this resource type.
58
+ */
59
+ export declare function registerOwnershipResolver(resourceType: string, resolver: VersionOwnershipResolver): void;
60
+ /**
61
+ * Returns the ownership resolver registered for a resource type, or
62
+ * `undefined` if none has been registered.
63
+ *
64
+ * @param resourceType - The resource type to look up.
65
+ * @returns The resolver, or `undefined`.
66
+ */
67
+ export declare function getOwnershipResolver(resourceType: string): VersionOwnershipResolver | undefined;
68
+ /**
69
+ * Removes any registered ownership resolver for the given resource type.
70
+ *
71
+ * @param resourceType - The resource type whose resolver should be removed.
72
+ * @returns `true` if a resolver was removed.
73
+ */
74
+ export declare function unregisterOwnershipResolver(resourceType: string): boolean;
75
+ /**
76
+ * Clears all registered ownership resolvers. Primarily useful in tests.
77
+ */
78
+ export declare function clearOwnershipResolvers(): void;
79
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC,iEAAiE;IACjE,YAAY,EAAE,MAAM,CAAA;IACpB,gEAAgE;IAChE,UAAU,EAAE,MAAM,CAAA;IAClB,0CAA0C;IAC1C,MAAM,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,wBAAwB,GAAG,CACrC,OAAO,EAAE,uBAAuB,KAC7B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAI/B;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,wBAAwB,GACjC,IAAI,CAEN;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,wBAAwB,GAAG,SAAS,CAE/F;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAEzE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Parent-resource ownership-resolver registry for HTTP-driven version access.
3
+ *
4
+ * The version-history store is polymorphic and append-only: it captures full
5
+ * snapshots of *any* resource type and has no permission model of its own. It
6
+ * therefore cannot, by itself, know whether the caller is allowed to read or
7
+ * restore a given version — that truth lives with whoever owns the **parent**
8
+ * resource (the document/project/etc. the snapshot belongs to), not with the
9
+ * version row's `userId` (which is merely who captured the snapshot and may be
10
+ * `null` for system-generated versions).
11
+ *
12
+ * This registry lets each parent resource register a
13
+ * {@link VersionOwnershipResolver} keyed by `resourceType` at startup, so the
14
+ * HTTP handlers can ask "may this caller access versions of
15
+ * `(resourceType, resourceId)`?" without baking concrete resource imports into
16
+ * the version-history package (mirrors the trash resource's restore-callback
17
+ * registry).
18
+ *
19
+ * **Fail-closed:** when no resolver is registered for a `resourceType`, the
20
+ * handlers deny access (404, no existence leak). Apps that mount the raw
21
+ * version-history routes MUST register a resolver for every resource type they
22
+ * version, or compose their own ownership gate — otherwise the routes are
23
+ * inert by design rather than open.
24
+ *
25
+ * @module
26
+ */
27
+ const ownershipResolvers = new Map();
28
+ /**
29
+ * Registers an ownership resolver for a parent resource type.
30
+ *
31
+ * Subsequent calls with the same `resourceType` overwrite the previous
32
+ * registration.
33
+ *
34
+ * @param resourceType - The parent resource type the resolver authorizes.
35
+ * @param resolver - The resolver to invoke when authorizing access to versions
36
+ * of this resource type.
37
+ */
38
+ export function registerOwnershipResolver(resourceType, resolver) {
39
+ ownershipResolvers.set(resourceType, resolver);
40
+ }
41
+ /**
42
+ * Returns the ownership resolver registered for a resource type, or
43
+ * `undefined` if none has been registered.
44
+ *
45
+ * @param resourceType - The resource type to look up.
46
+ * @returns The resolver, or `undefined`.
47
+ */
48
+ export function getOwnershipResolver(resourceType) {
49
+ return ownershipResolvers.get(resourceType);
50
+ }
51
+ /**
52
+ * Removes any registered ownership resolver for the given resource type.
53
+ *
54
+ * @param resourceType - The resource type whose resolver should be removed.
55
+ * @returns `true` if a resolver was removed.
56
+ */
57
+ export function unregisterOwnershipResolver(resourceType) {
58
+ return ownershipResolvers.delete(resourceType);
59
+ }
60
+ /**
61
+ * Clears all registered ownership resolvers. Primarily useful in tests.
62
+ */
63
+ export function clearOwnershipResolvers() {
64
+ ownershipResolvers.clear();
65
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Maps route handler names to their implementations.
3
+ *
4
+ * @module
5
+ */
6
+ import { versionCount } from './handlers/count.js';
7
+ import { create } from './handlers/create.js';
8
+ import { diff } from './handlers/diff.js';
9
+ import { list } from './handlers/list.js';
10
+ import { read } from './handlers/read.js';
11
+ import { readByNumber } from './handlers/readByNumber.js';
12
+ import { restore } from './handlers/restore.js';
13
+ /**
14
+ * Handler map for version-history routes.
15
+ */
16
+ export declare const requestHandlerMap: {
17
+ readonly create: typeof create;
18
+ readonly list: typeof list;
19
+ readonly versionCount: typeof versionCount;
20
+ readonly readByNumber: typeof readByNumber;
21
+ readonly read: typeof read;
22
+ readonly restore: typeof restore;
23
+ readonly diff: typeof diff;
24
+ };
25
+ //# sourceMappingURL=requestHandlerMap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAA;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAA;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAA;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAA;AAE/C;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;CAQpB,CAAA"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Maps route handler names to their implementations.
3
+ *
4
+ * @module
5
+ */
6
+ import { versionCount } from './handlers/count.js';
7
+ import { create } from './handlers/create.js';
8
+ import { diff } from './handlers/diff.js';
9
+ import { list } from './handlers/list.js';
10
+ import { read } from './handlers/read.js';
11
+ import { readByNumber } from './handlers/readByNumber.js';
12
+ import { restore } from './handlers/restore.js';
13
+ /**
14
+ * Handler map for version-history routes.
15
+ */
16
+ export const requestHandlerMap = {
17
+ create,
18
+ list,
19
+ versionCount,
20
+ readByNumber,
21
+ read,
22
+ restore,
23
+ diff,
24
+ };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Version-history route definitions.
3
+ *
4
+ * Declarative routing — `mlcl inject` reads this to generate the Express router.
5
+ *
6
+ * Append-only by design: there are no `PUT` or `DELETE` routes for individual
7
+ * versions. The only mutation paths are `create` (capture a new snapshot) and
8
+ * `restore` (capture a new snapshot equal to a prior one).
9
+ *
10
+ * **Secure by default.** Snapshots can hold any tenant's data, so EVERY route
11
+ * requires an authenticated session (`authenticate`) AND its handler re-derives
12
+ * the caller from `res.locals.session.userId` and authorizes access to
13
+ * the *parent* resource via the pluggable, fail-closed ownership resolver
14
+ * (`registerOwnershipResolver`). The in-handler gate holds even if the injector
15
+ * drops a middleware string (defense-in-depth, mirroring
16
+ * `@molecule/api-resource-trash`); with no registered resolver every read/list/
17
+ * diff/restore returns 404 (no existence leak) rather than exposing snapshots.
18
+ *
19
+ * Legitimate cross-tenant access (an admin/compliance console) is opt-in:
20
+ * compose the {@link versionHistoryAdmin} middleware onto a route to widen an
21
+ * authenticated *admin* to all users' versions. Without it, every caller is
22
+ * subject to the ownership resolver — there is no open endpoint.
23
+ *
24
+ * @module
25
+ */
26
+ /**
27
+ * Routes for the version-history resource. All routes require `authenticate`;
28
+ * the handlers additionally authorize every read/mutation against the caller's
29
+ * ownership of the parent resource.
30
+ */
31
+ export declare const routes: readonly [{
32
+ readonly method: "post";
33
+ readonly path: "/:resourceType/:resourceId/versions";
34
+ readonly handler: "create";
35
+ readonly middlewares: readonly ["authenticate"];
36
+ }, {
37
+ readonly method: "get";
38
+ readonly path: "/:resourceType/:resourceId/versions";
39
+ readonly handler: "list";
40
+ readonly middlewares: readonly ["authenticate"];
41
+ }, {
42
+ readonly method: "get";
43
+ readonly path: "/:resourceType/:resourceId/versions/count";
44
+ readonly handler: "versionCount";
45
+ readonly middlewares: readonly ["authenticate"];
46
+ }, {
47
+ readonly method: "get";
48
+ readonly path: "/:resourceType/:resourceId/versions/:version";
49
+ readonly handler: "readByNumber";
50
+ readonly middlewares: readonly ["authenticate"];
51
+ }, {
52
+ readonly method: "get";
53
+ readonly path: "/versions/:versionId";
54
+ readonly handler: "read";
55
+ readonly middlewares: readonly ["authenticate"];
56
+ }, {
57
+ readonly method: "post";
58
+ readonly path: "/versions/:versionId/restore";
59
+ readonly handler: "restore";
60
+ readonly middlewares: readonly ["authenticate"];
61
+ }, {
62
+ readonly method: "get";
63
+ readonly path: "/versions/:fromVersionId/diff/:toVersionId";
64
+ readonly handler: "diff";
65
+ readonly middlewares: readonly ["authenticate"];
66
+ }];
67
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;GAIG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCT,CAAA"}
package/dist/routes.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Version-history route definitions.
3
+ *
4
+ * Declarative routing — `mlcl inject` reads this to generate the Express router.
5
+ *
6
+ * Append-only by design: there are no `PUT` or `DELETE` routes for individual
7
+ * versions. The only mutation paths are `create` (capture a new snapshot) and
8
+ * `restore` (capture a new snapshot equal to a prior one).
9
+ *
10
+ * **Secure by default.** Snapshots can hold any tenant's data, so EVERY route
11
+ * requires an authenticated session (`authenticate`) AND its handler re-derives
12
+ * the caller from `res.locals.session.userId` and authorizes access to
13
+ * the *parent* resource via the pluggable, fail-closed ownership resolver
14
+ * (`registerOwnershipResolver`). The in-handler gate holds even if the injector
15
+ * drops a middleware string (defense-in-depth, mirroring
16
+ * `@molecule/api-resource-trash`); with no registered resolver every read/list/
17
+ * diff/restore returns 404 (no existence leak) rather than exposing snapshots.
18
+ *
19
+ * Legitimate cross-tenant access (an admin/compliance console) is opt-in:
20
+ * compose the {@link versionHistoryAdmin} middleware onto a route to widen an
21
+ * authenticated *admin* to all users' versions. Without it, every caller is
22
+ * subject to the ownership resolver — there is no open endpoint.
23
+ *
24
+ * @module
25
+ */
26
+ /**
27
+ * Routes for the version-history resource. All routes require `authenticate`;
28
+ * the handlers additionally authorize every read/mutation against the caller's
29
+ * ownership of the parent resource.
30
+ */
31
+ export const routes = [
32
+ {
33
+ method: 'post',
34
+ path: '/:resourceType/:resourceId/versions',
35
+ handler: 'create',
36
+ middlewares: ['authenticate'],
37
+ },
38
+ {
39
+ method: 'get',
40
+ path: '/:resourceType/:resourceId/versions',
41
+ handler: 'list',
42
+ middlewares: ['authenticate'],
43
+ },
44
+ {
45
+ method: 'get',
46
+ path: '/:resourceType/:resourceId/versions/count',
47
+ handler: 'versionCount',
48
+ middlewares: ['authenticate'],
49
+ },
50
+ {
51
+ method: 'get',
52
+ path: '/:resourceType/:resourceId/versions/:version',
53
+ handler: 'readByNumber',
54
+ middlewares: ['authenticate'],
55
+ },
56
+ { method: 'get', path: '/versions/:versionId', handler: 'read', middlewares: ['authenticate'] },
57
+ {
58
+ method: 'post',
59
+ path: '/versions/:versionId/restore',
60
+ handler: 'restore',
61
+ middlewares: ['authenticate'],
62
+ },
63
+ {
64
+ method: 'get',
65
+ path: '/versions/:fromVersionId/diff/:toVersionId',
66
+ handler: 'diff',
67
+ middlewares: ['authenticate'],
68
+ },
69
+ ];