@astram/guard 0.31.0 → 0.33.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 (38) hide show
  1. package/README.md +25 -0
  2. package/dist/agent/agent-provenance.d.ts +24 -0
  3. package/dist/agent/agent-provenance.d.ts.map +1 -0
  4. package/dist/agent/agent-provenance.js +40 -0
  5. package/dist/authz/manifest-operation-authority-adapter.d.ts +9 -1
  6. package/dist/authz/manifest-operation-authority-adapter.d.ts.map +1 -1
  7. package/dist/authz/manifest-operation-authority-adapter.js +17 -1
  8. package/dist/authz/operation-marker-check.d.ts +12 -1
  9. package/dist/authz/operation-marker-check.d.ts.map +1 -1
  10. package/dist/authz/operation-marker-check.js +13 -1
  11. package/dist/authz/record-share-writer.d.ts +49 -11
  12. package/dist/authz/record-share-writer.d.ts.map +1 -1
  13. package/dist/authz/record-share-writer.js +68 -20
  14. package/dist/authz/wire-record-authorization.d.ts.map +1 -1
  15. package/dist/authz/wire-record-authorization.js +6 -4
  16. package/dist/config/app-config.d.ts +15 -3
  17. package/dist/config/app-config.d.ts.map +1 -1
  18. package/dist/config/app-config.js +12 -3
  19. package/dist/index.d.ts +4 -3
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +18 -4
  22. package/dist/internal.d.ts +6 -0
  23. package/dist/internal.d.ts.map +1 -1
  24. package/dist/internal.js +10 -1
  25. package/dist/module/shield-tokens.d.ts +164 -0
  26. package/dist/module/shield-tokens.d.ts.map +1 -1
  27. package/dist/module/shield-tokens.js +57 -1
  28. package/dist/module/shield.module.d.ts +17 -1
  29. package/dist/module/shield.module.d.ts.map +1 -1
  30. package/dist/module/shield.module.js +2 -2
  31. package/dist/notifications/notification.service.d.ts +2 -0
  32. package/dist/notifications/notification.service.d.ts.map +1 -1
  33. package/dist/notifications/notification.service.js +8 -0
  34. package/dist/storage/storage.providers.d.ts +36 -3
  35. package/dist/storage/storage.providers.d.ts.map +1 -1
  36. package/dist/storage/storage.providers.js +203 -3
  37. package/migrations/1710000000126-AddRecordShareSource.cjs +187 -0
  38. package/package.json +5 -5
@@ -1,10 +1,43 @@
1
- import type { Provider } from '@nestjs/common';
2
- import { type ObjectStore, type ShippedFileProfileName } from '@astram/core';
1
+ import { type Provider } from '@nestjs/common';
2
+ import { type FileProfile, type ObjectStore, type ShippedFileProfileName } from '@astram/core';
3
3
  import { SHIELD_FILE_INGEST, SHIELD_OBJECT_STORE } from '../module/shield-tokens.js';
4
4
  /** The `storage` option on `ShieldModule.forRoot` / `forRootAsync`. */
5
5
  export type ShieldStorageOption = ObjectStore | 'env';
6
6
  /** The tokens `ShieldModule` exports app-wide for the storage option. */
7
7
  export declare const STORAGE_EXPORTS: readonly [typeof SHIELD_OBJECT_STORE, typeof SHIELD_FILE_INGEST];
8
+ /** One consumer-owned upload profile (`ShieldModule.forRoot({ appFileProfiles })`, DP1). */
9
+ export interface AppFileProfile {
10
+ /** `^[a-z][a-z0-9_]{0,31}$`, not a shipped name; the `FileIntake({ profile })` name. */
11
+ readonly name: string;
12
+ /**
13
+ * Core `FileProfile`: its own `magic` (a ZIP-based format MUST call core `zipWithinLimits`
14
+ * first), lower-case `type/subtype` content types (first = canonical), lower-case extensions.
15
+ */
16
+ readonly profile: FileProfile;
17
+ }
18
+ /** At most this many app profiles (SPEC §10). */
19
+ export declare const MAX_APP_FILE_PROFILES = 16;
20
+ /**
21
+ * Types refused by exact match: the SPEC §10 list (html, xhtml, svg, javascript, shell,
22
+ * octet-stream) extended by the supervisor (2026-11-03, stricter than the SPEC) with xml, php,
23
+ * wasm, shell and script types and javascript variants. {@link isDeniedAppContentType} adds the
24
+ * class patterns (`+xml`, php, javascript family, shell and script subtypes).
25
+ */
26
+ export declare const APP_CONTENT_TYPE_DENY_LIST: readonly string[];
27
+ /**
28
+ * True when an app profile may not use this (lower-case) content type: on the exact list or in a
29
+ * denied class. Types a browser could render or execute, scripts a server or desktop could run, or
30
+ * types that say nothing.
31
+ */
32
+ export declare function isDeniedAppContentType(lowerType: string): boolean;
33
+ /**
34
+ * Validate `appFileProfiles` (SPEC §5 B, §10; plan D-2); throws at registration. Messages are
35
+ * fixed text naming the entry index and the rule (and a content type's or extension's position),
36
+ * never a value. `_shippedRegistered` is unused by the rules (a shipped type or extension is
37
+ * refused whether its profile is registered or not, technical answer 1) and kept for the call
38
+ * site's clarity.
39
+ */
40
+ export declare function checkAppFileProfiles(entries: unknown, _shippedRegistered: readonly ShippedFileProfileName[]): readonly AppFileProfile[];
8
41
  /** Build the storage providers for one `ShieldModule` registration (see the file header). */
9
- export declare function storageProviders(storage: ShieldStorageOption | undefined, fileProfiles?: readonly ShippedFileProfileName[]): Provider[];
42
+ export declare function storageProviders(storage: ShieldStorageOption | undefined, fileProfiles?: readonly ShippedFileProfileName[], appFileProfiles?: readonly AppFileProfile[]): Provider[];
10
43
  //# sourceMappingURL=storage.providers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.providers.d.ts","sourceRoot":"","sources":["../../src/storage/storage.providers.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,sBAAsB,EAC5B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAIrF,uEAAuE;AACvE,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG,KAAK,CAAC;AAEtD,yEAAyE;AACzE,eAAO,MAAM,eAAe,kEAAqD,CAAC;AA+BlF,6FAA6F;AAC7F,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,YAAY,GAAE,SAAS,sBAAsB,EAA0B,GACtE,QAAQ,EAAE,CAgDZ"}
1
+ {"version":3,"file":"storage.providers.d.ts","sourceRoot":"","sources":["../../src/storage/storage.providers.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAU,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,sBAAsB,EAC5B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAIrF,uEAAuE;AACvE,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG,KAAK,CAAC;AAEtD,yEAAyE;AACzE,eAAO,MAAM,eAAe,kEAAqD,CAAC;AA+BlF,4FAA4F;AAC5F,MAAM,WAAW,cAAc;IAC7B,wFAAwF;IACxF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;CAC/B;AAED,iDAAiD;AACjD,eAAO,MAAM,qBAAqB,KAAK,CAAC;AAKxC;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EA2CtD,CAAC;AAWH;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAIjE;AAaD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,OAAO,EAChB,kBAAkB,EAAE,SAAS,sBAAsB,EAAE,GACpD,SAAS,cAAc,EAAE,CA4E3B;AAED,6FAA6F;AAC7F,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,YAAY,GAAE,SAAS,sBAAsB,EAA0B,EACvE,eAAe,CAAC,EAAE,SAAS,cAAc,EAAE,GAC1C,QAAQ,EAAE,CAsEZ"}
@@ -33,7 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.STORAGE_EXPORTS = void 0;
36
+ exports.APP_CONTENT_TYPE_DENY_LIST = exports.MAX_APP_FILE_PROFILES = exports.STORAGE_EXPORTS = void 0;
37
+ exports.isDeniedAppContentType = isDeniedAppContentType;
38
+ exports.checkAppFileProfiles = checkAppFileProfiles;
37
39
  exports.storageProviders = storageProviders;
38
40
  /**
39
41
  * `ShieldModule` providers for the `storage` and `fileProfiles` options (FILE_STORAGE SPEC §6,
@@ -50,9 +52,16 @@ exports.storageProviders = storageProviders;
50
52
  * `fileProfiles` is validated when the providers are built, so a bad list aborts boot. Its
51
53
  * messages are fixed text (an entry's position, never its value).
52
54
  *
55
+ * `appFileProfiles` (app-file-profiles SPEC §5 A–B, DP1): up to 16 named consumer profiles
56
+ * registered on the same ingest next to the shipped ones, checked by {@link checkAppFileProfiles}
57
+ * at registration (index + rule in the message, never a value). Their content types and
58
+ * extensions never overlap a shipped profile (registered or not) or each other, so a stored type
59
+ * always maps to one profile and an app type is never read as a shipped analyser format.
60
+ *
53
61
  * `S3ObjectStore` (and so `@aws-sdk/client-s3`) is loaded lazily, only for `'env'` with a bucket.
54
62
  */
55
63
  const node_crypto_1 = require("node:crypto");
64
+ const common_1 = require("@nestjs/common");
56
65
  const core_1 = require("@astram/core");
57
66
  const app_config_js_1 = require("../config/app-config.js");
58
67
  const boot_secrets_js_1 = require("../secrets/boot-secrets.js");
@@ -82,8 +91,179 @@ function checkFileProfiles(names) {
82
91
  });
83
92
  return names;
84
93
  }
94
+ /** At most this many app profiles (SPEC §10). */
95
+ exports.MAX_APP_FILE_PROFILES = 16;
96
+ const APP_NAME_RE = /^[a-z][a-z0-9_]{0,31}$/;
97
+ const APP_EXTENSION_RE = /^\.[a-z0-9]{1,10}$/;
98
+ /** Plan D-2 (stricter than SPEC §5 B): a plain lower-case `type/subtype`, no parameters. */
99
+ const APP_CONTENT_TYPE_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
100
+ /**
101
+ * Types refused by exact match: the SPEC §10 list (html, xhtml, svg, javascript, shell,
102
+ * octet-stream) extended by the supervisor (2026-11-03, stricter than the SPEC) with xml, php,
103
+ * wasm, shell and script types and javascript variants. {@link isDeniedAppContentType} adds the
104
+ * class patterns (`+xml`, php, javascript family, shell and script subtypes).
105
+ */
106
+ exports.APP_CONTENT_TYPE_DENY_LIST = Object.freeze([
107
+ // SPEC §10
108
+ 'text/html',
109
+ 'application/xhtml+xml',
110
+ 'image/svg+xml',
111
+ 'application/javascript',
112
+ 'text/javascript',
113
+ 'application/x-sh',
114
+ 'application/octet-stream',
115
+ // xml
116
+ 'application/xml',
117
+ 'text/xml',
118
+ // php
119
+ 'application/x-httpd-php',
120
+ 'application/x-php',
121
+ 'application/php',
122
+ 'text/x-php',
123
+ 'text/php',
124
+ // wasm
125
+ 'application/wasm',
126
+ // shell and script
127
+ 'application/x-csh',
128
+ 'application/x-shellscript',
129
+ 'text/x-shellscript',
130
+ 'text/x-sh',
131
+ 'application/x-powershell',
132
+ 'text/x-python',
133
+ 'application/x-python-code',
134
+ 'text/x-perl',
135
+ 'application/x-perl',
136
+ 'text/x-ruby',
137
+ 'application/x-ruby',
138
+ 'application/x-bat',
139
+ 'application/x-msdos-program',
140
+ 'application/x-msdownload',
141
+ // javascript variants
142
+ 'application/x-javascript',
143
+ 'text/x-javascript',
144
+ 'application/ecmascript',
145
+ 'text/ecmascript',
146
+ 'application/x-ecmascript',
147
+ 'text/jscript',
148
+ 'text/livescript',
149
+ ]);
150
+ const DENIED_EXACT = new Set(exports.APP_CONTENT_TYPE_DENY_LIST);
151
+ /** Subtype patterns per class (supervisor 2026-11-03): any `+xml`; php; javascript family; shells. */
152
+ const DENIED_SUBTYPE_PATTERNS = Object.freeze([
153
+ /\+xml$/,
154
+ /php/,
155
+ /(java|ecma|j|live)script/,
156
+ /^(x-)?(sh|csh|bash|zsh|ksh|fish|shellscript|powershell|bat|cmd)$/,
157
+ ]);
158
+ /**
159
+ * True when an app profile may not use this (lower-case) content type: on the exact list or in a
160
+ * denied class. Types a browser could render or execute, scripts a server or desktop could run, or
161
+ * types that say nothing.
162
+ */
163
+ function isDeniedAppContentType(lowerType) {
164
+ if (DENIED_EXACT.has(lowerType))
165
+ return true;
166
+ const subtype = lowerType.slice(lowerType.indexOf('/') + 1);
167
+ return DENIED_SUBTYPE_PATTERNS.some((re) => re.test(subtype));
168
+ }
169
+ /** Every shipped profile's content types / extensions, lower-cased (registered or not). */
170
+ const SHIPPED_TYPES = new Set(Object.values(core_1.SHIPPED_FILE_PROFILES).flatMap((p) => p.contentTypes.map((t) => t.toLowerCase())));
171
+ const SHIPPED_EXTENSIONS = new Set(Object.values(core_1.SHIPPED_FILE_PROFILES).flatMap((p) => p.extensions.map((e) => e.toLowerCase())));
172
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
173
+ /**
174
+ * Validate `appFileProfiles` (SPEC §5 B, §10; plan D-2); throws at registration. Messages are
175
+ * fixed text naming the entry index and the rule (and a content type's or extension's position),
176
+ * never a value. `_shippedRegistered` is unused by the rules (a shipped type or extension is
177
+ * refused whether its profile is registered or not, technical answer 1) and kept for the call
178
+ * site's clarity.
179
+ */
180
+ function checkAppFileProfiles(entries, _shippedRegistered) {
181
+ if (entries === undefined)
182
+ return [];
183
+ if (!Array.isArray(entries) || entries.length > exports.MAX_APP_FILE_PROFILES) {
184
+ throw new Error(`ShieldModule appFileProfiles must be a list of at most ${exports.MAX_APP_FILE_PROFILES} entries`);
185
+ }
186
+ const names = new Set();
187
+ const types = new Set();
188
+ const extensions = new Set();
189
+ const out = [];
190
+ entries.forEach((raw, i) => {
191
+ const fail = (rule) => {
192
+ throw new Error(`ShieldModule appFileProfiles entry ${i} ${rule}`);
193
+ };
194
+ if (!isRecord(raw))
195
+ fail('is not an object');
196
+ const e = raw;
197
+ if (!isRecord(e.profile))
198
+ fail('profile is not an object');
199
+ const p = e.profile;
200
+ const name = e.name;
201
+ if (typeof name !== 'string' || !APP_NAME_RE.test(name)) {
202
+ fail('name must match ^[a-z][a-z0-9_]{0,31}$');
203
+ }
204
+ if (Object.hasOwn(core_1.SHIPPED_FILE_PROFILES, name)) {
205
+ fail('name is a shipped profile name');
206
+ }
207
+ if (names.has(name))
208
+ fail('repeats an earlier name');
209
+ if (typeof p.magic !== 'function')
210
+ fail('magic must be a function');
211
+ const maxBytes = p.maxBytes;
212
+ if (typeof maxBytes !== 'number' ||
213
+ !Number.isInteger(maxBytes) ||
214
+ maxBytes <= 0 ||
215
+ maxBytes > core_1.FILE_MAX_BYTES_CEILING) {
216
+ fail(`maxBytes must be a positive integer at most ${core_1.FILE_MAX_BYTES_CEILING}`);
217
+ }
218
+ if (!Array.isArray(p.contentTypes) || p.contentTypes.length === 0) {
219
+ fail('contentTypes must be a non-empty list');
220
+ }
221
+ if (!Array.isArray(p.extensions) || p.extensions.length === 0) {
222
+ fail('extensions must be a non-empty list');
223
+ }
224
+ const ownTypes = p.contentTypes.map((t, j) => {
225
+ if (typeof t !== 'string' || !APP_CONTENT_TYPE_RE.test(t)) {
226
+ fail(`content type ${j} must be a plain lower-case type/subtype`);
227
+ }
228
+ const lower = t.toLowerCase();
229
+ if (isDeniedAppContentType(lower))
230
+ fail(`content type ${j} is on the deny list`);
231
+ if (SHIPPED_TYPES.has(lower))
232
+ fail(`content type ${j} belongs to a shipped profile`);
233
+ if (types.has(lower))
234
+ fail(`content type ${j} is used by another app profile`);
235
+ return lower;
236
+ });
237
+ const ownExtensions = p.extensions.map((x, j) => {
238
+ if (typeof x !== 'string' || !APP_EXTENSION_RE.test(x)) {
239
+ fail(`extension ${j} must match ^\\.[a-z0-9]{1,10}$`);
240
+ }
241
+ const lower = x.toLowerCase();
242
+ if (SHIPPED_EXTENSIONS.has(lower))
243
+ fail(`extension ${j} belongs to a shipped profile`);
244
+ if (extensions.has(lower))
245
+ fail(`extension ${j} is used by another app profile`);
246
+ return lower;
247
+ });
248
+ names.add(name);
249
+ for (const t of ownTypes)
250
+ types.add(t);
251
+ for (const x of ownExtensions)
252
+ extensions.add(x);
253
+ // Frozen copies of what was checked: a later change to the app's own objects cannot reach the
254
+ // ingest (review P2-3).
255
+ const checked = Object.freeze({
256
+ maxBytes: maxBytes,
257
+ contentTypes: Object.freeze([...p.contentTypes]),
258
+ extensions: Object.freeze([...p.extensions]),
259
+ magic: p.magic,
260
+ });
261
+ out.push(Object.freeze({ name: name, profile: checked }));
262
+ });
263
+ return Object.freeze(out);
264
+ }
85
265
  /** Build the storage providers for one `ShieldModule` registration (see the file header). */
86
- function storageProviders(storage, fileProfiles = DEFAULT_FILE_PROFILES) {
266
+ function storageProviders(storage, fileProfiles = DEFAULT_FILE_PROFILES, appFileProfiles) {
87
267
  if (storage !== undefined && storage !== 'env') {
88
268
  const s = storage;
89
269
  if (STORE_METHODS.some((m) => typeof s?.[m] !== 'function')) {
@@ -91,6 +271,7 @@ function storageProviders(storage, fileProfiles = DEFAULT_FILE_PROFILES) {
91
271
  }
92
272
  }
93
273
  const profileNames = [...checkFileProfiles(fileProfiles)];
274
+ const apps = checkAppFileProfiles(appFileProfiles, profileNames);
94
275
  const configToken = Symbol('SHIELD_OBJECT_STORAGE_CONFIG');
95
276
  return [
96
277
  {
@@ -125,7 +306,26 @@ function storageProviders(storage, fileProfiles = DEFAULT_FILE_PROFILES) {
125
306
  ? { ...shipped, maxBytes: config.maxBytes }
126
307
  : shipped;
127
308
  }
128
- return (0, core_1.createFileIngest)({ digest: new node_sha256_digest_js_1.NodeSha256Digest(), newId: node_crypto_1.randomUUID, profiles });
309
+ // App profiles (DP1; supervisor 2026-11-03, stricter than the SPEC): an explicit
310
+ // OBJECT_STORAGE_MAX_BYTES can only LOWER an app's declared cap, never raise it
311
+ // (shipped profiles above keep the replace rule).
312
+ for (const app of apps) {
313
+ profiles[app.name] =
314
+ config?.maxBytesExplicit && config.maxBytes < app.profile.maxBytes
315
+ ? { ...app.profile, maxBytes: config.maxBytes }
316
+ : app.profile;
317
+ }
318
+ const ingest = (0, core_1.createFileIngest)({
319
+ digest: new node_sha256_digest_js_1.NodeSha256Digest(),
320
+ newId: node_crypto_1.randomUUID,
321
+ profiles,
322
+ });
323
+ if (apps.length > 0) {
324
+ // Names only: never a content type, extension or anything of `magic`.
325
+ new common_1.Logger('ShieldStorage').log(`app file profiles registered: ${apps.map((a) => a.name).join(', ')} ` +
326
+ '(a ZIP-based profile magic must call zipWithinLimits first)');
327
+ }
328
+ return ingest;
129
329
  },
130
330
  inject: [configToken],
131
331
  },
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Framework authz migration — provenance on `<authz>.record_share` for the file-share port (GAPS #57;
3
+ * spec `docs/features/file-share-port/SPEC.md` v1 §4 A; id 126 per `docs/migrations/RESERVATIONS.md`).
4
+ *
5
+ * Adds three columns, all `NOT NULL DEFAULT ''` ('' on all three = an owner-made share):
6
+ * - `rs_source_type_key` VARCHAR(64) parent object type key;
7
+ * - `rs_source_record_uuid` VARCHAR(36) parent record id;
8
+ * - `rs_source_operation` VARCHAR(64) `shield:file-share` for a port row.
9
+ * Not nullable on purpose: MariaDB treats NULLs as distinct in a UNIQUE index, so nullable source
10
+ * columns would stop de-duplicating owner re-shares.
11
+ *
12
+ * Constraints and indexes (all named):
13
+ * - `ck_rs_source_complete` CHECK: the three source columns are all '' or all non-empty;
14
+ * - `uq_rs_grant_source` UNIQUE (tenant, type, record, grantee kind, grantee, action, source type,
15
+ * source record) replaces `uq_rs_grant`, which is dropped only once the new index exists (owner
16
+ * shares keep their old uniqueness under source ''; each parent gets its own row);
17
+ * - `idx_rs_source` (tenant, source type, source record) for `revokeForParent`.
18
+ * No foreign key (the parent lives in an app table in another database; `record_share` has none).
19
+ *
20
+ * Idempotent: every column, the check and each index is added only when `information_schema` shows it
21
+ * absent; a half-applied state is completed and a re-run issues no DDL. No data change: existing rows
22
+ * take the defaults (owner-made). No ids hard-coded.
23
+ *
24
+ * `down` refuses (throws a fixed message, changes nothing) while any row has a non-empty source: it
25
+ * never deletes shares. Otherwise it re-creates `uq_rs_grant` first, then drops `uq_rs_grant_source`,
26
+ * `idx_rs_source`, the check and the three columns, each only when present.
27
+ *
28
+ * Database name from `ctx.schemas` (`frameworkSchemasForMigration(...).authz`), so the four-database,
29
+ * namespace and single layouts all work. Sorts after `...014` (creates `record_share`) and above every
30
+ * published and reserved id (120 published, 121–125 reserved).
31
+ */
32
+
33
+ const { frameworkSchemasForMigration } = require('@astram/core');
34
+
35
+ const MIGRATION = '1710000000126-AddRecordShareSource';
36
+ const TABLE = 'record_share';
37
+ const CHECK = 'ck_rs_source_complete';
38
+ const OLD_UNIQUE = 'uq_rs_grant';
39
+ const NEW_UNIQUE = 'uq_rs_grant_source';
40
+ const SOURCE_INDEX = 'idx_rs_source';
41
+
42
+ /** In table order; each placed after the previous one (the first after `rs_created_at`). */
43
+ const COLUMNS = [
44
+ { name: 'rs_source_type_key', type: 'VARCHAR(64)', after: 'rs_created_at' },
45
+ { name: 'rs_source_record_uuid', type: 'VARCHAR(36)', after: 'rs_source_type_key' },
46
+ { name: 'rs_source_operation', type: 'VARCHAR(64)', after: 'rs_source_record_uuid' },
47
+ ];
48
+
49
+ const GRANT_KEY = 'rs_tenant_uuid, rs_type_key, rs_record_uuid, rs_grantee_kind, rs_grantee_uuid, rs_action';
50
+ const CHECK_CLAUSE =
51
+ "(rs_source_type_key = '' AND rs_source_record_uuid = '' AND rs_source_operation = '') OR " +
52
+ "(rs_source_type_key <> '' AND rs_source_record_uuid <> '' AND rs_source_operation <> '')";
53
+
54
+ const DOWN_REFUSED =
55
+ `${MIGRATION}: refusing to roll back: record_share holds shares made through the file-share port ` +
56
+ '(non-empty source columns). Revoke them first (revokeForParent); nothing was changed.';
57
+
58
+ async function exists(query, sql, params) {
59
+ const rows = await query(sql, params);
60
+ return Array.isArray(rows) && rows.length > 0;
61
+ }
62
+
63
+ const tableExists = (query, schema) =>
64
+ exists(
65
+ query,
66
+ `SELECT 1 AS n FROM information_schema.TABLES
67
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1`,
68
+ [schema, TABLE],
69
+ );
70
+
71
+ const columnExists = (query, schema, column) =>
72
+ exists(
73
+ query,
74
+ `SELECT 1 AS n FROM information_schema.COLUMNS
75
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1`,
76
+ [schema, TABLE, column],
77
+ );
78
+
79
+ const checkExists = (query, schema) =>
80
+ exists(
81
+ query,
82
+ `SELECT 1 AS n FROM information_schema.CHECK_CONSTRAINTS
83
+ WHERE CONSTRAINT_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_NAME = ? LIMIT 1`,
84
+ [schema, TABLE, CHECK],
85
+ );
86
+
87
+ const indexExists = (query, schema, index) =>
88
+ exists(
89
+ query,
90
+ `SELECT 1 AS n FROM information_schema.STATISTICS
91
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME = ? LIMIT 1`,
92
+ [schema, TABLE, index],
93
+ );
94
+
95
+ const tbl = (schema) => `\`${schema}\`.\`${TABLE}\``;
96
+
97
+ async function up(ctx) {
98
+ const { query } = ctx;
99
+ const AUTHZ = frameworkSchemasForMigration(ctx, process.env).authz;
100
+ const T = tbl(AUTHZ);
101
+
102
+ if (!(await tableExists(query, AUTHZ))) {
103
+ throw new Error(
104
+ `${MIGRATION}: ${AUTHZ}.${TABLE} does not exist; run 1710000000014-CreateRecordShare first.`,
105
+ );
106
+ }
107
+
108
+ // 1. Columns: one ALTER (atomic) adding only the absent ones.
109
+ const add = [];
110
+ for (const c of COLUMNS) {
111
+ if (!(await columnExists(query, AUTHZ, c.name))) {
112
+ add.push(`ADD COLUMN IF NOT EXISTS ${c.name} ${c.type} NOT NULL DEFAULT '' AFTER ${c.after}`);
113
+ }
114
+ }
115
+ if (add.length > 0) {
116
+ await query(`ALTER TABLE ${T} ${add.join(', ')}`);
117
+ }
118
+
119
+ // 2. The completeness check (existing rows hold the '' defaults and pass).
120
+ if (!(await checkExists(query, AUTHZ))) {
121
+ await query(`ALTER TABLE ${T} ADD CONSTRAINT ${CHECK} CHECK (${CHECK_CLAUSE})`);
122
+ }
123
+
124
+ // 3. The source-aware unique, then drop the old one only once the new one is confirmed present.
125
+ if (!(await indexExists(query, AUTHZ, NEW_UNIQUE))) {
126
+ await query(
127
+ `CREATE UNIQUE INDEX IF NOT EXISTS ${NEW_UNIQUE} ON ${T}
128
+ (${GRANT_KEY}, rs_source_type_key, rs_source_record_uuid)`,
129
+ );
130
+ }
131
+ if (await indexExists(query, AUTHZ, OLD_UNIQUE)) {
132
+ if (!(await indexExists(query, AUTHZ, NEW_UNIQUE))) {
133
+ throw new Error(
134
+ `${MIGRATION}: ${NEW_UNIQUE} is missing on ${AUTHZ}.${TABLE}; ${OLD_UNIQUE} was kept. Re-run.`,
135
+ );
136
+ }
137
+ await query(`DROP INDEX IF EXISTS ${OLD_UNIQUE} ON ${T}`);
138
+ }
139
+
140
+ // 4. The revokeForParent lookup index.
141
+ if (!(await indexExists(query, AUTHZ, SOURCE_INDEX))) {
142
+ await query(
143
+ `CREATE INDEX IF NOT EXISTS ${SOURCE_INDEX} ON ${T}
144
+ (rs_tenant_uuid, rs_source_type_key, rs_source_record_uuid)`,
145
+ );
146
+ }
147
+ }
148
+
149
+ async function down(ctx) {
150
+ const { query } = ctx;
151
+ const AUTHZ = frameworkSchemasForMigration(ctx, process.env).authz;
152
+ const T = tbl(AUTHZ);
153
+
154
+ if (!(await tableExists(query, AUTHZ))) return;
155
+
156
+ const present = [];
157
+ for (const c of COLUMNS) {
158
+ if (await columnExists(query, AUTHZ, c.name)) present.push(c.name);
159
+ }
160
+
161
+ // Refuse before any change while a port row exists (never delete shares).
162
+ if (present.length > 0) {
163
+ const where = present.map((name) => `${name} <> ''`).join(' OR ');
164
+ if (await exists(query, `SELECT 1 AS n FROM ${T} WHERE ${where} LIMIT 1`, [])) {
165
+ throw new Error(DOWN_REFUSED);
166
+ }
167
+ }
168
+
169
+ // With every source '' the old six-column key is unique again: restore it before dropping the new one.
170
+ if (!(await indexExists(query, AUTHZ, OLD_UNIQUE))) {
171
+ await query(`CREATE UNIQUE INDEX IF NOT EXISTS ${OLD_UNIQUE} ON ${T} (${GRANT_KEY})`);
172
+ }
173
+ if (await indexExists(query, AUTHZ, NEW_UNIQUE)) {
174
+ await query(`DROP INDEX IF EXISTS ${NEW_UNIQUE} ON ${T}`);
175
+ }
176
+ if (await indexExists(query, AUTHZ, SOURCE_INDEX)) {
177
+ await query(`DROP INDEX IF EXISTS ${SOURCE_INDEX} ON ${T}`);
178
+ }
179
+ if (await checkExists(query, AUTHZ)) {
180
+ await query(`ALTER TABLE ${T} DROP CONSTRAINT IF EXISTS ${CHECK}`);
181
+ }
182
+ if (present.length > 0) {
183
+ await query(`ALTER TABLE ${T} ${present.map((name) => `DROP COLUMN IF EXISTS ${name}`).join(', ')}`);
184
+ }
185
+ }
186
+
187
+ module.exports = { up, down };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astram/guard",
3
- "version": "0.31.0",
3
+ "version": "0.33.0",
4
4
  "license": "MIT",
5
5
  "description": "Astram framework — the enforcement guard + real-world adapters (the 'hands'). One global deny-by-default gate every request passes through (ADR-0002), classification decorators, boot-pool assertion (ADR-0018), the forRoot() registration seam, and the DB/Redis/crypto adapters that connect the sealed core to a real backend. Depends on @astram/core (ADR-0003, ADR-0023).",
6
6
  "type": "commonjs",
@@ -36,8 +36,8 @@
36
36
  "argon2": "^0.41.1",
37
37
  "ioredis": "^5.4.1",
38
38
  "mariadb": "^3.5.4",
39
- "@astram/core": "1.18.0",
40
- "@astram/engine": "0.18.0"
39
+ "@astram/core": "1.19.0",
40
+ "@astram/engine": "0.19.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@nestjs/common": "^11",
@@ -45,7 +45,7 @@
45
45
  "@nestjs/platform-express": "^11",
46
46
  "reflect-metadata": "^0.2",
47
47
  "rxjs": "^7",
48
- "@astram/messaging": "^0.1.19"
48
+ "@astram/messaging": "^0.1.21"
49
49
  },
50
50
  "peerDependenciesMeta": {
51
51
  "@astram/messaging": {
@@ -68,7 +68,7 @@
68
68
  "typescript": "^5.7.0",
69
69
  "unplugin-swc": "^1.5.1",
70
70
  "vitest": "^2.1.8",
71
- "@astram/messaging": "0.1.19"
71
+ "@astram/messaging": "0.1.21"
72
72
  },
73
73
  "repository": {
74
74
  "type": "git",