@pikku/inspector 0.12.50 → 0.12.52

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 (99) hide show
  1. package/CHANGELOG.md +441 -0
  2. package/OPTIMIZATION-PLAN.md +9 -3
  3. package/dist/add/add-auth.d.ts +1 -1
  4. package/dist/add/add-auth.js +1 -1
  5. package/dist/add/add-cli.js +7 -0
  6. package/dist/add/add-credential.js +1 -1
  7. package/dist/add/add-functions.js +156 -7
  8. package/dist/add/add-http-route.js +16 -6
  9. package/dist/add/add-middleware.js +46 -3
  10. package/dist/add/add-personas.d.ts +13 -0
  11. package/dist/add/add-personas.js +210 -0
  12. package/dist/add/add-scope.js +1 -1
  13. package/dist/add/add-secret.js +1 -1
  14. package/dist/add/add-system-role.d.ts +2 -0
  15. package/dist/add/add-system-role.js +102 -0
  16. package/dist/add/add-variable.js +1 -1
  17. package/dist/add/add-wire-addon.js +31 -0
  18. package/dist/error-codes.d.ts +10 -1
  19. package/dist/error-codes.js +11 -0
  20. package/dist/index.d.ts +1 -1
  21. package/dist/inspector.js +33 -1
  22. package/dist/types.d.ts +46 -2
  23. package/dist/utils/annotate-http-route-auth.d.ts +22 -0
  24. package/dist/utils/annotate-http-route-auth.js +48 -0
  25. package/dist/utils/extract-function-name.js +13 -4
  26. package/dist/utils/extract-function-node.js +18 -1
  27. package/dist/utils/extract-secret-usage.d.ts +9 -0
  28. package/dist/utils/extract-secret-usage.js +61 -0
  29. package/dist/utils/literal-properties.d.ts +22 -0
  30. package/dist/utils/literal-properties.js +69 -0
  31. package/dist/utils/load-addon-functions-meta.js +26 -1
  32. package/dist/utils/permissions.js +8 -0
  33. package/dist/utils/post-process.d.ts +68 -3
  34. package/dist/utils/post-process.js +243 -13
  35. package/dist/utils/secret-alias-services.d.ts +8 -0
  36. package/dist/utils/secret-alias-services.js +45 -0
  37. package/dist/utils/secret-brokers.d.ts +2 -0
  38. package/dist/utils/secret-brokers.js +9 -0
  39. package/dist/utils/serialize-inspector-state.d.ts +10 -0
  40. package/dist/utils/serialize-inspector-state.js +18 -0
  41. package/dist/utils/serialize-middleware-groups-meta.js +3 -0
  42. package/dist/utils/validate-exposed-functions-gated.d.ts +14 -0
  43. package/dist/utils/validate-exposed-functions-gated.js +85 -0
  44. package/dist/utils/validate-tags-resolve-to-middleware.d.ts +20 -0
  45. package/dist/utils/validate-tags-resolve-to-middleware.js +41 -0
  46. package/dist/visit.js +4 -0
  47. package/package.json +3 -3
  48. package/src/add/add-auth.test.ts +5 -3
  49. package/src/add/add-auth.ts +1 -1
  50. package/src/add/add-cli.ts +8 -0
  51. package/src/add/add-credential.ts +1 -1
  52. package/src/add/add-functions.test.ts +263 -1
  53. package/src/add/add-functions.ts +219 -9
  54. package/src/add/add-http-route.ts +20 -7
  55. package/src/add/add-middleware.test.ts +196 -0
  56. package/src/add/add-middleware.ts +64 -4
  57. package/src/add/add-personas.test.ts +268 -0
  58. package/src/add/add-personas.ts +276 -0
  59. package/src/add/add-scenario-step.test.ts +49 -3
  60. package/src/add/add-scope.test.ts +30 -30
  61. package/src/add/add-scope.ts +1 -1
  62. package/src/add/add-secret.ts +1 -1
  63. package/src/add/add-subject-scenario-steps.test.ts +161 -0
  64. package/src/add/add-system-role.test.ts +214 -0
  65. package/src/add/add-system-role.ts +164 -0
  66. package/src/add/add-variable.ts +1 -1
  67. package/src/add/add-wire-addon.test.ts +111 -0
  68. package/src/add/add-wire-addon.ts +29 -0
  69. package/src/add/addon-bans.test.ts +4 -4
  70. package/src/add/config-value-metadata.test.ts +11 -11
  71. package/src/add/wire-name-literal.test.ts +2 -2
  72. package/src/error-codes.ts +13 -0
  73. package/src/index.ts +4 -1
  74. package/src/inspector.ts +39 -0
  75. package/src/types.ts +47 -2
  76. package/src/utils/annotate-http-route-auth.test.ts +163 -0
  77. package/src/utils/annotate-http-route-auth.ts +52 -0
  78. package/src/utils/extract-function-name.ts +14 -4
  79. package/src/utils/extract-function-node.ts +18 -6
  80. package/src/utils/extract-secret-usage.test.ts +81 -0
  81. package/src/utils/extract-secret-usage.ts +73 -0
  82. package/src/utils/literal-properties.ts +97 -0
  83. package/src/utils/load-addon-functions-meta.ts +32 -2
  84. package/src/utils/permissions-shorthand.test.ts +79 -0
  85. package/src/utils/permissions.ts +7 -0
  86. package/src/utils/post-process.test.ts +133 -0
  87. package/src/utils/post-process.ts +310 -12
  88. package/src/utils/secret-alias-services.test.ts +146 -0
  89. package/src/utils/secret-alias-services.ts +58 -0
  90. package/src/utils/secret-brokers.test.ts +53 -0
  91. package/src/utils/secret-brokers.ts +11 -0
  92. package/src/utils/serialize-inspector-state.ts +28 -0
  93. package/src/utils/serialize-middleware-groups-meta.ts +3 -0
  94. package/src/utils/validate-exposed-functions-gated.test.ts +230 -0
  95. package/src/utils/validate-exposed-functions-gated.ts +94 -0
  96. package/src/utils/validate-tags-resolve-to-middleware.test.ts +105 -0
  97. package/src/utils/validate-tags-resolve-to-middleware.ts +48 -0
  98. package/src/visit.ts +4 -0
  99. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,146 @@
1
+ import { describe, test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import ts from 'typescript'
4
+ import {
5
+ findSecretAliasServices,
6
+ isSecretServiceType,
7
+ } from './secret-alias-services.js'
8
+
9
+ const SECRET_SERVICE = `
10
+ interface SecretService {
11
+ getSecret(key: string): Promise<string>
12
+ hasSecret(key: string): Promise<boolean>
13
+ setSecret(key: string, value: unknown): Promise<void>
14
+ deleteSecret(key: string): Promise<void>
15
+ getSecrets(keys: string[]): Promise<Record<string, unknown>>
16
+ }
17
+ `
18
+
19
+ const singletonServicesTypeOf = (source: string) => {
20
+ const fileName = '/services.ts'
21
+ const host: ts.CompilerHost = {
22
+ ...ts.createCompilerHost({}),
23
+ getSourceFile: (name, languageVersion) =>
24
+ name === fileName
25
+ ? ts.createSourceFile(name, source, languageVersion, true)
26
+ : undefined,
27
+ fileExists: (name) => name === fileName,
28
+ readFile: (name) => (name === fileName ? source : undefined),
29
+ }
30
+ const program = ts.createProgram([fileName], { noLib: true }, host)
31
+ const checker = program.getTypeChecker()
32
+ const sourceFile = program.getSourceFile(fileName)!
33
+ const declaration = sourceFile.statements.find(
34
+ (statement): statement is ts.InterfaceDeclaration =>
35
+ ts.isInterfaceDeclaration(statement) &&
36
+ statement.name.text === 'SingletonServices'
37
+ )!
38
+ return {
39
+ checker,
40
+ type: checker.getTypeAtLocation(declaration),
41
+ }
42
+ }
43
+
44
+ describe('findSecretAliasServices', () => {
45
+ test('finds a secret service exposed under another name', () => {
46
+ const { type, checker } = singletonServicesTypeOf(`
47
+ ${SECRET_SERVICE}
48
+ interface SingletonServices {
49
+ secrets: SecretService
50
+ cfg: SecretService
51
+ }
52
+ `)
53
+ assert.deepEqual(findSecretAliasServices(type, checker), ['cfg'])
54
+ })
55
+
56
+ test('never reports `secrets` itself', () => {
57
+ const { type, checker } = singletonServicesTypeOf(`
58
+ ${SECRET_SERVICE}
59
+ interface SingletonServices {
60
+ secrets: SecretService
61
+ }
62
+ `)
63
+ assert.deepEqual(findSecretAliasServices(type, checker), [])
64
+ })
65
+
66
+ test('leaves ordinary services alone', () => {
67
+ const { type, checker } = singletonServicesTypeOf(`
68
+ ${SECRET_SERVICE}
69
+ interface Logger { info(message: string): void }
70
+ interface SingletonServices {
71
+ secrets: SecretService
72
+ logger: Logger
73
+ }
74
+ `)
75
+ assert.deepEqual(findSecretAliasServices(type, checker), [])
76
+ })
77
+
78
+ test('is not fooled by a service that only has getSecret', () => {
79
+ const { type, checker } = singletonServicesTypeOf(`
80
+ ${SECRET_SERVICE}
81
+ interface Partialish { getSecret(key: string): Promise<string> }
82
+ interface SingletonServices {
83
+ secrets: SecretService
84
+ partialish: Partialish
85
+ }
86
+ `)
87
+ assert.deepEqual(findSecretAliasServices(type, checker), [])
88
+ })
89
+
90
+ test('sees through an optional service', () => {
91
+ const { type, checker } = singletonServicesTypeOf(`
92
+ ${SECRET_SERVICE}
93
+ interface SingletonServices {
94
+ secrets: SecretService
95
+ cfg?: SecretService
96
+ }
97
+ `)
98
+ assert.deepEqual(findSecretAliasServices(type, checker), ['cfg'])
99
+ })
100
+
101
+ test('finds a subtype that adds methods', () => {
102
+ const { type, checker } = singletonServicesTypeOf(`
103
+ ${SECRET_SERVICE}
104
+ interface Scoped extends SecretService { getAllStatus(): Promise<void> }
105
+ interface SingletonServices {
106
+ secrets: SecretService
107
+ scoped: Scoped
108
+ }
109
+ `)
110
+ assert.deepEqual(findSecretAliasServices(type, checker), ['scoped'])
111
+ })
112
+
113
+ test('reports every alias, sorted', () => {
114
+ const { type, checker } = singletonServicesTypeOf(`
115
+ ${SECRET_SERVICE}
116
+ interface SingletonServices {
117
+ secrets: SecretService
118
+ zed: SecretService
119
+ alpha: SecretService
120
+ }
121
+ `)
122
+ assert.deepEqual(findSecretAliasServices(type, checker), ['alpha', 'zed'])
123
+ })
124
+ })
125
+
126
+ describe('isSecretServiceType', () => {
127
+ test('refuses a type whose members are not callable', () => {
128
+ const { type, checker } = singletonServicesTypeOf(`
129
+ ${SECRET_SERVICE}
130
+ interface Lookalike {
131
+ getSecret: string
132
+ hasSecret: string
133
+ setSecret: string
134
+ deleteSecret: string
135
+ getSecrets: string
136
+ }
137
+ interface SingletonServices { lookalike: Lookalike }
138
+ `)
139
+ const property = type.getProperty('lookalike')!
140
+ const propertyType = checker.getTypeOfSymbolAtLocation(
141
+ property,
142
+ property.valueDeclaration!
143
+ )
144
+ assert.equal(isSecretServiceType(propertyType, checker), false)
145
+ })
146
+ })
@@ -0,0 +1,58 @@
1
+ import type ts from 'typescript'
2
+
3
+ const SECRET_SERVICE_METHODS = [
4
+ 'getSecret',
5
+ 'hasSecret',
6
+ 'setSecret',
7
+ 'deleteSecret',
8
+ 'getSecrets',
9
+ ]
10
+
11
+ /** Whether a type structurally satisfies `SecretService`. */
12
+ export const isSecretServiceType = (
13
+ type: ts.Type,
14
+ checker: ts.TypeChecker
15
+ ): boolean => {
16
+ const nonNullable = checker.getNonNullableType(type)
17
+ return SECRET_SERVICE_METHODS.every((method) => {
18
+ const property = nonNullable.getProperty(method)
19
+ if (!property) {
20
+ return false
21
+ }
22
+ const declaration = property.valueDeclaration ?? property.declarations?.[0]
23
+ if (!declaration) {
24
+ return false
25
+ }
26
+ const propertyType = checker.getTypeOfSymbolAtLocation(
27
+ property,
28
+ declaration
29
+ )
30
+ return propertyType.getCallSignatures().length > 0
31
+ })
32
+ }
33
+
34
+ /**
35
+ * Singleton service names, other than `secrets`, whose type is a
36
+ * `SecretService`.
37
+ */
38
+ export const findSecretAliasServices = (
39
+ singletonServicesType: ts.Type,
40
+ checker: ts.TypeChecker
41
+ ): string[] => {
42
+ const aliases: string[] = []
43
+ for (const property of singletonServicesType.getProperties()) {
44
+ const name = property.getName()
45
+ if (name === 'secrets') {
46
+ continue
47
+ }
48
+ const declaration = property.valueDeclaration ?? property.declarations?.[0]
49
+ if (!declaration) {
50
+ continue
51
+ }
52
+ const type = checker.getTypeOfSymbolAtLocation(property, declaration)
53
+ if (isSecretServiceType(type, checker)) {
54
+ aliases.push(name)
55
+ }
56
+ }
57
+ return aliases.sort()
58
+ }
@@ -0,0 +1,53 @@
1
+ import { describe, test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { isSecretBrokerFunction } from './secret-brokers.js'
4
+ import { computeSecretBrokers } from './post-process.js'
5
+ import type { InspectorState } from '../types.js'
6
+
7
+ describe('isSecretBrokerFunction', () => {
8
+ test('admits the console secret-admin functions', () => {
9
+ assert.ok(isSecretBrokerFunction('pikkuConsoleGetSecret'))
10
+ assert.ok(isSecretBrokerFunction('pikkuConsoleSetSecret'))
11
+ assert.ok(isSecretBrokerFunction('pikkuConsoleHasSecret'))
12
+ })
13
+
14
+ test('admits them when namespaced by an addon', () => {
15
+ assert.ok(isSecretBrokerFunction('pikku:pikkuConsoleGetSecret'))
16
+ })
17
+
18
+ test('admits nothing else', () => {
19
+ assert.equal(isSecretBrokerFunction('pikkuConsoleGetVariable'), false)
20
+ assert.equal(isSecretBrokerFunction('httpRequest'), false)
21
+ assert.equal(isSecretBrokerFunction('myFunction'), false)
22
+ })
23
+
24
+ test('is not fooled by a name that merely contains a broker name', () => {
25
+ assert.equal(isSecretBrokerFunction('notPikkuConsoleGetSecret'), false)
26
+ assert.equal(isSecretBrokerFunction('pikkuConsoleGetSecretly'), false)
27
+ })
28
+ })
29
+
30
+ describe('computeSecretBrokers', () => {
31
+ const stateWith = (meta: Record<string, any>) =>
32
+ ({ functions: { meta } }) as unknown as InspectorState
33
+
34
+ test('flags a broker so the runner keeps its secrets', () => {
35
+ const state = stateWith({
36
+ pikkuConsoleGetSecret: { pikkuFuncId: 'pikkuConsoleGetSecret' },
37
+ })
38
+ computeSecretBrokers(state)
39
+ assert.equal(state.functions.meta.pikkuConsoleGetSecret!.secretBroker, true)
40
+ })
41
+
42
+ test('leaves an ordinary function unflagged', () => {
43
+ const state = stateWith({ createTodo: { pikkuFuncId: 'createTodo' } })
44
+ computeSecretBrokers(state)
45
+ assert.equal(state.functions.meta.createTodo!.secretBroker, undefined)
46
+ })
47
+
48
+ test('falls back to the meta key when there is no pikkuFuncId', () => {
49
+ const state = stateWith({ pikkuConsoleSetSecret: {} })
50
+ computeSecretBrokers(state)
51
+ assert.equal(state.functions.meta.pikkuConsoleSetSecret!.secretBroker, true)
52
+ })
53
+ })
@@ -0,0 +1,11 @@
1
+ /** The console's secret administration functions, and nothing else. */
2
+ const SECRET_BROKER_FUNCTIONS = new Set([
3
+ 'pikkuConsoleSetSecret',
4
+ 'pikkuConsoleGetSecret',
5
+ 'pikkuConsoleHasSecret',
6
+ ])
7
+
8
+ /** Whether this function keeps the full `SecretService`. */
9
+ export const isSecretBrokerFunction = (functionId: string): boolean =>
10
+ SECRET_BROKER_FUNCTIONS.has(functionId) ||
11
+ SECRET_BROKER_FUNCTIONS.has(functionId.split(':').pop() ?? '')
@@ -1,3 +1,4 @@
1
+ import type { SecretUsage } from './extract-secret-usage.js'
1
2
  import type { JSONValue } from '@pikku/core'
2
3
  import type {
3
4
  InspectorDiagnostic,
@@ -201,6 +202,7 @@ export interface SerializableInspectorState {
201
202
  secrets: {
202
203
  definitions: InspectorState['secrets']['definitions']
203
204
  files: string[]
205
+ usage: Record<string, SecretUsage>
204
206
  }
205
207
  credentials: {
206
208
  definitions: InspectorState['credentials']['definitions']
@@ -210,6 +212,14 @@ export interface SerializableInspectorState {
210
212
  definitions: InspectorState['scopes']['definitions']
211
213
  files: string[]
212
214
  }
215
+ systemRoles: {
216
+ definitions: InspectorState['systemRoles']['definitions']
217
+ files: string[]
218
+ }
219
+ personas: {
220
+ definitions: InspectorState['personas']['definitions']
221
+ files: string[]
222
+ }
213
223
  variables: {
214
224
  definitions: InspectorState['variables']['definitions']
215
225
  files: string[]
@@ -416,6 +426,7 @@ export function serializeInspectorState(
416
426
  secrets: {
417
427
  definitions: state.secrets.definitions,
418
428
  files: Array.from(state.secrets.files),
429
+ usage: Object.fromEntries(state.secrets.usage),
419
430
  },
420
431
  credentials: {
421
432
  definitions: state.credentials.definitions,
@@ -425,6 +436,14 @@ export function serializeInspectorState(
425
436
  definitions: state.scopes.definitions,
426
437
  files: Array.from(state.scopes.files),
427
438
  },
439
+ systemRoles: {
440
+ definitions: state.systemRoles.definitions,
441
+ files: Array.from(state.systemRoles.files),
442
+ },
443
+ personas: {
444
+ definitions: state.personas.definitions,
445
+ files: Array.from(state.personas.files),
446
+ },
428
447
  variables: {
429
448
  definitions: state.variables.definitions,
430
449
  files: Array.from(state.variables.files),
@@ -611,6 +630,7 @@ export function deserializeInspectorState(
611
630
  secrets: {
612
631
  definitions: data.secrets?.definitions || [],
613
632
  files: new Set(data.secrets?.files || []),
633
+ usage: new Map(Object.entries(data.secrets?.usage || {})),
614
634
  },
615
635
  credentials: {
616
636
  definitions: data.credentials?.definitions || [],
@@ -620,6 +640,14 @@ export function deserializeInspectorState(
620
640
  definitions: data.scopes?.definitions || [],
621
641
  files: new Set(data.scopes?.files || []),
622
642
  },
643
+ systemRoles: {
644
+ definitions: data.systemRoles?.definitions || [],
645
+ files: new Set(data.systemRoles?.files || []),
646
+ },
647
+ personas: {
648
+ definitions: data.personas?.definitions || [],
649
+ files: new Set(data.personas?.files || []),
650
+ },
623
651
  variables: {
624
652
  definitions: data.variables?.definitions || [],
625
653
  files: new Set(data.variables?.files || []),
@@ -13,6 +13,9 @@ const serializeGroupMap = (
13
13
  count: meta.count,
14
14
  instanceIds: meta.instanceIds,
15
15
  isFactory: meta.isFactory,
16
+ ...(meta.additionalRegistrations && {
17
+ additionalRegistrations: meta.additionalRegistrations,
18
+ }),
16
19
  }
17
20
  }
18
21
  return result
@@ -0,0 +1,230 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, test, beforeEach } from 'node:test'
3
+ import { ErrorCode } from '../error-codes.js'
4
+ import { validateExposedFunctionsGated } from './validate-exposed-functions-gated.js'
5
+
6
+ const ADDON_PACKAGE = '@addon/console'
7
+
8
+ let diagnostics: Array<{ severity: string; code: string; message: string }>
9
+
10
+ const logger = {
11
+ debug: () => {},
12
+ info: () => {},
13
+ warn: () => {},
14
+ error: () => {},
15
+ critical: () => {},
16
+ diagnostic: (d: any) => diagnostics.push(d),
17
+ hasCriticalErrors: () => false,
18
+ } as any
19
+
20
+ /**
21
+ * The two pieces of state the check reads: every function's meta, and every
22
+ * wireAddon declaration the inspector found.
23
+ */
24
+ const stateWith = (
25
+ meta: Record<string, unknown>,
26
+ addons: Record<string, unknown> = {}
27
+ ) =>
28
+ ({
29
+ functions: { meta },
30
+ rpc: { wireAddonDeclarations: new Map(Object.entries(addons)) },
31
+ }) as any
32
+
33
+ /** An exposed sessionless function with no gate of any kind — the bad shape. */
34
+ const ungatedFunction = (overrides: Record<string, unknown> = {}) => ({
35
+ pikkuFuncId: 'credentialGet',
36
+ expose: true,
37
+ sessionless: true,
38
+ ...overrides,
39
+ })
40
+
41
+ const run = (state: any) => {
42
+ validateExposedFunctionsGated(logger, state)
43
+ return diagnostics
44
+ }
45
+
46
+ const warning = () => {
47
+ const found = diagnostics.find(
48
+ (d) => d.code === ErrorCode.EXPOSED_FUNCTION_HAS_NO_GATE
49
+ )
50
+ return found
51
+ }
52
+
53
+ beforeEach(() => {
54
+ diagnostics = []
55
+ })
56
+
57
+ describe('validateExposedFunctionsGated', () => {
58
+ test('warns about an exposed sessionless function with no gate', () => {
59
+ run(stateWith({ credentialGet: ungatedFunction() }))
60
+
61
+ const found = warning()
62
+ assert.ok(found, 'expected a diagnostic')
63
+ assert.equal(found.severity, 'warn')
64
+ assert.match(found.message, /credentialGet/)
65
+ })
66
+
67
+ test('names every ungated function, not just a count', () => {
68
+ run(
69
+ stateWith({
70
+ credentialGet: ungatedFunction(),
71
+ installAddon: ungatedFunction({ pikkuFuncId: 'installAddon' }),
72
+ })
73
+ )
74
+
75
+ assert.match(warning()!.message, /credentialGet/)
76
+ assert.match(warning()!.message, /installAddon/)
77
+ })
78
+
79
+ test('stays silent for a function that is not exposed', () => {
80
+ run(stateWith({ credentialGet: ungatedFunction({ expose: undefined }) }))
81
+
82
+ assert.equal(warning(), undefined)
83
+ })
84
+
85
+ test('stays silent for a pikkuFunc, which always requires a session', () => {
86
+ run(stateWith({ credentialGet: ungatedFunction({ sessionless: false }) }))
87
+
88
+ assert.equal(warning(), undefined)
89
+ })
90
+
91
+ test('stays silent for a scenario step, which rpcExposed refuses anyway', () => {
92
+ run(stateWith({ step: ungatedFunction({ scenarioStep: true }) }))
93
+
94
+ assert.equal(warning(), undefined)
95
+ })
96
+
97
+ describe('a function that gates itself', () => {
98
+ test('is silent when it declares auth', () => {
99
+ run(stateWith({ credentialGet: ungatedFunction({ auth: true }) }))
100
+
101
+ assert.equal(warning(), undefined)
102
+ })
103
+
104
+ test('is silent when it declares it authenticates in its own body', () => {
105
+ // A webhook receiver verifying a signature has a real gate this check
106
+ // cannot see. Without a way to say so the warning would fire forever on
107
+ // functions that are fine, and a warning that is usually wrong is one
108
+ // nobody reads.
109
+ run(
110
+ stateWith({
111
+ stripeWebhook: ungatedFunction({ selfAuthenticated: true }),
112
+ })
113
+ )
114
+
115
+ assert.equal(warning(), undefined)
116
+ })
117
+
118
+ test('still warns when the declaration is explicitly false', () => {
119
+ run(
120
+ stateWith({
121
+ credentialGet: ungatedFunction({ selfAuthenticated: false }),
122
+ })
123
+ )
124
+
125
+ assert.ok(warning())
126
+ })
127
+
128
+ test('is silent when it declares scopes', () => {
129
+ run(stateWith({ credentialGet: ungatedFunction({ scopes: ['admin'] }) }))
130
+
131
+ assert.equal(warning(), undefined)
132
+ })
133
+
134
+ test('is silent when it declares permissions', () => {
135
+ run(
136
+ stateWith({
137
+ credentialGet: ungatedFunction({
138
+ permissions: [{ type: 'wire', name: 'isAdmin' }],
139
+ }),
140
+ })
141
+ )
142
+
143
+ assert.equal(warning(), undefined)
144
+ })
145
+
146
+ test('still warns when scopes is present but empty', () => {
147
+ run(stateWith({ credentialGet: ungatedFunction({ scopes: [] }) }))
148
+
149
+ assert.ok(warning(), 'an empty scopes array gates nothing')
150
+ })
151
+ })
152
+
153
+ describe('a function gated by its addon', () => {
154
+ test('is silent when the addon declares scopes', () => {
155
+ run(
156
+ stateWith(
157
+ {
158
+ credentialGet: ungatedFunction({ packageName: ADDON_PACKAGE }),
159
+ },
160
+ { console: { package: ADDON_PACKAGE, scopes: ['admin'] } }
161
+ )
162
+ )
163
+
164
+ assert.equal(warning(), undefined)
165
+ })
166
+
167
+ test('is silent when the addon declares auth', () => {
168
+ run(
169
+ stateWith(
170
+ {
171
+ credentialGet: ungatedFunction({ packageName: ADDON_PACKAGE }),
172
+ },
173
+ { console: { package: ADDON_PACKAGE, auth: true } }
174
+ )
175
+ )
176
+
177
+ assert.equal(warning(), undefined)
178
+ })
179
+
180
+ test('warns when the addon is wired without any gate', () => {
181
+ run(
182
+ stateWith(
183
+ {
184
+ credentialGet: ungatedFunction({ packageName: ADDON_PACKAGE }),
185
+ },
186
+ { console: { package: ADDON_PACKAGE } }
187
+ )
188
+ )
189
+
190
+ assert.ok(warning(), 'wireAddon with no scopes or auth gates nothing')
191
+ })
192
+
193
+ test('warns when the gated addon is a different package', () => {
194
+ run(
195
+ stateWith(
196
+ {
197
+ credentialGet: ungatedFunction({ packageName: ADDON_PACKAGE }),
198
+ },
199
+ { other: { package: '@addon/other', scopes: ['admin'] } }
200
+ )
201
+ )
202
+
203
+ assert.ok(warning())
204
+ })
205
+
206
+ test('is silent when any one instance of the package is gated', () => {
207
+ // resolveAddonScopes unions across every instance of the package, so a
208
+ // second ungated namespace does not open the first.
209
+ run(
210
+ stateWith(
211
+ {
212
+ credentialGet: ungatedFunction({ packageName: ADDON_PACKAGE }),
213
+ },
214
+ {
215
+ console: { package: ADDON_PACKAGE, scopes: ['admin'] },
216
+ consoleReadonly: { package: ADDON_PACKAGE },
217
+ }
218
+ )
219
+ )
220
+
221
+ assert.equal(warning(), undefined)
222
+ })
223
+ })
224
+
225
+ test('stays silent when nothing is exposed', () => {
226
+ run(stateWith({}))
227
+
228
+ assert.equal(diagnostics.length, 0)
229
+ })
230
+ })
@@ -0,0 +1,94 @@
1
+ import { ErrorCode } from '../error-codes.js'
2
+ import type { InspectorLogger, InspectorState } from '../types.js'
3
+
4
+ /**
5
+ * A function reachable through the generated `POST /rpc/:rpcName` dispatcher
6
+ * that nothing will stop.
7
+ *
8
+ * `rpc.exposed` refuses anything without `expose: true`, so the population is
9
+ * small and deliberate — someone typed it. What makes one dangerous is the
10
+ * combination: exposed, sessionless, and carrying no gate of its own or from
11
+ * the addon it belongs to. The dispatcher cannot help, because it does not know
12
+ * what it is dispatching to.
13
+ *
14
+ * knowledge: decisions/security/console-addon-privileged-functions-gate-themselves.md
15
+ */
16
+ export function validateExposedFunctionsGated(
17
+ logger: InspectorLogger,
18
+ state: InspectorState
19
+ ): void {
20
+ const ungated: string[] = []
21
+
22
+ for (const [funcName, meta] of Object.entries(state.functions.meta)) {
23
+ if (!meta.expose) continue
24
+
25
+ // A pikkuFunc always requires a session, on every path.
26
+ if (meta.sessionless === false) continue
27
+
28
+ // Scenario steps are refused by rpcExposed regardless of `expose`.
29
+ if (meta.scenarioStep) continue
30
+
31
+ // The author declared that the body authorizes its own callers — a gate
32
+ // this check has no way to see. Taking the claim at face value is the
33
+ // point: without it the warning fires forever on functions that are fine,
34
+ // and a warning that is usually wrong stops being read.
35
+ if (meta.selfAuthenticated === true) continue
36
+
37
+ // The function gates itself.
38
+ if (meta.auth === true) continue
39
+ if (meta.scopes && meta.scopes.length > 0) continue
40
+ if (meta.permissions && meta.permissions.length > 0) continue
41
+
42
+ if (isGatedByItsAddon(state, meta.packageName)) continue
43
+
44
+ ungated.push(funcName)
45
+ }
46
+
47
+ if (ungated.length === 0) return
48
+
49
+ const shown = ungated.slice(0, 10)
50
+ const rest = ungated.length - shown.length
51
+
52
+ logger.diagnostic({
53
+ severity: 'warn',
54
+ code: ErrorCode.EXPOSED_FUNCTION_HAS_NO_GATE,
55
+ message:
56
+ `${ungated.length} exposed function${ungated.length === 1 ? '' : 's'} ` +
57
+ `require neither a session nor any permission or scope, and ` +
58
+ `${ungated.length === 1 ? 'is' : 'are'} reachable by anyone through ` +
59
+ `POST /rpc/:rpcName: ${shown.join(', ')}` +
60
+ (rest > 0 ? `, and ${rest} more` : '') +
61
+ `. Add scopes or permissions to the function, gate the whole addon with ` +
62
+ `wireAddon({ scopes: [...] }), or drop \`expose: true\` if it was not ` +
63
+ `meant to be callable from outside.`,
64
+ })
65
+ }
66
+
67
+ /**
68
+ * Whether every function in this package is already gated by its `wireAddon`.
69
+ * Those gates are applied by `runPikkuFunc` on every wiring path, so a function
70
+ * with no gate of its own is still covered by them.
71
+ *
72
+ * An addon whose `scopes`/`auth` were not statically knowable reads as
73
+ * unknown, and unknown is treated as gated — a false negative here costs a
74
+ * missing warning, a false positive costs trust in every warning.
75
+ *
76
+ * knowledge: decisions/security/addon-scopes-are-resolved-where-the-function-runs.md
77
+ */
78
+ function isGatedByItsAddon(
79
+ state: InspectorState,
80
+ packageName: string | undefined
81
+ ): boolean {
82
+ if (!packageName) return false
83
+
84
+ const declarations = state.rpc?.wireAddonDeclarations
85
+ if (!declarations) return false
86
+
87
+ for (const declaration of declarations.values()) {
88
+ if (declaration.package !== packageName) continue
89
+ if (declaration.auth === true) return true
90
+ if (declaration.scopes && declaration.scopes.length > 0) return true
91
+ }
92
+
93
+ return false
94
+ }