@fabrika/provider-contract 0.9.0-dev.10 → 0.9.0-dev.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-contract",
3
- "version": "0.9.0-dev.10",
3
+ "version": "0.9.0-dev.12",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,11 +38,11 @@
38
38
  }
39
39
  },
40
40
  "scripts": {
41
- "typecheck": "tsc --noEmit",
41
+ "typecheck": "tsrs --build tsconfig.test.json",
42
42
  "test": "bun test"
43
43
  },
44
44
  "dependencies": {
45
- "@fabrika/auth-core": "0.9.0-dev.10",
46
- "@fabrika/proxy-core": "0.9.0-dev.10"
45
+ "@fabrika/auth-core": "0.9.0-dev.12",
46
+ "@fabrika/proxy-core": "0.9.0-dev.12"
47
47
  }
48
48
  }
package/src/control.ts CHANGED
@@ -375,6 +375,16 @@ export interface ProviderNamespaceDevSandbox {
375
375
  readonly access: ProviderApprovedAccess
376
376
  }
377
377
 
378
+ /** What decides the hosts a namespace entry point routes one member on: `ProviderNamespaceMember` without its secrets. */
379
+ export interface ProviderNamespaceMemberRouting {
380
+ readonly appId: string
381
+ readonly env: string
382
+ readonly domain?: string
383
+ readonly artifact: ProviderEnvelope
384
+ readonly access?: ProviderApprovedAccess
385
+ readonly devSandboxes?: readonly Pick<ProviderNamespaceDevSandbox, 'workspaceId' | 'host'>[]
386
+ }
387
+
378
388
  /** One idempotent namespace lifecycle invocation. */
379
389
  export interface ProviderNamespaceMutationInput {
380
390
  readonly namespace: ProviderDeploymentNamespace
@@ -563,6 +573,11 @@ export interface ProviderNamespaceCapabilities {
563
573
  reconcile(input: ProviderNamespaceMutationInput): Promise<ProviderDeploymentNamespace>
564
574
  /** Absent means the namespace has no entry point that follows its members. */
565
575
  republish?(input: ProviderNamespaceRepublishInput): Promise<ProviderNamespaceRepublishResult>
576
+ /**
577
+ * The hosts the namespace's entry point routes this member on, lower-cased, by the rule its compiler applies; none for
578
+ * a member it does not route. Throws for a member it cannot route. Absent means no member is routed by host.
579
+ */
580
+ memberHosts?(member: ProviderNamespaceMemberRouting): readonly string[]
566
581
  /**
567
582
  * Read-only: whether each claimed resource still exists, one answer per key. Throws when it cannot tell, so Control
568
583
  * releases a claim only over a resource the provider confirmed gone. Absent means no claim can be released.
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './authoring'
2
2
  export * from './control'
3
3
  export * from './json'
4
+ export * from './plain-credentials'
4
5
  export * from './schema'
5
6
  export * from './steps'
@@ -0,0 +1,278 @@
1
+ // Whether a value about to sit somewhere readable looks like a credential.
2
+ //
3
+ // A plain variable is read by everyone who may read the configuration it lives in: on Zerops every member of the
4
+ // project, on Control everyone who manages the application. A credential belongs where nobody reads it back (a
5
+ // sensitive service variable, an application secret). The check is a heuristic over the NAME and the VALUE, and it
6
+ // errs towards refusing, so each place that runs it has an explicit opt-out for a value it got wrong.
7
+ //
8
+ // Nothing here returns, logs or embeds the value: a finding names only why it matched.
9
+
10
+ /** Why a name and value look like a credential. `because` completes "… looks like a credential: <because>". */
11
+ export interface PlainCredentialFinding {
12
+ readonly basis: 'name' | 'value'
13
+ readonly because: string
14
+ }
15
+
16
+ /** Words in a variable name that mark a credential on their own; `BASIC` followed by `AUTH` does too. */
17
+ const CREDENTIAL_WORDS: ReadonlySet<string> = new Set([
18
+ 'TOKEN',
19
+ 'SECRET',
20
+ 'PASSWORD',
21
+ 'PASSWD',
22
+ 'PASS',
23
+ 'PASSPHRASE',
24
+ 'PWD',
25
+ 'CREDENTIAL',
26
+ 'CREDENTIALS',
27
+ 'APIKEY',
28
+ 'PRIVATEKEY',
29
+ 'BASICAUTH',
30
+ 'HTPASSWD',
31
+ ])
32
+
33
+ /** Words that make `KEY` (or `KEYS`) something other than a credential: `KEY_ID`, `PUBLIC_KEY`, `SITE_KEY`, `CACHE_KEY`. */
34
+ // Not `PRIMARY`: some providers call a secret a primary key (an account's primary access key).
35
+ const NON_CREDENTIAL_KEY_WORDS: ReadonlySet<string> = new Set([
36
+ 'ID',
37
+ 'IDS',
38
+ 'PUBLIC',
39
+ 'PUBLISHABLE',
40
+ 'SITE',
41
+ 'CACHE',
42
+ 'PARTITION',
43
+ 'SORT',
44
+ 'FOREIGN',
45
+ ])
46
+
47
+ /** The words beside `KEY` that make its value public, not merely not a credential. */
48
+ const PUBLIC_KEY_WORDS: ReadonlySet<string> = new Set(['PUBLIC', 'PUBLISHABLE', 'SITE'])
49
+
50
+ /**
51
+ * A last word that makes the name describe a credential rather than hold one: `TOKEN_URL`, `PASSWORD_MIN_LENGTH`,
52
+ * `SECRET_NAME`, `API_KEY_HEADER`.
53
+ */
54
+ const DESCRIPTOR_WORDS: ReadonlySet<string> = new Set([
55
+ 'URL',
56
+ 'URI',
57
+ 'ENDPOINT',
58
+ 'HOST',
59
+ 'ORIGIN',
60
+ 'PATH',
61
+ 'FILE',
62
+ 'DIR',
63
+ 'ID',
64
+ 'IDS',
65
+ 'NAME',
66
+ 'NAMES',
67
+ 'HEADER',
68
+ 'PARAM',
69
+ 'TTL',
70
+ 'LIFETIME',
71
+ 'EXPIRY',
72
+ 'EXPIRES',
73
+ 'LENGTH',
74
+ 'SIZE',
75
+ 'ALGORITHM',
76
+ 'ISSUER',
77
+ 'AUDIENCE',
78
+ 'MODE',
79
+ 'ENABLED',
80
+ 'REQUIRED',
81
+ 'PREFIX',
82
+ 'POLICY',
83
+ 'TYPE',
84
+ 'VERSION',
85
+ 'COUNT',
86
+ 'LIMIT',
87
+ 'TIMEOUT',
88
+ 'REALM',
89
+ ])
90
+
91
+ /** `FABRIKA_EMAIL_POSTMARK_SERVER_TOKEN`, `apiKey`, `basic-auth.password` → upper-case words. */
92
+ const nameWords = (name: string): readonly string[] =>
93
+ name
94
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
95
+ .toUpperCase()
96
+ .split(/[^A-Z0-9]+/)
97
+ .filter((word) => word !== '')
98
+
99
+ /** Whether the `KEY` at `index` is an id, a public key or a cache key: a word beside it says so. */
100
+ const nonCredentialKey = (words: readonly string[], index: number): boolean => {
101
+ const before = words[index - 1]
102
+ const after = words[index + 1]
103
+ return (before !== undefined && NON_CREDENTIAL_KEY_WORDS.has(before)) || (after !== undefined && NON_CREDENTIAL_KEY_WORDS.has(after))
104
+ }
105
+
106
+ /** The word of a credential name that matched, or null. */
107
+ const credentialWordIn = (words: readonly string[]): string | null => {
108
+ const last = words.at(-1)
109
+ if (last === undefined || DESCRIPTOR_WORDS.has(last)) return null
110
+ for (const [index, word] of words.entries()) {
111
+ if (CREDENTIAL_WORDS.has(word)) return word
112
+ if (word === 'BASIC' && words[index + 1] === 'AUTH') return 'BASIC_AUTH'
113
+ if ((word === 'KEY' || word === 'KEYS') && !nonCredentialKey(words, index)) return word
114
+ }
115
+ return null
116
+ }
117
+
118
+ /**
119
+ * Whether the name says its value is public: a publishable, site or public key, or an id, in a name with no credential
120
+ * word. Such a value is often long and random (`pk_live_…`, a reCAPTCHA site key, a VAPID public key), so the
121
+ * random-string rule does not apply to it. A name that also says `SECRET` (`SECRET_KEY_ID`) is not public.
122
+ */
123
+ const namesAPublicValue = (words: readonly string[]): boolean => {
124
+ if (words.some((word, index) => CREDENTIAL_WORDS.has(word) || (word === 'BASIC' && words[index + 1] === 'AUTH'))) return false
125
+ const publicKey = words.some((word, index) =>
126
+ (word === 'KEY' || word === 'KEYS')
127
+ && [words[index - 1], words[index + 1]].some((beside) => beside !== undefined && PUBLIC_KEY_WORDS.has(beside))
128
+ )
129
+ return publicKey || words.at(-1) === 'ID' || words.at(-1) === 'IDS'
130
+ }
131
+
132
+ /**
133
+ * A Zerops or shell reference (`${db_password}`) names a value held elsewhere, so it is not one here. Removing them
134
+ * leaves the literal part of a value; a value that is only references holds no literal at all.
135
+ */
136
+ const withoutReferences = (value: string): string => value.replace(/\$\{[^}]*\}/g, '')
137
+
138
+ /** Prefixes that issuers put on their tokens. */
139
+ const TOKEN_PREFIXES: readonly (readonly [RegExp, string])[] = [
140
+ [/^px_[A-Za-z0-9_-]{8,}/, 'a Fabrika key'],
141
+ [/^(ghp|gho|ghs|ghu|ghr)_[A-Za-z0-9]{20,}/, 'a GitHub token'],
142
+ [/^github_pat_[A-Za-z0-9_]{20,}/, 'a GitHub token'],
143
+ [/^glpat-[A-Za-z0-9_-]{16,}/, 'a GitLab token'],
144
+ [/^(sk|rk)_(live|test)_[A-Za-z0-9]{16,}/, 'a Stripe key'],
145
+ [/^whsec_[A-Za-z0-9+/=]{16,}/, 'a webhook signing secret'],
146
+ [/^xox[abposr]-[A-Za-z0-9-]{10,}/, 'a Slack token'],
147
+ [/^sk-[A-Za-z0-9_-]{20,}/, 'an API secret key'],
148
+ [/^AKIA[0-9A-Z]{16}$/, 'an AWS access key'],
149
+ [/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/, 'a signed JSON Web Token'],
150
+ ]
151
+
152
+ /** Shannon entropy in bits per character. */
153
+ const entropy = (text: string): number => {
154
+ const counts = new Map<string, number>()
155
+ for (const character of text) counts.set(character, (counts.get(character) ?? 0) + 1)
156
+ let bits = 0
157
+ for (const count of counts.values()) {
158
+ const share = count / text.length
159
+ bits -= share * Math.log2(share)
160
+ }
161
+ return bits
162
+ }
163
+
164
+ /** The share of `text` that matches `pattern`, a single-character class. */
165
+ const share = (text: string, pattern: RegExp): number => (text.match(pattern)?.length ?? 0) / text.length
166
+
167
+ /**
168
+ * A random-looking single word: at least 24 characters of a token alphabet, at least a fifth of them upper case and a
169
+ * fifth lower case, and at least 4 bits of entropy per character. A camel-case name has far fewer capitals than a
170
+ * random string. Hexadecimal (a digest, a UUID) has one letter case and at most 4 bits, so it never matches: a hex
171
+ * credential is caught by its name or not at all.
172
+ */
173
+ const looksRandom = (text: string): boolean =>
174
+ text.length >= 24
175
+ && /^[A-Za-z0-9+/=_-]+$/.test(text)
176
+ && share(text, /[A-Z]/g) >= 0.2
177
+ && share(text, /[a-z]/g) >= 0.2
178
+ && entropy(text) >= 4
179
+
180
+ /**
181
+ * The literal part of a value: references removed, and an Authorization scheme left standing alone by that removal
182
+ * (`Bearer ${token}`) dropped with them.
183
+ */
184
+ const literalOf = (value: string): string => withoutReferences(value).trim().replace(/^(Basic|Bearer|Token)$/i, '')
185
+
186
+ /**
187
+ * A setting's value, unwrapped from how a response header is written in `zerops.yaml` (`"'true' always"`): surrounding
188
+ * quotes and nginx's trailing `always` removed.
189
+ */
190
+ const settingOf = (literal: string): string => {
191
+ let text = literal.replace(/\s+always$/i, '').trim()
192
+ for (let round = 0; round < 2; round++) text = text.replace(/^(['"])(.*)\1$/, '$2').trim()
193
+ return text
194
+ }
195
+
196
+ /** A boolean is never a credential, whatever the name says (`Access-Control-Allow-Credentials: true`). */
197
+ const isBoolean = (setting: string): boolean => /^(true|false|yes|no|on|off)$/i.test(setting)
198
+
199
+ /**
200
+ * A short integer, a decimal or a duration: what a setting that only describes a credential holds (`TOKEN_EXPIRES_IN`,
201
+ * `KEY_ROTATION_DAYS`). It counts only when a word after the credential word names a quantity: `DB_PASSWORD=1234` and
202
+ * `DB_PASSWORD_PROD=1234` are a PIN, and an integer of six digits or more counts anywhere.
203
+ */
204
+ const isQuantity = (setting: string): boolean => /^(\d{1,5}|\d+\.\d+|\d+(ms|s|m|h|d))$/i.test(setting)
205
+
206
+ /** Words that make a name after its credential word a quantity: `TOKEN_EXPIRES_IN`, `KEY_ROTATION_DAYS`, `PASS_RATE`. */
207
+ const QUANTITY_WORDS: ReadonlySet<string> = new Set([
208
+ 'EXPIRES',
209
+ 'EXPIRY',
210
+ 'IN',
211
+ 'AGE',
212
+ 'LIFE',
213
+ 'LIFETIME',
214
+ 'TTL',
215
+ 'ROTATION',
216
+ 'DAYS',
217
+ 'HOURS',
218
+ 'MINUTES',
219
+ 'SECONDS',
220
+ 'INTERVAL',
221
+ 'PERIOD',
222
+ 'WINDOW',
223
+ 'RATE',
224
+ 'THRESHOLD',
225
+ 'RATIO',
226
+ 'MIN',
227
+ 'MAX',
228
+ 'LENGTH',
229
+ 'SIZE',
230
+ 'COUNT',
231
+ 'LIMIT',
232
+ 'RETRIES',
233
+ 'ATTEMPTS',
234
+ 'TIMEOUT',
235
+ ])
236
+
237
+ /** Whether a word after the credential word that matched names a quantity. */
238
+ const describesAQuantity = (words: readonly string[], word: string): boolean => {
239
+ const at = words.indexOf(word === 'BASIC_AUTH' ? 'AUTH' : word)
240
+ return at !== -1 && words.slice(at + 1).some((after) => QUANTITY_WORDS.has(after))
241
+ }
242
+
243
+ /** What the VALUE alone says, or null. Never echoes it. */
244
+ const valueFinding = (literal: string, publicValue: boolean): string | null => {
245
+ if (literal === '') return null
246
+ if (/-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(literal)) return 'it holds a private key'
247
+ if (/^(Basic|Bearer|Token)\s+\S{8,}$/i.test(literal)) return 'it is an Authorization header value'
248
+ // `scheme://user:password@host`: a password in the URL's userinfo. A reference in the password was removed above.
249
+ if (/^[a-z][a-z0-9+.-]*:\/\/[^/@:\s]*:[^/@\s]+@/i.test(literal)) return 'its URL carries a password'
250
+ for (const [pattern, kind] of TOKEN_PREFIXES) {
251
+ if (pattern.test(literal)) return `it reads like ${kind}`
252
+ }
253
+ if (!publicValue && looksRandom(literal)) return 'it is a long random string'
254
+ return null
255
+ }
256
+
257
+ /**
258
+ * Whether a plain `name = value` looks like a credential, and why; null when it does not.
259
+ *
260
+ * The name matches on a credential word (`TOKEN`, `SECRET`, `PASSWORD`, `PASS`, `BASIC_AUTH`, a `KEY` or `KEYS` that is
261
+ * not an id, a public key or a cache key), unless its last word makes it describe one (`TOKEN_URL`,
262
+ * `PASSWORD_MIN_LENGTH`). A name match needs a literal that could be a credential: an empty value, one made only of
263
+ * references or a boolean is not, nor a short number or duration under a name that says it is a quantity. The value matches on its own: a private key, an
264
+ * Authorization header, a URL with a password, an issuer's token prefix, or a long random string unless the name says
265
+ * the value is public (a publishable or site key, an id).
266
+ */
267
+ export function plainCredentialFinding(name: string, value: string): PlainCredentialFinding | null {
268
+ const words = nameWords(name)
269
+ const literal = literalOf(value)
270
+ const word = credentialWordIn(words)
271
+ const setting = settingOf(literal)
272
+ const describes = isBoolean(setting) || (word !== null && isQuantity(setting) && describesAQuantity(words, word))
273
+ if (word !== null && literal !== '' && !describes) {
274
+ return { basis: 'name', because: `its name contains \`${word}\`` }
275
+ }
276
+ const because = valueFinding(literal, namesAPublicValue(words))
277
+ return because === null ? null : { basis: 'value', because }
278
+ }
@@ -321,6 +321,15 @@ export interface ProviderNamespaceDevSandbox {
321
321
  /** The access of the workspace's own published bootstrap run. */
322
322
  readonly access: ProviderApprovedAccess;
323
323
  }
324
+ /** What decides the hosts a namespace entry point routes one member on: `ProviderNamespaceMember` without its secrets. */
325
+ export interface ProviderNamespaceMemberRouting {
326
+ readonly appId: string;
327
+ readonly env: string;
328
+ readonly domain?: string;
329
+ readonly artifact: ProviderEnvelope;
330
+ readonly access?: ProviderApprovedAccess;
331
+ readonly devSandboxes?: readonly Pick<ProviderNamespaceDevSandbox, 'workspaceId' | 'host'>[];
332
+ }
324
333
  /** One idempotent namespace lifecycle invocation. */
325
334
  export interface ProviderNamespaceMutationInput {
326
335
  readonly namespace: ProviderDeploymentNamespace;
@@ -488,6 +497,11 @@ export interface ProviderNamespaceCapabilities {
488
497
  reconcile(input: ProviderNamespaceMutationInput): Promise<ProviderDeploymentNamespace>;
489
498
  /** Absent means the namespace has no entry point that follows its members. */
490
499
  republish?(input: ProviderNamespaceRepublishInput): Promise<ProviderNamespaceRepublishResult>;
500
+ /**
501
+ * The hosts the namespace's entry point routes this member on, lower-cased, by the rule its compiler applies; none for
502
+ * a member it does not route. Throws for a member it cannot route. Absent means no member is routed by host.
503
+ */
504
+ memberHosts?(member: ProviderNamespaceMemberRouting): readonly string[];
491
505
  /**
492
506
  * Read-only: whether each claimed resource still exists, one answer per key. Throws when it cannot tell, so Control
493
507
  * releases a claim only over a resource the provider confirmed gone. Absent means no claim can be released.
@@ -1,5 +1,6 @@
1
1
  export * from './authoring';
2
2
  export * from './control';
3
3
  export * from './json';
4
+ export * from './plain-credentials';
4
5
  export * from './schema';
5
6
  export * from './steps';
@@ -0,0 +1,16 @@
1
+ /** Why a name and value look like a credential. `because` completes "… looks like a credential: <because>". */
2
+ export interface PlainCredentialFinding {
3
+ readonly basis: 'name' | 'value';
4
+ readonly because: string;
5
+ }
6
+ /**
7
+ * Whether a plain `name = value` looks like a credential, and why; null when it does not.
8
+ *
9
+ * The name matches on a credential word (`TOKEN`, `SECRET`, `PASSWORD`, `PASS`, `BASIC_AUTH`, a `KEY` or `KEYS` that is
10
+ * not an id, a public key or a cache key), unless its last word makes it describe one (`TOKEN_URL`,
11
+ * `PASSWORD_MIN_LENGTH`). A name match needs a literal that could be a credential: an empty value, one made only of
12
+ * references or a boolean is not, nor a short number or duration under a name that says it is a quantity. The value matches on its own: a private key, an
13
+ * Authorization header, a URL with a password, an issuer's token prefix, or a long random string unless the name says
14
+ * the value is public (a publishable or site key, an id).
15
+ */
16
+ export declare function plainCredentialFinding(name: string, value: string): PlainCredentialFinding | null;