@descix/platform-api 5.1.1 → 5.3.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.
@@ -6,7 +6,7 @@
6
6
  * would be a second owner for as long as the companion repoint takes; a pointer is the same
7
7
  * owner reached by an older name.
8
8
  *
9
- * It exists only until DeSciX_Cloud's imports are repointed at `@descix/cloud-core/naming`,
9
+ * It exists only until Cloud's imports are repointed at `@descix/cloud-core/naming`,
10
10
  * after which this file and its subpath export are DELETED. That repoint is a companion row
11
11
  * and is deliberately NOT part of this change.
12
12
  */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The Firestore database an operator run on `env` must target, MEASURED from the booted service config:
3
+ * FIRESTORE_DATABASE_ID of the service's own defaults-config-<env>.json exactly as @descix/cloud-core
4
+ * loaded it (CloudConfig.envDefaultsLayer(), the per-env layer before any override), and the config's
5
+ * DEPLOY_ENV must be `env`. Never caller-asserted.
6
+ *
7
+ * It reads the CloudConfig of the @descix/cloud-core module instance THIS package resolves: when a process
8
+ * holds two cloud-core copies (a service's node_modules and this package's), the copy this package resolves
9
+ * may hold no booted config, and this refuses naming the copy it resolved. Reads config only, never a database client.
10
+ */
11
+ import { getCloudConfig } from '@descix/cloud-core';
12
+ import { OPERATOR_ENVS, OperatorGuardError, OperatorGuardRefusal } from './index.js';
13
+
14
+ function resolvedCloudCore() {
15
+ try {
16
+ return import.meta.resolve('@descix/cloud-core');
17
+ } catch {
18
+ return '@descix/cloud-core (unresolvable)';
19
+ }
20
+ }
21
+
22
+ /**
23
+ * @param {string} env - dev | demo | prod
24
+ * @returns {{ databaseId: string, file: string }}
25
+ * @throws {OperatorGuardError} OPERATOR_ENV_INVALID | OPERATOR_TARGET_INVALID
26
+ */
27
+ export function bootedEnvDatabaseId(env) {
28
+ const bad = (why) => new OperatorGuardError(OperatorGuardRefusal.TARGET_INVALID, `${why}. Nothing was read or written.`);
29
+ if (!OPERATOR_ENVS.includes(env)) {
30
+ throw new OperatorGuardError(OperatorGuardRefusal.ENV_INVALID, `env is required and has no default (got ${JSON.stringify(env)}). Name one of: ${OPERATOR_ENVS.join(', ')}.`);
31
+ }
32
+ let cfg;
33
+ try {
34
+ cfg = getCloudConfig();
35
+ } catch (e) {
36
+ throw bad(`The @descix/cloud-core this package resolves (${resolvedCloudCore()}) holds no booted config (${e?.message ?? e}); if the service booted a different copy of @descix/cloud-core, two module instances are in this process`);
37
+ }
38
+ if (cfg.DEPLOY_ENV !== env) throw bad(`The booted service config is DEPLOY_ENV ${JSON.stringify(cfg.DEPLOY_ENV ?? null)}, not ${env}`);
39
+ if (typeof cfg.envDefaultsLayer !== 'function') {
40
+ throw bad(`The @descix/cloud-core this package resolves (${resolvedCloudCore()}) has no CloudConfig.envDefaultsLayer(); it is older than this package needs`);
41
+ }
42
+ const layer = cfg.envDefaultsLayer();
43
+ if (!layer) throw bad(`The booted service loaded no defaults-config-${env}.json, so no Firestore database is known for env ${env}`);
44
+ if (layer.env !== env) throw bad(`The booted service's per-env layer is ${layer.file} (env ${layer.env}), not env ${env}`);
45
+ const id = layer.values?.FIRESTORE_DATABASE_ID;
46
+ if (typeof id !== 'string' || !id) throw bad(`${layer.file} names no FIRESTORE_DATABASE_ID`);
47
+ return Object.freeze({ databaseId: id, file: layer.file });
48
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @descix/platform-api/operator — the guards every in-process operator tool shares (the Powch passkey
3
+ * re-key, the account admin's delete and merge): which environments an operator run may name, that the
4
+ * Firestore client it booted targets that environment's database, and THE operator email rule.
5
+ *
6
+ * The rule is the one owner of "which accounts may an operator tool touch": a structured
7
+ * { localPart, plusAddressing, domains } matched against an account's `verified_email` only (the
8
+ * unverified `email` field is never consulted). Required, validated, fail closed: there is no default
9
+ * rule and no unfiltered listing.
10
+ *
11
+ * Pure: no Firestore, no file, no network. A consumer words a guard refusal in its own code table and
12
+ * keeps this error as the cause.
13
+ */
14
+
15
+ /** The environments an operator run names. */
16
+ export const OPERATOR_ENVS = Object.freeze(['dev', 'demo', 'prod']);
17
+
18
+ /** Why an operator guard refused. Nothing was read or written on any of them. */
19
+ export const OperatorGuardRefusal = Object.freeze({
20
+ /** The email rule is missing, empty or malformed (fail closed: no rule, no run). */
21
+ RULE_INVALID: 'OPERATOR_RULE_INVALID',
22
+ /** The env is not one of OPERATOR_ENVS. */
23
+ ENV_INVALID: 'OPERATOR_ENV_INVALID',
24
+ /** The target names no project/database/secret, or its database is not the env's. */
25
+ TARGET_INVALID: 'OPERATOR_TARGET_INVALID',
26
+ });
27
+
28
+ export class OperatorGuardError extends Error {
29
+ constructor(code, message) {
30
+ if (!Object.values(OperatorGuardRefusal).includes(code)) throw new Error(`OperatorGuardError: unknown code ${code}`);
31
+ super(message);
32
+ this.name = 'OperatorGuardError';
33
+ this.code = code;
34
+ }
35
+ }
36
+
37
+ const LOCAL_PART = /^[a-z0-9._%-]+$/;
38
+ const TAGGED_LOCAL_PART = /^[a-z0-9._%-]+(\+[a-z0-9._%-]+)?$/;
39
+ /** A plus-tag: the local part's characters and further '+' (operator+a+b); never whitespace or a control character. */
40
+ const TAG = /^[a-z0-9._%+-]+$/;
41
+ const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
42
+ const RULE_KEYS = Object.freeze(['localPart', 'plusAddressing', 'domains']);
43
+
44
+ /**
45
+ * The operator email rule, validated; fail closed. Shape (all three keys required, lowercase, nothing
46
+ * defaulted):
47
+ * { localPart: 'operator', plusAddressing: true, domains: ['example.org', 'example.net', 'example.com'] }
48
+ * names exactly `operator@<domain>` and, with plusAddressing, `operator+<tag>@<domain>` (a non-empty tag of
49
+ * [a-z0-9._%+-], so never whitespace or a control character) for a domain in the set, compared exactly
50
+ * (no subdomain, no suffix). With plusAddressing false the local part may itself carry one tag ('operator+x')
51
+ * and names only that address.
52
+ * @param {unknown} rule
53
+ * @returns {Readonly<{ localPart: string, plusAddressing: boolean, domains: readonly string[] }>}
54
+ * @throws {OperatorGuardError} OPERATOR_RULE_INVALID
55
+ */
56
+ export function normalizeOperatorEmailRule(rule) {
57
+ const bad = (why) => new OperatorGuardError(OperatorGuardRefusal.RULE_INVALID, `The operator email rule ${why}; there is no default rule and nothing is listed or written without one. Shape: { localPart: 'operator', plusAddressing: true, domains: ['example.org'] }`);
58
+ if (rule === null || typeof rule !== 'object' || Array.isArray(rule)) throw bad('is required');
59
+ const extra = Object.keys(rule).filter((k) => !RULE_KEYS.includes(k));
60
+ if (extra.length) throw bad(`has unknown keys ${extra.join(', ')}`);
61
+ const { localPart, plusAddressing, domains } = rule;
62
+ if (typeof plusAddressing !== 'boolean') throw bad('needs plusAddressing true or false');
63
+ if (typeof localPart !== 'string' || !(plusAddressing ? LOCAL_PART : TAGGED_LOCAL_PART).test(localPart)) {
64
+ throw bad(`needs a lowercase localPart${plusAddressing ? ' without a + tag' : ''} (got ${JSON.stringify(localPart)})`);
65
+ }
66
+ if (!Array.isArray(domains) || domains.length === 0) throw bad('needs a non-empty domains list');
67
+ const bogus = domains.filter((d) => typeof d !== 'string' || !DOMAIN.test(d));
68
+ if (bogus.length) throw bad(`has domains that are not lowercase host names: ${JSON.stringify(bogus)}`);
69
+ return Object.freeze({ localPart, plusAddressing, domains: Object.freeze([...new Set(domains)]) });
70
+ }
71
+
72
+ /**
73
+ * Whether the rule names `address`. The address is compared as the platform stores it, trimmed and
74
+ * lowercased (normalizeEmail), so OPERATOR+x@EXAMPLE.ORG is operator+x@example.org. A non-string is never named.
75
+ * @param {ReturnType<typeof normalizeOperatorEmailRule>} rule - a normalized rule
76
+ * @param {string|null|undefined} address
77
+ */
78
+ export function operatorEmailAllowed(rule, address) {
79
+ if (!rule || !Object.isFrozen(rule) || !Array.isArray(rule.domains)) {
80
+ throw new OperatorGuardError(OperatorGuardRefusal.RULE_INVALID, 'operatorEmailAllowed needs a rule from normalizeOperatorEmailRule');
81
+ }
82
+ if (typeof address !== 'string') return false;
83
+ const parts = address.trim().toLowerCase().split('@');
84
+ if (parts.length !== 2) return false;
85
+ const [local, domain] = parts;
86
+ if (!rule.domains.includes(domain)) return false;
87
+ if (local === rule.localPart) return true;
88
+ const tagged = `${rule.localPart}+`;
89
+ return rule.plusAddressing && local.startsWith(tagged) && TAG.test(local.slice(tagged.length));
90
+ }
91
+
92
+ /**
93
+ * The rule naming exactly one address (a CLI's --email): its local part, tag included, and its domain.
94
+ * @param {string} address
95
+ * @throws {OperatorGuardError} OPERATOR_RULE_INVALID
96
+ */
97
+ export function operatorEmailRuleForAddress(address) {
98
+ const parts = typeof address === 'string' ? address.trim().toLowerCase().split('@') : [];
99
+ if (parts.length !== 2) {
100
+ throw new OperatorGuardError(OperatorGuardRefusal.RULE_INVALID, `${JSON.stringify(address)} is not one email address; name the account's own address`);
101
+ }
102
+ return normalizeOperatorEmailRule({ localPart: parts[0], plusAddressing: false, domains: [parts[1]] });
103
+ }
104
+
105
+ /**
106
+ * The range-read prefixes that reach every address the rule can name: '<localPart>@' and, with
107
+ * plusAddressing, '<localPart>+'. A reader range-reads by them and then filters with operatorEmailAllowed
108
+ * (a prefix also reaches addresses the rule does not name, e.g. another domain).
109
+ * @param {ReturnType<typeof normalizeOperatorEmailRule>} rule
110
+ * @returns {string[]}
111
+ */
112
+ export function operatorEmailRulePrefixes(rule) {
113
+ if (!rule || !Object.isFrozen(rule) || typeof rule.localPart !== 'string') {
114
+ throw new OperatorGuardError(OperatorGuardRefusal.RULE_INVALID, 'operatorEmailRulePrefixes needs a rule from normalizeOperatorEmailRule');
115
+ }
116
+ return [`${rule.localPart}@`, ...(rule.plusAddressing ? [`${rule.localPart}+`] : [])];
117
+ }
118
+
119
+ /**
120
+ * Refuse unless `env` is an operator env and the Firestore client this run reads and writes through
121
+ * (`target`, what the booted service actually targets, overrides included) is the database the env names
122
+ * (`expectedDatabaseId`, from the service's own per-env config, e.g. FIRESTORE_DATABASE_ID of its
123
+ * defaults-config-<env>.json).
124
+ * @param {{ env: string, target: { projectId: string, databaseId: string, secretName: string }, expectedDatabaseId: string }} args
125
+ * @throws {OperatorGuardError} OPERATOR_ENV_INVALID | OPERATOR_TARGET_INVALID
126
+ */
127
+ export function assertOperatorTarget({ env, target, expectedDatabaseId } = {}) {
128
+ if (!OPERATOR_ENVS.includes(env)) {
129
+ throw new OperatorGuardError(OperatorGuardRefusal.ENV_INVALID, `env is required and has no default (got ${JSON.stringify(env)}). Name one of: ${OPERATOR_ENVS.join(', ')}.`);
130
+ }
131
+ for (const k of ['projectId', 'databaseId', 'secretName']) {
132
+ if (typeof target?.[k] !== 'string' || !target[k]) {
133
+ throw new OperatorGuardError(OperatorGuardRefusal.TARGET_INVALID, `The run's target has no ${k}; refusing to read or write anywhere unnamed`);
134
+ }
135
+ }
136
+ if (typeof expectedDatabaseId !== 'string' || !expectedDatabaseId) {
137
+ throw new OperatorGuardError(OperatorGuardRefusal.TARGET_INVALID, `No configured Firestore database is known for env ${env}; refusing to guess`);
138
+ }
139
+ if (target.databaseId !== expectedDatabaseId) {
140
+ throw new OperatorGuardError(OperatorGuardRefusal.TARGET_INVALID, `The Firestore client targets database '${target.databaseId}', but env ${env} is '${expectedDatabaseId}'. An override (environment variable or dev-overrides.json) is redirecting this run. Nothing was read or written.`);
141
+ }
142
+ }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Pure role-based permission checks. No Google Groups dependency.
5
5
  * Google Groups-based admin checks (isPlatformAdmin, isCommunityAdmin, isAppAdmin,
6
- * checkUserPermission) remain in DeSciX_Cloud/microservice/services/permissionService.js
6
+ * checkUserPermission) remain in Cloud's permissionService.js
7
7
  * as they depend on Cloud-specific infrastructure (googleGroupsService.js).
8
8
  */
9
9
 
@@ -6,7 +6,7 @@
6
6
  * would be a second owner for as long as the companion repoint takes; a pointer is the same
7
7
  * owner reached by an older name.
8
8
  *
9
- * It exists only until DeSciX_Cloud's imports are repointed at `@descix/cloud-core/service-bootstrap`,
9
+ * It exists only until Cloud's imports are repointed at `@descix/cloud-core/service-bootstrap`,
10
10
  * after which this file and its subpath export are DELETED. That repoint is a companion row
11
11
  * and is deliberately NOT part of this change.
12
12
  */