Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SPWalletCore9// File : Sources/SPWalletCore/Domains/Execution/DeveloperAPI.swift10// Description : Managing API keys and webhooks from the owner's session.11// Creating a key, rotating it, or changing it in a way that12// gives it MORE authority needs the passkey over an intent13// that is recomputed and compared with the request here14// (scopes, expiry, limits, restrictions, rate, mandate15// binding). Revoking and narrowing need the session only.16// This is the owner's side: the machine API that the keys17// open (/api/v1/trading with a bearer token) is not here.18// Module : SPWalletCore19// Repository : https://git.spboucher.ai/sp-wallet-core20// Created : 2026-11-1821// Last Modified : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation9697/** A verified key-management intent, ready for the passkey. */98public struct APIKeyApproval: Sendable {99 public let approval: VerifiedApproval<APIKeyIntent>100 /** unix ms: the server forgets the intent after it (3 minutes) */101 public let expiresAt: Int102 public var intent: APIKeyIntent { approval.object }103 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }104}105106public struct DeveloperAPI: Sendable {107 let client: APIClient108 public init(_ client: APIClient) { self.client = client }109110 private struct ApprovalBody: Encodable, Sendable { let intentId: String; let assertion: PasskeyAssertion }111 private struct One: Decodable, Sendable { let key: APIKey }112 private static func path(_ id: String) -> String { "/developer/keys/\(APIClient.segment(id))" }113114 // MARK: keys115116 public func keys() async throws -> APIKeyList { try await client.get("/developer/keys") }117118 /**119 Step 1 of a creation. Verified: the intent creates a key with exactly the name, scopes, limits, restrictions, rate and120 mandate binding requested, expiring exactly `expiresInDays` after its preparation, for THIS wallet origin.121 */122 public func prepareCreate(_ r: APIKeyCreateRequest, now: Date = Date()) async throws -> APIKeyApproval {123 let a = try await prepared("/developer/keys/prepare", body: r, action: "create", now: now)124 guard let k = a.intent.key else { throw ApprovalError.unsupported("no key in the intent") }125 guard k.name == r.name.trimmingCharacters(in: .whitespacesAndNewlines) else { throw ApprovalError.inconsistent("name") }126 guard k.scopes == APIKeyIntent.uniq(r.scopes) else { throw ApprovalError.inconsistent("scopes") }127 guard k.limits == r.limits else { throw ApprovalError.inconsistent("limits") }128 guard k.restrictions == r.restrictions.cleaned else { throw ApprovalError.inconsistent("restrictions") }129 guard k.rateLimitPerMin == r.rateLimitPerMin else { throw ApprovalError.inconsistent("rate limit") }130 guard k.mandateId == r.mandateId else { throw ApprovalError.inconsistent("mandate binding") }131 guard let prepared = ISO8601.parse(a.intent.preparedAt), let expires = ISO8601.parse(k.expiresAt),132 Int64((expires.timeIntervalSince1970 * 1000).rounded()) - Int64((prepared.timeIntervalSince1970 * 1000).rounded()) == Int64(r.expiresInDays) * 86_400_000 else { throw ApprovalError.inconsistent("expiry") }133 return a134 }135136 /** Step 2: the key exists after this call, and its secret is in THIS answer only. A lost answer cannot be replayed: revoke the key (it is in `keys()`) and create another. */137 public func create(_ a: APIKeyApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> IssuedAPIKey {138 guard a.intent.action == "create", let wanted = a.intent.key else { throw ApprovalError.inconsistent("not a creation intent") }139 let j: JSONValue = try await client.post("/developer/keys", body: try await approvalBody(a, authenticator, now))140 return try Self.issued(j, expecting: wanted)141 }142143 /** Session only, idempotent: revoking only removes authority. */144 public func revoke(id: String, reason: String) async throws -> APIKey {145 struct Body: Encodable, Sendable { let reason: String }146 return try await client.post(Self.path(id) + "/revoke", body: Body(reason: String(reason.trimmingCharacters(in: .whitespacesAndNewlines).prefix(200))), as: One.self).key147 }148149 /** Step 1 of a rotation: a new id and a new secret with the same scopes, limits, restrictions and expiry; the old key stops working. */150 public func prepareRotate(id: String, now: Date = Date()) async throws -> APIKeyApproval {151 let a = try await prepared(Self.path(id) + "/rotate/prepare", body: EmptyBody(), action: "rotate", now: now)152 guard a.intent.keyId == id, let new = a.intent.newKeyId, new != id else { throw ApprovalError.inconsistent("the intent rotates another key") }153 return a154 }155156 /** Step 2. A mandate names ONE key id: `mandate` of the answer says whether it was carried to the new id (otherwise the new key's execution scopes are inert). */157 public func rotate(_ a: APIKeyApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> IssuedAPIKey {158 guard a.intent.action == "rotate", let old = a.intent.keyId, let new = a.intent.newKeyId else { throw ApprovalError.inconsistent("not a rotation intent") }159 let j: JSONValue = try await client.post(Self.path(old) + "/rotate", body: try await approvalBody(a, authenticator, now))160 guard let secret = j["secret"]?.stringValue, let kj = j["key"] else { throw APIError(status: 200, code: "decoding", message: "unexpected answer of a key rotation") }161 let key: APIKey = try kj.decode()162 var d: [String] = []163 if key.id != new { d.append("id") }164 if !secret.hasPrefix("spw_live_\(key.id)_") { d.append("secret") }165 if j["revoked"]?.stringValue != old { d.append("revoked") }166 return IssuedAPIKey(key: key, secret: OneTimeSecret(secret), revoked: j["revoked"]?.stringValue, mandate: j["mandate"], discrepancies: d)167 }168169 /**170 Change a key with the session alone: accepted only when no change gives the key more authority; otherwise the server answers171 403 `passkey_required` naming what widens (use `prepareUpdate`).172 */173 public func narrow(id: String, changes: APIKeyChanges) async throws -> APIKey {174 struct Body: Encodable, Sendable { let changes: APIKeyChanges }175 return try await client.post(Self.path(id) + "/update", body: Body(changes: changes), as: One.self).key176 }177178 /** Step 1 of a change. Verified: the intent is for this key and carries exactly the changes requested; `intent.widening` lists what gives MORE authority. */179 public func prepareUpdate(id: String, changes: APIKeyChanges, now: Date = Date()) async throws -> APIKeyApproval {180 struct Body: Encodable, Sendable { let changes: APIKeyChanges }181 let a = try await prepared(Self.path(id) + "/update/prepare", body: Body(changes: changes), action: "update", now: now)182 guard a.intent.keyId == id else { throw ApprovalError.inconsistent("the intent changes another key") }183 guard a.intent.changes == changes.normalized else { throw ApprovalError.inconsistent("the changes to approve are not the changes requested") }184 return a185 }186187 public func update(_ a: APIKeyApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> APIKey {188 guard a.intent.action == "update", let id = a.intent.keyId else { throw ApprovalError.inconsistent("not an update intent") }189 return try await client.post(Self.path(id) + "/update", body: try await approvalBody(a, authenticator, now), as: One.self).key190 }191192 /** Calls made with the keys: method, route PATTERN, status, latency — never a body, a query string or a header. */193 public func usage(keyId: String? = nil, limit: Int = 100) async throws -> APIKeyUsage { try await client.get("/developer/usage", query: ["key": keyId, "limit": String(min(max(limit, 1), 500))]) }194195 public func status() async throws -> DeveloperStatus { try await client.get("/developer/status") }196197 // MARK: webhooks198199 public func webhooks() async throws -> WebhookList { try await client.get("/developer/webhooks") }200201 public func deliveries(webhookId: String? = nil, limit: Int = 50) async throws -> [WebhookDelivery] {202 struct R: Decodable, Sendable { let deliveries: [WebhookDelivery] }203 return try await client.get("/developer/webhooks/deliveries", query: ["webhook": webhookId, "limit": String(min(max(limit, 1), 200))], as: R.self).deliveries204 }205206 /** The signing secret is in this answer only. */207 public func createWebhook(url: String, events: [String], label: String) async throws -> IssuedWebhookSecret {208 struct Body: Encodable, Sendable { let url: String; let events: [String]; let label: String }209 return try Self.issuedWebhook(try await client.post("/developer/webhooks", body: Body(url: url, events: events, label: label)))210 }211212 public func updateWebhook(id: String, enabled: Bool? = nil, events: [String]? = nil, label: String? = nil, idempotencyKey: String) async throws -> Webhook {213 struct Body: Encodable, Sendable { let enabled: Bool?; let events: [String]?; let label: String? }214 struct R: Decodable, Sendable { let webhook: Webhook }215 return try await client.post("/developer/webhooks/\(APIClient.segment(id))", body: Body(enabled: enabled, events: events, label: label), idempotencyKey: idempotencyKey, as: R.self).webhook216 }217218 /** A new signing secret, in this answer only; the previous one stops verifying. */219 public func rotateWebhookSecret(id: String) async throws -> IssuedWebhookSecret {220 try Self.issuedWebhook(try await client.post("/developer/webhooks/\(APIClient.segment(id))/secret"))221 }222223 public func deleteWebhook(id: String) async throws { let _: OKResponse = try await client.delete("/developer/webhooks/\(APIClient.segment(id))") }224225 // MARK: internals226227 private func prepared(_ path: String, body: any Encodable & Sendable, action: String, now: Date) async throws -> APIKeyApproval {228 struct Answer: Decodable, Sendable { let intentId: String; let intent: JSONValue; let sha256: String; let expiresAt: Int; let options: PasskeyRequestOptions }229 let p: Answer = try await client.post(path, body: body)230 let intent = try APIKeyIntent(served: p.intent)231 guard intent.action == action else { throw ApprovalError.inconsistent("the intent is a \(intent.action), a \(action) was requested") }232 guard intent.intentId == p.intentId else { throw ApprovalError.inconsistent("intent id") }233 guard intent.origin == client.configuration.originHeader else { throw ApprovalError.inconsistent("the intent was prepared for another origin") }234 try ApprovalBinding.requireStatedHash(p.sha256, of: intent, what: "intent")235 guard Date(timeIntervalSince1970: TimeInterval(p.expiresAt) / 1000) > now else { throw ApprovalError.expired }236 return APIKeyApproval(approval: try ApprovalBinding.verify(intent, options: p.options, rpId: client.configuration.rpId), expiresAt: p.expiresAt)237 }238239 private func approvalBody(_ a: APIKeyApproval, _ authenticator: PasskeyAuthenticator, _ now: Date) async throws -> ApprovalBody {240 guard a.expiry > now else { throw ApprovalError.expired }241 return ApprovalBody(intentId: a.intent.intentId, assertion: try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId))242 }243244 /** Never throws once the secret is in hand for a mere difference: the key exists and its secret is shown once — differences are REPORTED. */245 static func issued(_ j: JSONValue, expecting k: APIKeyIntent.Key) throws -> IssuedAPIKey {246 guard let secret = j["secret"]?.stringValue, let kj = j["key"] else { throw APIError(status: 200, code: "decoding", message: "unexpected answer of a key creation") }247 let key: APIKey = try kj.decode()248 var d: [String] = []249 if key.id != k.id { d.append("id") }250 if key.name != k.name { d.append("name") }251 if Set(key.scopes) != Set(k.scopes) { d.append("scopes") }252 if key.limits != k.limits { d.append("limits") }253 if key.restrictions != k.restrictions { d.append("restrictions") }254 if key.rateLimitPerMin != k.rateLimitPerMin { d.append("rateLimitPerMin") }255 if key.mandateId != k.mandateId.value { d.append("mandateId") }256 if let e = ISO8601.parse(k.expiresAt), Int((e.timeIntervalSince1970 * 1000).rounded()) != key.expiresAt { d.append("expiresAt") }257 if !secret.hasPrefix("spw_live_\(key.id)_") { d.append("secret") }258 return IssuedAPIKey(key: key, secret: OneTimeSecret(secret), revoked: nil, mandate: nil, discrepancies: d)259 }260261 private static func issuedWebhook(_ j: JSONValue) throws -> IssuedWebhookSecret {262 guard let secret = j["secret"]?.stringValue, let w = j["webhook"] else { throw APIError(status: 200, code: "decoding", message: "unexpected answer of a webhook secret") }263 return IssuedWebhookSecret(webhook: try w.decode(), secret: OneTimeSecret(secret))264 }265}266