@krak-stack/assets 0.1.2 → 0.1.6

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 (94) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +206 -14
  3. package/dist/access.d.ts +44 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +56 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/api.builder.d.ts +100 -0
  8. package/dist/api.builder.d.ts.map +1 -0
  9. package/dist/api.builder.js +233 -0
  10. package/dist/api.builder.js.map +1 -0
  11. package/dist/api.d.ts +2 -0
  12. package/dist/api.d.ts.map +1 -0
  13. package/dist/api.group.d.ts +222 -0
  14. package/dist/api.group.d.ts.map +1 -0
  15. package/dist/api.group.js +83 -0
  16. package/dist/api.group.js.map +1 -0
  17. package/dist/api.js +2 -0
  18. package/dist/api.js.map +1 -0
  19. package/dist/catalog.d.ts +91 -0
  20. package/dist/catalog.d.ts.map +1 -0
  21. package/dist/catalog.js +52 -0
  22. package/dist/catalog.js.map +1 -0
  23. package/dist/client.d.ts +245 -0
  24. package/dist/client.d.ts.map +1 -0
  25. package/dist/client.js +8 -0
  26. package/dist/client.js.map +1 -0
  27. package/dist/commands.d.ts +55 -0
  28. package/dist/commands.d.ts.map +1 -0
  29. package/dist/commands.js +127 -0
  30. package/dist/commands.js.map +1 -0
  31. package/dist/components/asset-input/html.d.ts +70 -0
  32. package/dist/components/asset-input/html.d.ts.map +1 -0
  33. package/dist/components/asset-input/html.js +1549 -0
  34. package/dist/components/asset-input/html.js.map +1 -0
  35. package/dist/components/asset-input/index.d.ts +280 -0
  36. package/dist/components/asset-input/react.d.ts +32 -0
  37. package/dist/components/asset-input/react.d.ts.map +1 -0
  38. package/dist/components/asset-input/react.js +2269 -0
  39. package/dist/components/asset-input/react.js.map +1 -0
  40. package/dist/components/asset-input/schema.d.ts +93 -0
  41. package/dist/components/asset-input/upload.d.ts +15 -0
  42. package/dist/components/asset-table/html.d.ts +110 -0
  43. package/dist/components/asset-table/html.d.ts.map +1 -0
  44. package/dist/components/asset-table/html.js +4934 -0
  45. package/dist/components/asset-table/html.js.map +1 -0
  46. package/dist/components/asset-table/index.d.ts +225 -0
  47. package/dist/components/asset-table/react.d.ts +21 -0
  48. package/dist/components/asset-table/react.d.ts.map +1 -0
  49. package/dist/components/asset-table/react.js +8241 -0
  50. package/dist/components/asset-table/react.js.map +1 -0
  51. package/dist/components/asset-table/schema.d.ts +73 -0
  52. package/dist/index.d.ts +266 -10
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +245 -35
  55. package/dist/index.js.map +1 -1
  56. package/dist/migrations/0003_upload_publications.d.ts +5 -0
  57. package/dist/migrations/0003_upload_publications.d.ts.map +1 -0
  58. package/dist/migrations/0003_upload_publications.js +14 -0
  59. package/dist/migrations/0003_upload_publications.js.map +1 -0
  60. package/dist/migrations/0004_upload_intents.d.ts +5 -0
  61. package/dist/migrations/0004_upload_intents.d.ts.map +1 -0
  62. package/dist/migrations/0004_upload_intents.js +14 -0
  63. package/dist/migrations/0004_upload_intents.js.map +1 -0
  64. package/dist/migrations.d.ts.map +1 -1
  65. package/dist/migrations.js +4 -0
  66. package/dist/migrations.js.map +1 -1
  67. package/dist/queries.d.ts +6 -0
  68. package/dist/queries.d.ts.map +1 -0
  69. package/dist/queries.js +18 -0
  70. package/dist/queries.js.map +1 -0
  71. package/dist/retrieval.d.ts +6 -1
  72. package/dist/retrieval.d.ts.map +1 -1
  73. package/dist/retrieval.js +50 -19
  74. package/dist/retrieval.js.map +1 -1
  75. package/dist/schema.d.ts +165 -9
  76. package/dist/schema.d.ts.map +1 -1
  77. package/dist/schema.js +119 -2
  78. package/dist/schema.js.map +1 -1
  79. package/dist/services/assets/library.d.ts +221 -0
  80. package/dist/services/assets/library.d.ts.map +1 -0
  81. package/dist/services/assets/library.js +101 -0
  82. package/dist/services/assets/library.js.map +1 -0
  83. package/dist/services/assets/schema.d.ts +3 -0
  84. package/dist/services/assets/url.d.ts +12 -0
  85. package/dist/services/assets/use-library.d.ts +20 -0
  86. package/dist/workflow.d.ts +20 -0
  87. package/dist/workflow.d.ts.map +1 -1
  88. package/dist/workflow.js +10 -0
  89. package/dist/workflow.js.map +1 -1
  90. package/dist/workflows.d.ts +3 -0
  91. package/dist/workflows.d.ts.map +1 -1
  92. package/dist/workflows.js +53 -4
  93. package/dist/workflows.js.map +1 -1
  94. package/package.json +45 -11
package/CHANGELOG.md CHANGED
@@ -1,5 +1,90 @@
1
1
  # @krak-stack/assets
2
2
 
3
+ ## 0.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - bac7f20: Keep keyboard focus visible on attachment action buttons without outlining the surrounding attachment or clipping the ring in scrolling lists.
8
+ - bac7f20: Refresh managed image thumbnails after an asset is replaced without changing its shared link. Show image thumbnails in selected Asset Input attachments.
9
+
10
+ Show local image thumbnails in the upload dialog, both before upload and during progress.
11
+ - bac7f20: Add an optional Upload button trigger to Asset Input that opens the dialog with no files staged.
12
+
13
+ Keep the staged files and upload progress visible until the dialog finishes closing, while still cancelling active uploads immediately.
14
+ - bac7f20: Keep the asset upload dialog within the viewport and scroll vertically without a horizontal scrollbar in React and Effect UI HTML.
15
+ - 386a549: Move the React and Effect UI HTML implementations of Asset Input and Asset Table into the Assets package. Both packages build from that source, so existing registry imports and source installs keep working.
16
+ - bac7f20: Expose project roles, permission policies, and `CurrentActor` through `@krak-stack/registry/access`, without coupling reusable services to an authentication provider. Assets reads the verified request actor directly and ships a standalone `AssetsAccess` role definition. `Assets.apiLayer()` uses those grants by default and accepts an explicit permission matrix for existing projects.
17
+
18
+ Compose Registry access definitions with `.merge(AssetsAccess)`. Matching role names gain the incoming grants without replacing existing grants or importing new roles. Override role matches when the names differ.
19
+
20
+ Mount an authorized asset list and stable file redirects through `Assets.apiLayer`, with a typed `AssetsApi` contract.
21
+
22
+ Expose a typed HTTP client at `@krak-stack/assets/client` and the opt-in `AssetList` Query at `@krak-stack/assets/queries`. List-only callers receive metadata without file URLs.
23
+
24
+ Export `assetWorkflowsLayer` to register document processing and upload scanning together on the application's workflow engine.
25
+
26
+ Complete browser uploads using the reserved asset ID, with a separate attempt ID only for replacements. Poll upload status on the asset URL, and open or download the file using its stable `url`. Organization asset statistics are computed in PostgreSQL.
27
+
28
+ Consolidate asset listing and organization-wide stats into `GET /api/assets`. The route returns all matching assets without server-side pagination.
29
+
30
+ Start uploads at `POST /api/assets`, fetch details at `GET /api/assets/:assetId`, and search or read document chunks at `GET /api/assets/:assetId/chunks`. HTTP clients use chunk IDs instead of processing IDs.
31
+
32
+ Move asset authoring HTTP handlers into the package: document retrieval, statistics, scanned uploads, replacement, and bulk deletion. Upload intents bind actor, organization, and replacement target. Export browser transport and mutation Commands through `@krak-stack/assets/commands`.
33
+ - Updated dependencies [bac7f20]
34
+ - Updated dependencies [bac7f20]
35
+ - Updated dependencies [386a549]
36
+ - Updated dependencies [bac7f20]
37
+ - Updated dependencies [386a549]
38
+ - Updated dependencies [bac7f20]
39
+ - Updated dependencies [386a549]
40
+ - Updated dependencies [386a549]
41
+ - Updated dependencies [386a549]
42
+ - Updated dependencies [bac7f20]
43
+ - Updated dependencies [386a549]
44
+ - Updated dependencies [504c0e3]
45
+ - @krak-stack/registry@0.11.9
46
+
47
+ ## 0.1.5
48
+
49
+ ### Patch Changes
50
+
51
+ - Updated dependencies [638519a]
52
+ - Updated dependencies [74bceea]
53
+ - Updated dependencies [82519d5]
54
+ - Updated dependencies [b1871af]
55
+ - Updated dependencies [9f769d7]
56
+ - Updated dependencies [82519d5]
57
+ - Updated dependencies [6b8496b]
58
+ - Updated dependencies [9f769d7]
59
+ - Updated dependencies [be41f07]
60
+ - Updated dependencies [805d5bd]
61
+ - Updated dependencies [294ec12]
62
+ - Updated dependencies [247eb93]
63
+ - Updated dependencies [9f769d7]
64
+ - Updated dependencies [9f769d7]
65
+ - Updated dependencies [f382af2]
66
+ - Updated dependencies [247eb93]
67
+ - Updated dependencies [2aeb055]
68
+ - @krak-stack/registry@0.11.0
69
+
70
+ ## 0.1.4
71
+
72
+ ### Patch Changes
73
+
74
+ - Export a standalone Effect ClamAV client at `@krak-stack/registry/clamav` and add opt-in durable malware scanning to Assets. Scanned uploads stay private until their verified bytes pass scanning.
75
+ - Updated dependencies
76
+ - Updated dependencies
77
+ - @krak-stack/registry@0.10.15
78
+
79
+ ## 0.1.3
80
+
81
+ ### Patch Changes
82
+
83
+ - Upgrade to Effect 4.1.0 and use Effect crypto services for UUIDv7 entity IDs, hashing, and secure capability generation. Preserve existing deterministic fingerprints and random upload capability tokens.
84
+ - Updated dependencies
85
+ - Updated dependencies [d3000ed]
86
+ - @krak-stack/registry@0.1.56
87
+
3
88
  ## 0.1.2
4
89
 
5
90
  ### Patch Changes
package/README.md CHANGED
@@ -5,18 +5,76 @@ and searchable passages through one Effect `Assets` service.
5
5
  Published as `@krak-stack/assets`, independently of application HTTP and auth layers.
6
6
 
7
7
  ```sh
8
- bun add @krak-stack/assets@0.1.1 @effect/sql-pg@4.0.0 effect@4.0.0
8
+ bun add @krak-stack/assets @effect/sql-pg@^4.2.0 effect@^4.2.0
9
9
  ```
10
10
 
11
11
  See the [Assets guide](https://krakstack.net/docs/assets) for application setup
12
12
  and retrieval examples. This README covers package boundaries and operations.
13
13
 
14
+ ## Asset picker and table
15
+
16
+ Import the React components from `@krak-stack/assets/asset-input/react` and
17
+ `@krak-stack/assets/asset-table/react`. For Effect UI HTML, use
18
+ `@krak-stack/assets/asset-input/html` and `@krak-stack/assets/asset-table/html`.
19
+ These entry points are separate from the server-side `Assets` service. Add
20
+ `@import "@krak-stack/registry/tailwind.css";` to your app’s Tailwind stylesheet
21
+ so it scans the component styles.
22
+
23
+ The component source lives in `packages/assets/src/components`. In the
24
+ workspace, build the registry before building Assets; both packages publish
25
+ compiled implementations from this source.
26
+
27
+ The app supplies asset records and optional stable URLs, controls selection, and
28
+ handles upload transport and authorization. Using the components does not
29
+ register any HTTP routes.
30
+
31
+ ## Opt-in malware scanning
32
+
33
+ Provide `ClamAV.layer` from `@krak-stack/registry/clamav` to
34
+ `Assets.layerWithMalwareScanning` alongside the usual PostgreSQL and S3 layers.
35
+ Use `assetWorkflowsLayer` to register both workflows with the same Assets service
36
+ and host-provided engine:
37
+
38
+ ```ts
39
+ import { assetWorkflowsLayer } from "@krak-stack/assets/workflows";
40
+
41
+ const assets = Assets.layerWithMalwareScanning.pipe(
42
+ Layer.provide(ClamAV.layer),
43
+ Layer.provide(s3Layer),
44
+ Layer.provide(databaseLayer),
45
+ );
46
+ const runtimeLayer = assetWorkflowsLayer.pipe(
47
+ Layer.provideMerge(assets),
48
+ Layer.provideMerge(workflowEngineLayer),
49
+ );
50
+ ```
51
+
52
+ The individual worker layers are still available when you need to compose them
53
+ separately. When calling the service directly, after the
54
+ browser completes its PUT, call `queueUploadScan` instead of `completeUpload`.
55
+ After submission succeeds, poll `getUploadScan` with the same authenticated
56
+ organization and actor. `published` returns an asset ID. An unfinished or
57
+ unknown workflow reports `pending` with no asset ID. `rejected`,
58
+ `unscannable`, `invalid`, and `failed` are terminal. Start a fresh upload after a
59
+ terminal failure. Finalization checks that the staged object exists before
60
+ queueing. The worker verifies its actual size and checksum before scanning.
61
+ The workflow engine handles retries; there is no scan
62
+ dispatcher. A receipt stored with the asset in PostgreSQL makes `published`
63
+ visible before extraction and prevents replay from recreating a deleted asset.
64
+ The receipt records a past publication, not current download availability.
65
+ Do not route uploads through a legacy runtime as a fallback.
66
+
67
+ Apply a lifecycle expiration rule only to `scan-staging/` in private object
68
+ storage (for example, seven days). Existing assets are not rescanned.
69
+ A clean result means no threat was detected, not that every format or embedded
70
+ object was inspected. Test the actual scanner configuration and accepted
71
+ formats before rollout.
72
+
14
73
  ## Boundaries
15
74
 
16
75
  - Import `Assets` from `@krak-stack/assets` and schemas from `@krak-stack/assets/schema`.
17
- - The package owns `assets`, `asset_processings`, `asset_chunks`, and `asset_migrations`.
18
- - The application owns HTTP contracts and handlers, route registration,
19
- authentication, trusted scope,
76
+ - The package owns the asset tables, workflows, and opt-in HTTP API.
77
+ - The application owns route registration, authentication, trusted scope,
20
78
  permission policies, UI, database configuration,
21
79
  workflow-engine configuration, and references from its own domain entities.
22
80
  - Dependencies are declared here: Effect, Effect Postgres, KrakStack S3, and Xberg.
@@ -28,8 +86,11 @@ and retrieval examples. This README covers package boundaries and operations.
28
86
 
29
87
  `Assets.layer` runs pending asset migrations before providing the asset service.
30
88
  It does not register HTTP routes or depend on an authentication implementation.
31
- Provide `SqlClient` and `S3Service`;
32
- operations that enqueue processing also require `WorkflowEngine`.
89
+ Provide `SqlClient` and `S3Service` to build the service. Listing, downloading,
90
+ and deleting files do not need a workflow engine. Operations that schedule
91
+ document processing or submit or poll an upload scan use the host's Effect
92
+ `WorkflowEngine`. Assets registers workflows on that engine; it does not create
93
+ its own.
33
94
  The SQL client must transform camel-case query names to snake case, snake-case
34
95
  result names to camel case, and leave JSON keys unchanged (`transformJson: false`).
35
96
 
@@ -46,7 +107,7 @@ const assetsLayer = Assets.layer.pipe(
46
107
 
47
108
  const runtimeLayer = assetProcessingWorkflowLayer.pipe(
48
109
  Layer.provideMerge(assetsLayer),
49
- Layer.provide(workflowEngineLayer),
110
+ Layer.provideMerge(workflowEngineLayer),
50
111
  );
51
112
  ```
52
113
 
@@ -63,14 +124,145 @@ Servers, workers, scripts, and service tests use the same `Assets.layer` or
63
124
 
64
125
  ## API composition
65
126
 
66
- The application defines its HTTP group and handlers, importing reusable schemas
67
- from `@krak-stack/assets/schema` and calling `Assets` directly. The package has no
68
- HTTP adapter or API exports.
127
+ Mount `Assets.apiLayer` alongside your other router layers. It does not require
128
+ adding a group to your root `HttpApi`. Import `AssetsApi` from
129
+ `@krak-stack/assets/api` to create a typed client for these routes:
130
+
131
+ - `GET /api/assets` returns `{ items, stats }`. It accepts `search` (filename
132
+ substring) and `kind`, and returns all matching items without pagination.
133
+ Results are ordered newest-updated first. Callers with `read` receive stable
134
+ file URLs; list-only callers receive metadata without URLs. The response never
135
+ includes object keys or signed storage URLs. `stats` contains the organization-wide `assetCount` and
136
+ `storageUsedBytes`, regardless of filters. Use this route instead of
137
+ `/api/assets/all` and `/api/assets/stats`.
138
+ - Open or download `asset.url` directly. It points to
139
+ `GET /api/assets/:assetId/file`, which checks access and redirects to a fresh
140
+ signed storage URL. Copy the stable URL, not the redirect target.
141
+ - `GET /api/assets/:assetId` returns document metadata, indexing status, and
142
+ outline. Use `outlineOffset` to continue the outline.
143
+ - `GET /api/assets/:assetId/chunks?query=onboarding&language=en` searches the
144
+ current text index. To read exact matches, call the same route with
145
+ `?ids=<chunk-id>&ids=<another-chunk-id>` instead. Stale IDs return `409`;
146
+ rerun the search. HTTP clients never need a processing ID.
147
+ - `POST /api/assets` reserves an asset ID and returns a signed PUT URL.
148
+ Replacements also return an `attemptId`.
149
+
150
+ The API also provides asset statistics, document overview and passage retrieval,
151
+ and mutation routes for uploads, replacements, and bulk deletion. Hosts that
152
+ already use a root `HttpApi` can add `AssetsApiGroup` and register
153
+ `Assets.apiHandlers(access)` with `handlers.handleAll(...)` instead of mounting both.
154
+
155
+ Provide `Assets` and the workflow engine per request:
156
+
157
+ ```ts
158
+ import { AssetsAccess } from "@krak-stack/assets/access";
159
+
160
+ const assetRoutes = Assets.apiLayer().pipe(
161
+ HttpRouter.provideRequest(assetsRuntimeLayer),
162
+ );
163
+ ```
164
+
165
+ The host's authentication middleware provides `CurrentActor` from
166
+ `@krak-stack/registry/access` for each verified request. The Auth SDK already
167
+ provides a compatible context. Assets does not import the Auth SDK.
168
+ Never take identity, organization scope, or permissions from the browser.
169
+
170
+ `AssetsAccess` is exported from the package root and the `/access` subpath.
171
+ The default roles are `owner` and `admin` (all asset operations), and `member`
172
+ (list and read). After verifying role membership, the host can populate
173
+ `CurrentActor.permissions` using `AssetsAccess.permissionsForRoles(verifiedRoles)`.
174
+ Assets checks effective grants, not role names on the actor. Pass a custom
175
+ matrix to use existing project grants instead; omitted operations are denied.
176
+
177
+ If your project uses the Registry’s `defineProjectAccess`, call
178
+ `defineProjectAccess(projectConfig).merge(AssetsAccess)` to add the built-in
179
+ asset grants to matching project roles. This preserves existing grants and
180
+ does not import roles. For different role names, pass
181
+ `{ roles: { librarian: "admin" } }` to `.merge`; use `null` to skip a role.
182
+ Populate `CurrentActor.permissions` with the merged definition’s
183
+ `permissionsForRoles(verifiedRoles)` and mount `Assets.apiLayer()` as usual.
184
+ Merging does not change existing API-key grants. Use a custom matrix if
185
+ Assets should continue to check those existing grants:
186
+
187
+ ```ts
188
+ const readOnly = AssetsAccess.fromMatrix({
189
+ list: "courses:asset:read",
190
+ read: "courses:asset:read",
191
+ });
192
+ const routes = Assets.apiLayer(readOnly);
193
+ ```
194
+
195
+ The API returns `401` without a verified actor and `403` when the caller
196
+ lacks organization access. The list route requires `list`; the file route
197
+ requires `read`. Missing permissions return `403` before storage access, so
198
+ `permissions: []` denies all asset operations. Uploads require `create`;
199
+ replacements require `update`; deletion requires `delete`. Use the scanned
200
+ asset service and register the upload scan workflow to enable HTTP uploads.
201
+ The server binds each upload to the initiating actor, organization, and upload
202
+ payload, including any replacement target. Completion and polling recheck
203
+ permissions against that binding.
204
+
205
+ After the signed PUT succeeds, call `POST /api/assets/:assetId/complete` with
206
+ no body, then poll `GET /api/assets/:assetId`. The initiating actor can see
207
+ `uploadStatus` before publication. After publication, callers with read access
208
+ receive asset details and the stable file URL. For replacements, pass
209
+ `?attemptId=…` on both calls; the plain asset URL continues to serve the
210
+ published file until its replacement is ready.
211
+
212
+ These permissions are organization-wide. For access limited to a specific
213
+ attachment, use a host-owned route that verifies both access to the parent
214
+ record and the record's actual attachment relationship before calling `Assets`.
215
+
216
+ ### Connect Asset Input and Asset Table
217
+
218
+ `@krak-stack/assets/client` exports the typed `makeAssetsClient` factory and
219
+ `AssetsClient.layer`, both built from `AssetsApi`. Use the client directly when
220
+ you only need HTTP. `AssetInput` and `AssetTable` can connect to that client
221
+ directly through the shared library layer, or you can pass `assets` to
222
+ render a host-provided list without HTTP.
223
+
224
+ ```ts
225
+ import { AssetsClient } from "@krak-stack/assets/client";
226
+ import { assetLibraryLayer, makeAssetLibraryRuntime } from "@krak-stack/assets/commands";
227
+ import { Layer } from "effect";
228
+ import { FetchHttpClient } from "effect/http";
229
+
230
+ // Browser: use the app origin so session cookies are sent same-origin.
231
+ const assetsClientLayer = AssetsClient.layer({
232
+ baseUrl: window.location.origin,
233
+ }).pipe(Layer.provide(FetchHttpClient.layer));
234
+ const runtime = makeAssetLibraryRuntime(assetsClientLayer); // React
235
+ const libraryLayer = assetLibraryLayer.pipe(Layer.provide(assetsClientLayer)); // HTML
236
+ ```
69
237
 
70
- Derive trusted organization and actor IDs from authentication, apply permission
71
- checks, and map service errors at the application's HTTP boundary. Never trust
72
- organization or actor IDs supplied by a browser as scope. Register the group in
73
- the application's root API to expose typed clients, OpenAPI, MCP, or CLI tools.
238
+ - **React:** Pass `{ runtime, access }` to either component. For example,
239
+ `<AssetTable runtime={runtime} access={access} />`. For a picker, also
240
+ pass `label`, `value`, and `onChange`. The components use `useModel`;
241
+ no app-owned asset atoms are needed. Dashboard consumers can use
242
+ `useAssetLibrary` from `@krak-stack/assets/asset-table/react`.
243
+ - **Effect UI HTML:** Provide `libraryLayer` to the parent with
244
+ `Component.provide(libraryLayer)` and pass `access` as a prop to either
245
+ component. The renderer provides the query cache; keep connected consumers
246
+ under the same root to share it. Handle `Changed` and `Published` events
247
+ in the picker’s parent. For reads only, `assetListLayer` from
248
+ `@krak-stack/assets/queries` implements the portable `AssetList` query.
249
+
250
+ Set `access` to `{ scopeKey, permissions }` using the verified host session.
251
+ Without `list`, no browse request is made. Without `read`, items have no file
252
+ URL, so the views use MIME icons and omit file actions. `create`, `update`,
253
+ and `delete` enable upload, replacement, and deletion respectively. Keep
254
+ the picker’s selected IDs in the host.
255
+
256
+ Use a non-secret key unique to the active actor and organization. The key
257
+ partitions the client cache and is never sent to the server. On sign-out or an
258
+ organization switch, unmount the old consumer and discard its query cache;
259
+ mount the next one only after the new auth context is active. Don't persist or
260
+ share this cache across sessions. The browser's permissions only guide
261
+ presentation; the server still authorizes each request.
262
+
263
+ `@krak-stack/assets/commands` exposes browser upload transport, publication,
264
+ and deletion effects, plus `PublishAsset` and `DeleteAssets` command layers.
265
+ Publication invalidates `AssetList` only after the scan publishes the asset.
74
266
 
75
267
  ## Migrations
76
268
 
@@ -0,0 +1,44 @@
1
+ import { Effect } from "effect";
2
+ import { HttpApiError } from "effect/http-api";
3
+ import { type AssetPermission } from "./schema.js";
4
+ /** An omitted operation grants no access. Values identify required permissions. */
5
+ export type AssetsPermissionMatrix = Readonly<Partial<Record<AssetPermission, string>>>;
6
+ declare const fromMatrix: (matrix: AssetsPermissionMatrix) => {
7
+ resolve: Effect.Effect<{
8
+ actorId: string;
9
+ organizationId: string;
10
+ permissions: ("create" | "delete" | "list" | "read" | "update")[];
11
+ }, HttpApiError.Forbidden | HttpApiError.Unauthorized, never>;
12
+ };
13
+ export type AssetsAuthorization = ReturnType<typeof fromMatrix>;
14
+ /** Adapts verified request grants to organization-wide Assets permissions. */
15
+ export declare const AssetsAccess: {
16
+ readonly roleNames: readonly ("admin" | "member" | "owner")[];
17
+ readonly permissionsForRoles: (verifiedRoles: Iterable<string>) => ReadonlySet<"assets:asset:create" | "assets:asset:delete" | "assets:asset:list" | "assets:asset:read" | "assets:asset:update">;
18
+ readonly project: "assets";
19
+ readonly actions: readonly ("asset:create" | "asset:delete" | "asset:list" | "asset:read" | "asset:update")[];
20
+ readonly roles: Readonly<Record<string, readonly ("asset:create" | "asset:delete" | "asset:list" | "asset:read" | "asset:update")[] | undefined>>;
21
+ readonly qualify: (action: "asset:create" | "asset:delete" | "asset:list" | "asset:read" | "asset:update") => "assets:asset:create" | "assets:asset:delete" | "assets:asset:list" | "assets:asset:read" | "assets:asset:update";
22
+ readonly permission: (action: "asset:create" | "asset:delete" | "asset:list" | "asset:read" | "asset:update") => import("@krak-stack/registry/access").Policy;
23
+ readonly merge: <OtherRole extends string, OtherGrant extends string>(other: {
24
+ readonly roleNames: readonly OtherRole[];
25
+ readonly permissionsForRoles: (verifiedRoles: Iterable<string>) => ReadonlySet<OtherGrant>;
26
+ }, options?: {
27
+ readonly roles: Readonly<Partial<Record<"admin" | "member" | "owner", NoInfer<OtherRole> | null>>>;
28
+ } | undefined) => import("@krak-stack/registry/access").ProjectAccess<"assets", "asset:create" | "asset:delete" | "asset:list" | "asset:read" | "asset:update", "admin" | "member" | "owner", "assets:asset:create" | "assets:asset:delete" | "assets:asset:list" | "assets:asset:read" | "assets:asset:update" | OtherGrant>;
29
+ readonly resolve: Effect.Effect<{
30
+ actorId: string;
31
+ organizationId: string;
32
+ permissions: ("create" | "delete" | "list" | "read" | "update")[];
33
+ }, HttpApiError.Forbidden | HttpApiError.Unauthorized, never>;
34
+ /** Use the exact permission identifiers supplied by a custom actor provider. */
35
+ readonly fromMatrix: (matrix: AssetsPermissionMatrix) => {
36
+ resolve: Effect.Effect<{
37
+ actorId: string;
38
+ organizationId: string;
39
+ permissions: ("create" | "delete" | "list" | "read" | "update")[];
40
+ }, HttpApiError.Forbidden | HttpApiError.Unauthorized, never>;
41
+ };
42
+ };
43
+ export {};
44
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAyB,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1E,mFAAmF;AACnF,MAAM,MAAM,sBAAsB,GAAG,QAAQ,CAC3C,OAAO,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CACzC,CAAC;AAEF,QAAA,MAAM,UAAU,WAAY,sBAAsB;IAM9C,OAAO;;;;;CAeV,CAAC;AAoBF,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;AAEhE,8EAA8E;AAC9E,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;IASvB,gFAAgF;kCArDtD,sBAAsB;QAM9C,OAAO;;;;;;CAiDD,CAAC"}
package/dist/access.js ADDED
@@ -0,0 +1,56 @@
1
+ import { CurrentActor, defineProjectAccess, principalId, } from "@krak-stack/registry/access";
2
+ import { Effect, Option } from "effect";
3
+ import { HttpApiError } from "effect/http-api";
4
+ import { AssetPermissionSchema } from "./schema.js";
5
+ const fromMatrix = (matrix) => {
6
+ const grants = AssetPermissionSchema.literals.flatMap((operation) => {
7
+ const required = matrix[operation];
8
+ return required === undefined ? [] : [{ operation, required }];
9
+ });
10
+ return {
11
+ resolve: Effect.gen(function* () {
12
+ const current = yield* Effect.serviceOption(CurrentActor);
13
+ if (Option.isNone(current))
14
+ return yield* new HttpApiError.Unauthorized({});
15
+ const { actor, organizationId, permissions } = current.value;
16
+ if (!organizationId)
17
+ return yield* new HttpApiError.Forbidden({});
18
+ return {
19
+ actorId: principalId(actor),
20
+ organizationId,
21
+ permissions: grants.flatMap(({ operation, required }) => permissions.has(required) ? [operation] : []),
22
+ };
23
+ }),
24
+ };
25
+ };
26
+ const actions = [
27
+ "asset:list",
28
+ "asset:read",
29
+ "asset:create",
30
+ "asset:update",
31
+ "asset:delete",
32
+ ];
33
+ const roles = {
34
+ owner: actions,
35
+ admin: actions,
36
+ member: ["asset:list", "asset:read"],
37
+ };
38
+ const access = defineProjectAccess({
39
+ project: "assets",
40
+ permissions: actions,
41
+ roles,
42
+ });
43
+ /** Adapts verified request grants to organization-wide Assets permissions. */
44
+ export const AssetsAccess = {
45
+ ...access,
46
+ ...fromMatrix({
47
+ list: access.qualify("asset:list"),
48
+ read: access.qualify("asset:read"),
49
+ create: access.qualify("asset:create"),
50
+ update: access.qualify("asset:update"),
51
+ delete: access.qualify("asset:delete"),
52
+ }),
53
+ /** Use the exact permission identifiers supplied by a custom actor provider. */
54
+ fromMatrix,
55
+ };
56
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.js","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,WAAW,GACZ,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAwB,MAAM,aAAa,CAAC;AAO1E,MAAM,UAAU,GAAG,CAAC,MAA8B,EAAE,EAAE;IACpD,MAAM,MAAM,GAAG,qBAAqB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;QAClE,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;QACnC,OAAO,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IACH,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;YAC3B,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;YAC1D,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC;gBACxB,OAAO,KAAK,CAAC,CAAC,IAAI,YAAY,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;YAClD,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC;YAC7D,IAAI,CAAC,cAAc;gBAAE,OAAO,KAAK,CAAC,CAAC,IAAI,YAAY,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAClE,OAAO;gBACL,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC;gBAC3B,cAAc;gBACd,WAAW,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,EAAE,CACtD,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAC7C;aACF,CAAC;QACJ,CAAC,CAAC;KACH,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,OAAO,GAAG;IACd,YAAY;IACZ,YAAY;IACZ,cAAc;IACd,cAAc;IACd,cAAc;CACN,CAAC;AACX,MAAM,KAAK,GAAG;IACZ,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,MAAM,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC;CAC5B,CAAC;AACX,MAAM,MAAM,GAAG,mBAAmB,CAAC;IACjC,OAAO,EAAE,QAAQ;IACjB,WAAW,EAAE,OAAO;IACpB,KAAK;CACN,CAAC,CAAC;AAIH,8EAA8E;AAC9E,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,GAAG,MAAM;IACT,GAAG,UAAU,CAAC;QACZ,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC;QAClC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC;QAClC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC;QACtC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC;QACtC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC;KACvC,CAAC;IACF,gFAAgF;IAChF,UAAU;CACF,CAAC"}
@@ -0,0 +1,100 @@
1
+ import { Effect, Layer, type Context } from "effect";
2
+ import { HttpServerResponse } from "effect/http";
3
+ import { HttpApiError, type HttpApiEndpoint } from "effect/http-api";
4
+ import type { AssetsAuthorization } from "./access.js";
5
+ import { AssetsApi } from "./api.group.js";
6
+ import type { Assets } from "./index.js";
7
+ import { AssetNotFound, AssetTextChunkInvalid, type AssetUploadInvalid } from "./schema.js";
8
+ type Endpoints = (typeof AssetsApi.groups.assets.endpoints)[keyof typeof AssetsApi.groups.assets.endpoints];
9
+ type Input<Name extends Endpoints["identifier"]> = Omit<HttpApiEndpoint.Request<Extract<Endpoints, {
10
+ identifier: Name;
11
+ }>>, "endpoint" | "group">;
12
+ export declare const makeAssetsHandlers: (service: Context.Key<Assets, typeof Assets.Service>, access: AssetsAuthorization) => {
13
+ list: (input: Input<"list">) => Effect.Effect<{
14
+ items: {
15
+ id: string;
16
+ name: string;
17
+ mimeType: string;
18
+ byteSize: number;
19
+ createdAt: Date;
20
+ updatedAt: Date;
21
+ url?: string | undefined;
22
+ }[];
23
+ stats: {
24
+ readonly assetCount: number;
25
+ readonly storageUsedBytes: number;
26
+ };
27
+ }, HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets | import("effect/http/HttpServerRequest").HttpServerRequest>;
28
+ file: (input: Input<"file">) => Effect.Effect<HttpServerResponse.HttpServerResponse, AssetNotFound | HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets>;
29
+ getAsset: (input: Input<"getAsset">) => Effect.Effect<{
30
+ id: string;
31
+ name: string;
32
+ mimeType: string;
33
+ status: "completed" | "failed" | "pending" | "running" | "unsupported";
34
+ totalBytes: number;
35
+ totalChunks: number;
36
+ failure: string | null;
37
+ outline: {
38
+ readonly headingPath: string;
39
+ readonly firstOrdinal: number;
40
+ readonly lastOrdinal: number;
41
+ }[];
42
+ nextOutlineOffset: number | null;
43
+ url: string;
44
+ } | {
45
+ assetId: string;
46
+ attemptId?: string | undefined;
47
+ uploadStatus: "failed" | "invalid" | "pending" | "published" | "rejected" | "unscannable";
48
+ }, AssetNotFound | HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets | import("effect/http/HttpServerRequest").HttpServerRequest | import("effect/workflow/WorkflowEngine").WorkflowEngine>;
49
+ getAssetChunks: (input: Input<"getAssetChunks">) => Effect.Effect<{
50
+ assetId: string;
51
+ chunks: {
52
+ ordinal: number;
53
+ content: string;
54
+ headingPath: string;
55
+ byteStart: number;
56
+ byteEnd: number;
57
+ firstPage: number | null;
58
+ lastPage: number | null;
59
+ id: string;
60
+ }[];
61
+ hits?: undefined;
62
+ nextOffset?: undefined;
63
+ } | {
64
+ chunks?: undefined;
65
+ assetId: string;
66
+ hits: {
67
+ id: string;
68
+ ordinal: number;
69
+ headingPath: string;
70
+ byteStart: number;
71
+ byteEnd: number;
72
+ firstPage: number | null;
73
+ lastPage: number | null;
74
+ snippet: string;
75
+ score: number;
76
+ }[];
77
+ nextOffset: number | null;
78
+ }, AssetNotFound | AssetTextChunkInvalid | import("./schema.js").AssetTextVersionChanged | HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets | import("effect/http/HttpServerRequest").HttpServerRequest>;
79
+ createAssetUpload: (input: Input<"createAssetUpload">) => Effect.Effect<{
80
+ uploadUrl: string;
81
+ contentType: string;
82
+ assetId: string;
83
+ attemptId?: string | undefined;
84
+ }, AssetNotFound | AssetUploadInvalid | HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets>;
85
+ completeAssetUpload: (input: Input<"completeAssetUpload">) => Effect.Effect<{
86
+ assetId: string;
87
+ attemptId?: string | undefined;
88
+ uploadStatus: "failed" | "invalid" | "pending" | "published" | "rejected" | "unscannable";
89
+ }, AssetNotFound | AssetUploadInvalid | HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets | import("effect/workflow/WorkflowEngine").WorkflowEngine>;
90
+ deleteAssets: (input: Input<"deleteAssets">) => Effect.Effect<{
91
+ deletedIds: string[];
92
+ failures: {
93
+ id: string;
94
+ reason: "in_use" | "not_found";
95
+ }[];
96
+ }, HttpApiError.Forbidden | HttpApiError.InternalServerError | HttpApiError.Unauthorized, Assets>;
97
+ };
98
+ export declare const makeAssetsApiLayer: (service: Context.Key<Assets, typeof Assets.Service>, access: AssetsAuthorization) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpRouter").HttpRouter | import("effect/Path").Path | (import("effect/http/HttpRouter").Request<"Requires", Assets> | import("effect/http/HttpRouter").Request<"Requires", import("effect/workflow/WorkflowEngine").WorkflowEngine>)>;
99
+ export {};
100
+ //# sourceMappingURL=api.builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.builder.d.ts","sourceRoot":"","sources":["../src/api.builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,OAAO,EAAE,MAAM,QAAQ,CAAC;AACrD,OAAO,EAAc,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAEL,YAAY,EACZ,KAAK,eAAe,EACrB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EACL,aAAa,EACb,qBAAqB,EAErB,KAAK,kBAAkB,EAExB,MAAM,aAAa,CAAC;AA8DrB,KAAK,SAAS,GACZ,CAAC,OAAO,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC7F,KAAK,KAAK,CAAC,IAAI,SAAS,SAAS,CAAC,YAAY,CAAC,IAAI,IAAI,CACrD,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE;IAAE,UAAU,EAAE,IAAI,CAAA;CAAE,CAAC,CAAC,EACjE,UAAU,GAAG,OAAO,CACrB,CAAC;AAQF,eAAO,MAAM,kBAAkB,YACpB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,MAAM,CAAC,OAAO,CAAC,UAC3C,mBAAmB;IAE3B,IAAI;;;;;;;;;;;;;;;IAoCJ,IAAI;IA2CJ,QAAQ;;;;;;;;;;;;;;;;;;;;IAsDR,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6Ed,iBAAiB;;;;;;IA4BjB,mBAAmB;;;;;IAuBnB,YAAY;;;;;;;CAsCZ,CAAC;AAEH,eAAO,MAAM,kBAAkB,YACpB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,MAAM,CAAC,OAAO,CAAC,UAC3C,mBAAmB,2ZAO5B,CAAC"}