backend-manager 5.2.13 → 5.2.14

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/CHANGELOG.md CHANGED
@@ -14,7 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
14
14
  - `Fixed` for any bug fixes.
15
15
  - `Security` in case of vulnerabilities.
16
16
 
17
- # [5.2.13] - 2026-05-28
17
+ # [5.2.14] - 2026-05-28
18
18
 
19
19
  ### Removed
20
20
 
@@ -27,6 +27,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
27
27
 
28
28
  ### Changed
29
29
 
30
+ - **Signup timestamps stamped from Firebase Auth `creationTime`.** Both write paths — the `onCreate` auth event (`src/manager/events/auth/on-create.js`) and the `user/signup` fallback route (`src/manager/routes/user/signup/post.js`) — now set `metadata.created` and `consent.{legal,marketing}.grantedAt`/`revokedAt` from `user.metadata.creationTime` instead of "now"/request-time. The OMEGA user migration treats Auth's `creationTime` as the SSOT and reconciles every doc against it; the prior few-seconds drift meant every new signup got re-fixed on the next migration run. Stamping from `creationTime` makes new docs match the migration's expected value exactly, ending the recurring churn.
31
+ - **`user/signup`: `flags.signupProcessed` is the sole idempotency gate.** Removed the 5-minute account-age reject (`MAX_ACCOUNT_AGE_MS`). A genuinely-unprocessed account can now complete signup whenever it retries — fixes the failure where a slow/missing `onCreate` plus a retry after 5 minutes caused a legitimate signup to be rejected. The frontend (UJM) gate is being moved to the same doc flag in a parallel change.
32
+ - **CLI: port-conflict prompt auto-confirms after 5s.** The "Kill these processes to free the ports?" prompt in `src/cli/commands/base-command.js` now auto-confirms `Y` after 5 seconds of no input (via `AbortSignal.timeout` → `AbortPromptError` → default `true`), so unattended test/dev loops (`emulator`, `serve`, `test`) no longer hang waiting for input. Manual `y`/`n` and Ctrl+C still work.
33
+ - **`AI` `claude-code` provider rewritten for serverside use** (`src/manager/libraries/ai/providers/claude-code.js`). Was a local-only wrapper around `@anthropic-ai/claude-agent-sdk` that spawned the `claude` binary (`forceLoginMethod: 'claudeai'`, keychain OAuth) — would not run in Cloud Functions. Now calls the Claude Messages API over plain HTTPS via `@anthropic-ai/sdk` using the OAuth token as `Authorization: Bearer` + `anthropic-beta: oauth-2025-04-20`, so it bills the Claude Pro/Max subscription (not API credits) and runs anywhere Node runs. Token resolution: `options.apiKey` → `config.claude_code.oauth_token` → `process.env.CLAUDE_CODE_OAUTH_TOKEN`. Renewal is a manual yearly `claude setup-token` (no auto-refresh). Verified live (text + JSON-schema paths). See `docs/ai-library.md`.
30
34
  - **Dependency bumps**: `@anthropic-ai/claude-agent-sdk` ^0.3.152 → ^0.3.153, `stripe` ^22.1.1 → ^22.2.0.
31
35
  - **`templates/_.env`**: consolidate OpenAI/Anthropic keys under an "AI" section and add `CLAUDE_CODE_OAUTH_TOKEN`.
32
36
  - **Marketing webhook tests** (`test/routes/marketing/webhook.js`): renamed `*-duplicate-event-skipped` → `*-reprocessed-idempotently` (assert re-delivery reprocesses and the user stays revoked); `sendgrid-event-without-eventId-*` now asserts the event is processed; beehiiv idempotency variant skips when no publication is configured. Updated `docs/consent.md` and `docs/testing.md` to describe the no-ledger design.
@@ -6,18 +6,32 @@
6
6
  |---|---|---|
7
7
  | `openai` | `gpt-5-mini` | Better at structured JSON via JSON schema |
8
8
  | `anthropic` | `claude-sonnet-4-6` | Better at SVG illustrations and creative output |
9
+ | `claude-code` | `claude-opus-4-7` | Same Claude models as `anthropic`, but bills a Claude Pro/Max **subscription** instead of API credits |
9
10
 
10
11
  Return shape (same for all providers): `{ content, output, tokens, raw }`.
11
12
 
12
- `options.response: 'json'` triggers JSON parsing — both providers strip fences and parse with JSON5 for robustness. `options.schema` enforces structure on OpenAI (real JSON schema) and is injected into the system prompt on Anthropic.
13
+ `options.response: 'json'` triggers JSON parsing — all providers strip fences and parse with JSON5 for robustness. `options.schema` enforces structure on OpenAI (real JSON schema) and is injected into the system prompt on Anthropic / claude-code.
13
14
 
14
15
  API keys: `BACKEND_MANAGER_OPENAI_API_KEY`, `BACKEND_MANAGER_ANTHROPIC_API_KEY` (process.env or config).
15
16
 
17
+ ## `claude-code` provider — subscription billing
18
+
19
+ The `claude-code` provider hits the same Claude Messages API as `anthropic`, but authenticates with a **Claude Code OAuth token** (`Authorization: Bearer ...` + `anthropic-beta: oauth-2025-04-20`) so usage bills the Claude Pro/Max subscription tied to the token rather than API credits.
20
+
21
+ It is **pure HTTPS** — no `claude` binary, no subprocess — so it runs in Cloud Functions / CI / anywhere Node runs.
22
+
23
+ Token resolution (first match wins): `options.apiKey` / constructor key → `config.claude_code.oauth_token` → `process.env.CLAUDE_CODE_OAUTH_TOKEN`.
24
+
25
+ Mint the token with `claude setup-token` (valid ~1 year). When it expires, requests 401 — re-mint and update the `CLAUDE_CODE_OAUTH_TOKEN` secret. There is no automatic refresh; renewal is a manual yearly step.
26
+
27
+ > **Caveats:** the Bearer/beta subscription path is undocumented and may change. Usage is subject to the subscription's rate limits (not API-tier limits). For high-volume production traffic, prefer `anthropic` + `BACKEND_MANAGER_ANTHROPIC_API_KEY`.
28
+
16
29
  The legacy `src/manager/libraries/openai.js` is a thin compatibility shim that re-exports the OpenAI provider class — existing callers using `new OpenAI(assistant, key)` still work unchanged.
17
30
 
18
31
  | File | Purpose |
19
32
  |---|---|
20
33
  | `src/manager/libraries/ai/index.js` | Unified `AI` class (dispatches by provider) |
21
34
  | `src/manager/libraries/ai/providers/openai.js` | OpenAI provider (original `openai.js` content) |
22
- | `src/manager/libraries/ai/providers/anthropic.js` | Anthropic provider (Claude Messages API) |
35
+ | `src/manager/libraries/ai/providers/anthropic.js` | Anthropic provider (Claude Messages API, x-api-key, API credits) |
36
+ | `src/manager/libraries/ai/providers/claude-code.js` | claude-code provider (Claude Messages API, OAuth Bearer, subscription billing) |
23
37
  | `src/manager/libraries/openai.js` | Back-compat shim → providers/openai.js |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "5.2.13",
3
+ "version": "5.2.14",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -130,10 +130,25 @@ class BaseCommand {
130
130
  }
131
131
  }
132
132
 
133
- const shouldKill = await confirm({
134
- message: 'Kill these processes to free the ports?',
135
- default: true,
136
- });
133
+ // Auto-confirm (Y) after a few seconds of no input so unattended test/dev loops don't
134
+ // hang. When the timeout fires the prompt is aborted via AbortSignal and we fall back to
135
+ // the default (true). inquirer owns the cursor and can't live-update its own message, so
136
+ // the countdown is shown statically in the prompt.
137
+ const AUTO_CONFIRM_SECONDS = 5;
138
+ let shouldKill;
139
+ try {
140
+ shouldKill = await confirm(
141
+ { message: `Kill these processes to free the ports? (auto-Y in ${AUTO_CONFIRM_SECONDS}s)`, default: true },
142
+ { signal: AbortSignal.timeout(AUTO_CONFIRM_SECONDS * 1000) },
143
+ );
144
+ } catch (error) {
145
+ // AbortPromptError (timeout reached) → take the default (true). Re-throw anything else.
146
+ if (error?.name !== 'AbortPromptError') {
147
+ throw error;
148
+ }
149
+ this.log(chalk.gray(' No input — auto-confirming (Y).'));
150
+ shouldKill = true;
151
+ }
137
152
 
138
153
  if (!shouldKill) {
139
154
  this.log(chalk.gray('\n Aborting. Free the ports and try again.\n'));
@@ -72,6 +72,18 @@ module.exports = async ({ Manager, assistant, user, context, libraries }) => {
72
72
  const meta = Manager.Metadata().set({ tag: 'auth:on-create' });
73
73
  userRecord.metadata = { ...userRecord.metadata, ...meta };
74
74
 
75
+ // Stamp metadata.created from Firebase Auth's creationTime (the canonical account-creation
76
+ // moment) rather than the User schema's "now" — otherwise the doc lands a beat after Auth,
77
+ // and the OMEGA user migration reconciles every new signup against Auth on its next run.
78
+ const creationTime = user.metadata?.creationTime;
79
+ if (creationTime) {
80
+ const createdDate = new Date(creationTime);
81
+ userRecord.metadata.created = {
82
+ timestamp: createdDate.toISOString(),
83
+ timestampUNIX: Math.round(createdDate.getTime() / 1000),
84
+ };
85
+ }
86
+
75
87
  assistant.log(`onCreate: Creating user doc for ${user.uid}`, userRecord);
76
88
 
77
89
  // Write user doc with retry
@@ -1,30 +1,40 @@
1
1
  /**
2
- * Claude Code provider — uses @anthropic-ai/claude-agent-sdk to call Claude via
3
- * the local user's Claude Code subscription (no API key, no Anthropic credits).
2
+ * Claude Code provider — calls Claude over plain HTTPS using a Claude Code /
3
+ * Claude Pro/Max OAuth token (NOT API credits).
4
4
  *
5
- * Pass `forceLoginMethod: 'claudeai'` so the SDK auths via the OS keychain
6
- * OAuth session that the user already logged into via the `claude` CLI.
5
+ * Unlike the Anthropic provider (which authenticates with an x-api-key and bills
6
+ * API credits), this provider sends the OAuth token as `Authorization: Bearer ...`
7
+ * plus the `anthropic-beta: oauth-2025-04-20` header, so usage bills against the
8
+ * Claude subscription tied to the token.
7
9
  *
8
- * This is strictly a local-development provider:
9
- * - Requires a logged-in Claude Code session on the host machine
10
- * - Will not work in Cloud Functions / CI / production
11
- * - Subject to your Claude Pro/Max rate limits (not API-tier limits)
10
+ * Token resolution (first match wins):
11
+ * 1. explicit key passed to the constructor / options.apiKey
12
+ * 2. Manager config: config.claude_code.oauth_token
13
+ * 3. process.env.CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`)
12
14
  *
13
- * Returns the same { content, output, tokens, raw } shape as the other providers
14
- * so callers don't care which is in use.
15
+ * This is pure HTTPS no `claude` binary, no subprocess so it runs in Cloud
16
+ * Functions / CI / anywhere Node runs. It is subject to the token's subscription
17
+ * rate limits (not API-tier limits).
18
+ *
19
+ * The OAuth token is minted with `claude setup-token` (valid ~1 year). When it
20
+ * expires (requests 401), re-mint and update the CLAUDE_CODE_OAUTH_TOKEN secret.
21
+ * NOTE: the Bearer/beta subscription path is undocumented and may change.
22
+ *
23
+ * Returns the same { content, output, tokens, raw } shape as the other providers.
15
24
  */
16
- const DEFAULT_MODEL = 'claude-opus-4-7';
17
-
18
- // Lazy import — only load the SDK if this provider is actually used
19
- let _query;
20
-
21
- function loadQuery() {
22
- if (!_query) {
23
- _query = require('@anthropic-ai/claude-agent-sdk').query;
24
- }
25
+ const _ = require('lodash');
26
+ const JSON5 = require('json5');
25
27
 
26
- return _query;
27
- }
28
+ const DEFAULT_MODEL = 'claude-opus-4-7';
29
+ const OAUTH_BETA = 'oauth-2025-04-20';
30
+
31
+ // Pricing per 1M tokens (USD) — informational only; subscription billing is flat.
32
+ const MODEL_TABLE = {
33
+ 'claude-opus-4-7': { input: 15.00, output: 75.00 },
34
+ 'claude-opus-4-6': { input: 15.00, output: 75.00 },
35
+ 'claude-sonnet-4-6': { input: 3.00, output: 15.00 },
36
+ 'claude-haiku-4-5': { input: 1.00, output: 5.00 },
37
+ };
28
38
 
29
39
  function ClaudeCode(assistant, key) {
30
40
  const self = this;
@@ -32,7 +42,9 @@ function ClaudeCode(assistant, key) {
32
42
  self.assistant = assistant;
33
43
  self.Manager = assistant?.Manager;
34
44
  self.user = assistant?.user;
35
- // key is ignored — claude-code uses OS keychain OAuth via forceLoginMethod: 'claudeai'
45
+ self.token = key
46
+ || self.Manager?.config?.claude_code?.oauth_token
47
+ || process.env.CLAUDE_CODE_OAUTH_TOKEN;
36
48
 
37
49
  self.tokens = {
38
50
  total: { count: 0, price: 0 },
@@ -47,121 +59,110 @@ ClaudeCode.prototype.request = async function (options) {
47
59
  const self = this;
48
60
  const assistant = self.assistant;
49
61
 
50
- options = options || {};
51
- const model = options.model || DEFAULT_MODEL;
62
+ options = _.merge({}, options);
63
+ options.model = options.model || DEFAULT_MODEL;
64
+ options.maxTokens = options.maxTokens || 2048;
65
+ options.temperature = typeof options.temperature === 'undefined' ? 0.7 : options.temperature;
52
66
 
53
- // Build prompt + system from the unified options shape
54
- const { system, prompt } = extractPromptAndSystem(options);
67
+ const token = options.apiKey || self.token;
55
68
 
56
- if (!prompt) {
57
- throw new Error('claude-code provider requires options.message.content or options.messages with a user turn');
69
+ if (!token) {
70
+ throw new Error('claude-code provider requires a Claude OAuth token (set CLAUDE_CODE_OAUTH_TOKEN via `claude setup-token`)');
58
71
  }
59
72
 
60
- const query = loadQuery();
61
- const startTime = Date.now();
73
+ // Lazy-require the SDK so projects that don't use this provider don't need it.
74
+ // We use the SDK purely as an HTTP client — `authToken` makes it send
75
+ // `Authorization: Bearer <token>` instead of `x-api-key`, and the beta header
76
+ // selects the subscription (OAuth) billing path. No `claude` binary involved.
77
+ const SDK = require('@anthropic-ai/sdk');
78
+ const client = new SDK({
79
+ authToken: token,
80
+ defaultHeaders: { 'anthropic-beta': OAUTH_BETA },
81
+ });
62
82
 
63
- // Build SDK options
64
- const sdkOptions = {
65
- model,
66
- forceLoginMethod: 'claudeai', // Use Claude Pro/Max subscription, not API key
67
- allowedTools: [], // Disable all built-in tools — we just want text/JSON in/out
68
- settingSources: [], // Don't load .claude/ or ~/.claude/ settings
69
- includePartialMessages: false,
83
+ const { system, messages } = buildMessages(options);
84
+
85
+ let systemFinal = system;
86
+
87
+ if (options.response === 'json') {
88
+ systemFinal = `${systemFinal || ''}\n\nYou MUST respond with valid JSON only. No prose, no markdown fences, no explanation — just the JSON object.${options.schema ? `\n\nThe JSON must conform to this schema:\n${JSON.stringify(options.schema)}` : ''}`.trim();
89
+ }
90
+
91
+ const requestBody = {
92
+ model: options.model,
93
+ max_tokens: options.maxTokens,
94
+ messages,
70
95
  };
71
96
 
72
- if (system) {
73
- sdkOptions.systemPrompt = system;
97
+ if (systemFinal) {
98
+ requestBody.system = systemFinal;
74
99
  }
75
100
 
76
- if (options.response === 'json' && options.schema) {
77
- sdkOptions.outputFormat = {
78
- type: 'json_schema',
79
- schema: options.schema,
80
- };
101
+ if (options.temperature !== undefined) {
102
+ requestBody.temperature = options.temperature;
81
103
  }
82
104
 
83
- let resultText = '';
84
- let structuredOutput = null;
85
- let usage = null;
86
- let totalCostUSD = 0;
105
+ let raw;
87
106
 
88
107
  try {
89
- for await (const message of query({ prompt, options: sdkOptions })) {
90
- // Collect text from assistant messages
91
- if (message.type === 'assistant') {
92
- for (const block of message.message?.content || []) {
93
- if (block.type === 'text') {
94
- resultText += block.text;
95
- }
96
- }
97
- }
98
-
99
- // Capture final result + usage from the result message
100
- if (message.type === 'result') {
101
- if (message.subtype === 'success') {
102
- structuredOutput = message.structured_output || null;
103
- resultText = message.result || resultText;
104
- }
105
-
106
- usage = message.usage;
107
- totalCostUSD = message.total_cost_usd || 0;
108
-
109
- if (message.is_error) {
110
- throw new Error(`claude-code: ${resultText || 'unknown error'}`);
111
- }
112
- }
113
- }
108
+ raw = await client.messages.create(requestBody);
114
109
  } catch (e) {
115
- assistant?.error?.(`claude-code request failed: ${e.message}`);
110
+ assistant?.error?.(`claude-code request failed: ${e.message}`, e);
116
111
  throw e;
117
112
  }
118
113
 
119
- // Update token counters
120
- if (usage) {
121
- self.tokens.input.count += usage.input_tokens || 0;
122
- self.tokens.output.count += usage.output_tokens || 0;
123
- self.tokens.total.count = self.tokens.input.count + self.tokens.output.count;
124
- self.tokens.total.price = totalCostUSD;
125
- }
114
+ const outputText = (raw.content || [])
115
+ .filter((c) => c.type === 'text')
116
+ .map((c) => c.text.trim())
117
+ .join('\n')
118
+ .trim();
126
119
 
127
- // Resolve content prefer structured_output (validated against schema)
128
- let content;
120
+ const modelConfig = MODEL_TABLE[options.model] || MODEL_TABLE[DEFAULT_MODEL];
129
121
 
130
- if (structuredOutput != null) {
131
- content = structuredOutput;
132
- } else if (options.response === 'json') {
133
- content = parseJsonLoose(resultText);
134
- } else {
135
- content = resultText;
136
- }
122
+ self.tokens.input.count += raw.usage?.input_tokens || 0;
123
+ self.tokens.output.count += raw.usage?.output_tokens || 0;
124
+ self.tokens.total.count = self.tokens.input.count + self.tokens.output.count;
125
+ self.tokens.input.price = (self.tokens.input.count * modelConfig.input) / 1_000_000;
126
+ self.tokens.output.price = (self.tokens.output.count * modelConfig.output) / 1_000_000;
127
+ self.tokens.total.price = self.tokens.input.price + self.tokens.output.price;
128
+
129
+ let parsed = outputText;
137
130
 
138
- assistant?.log?.(`claude-code: ${Date.now() - startTime}ms, ${usage?.output_tokens || 0} output tokens, $${totalCostUSD?.toFixed(4) || '0.0000'}`);
131
+ if (options.response === 'json') {
132
+ parsed = parseJsonLoose(outputText);
133
+ }
139
134
 
140
135
  return {
141
- output: [{ type: 'output_text', text: resultText }],
142
- content,
136
+ output: raw.content || [],
137
+ content: parsed,
143
138
  tokens: self.tokens,
144
- raw: { usage, totalCostUSD },
139
+ raw,
145
140
  };
146
141
  };
147
142
 
148
143
  /**
149
- * Map unified options into a system prompt + a single user prompt string.
144
+ * Build Anthropic system + messages from the unified option shape.
145
+ *
146
+ * Accepts either:
147
+ * - options.messages: [{ role: 'system'|'user'|'assistant', content: string }]
148
+ * - options.prompt.content (system) + options.message.content (user)
150
149
  */
151
- function extractPromptAndSystem(options) {
150
+ function buildMessages(options) {
152
151
  if (Array.isArray(options.messages) && options.messages.length) {
153
152
  const system = options.messages.find((m) => m.role === 'system')?.content;
154
- const lastUser = [...options.messages].reverse().find((m) => m.role !== 'system');
153
+ const messages = options.messages
154
+ .filter((m) => m.role !== 'system')
155
+ .map((m) => ({ role: m.role, content: stringifyContent(m.content) }));
155
156
 
156
- return {
157
- system: stringifyContent(system),
158
- prompt: stringifyContent(lastUser?.content),
159
- };
157
+ return { system: stringifyContent(system), messages };
160
158
  }
161
159
 
160
+ const system = stringifyContent(options.prompt?.content || '');
161
+ const userContent = stringifyContent(options.message?.content || '');
162
+
162
163
  return {
163
- system: stringifyContent(options.prompt?.content),
164
- prompt: stringifyContent(options.message?.content),
164
+ system,
165
+ messages: [{ role: 'user', content: userContent }],
165
166
  };
166
167
  }
167
168
 
@@ -185,19 +186,22 @@ function stringifyContent(content) {
185
186
  }
186
187
 
187
188
  function parseJsonLoose(text) {
188
- if (!text) return text;
189
+ let cleaned = (text || '').trim();
190
+
191
+ cleaned = cleaned.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
189
192
 
190
- let cleaned = text.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
191
- const firstObj = cleaned.indexOf('{');
192
- const firstArr = cleaned.indexOf('[');
193
- const start = [firstObj, firstArr].filter((i) => i >= 0).sort((a, b) => a - b)[0];
193
+ const candidates = [cleaned.indexOf('{'), cleaned.indexOf('[')].filter((i) => i >= 0);
194
194
 
195
- if (start > 0) {
196
- cleaned = cleaned.slice(start);
195
+ if (candidates.length) {
196
+ const firstBrace = Math.min(...candidates);
197
+
198
+ if (firstBrace > 0) {
199
+ cleaned = cleaned.slice(firstBrace);
200
+ }
197
201
  }
198
202
 
199
203
  try {
200
- return JSON.parse(cleaned);
204
+ return JSON5.parse(cleaned);
201
205
  } catch {
202
206
  return text;
203
207
  }
@@ -4,14 +4,13 @@ const { validate: validateEmail, isDisposable } = require('../../../libraries/em
4
4
 
5
5
  const MAX_POLL_TIME_MS = 30000;
6
6
  const POLL_INTERVAL_MS = 500;
7
- const MAX_ACCOUNT_AGE_MS = 5 * 60 * 1000; // 5 minutes
8
7
 
9
8
  /**
10
9
  * POST /user/signup - Complete user signup
11
10
  *
12
11
  * Called by client after account creation to:
13
12
  * 1. Poll for user doc to exist (waits for onCreate to complete)
14
- * 2. Validate (already processed, account age)
13
+ * 2. Validate (reject only if flags.signupProcessed is already true)
15
14
  * 3. Gather all data (client details, inferred contact)
16
15
  * 4. Write everything to user doc in one merge
17
16
  * 5. Process affiliate referral (writes to referrer's doc)
@@ -49,23 +48,20 @@ module.exports = async ({ assistant, user, settings, libraries }) => {
49
48
  return assistant.respond('Signup has already been processed', { code: 400 });
50
49
  }
51
50
 
52
- // 3. Backup check: reject if account is older than 5 minutes
51
+ // 3. Fetch the Auth user needed for the canonical creationTime used to stamp
52
+ // metadata.created and consent timestamps. flags.signupProcessed (checked above) is
53
+ // the sole idempotency gate; there is intentionally no account-age window, so a
54
+ // legitimately-unprocessed account can complete signup whenever it retries.
53
55
  const authUser = await admin.auth().getUser(uid).catch((e) => e);
54
56
 
55
57
  if (authUser instanceof Error) {
56
58
  return assistant.respond(`Failed to get auth user: ${authUser.message}`, { code: 500 });
57
59
  }
58
60
 
59
- const accountAgeMs = Date.now() - new Date(authUser.metadata.creationTime).getTime();
60
-
61
- if (accountAgeMs > MAX_ACCOUNT_AGE_MS) {
62
- return assistant.respond('Account is too old to process signup', { code: 400 });
63
- }
64
-
65
61
  // 4. Gather all data, then write once
66
62
  const email = user.auth.email;
67
63
  const inferred = await inferUserContact(assistant, email);
68
- const userRecord = buildUserRecord(assistant, settings, inferred);
64
+ const userRecord = buildUserRecord(assistant, settings, inferred, authUser.metadata.creationTime);
69
65
 
70
66
  assistant.log(`signup(): Writing user record for ${uid}`, userRecord);
71
67
 
@@ -117,7 +113,7 @@ async function pollForUserDoc(assistant, uid) {
117
113
  /**
118
114
  * Build the full user record: client details, attribution, and inferred contact
119
115
  */
120
- function buildUserRecord(assistant, settings, inferred) {
116
+ function buildUserRecord(assistant, settings, inferred, creationTime) {
121
117
  const Manager = assistant.Manager;
122
118
  const attribution = settings.attribution;
123
119
 
@@ -142,10 +138,22 @@ function buildUserRecord(assistant, settings, inferred) {
142
138
  },
143
139
  },
144
140
  attribution: attribution || {},
145
- consent: buildConsentRecord(assistant, settings.consent),
141
+ consent: buildConsentRecord(assistant, settings.consent, creationTime),
146
142
  metadata: Manager.Metadata().set({ tag: 'user/signup' }),
147
143
  };
148
144
 
145
+ // Stamp metadata.created from Firebase Auth's creationTime so it matches Auth's canonical
146
+ // value. Normally onCreate sets this, but if onCreate didn't fire this merge write is the
147
+ // doc's first creation — without this the doc lands with no created date and the OMEGA
148
+ // migration has to backfill it. Idempotent: when onCreate already wrote it, this matches.
149
+ if (creationTime) {
150
+ const createdDate = new Date(creationTime);
151
+ record.metadata.created = {
152
+ timestamp: createdDate.toISOString(),
153
+ timestampUNIX: Math.round(createdDate.getTime() / 1000),
154
+ };
155
+ }
156
+
149
157
  // Add inferred name/company if available
150
158
  if (inferred) {
151
159
  record.personal = {
@@ -168,18 +176,24 @@ function buildUserRecord(assistant, settings, inferred) {
168
176
  * Client sends: { legal: { granted, text }, marketing: { granted, text } }
169
177
  * Server writes: { legal: { status, grantedAt: {...} }, marketing: { status, grantedAt: {...}, revokedAt: {...} } }
170
178
  *
171
- * Server time (not client-supplied) is authoritative — defends against clock manipulation.
179
+ * Server-derived time (not client-supplied) is authoritative — defends against clock
180
+ * manipulation. Uses Auth's creationTime so consent timestamps match metadata.created.
172
181
  * IP is captured from request geolocation.
173
182
  *
174
183
  * Legal is REQUIRED — the client must send legal.granted=true. If missing/false we still
175
184
  * record what the client sent, but the route will not have reached this point in practice
176
185
  * (the signup-form HTML5-requires the legal checkbox).
177
186
  */
178
- function buildConsentRecord(assistant, clientConsent) {
187
+ function buildConsentRecord(assistant, clientConsent, creationTime) {
179
188
  const consent = clientConsent || {};
180
189
  const ip = assistant.request.geolocation?.ip || null;
181
- const timestamp = assistant.meta.startTime.timestamp;
182
- const timestampUNIX = assistant.meta.startTime.timestampUNIX;
190
+
191
+ // Stamp grantedAt/revokedAt from Auth's creationTime so consent timestamps match
192
+ // metadata.created (the OMEGA migration treats metadata.created as the SSOT and reconciles
193
+ // consent.grantedAt against it). Fall back to request start time if creationTime is absent.
194
+ const createdDate = creationTime ? new Date(creationTime) : null;
195
+ const timestamp = createdDate ? createdDate.toISOString() : assistant.meta.startTime.timestamp;
196
+ const timestampUNIX = createdDate ? Math.round(createdDate.getTime() / 1000) : assistant.meta.startTime.timestampUNIX;
183
197
 
184
198
  // Build empty leaf shape — used wherever grantedAt or revokedAt is "not set"
185
199
  const emptyMeta = { timestamp: null, timestampUNIX: null, source: null, ip: null, text: null };
@@ -244,8 +244,6 @@ module.exports = {
244
244
  };
245
245
 
246
246
  // Use absurdly-old client timestamp to prove server time wins (defense vs clock skew)
247
- const beforeMs = Date.now();
248
-
249
247
  const signupResponse = await http.as('consent-granted').post('user/signup', {
250
248
  consent: {
251
249
  legal: { granted: true, text: consentText.legal, timestamp: '2000-01-01T00:00:00.000Z' },
@@ -255,7 +253,6 @@ module.exports = {
255
253
 
256
254
  assert.isSuccess(signupResponse, `Signup should succeed: ${JSON.stringify(signupResponse, null, 2)}`);
257
255
 
258
- const afterMs = Date.now();
259
256
  const userDoc = await firestore.get(`users/${accounts['consent-granted'].uid}`);
260
257
 
261
258
  // Legal
@@ -265,14 +262,16 @@ module.exports = {
265
262
  assert.ok(userDoc?.consent?.legal?.grantedAt?.timestamp, 'legal grantedAt.timestamp should be set');
266
263
  assert.equal(typeof userDoc?.consent?.legal?.grantedAt?.timestampUNIX, 'number', 'legal grantedAt.timestampUNIX should be number');
267
264
 
268
- // Server time MUST be used (the client-supplied 2000-01-01 should NOT appear)
265
+ // Server-derived time MUST be used (the client-supplied 2000-01-01 should NOT appear).
266
+ // grantedAt is stamped from Auth's creationTime, the same source as metadata.created,
267
+ // so the two must be equal — and the client's 2000-01-01 (UNIX 946684800) is rejected.
269
268
  const legalUNIX = userDoc.consent.legal.grantedAt.timestampUNIX;
270
- const beforeUNIX = Math.floor(beforeMs / 1000);
271
- const afterUNIX = Math.floor(afterMs / 1000);
272
- assert.ok(
273
- legalUNIX >= beforeUNIX && legalUNIX <= afterUNIX,
274
- `legal grantedAt.timestampUNIX (${legalUNIX}) must be server time, not client time. expected between ${beforeUNIX} and ${afterUNIX}`
269
+ const createdUNIX = userDoc.metadata.created.timestampUNIX;
270
+ assert.equal(
271
+ legalUNIX, createdUNIX,
272
+ `legal grantedAt.timestampUNIX (${legalUNIX}) should match metadata.created (${createdUNIX}) both from Auth creationTime`
275
273
  );
274
+ assert.notEqual(legalUNIX, 946684800, 'legal grantedAt must NOT be the client-supplied 2000-01-01 time');
276
275
 
277
276
  // Marketing
278
277
  assert.equal(userDoc?.consent?.marketing?.status, 'granted', 'consent.marketing.status should be granted');